From c0a5d66fa60c7fd8e95700242c3f64ea23560fe5 Mon Sep 17 00:00:00 2001 From: Almogaver295 <133548141+guimsolutions@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:33:16 +0100 Subject: [PATCH 001/110] feat(vulkan): support Texture1D, Texture1DArray and Texture3D UAVs D3D-78: keep storage-only 1D-array bindings separate from upstream multisample SRVs. Validate typed views and W ranges; use sliced storage views with tagged coordinates, typed loads, stores and R32_UINT atomics. Keep clears safe and align the existing descriptor, RGB9E5 and shader regressions with the runtime contract. Reconstructs bf9201c8 and the implementation portions of the original branch through a56b8589. D3D-63 resource creation already comes from upstream c7d5f8e8. --- runtime/shims/d3d12_com.cpp | 8 + runtime/shims/d3d12_com.h | 4 + runtime/shims/d3d12_vulkan_device.cpp | 339 ++++++++++++++++------ runtime/src/command_list.h | 1 + runtime/src/gfx10_descriptors.h | 20 ++ runtime/src/vulkan_bindless.h | 66 +++-- runtime/src/vulkan_replay.h | 10 +- runtime/test/bindless_sizing_test.cpp | 48 +++- runtime/test/d3d12_r9g9b9e5_uav_test.cpp | 98 +++++-- runtime/test/d3d12_texture1d_test.cpp | 15 +- runtime/test/glsl/cs_r9g9b9e5_uav.comp | 21 +- runtime/test/shaders/cs_imgatomic3d.asm | 4 +- runtime/test/shaders/ps_imgatomic.asm | 4 +- runtime/test/vk_bindless_test.cpp | 62 ++-- runtime/test/vk_pipeline_check.cpp | 63 +++-- runtime/test/vk_store_test.cpp | 96 +++++-- runtime/test/vk_test_device.h | 44 ++- tests/test_image_load_typed.py | 166 ++++++++++- tests/test_spirv_metal_set0.py | 2 +- tests/test_spirv_metal_set0_aliases.py | 2 +- tests/test_spirv_metal_set0_extra.py | 39 +-- tools/rdna2spirv.py | 343 ++++++++++++++++------- 22 files changed, 1101 insertions(+), 354 deletions(-) diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 6858f073ca..db80e7380d 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -867,11 +867,19 @@ class GraphicsCommandList final g::Image image{}; if (!g::decode(words, image)) return false; const bool volume = image.type == g::ImageType::image_3d; + if (g::partial_volume_uav(words, image)) { + // Transfer clears operate on a whole 3D mip, not a storage image view. Refuse instead of + // overwriting slices outside the UAV; a sliced clear needs a separate replay path. + stub("ClearUnorderedAccessView of a partial 3D mip"); + return false; + } out.buffer = false; out.format = std::uint32_t(descriptor_format(image.format, image.swizzle)); out.mip = image.first_mip; out.first_layer = volume ? 0 : image.first_layer; // a 3D view clears every slice of its mip out.layer_count = volume ? 1 : image.layer_count; + out.exact_clear_format = volume || image.type == g::ImageType::image_1d || + image.type == g::ImageType::image_1d_array; return out.format != VK_FORMAT_UNDEFINED; } g::BufferWords buffer_words{}; diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 6cab20a8e4..a2ad1409f0 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -154,6 +154,10 @@ struct VulkanDeviceInfo { // Optional VK_KHR_acceleration_structure + VK_KHR_deferred_host_operations + VK_KHR_ray_query are enabled: // GetRaytracingAccelerationStructurePrebuildInfo and BuildRaytracingAccelerationStructure (BLAS + TLAS) work. bool ray_tracing = false; + // robustImageAccess is enabled on `device`, so typed 1D-family and 3D UAV loads are range checked. + bool robust_image_access = false; + // VK_EXT_image_sliced_view_of_3d (imageSlicedViewOf3D) is also enabled for partial 3D UAVs. + bool sliced_3d_uav = false; // BuildRaytracingAccelerationStructure writes the console's XDXR BVH4 records into the destination buffer // (src/xdxr_build.h), the layout the game's translated traversal shaders read, instead of building a // VkAccelerationStructureKHR; needs buffer_device_address and the GPU address arena. The standalone device sets it diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index ded17e79d2..1af93b4067 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -761,6 +761,14 @@ struct DeviceState { return S_OK; } + VkFormatFeatureFlags2 optimal_features(VkFormat format) const { + if (!format_properties2) return 0; + VkFormatProperties3 features{VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_3}; + VkFormatProperties2 properties{VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2, &features}; + format_properties2(info.physical, format, &properties); + return features.optimalTilingFeatures; + } + // D3D12_OPTIONS1's wave facts, from the physical device: which subgroup operations exist and what wave sizes it // can run. Zeros and false when the device cannot be asked, which the query then reports as unsupported. const SubgroupFacts& subgroup_facts() { @@ -963,19 +971,27 @@ struct DeviceState { const std::uint64_t slot_handle = (static_cast(entry.dimension) << 32) | static_cast(entry.index); context->defer_destroy(leonida::DeferredDeletionQueue::Kind::bindless_slot, slot_handle); - context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_view, entry.sampled); + if (entry.sampled) context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_view, entry.sampled); if (entry.storage) context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_view, entry.storage); } + struct VolumeSlices { + UINT first = 0; + UINT count = 0; // 0: no restriction (ordinary view of the whole mip) + }; + // Gives the T# `words` a view in set 0 and an entry in the hash table, unless it has them. `storage`: shaders // write through it too (an unordered-access view), so it also goes into the storage arrays, which are // shorter. False when set 0 cannot show the image; the descriptor then finds the fallback at index 0. bool bind_image(const leonida::gfx10::ImageWords& words, const leonida::gfx10::Image& image, VkImage vk_image, - VkFormat image_format, VkImageAspectFlags aspects, bool storage, - bool allow_channel_cast = false, bool r9g9b9e5_as_r32_uint = false) { + VkFormat view_format, VkFormat channels_format, VkFormat storage_format, + VkImageAspectFlags aspects, bool sampled, bool storage, VolumeSlices slices) { namespace g = leonida::gfx10; std::lock_guard lock(descriptor_mutex); - if (!bindless) return false; + if (!bindless) { + if (storage) log_once("unordered-access view needs the Vulkan bindless set; type", int(image.type)); + return false; + } const auto existing = image_entries.find(words); if (existing != image_entries.end() && (existing->second.storage || !storage)) return true; @@ -986,6 +1002,7 @@ struct DeviceState { case g::ImageType::cube: dimension = leonida::ImageDimension::dim_2d_array; break; case g::ImageType::image_3d: dimension = leonida::ImageDimension::dim_3d; break; case g::ImageType::image_1d: dimension = leonida::ImageDimension::dim_1d; break; + case g::ImageType::image_1d_array: dimension = leonida::ImageDimension::dim_1d_array; break; case g::ImageType::image_2d_msaa: dimension = leonida::ImageDimension::dim_2d_ms; break; case g::ImageType::image_2d_msaa_array: dimension = leonida::ImageDimension::dim_2d_ms_array; break; default: @@ -994,41 +1011,31 @@ struct DeviceState { } const bool depth_or_stencil = (aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) != 0; if (storage && depth_or_stencil) { - log_once("storage view not supported for depth-stencil image format:", int(image_format)); + log_once("storage view not supported for depth-stencil image format:", int(view_format)); return false; } - // A T# of 8_UINT on a depth-stencil image is a view of its stencil plane (image_descriptor, D3D-75). Vulkan - // views it in the image's own format with the stencil aspect, and returns the value in R, as a T# whose - // format is 8_UINT reads it from X. - const bool stencil = (aspects & VK_IMAGE_ASPECT_STENCIL_BIT) && image.format == g::stencil_format; - const VkFormat logical_format = r9g9b9e5_as_r32_uint ? VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 : image_format; - VkFormat view_format = - stencil ? image_format : g::vulkan_view_format(logical_format, image.format, allow_channel_cast); - VkFormat channels_format = view_format; // whose channels the T#'s swizzle selects from - if (view_format == VK_FORMAT_UNDEFINED) { // a 96-bit texture's T# names RGB32; its image is RGBA32 - view_format = rgb96_view_format(image_format, image.format); - channels_format = rgb96_named_format(view_format); - } if (view_format == VK_FORMAT_UNDEFINED || (depth_or_stencil && !g::is_depth_stencil_format(view_format))) { log_once("no Vulkan view format for the GFX10 format of a view:", int(image.format)); return false; } + // A T# of 8_UINT on a depth-stencil image is a view of its stencil plane (image_descriptor, D3D-75). Vulkan + // views it in the image's own format with the stencil aspect, and returns the value in R, as a T# whose + // format is 8_UINT reads it from X. + const bool stencil = (aspects & VK_IMAGE_ASPECT_STENCIL_BIT) && image.format == g::stencil_format; const unsigned sampled_class = g::multisampled(image.type) ? numeric_class(view_format) : 0; if (g::multisampled(image.type) && !bindless->supports_ms_class(sampled_class)) { log_once("set 0 has no multisample binding for this numeric class:", int(sampled_class)); return false; } auto& vk = context->vk; + VkImageViewUsageCreateInfo view_usage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO}; + view_usage.usage = VK_IMAGE_USAGE_SAMPLED_BIT; VkImageViewCreateInfo view_info{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; + view_info.pNext = &view_usage; view_info.image = vk_image; view_info.viewType = g::vulkan_view_type(image.type); view_info.format = view_format; - VkImageViewUsageCreateInfo sampled_usage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO}; - if (r9g9b9e5_as_r32_uint) { - sampled_usage.usage = VK_IMAGE_USAGE_SAMPLED_BIT; - view_info.pNext = &sampled_usage; - } auto swizzle = image.swizzle; VkImageViewMinLodCreateInfoEXT clamp{VK_STRUCTURE_TYPE_IMAGE_VIEW_MIN_LOD_CREATE_INFO_EXT}; const bool supports_lod_clamp = image.type == g::ImageType::image_1d || image.type == g::ImageType::image_2d || @@ -1046,8 +1053,7 @@ struct DeviceState { log_once("SRV requires VK_EXT_image_view_min_lod; first mip", int(image.first_mip)); return false; } - clamp.pNext = view_info.pNext; - view_info.pNext = &clamp; + view_usage.pNext = &clamp; } } view_info.components = g::vulkan_swizzle(swizzle, channels_format); @@ -1058,20 +1064,31 @@ struct DeviceState { : VK_IMAGE_ASPECT_COLOR_BIT), image.first_mip, image.mip_count, image.first_layer, image.layer_count}; ImageEntry entry{dimension, 0, VK_NULL_HANDLE, VK_NULL_HANDLE, image.address}; - if (vk.vkCreateImageView(info.device, &view_info, nullptr, &entry.sampled) != VK_SUCCESS) return false; + if (sampled) { + const VkResult result = vk.vkCreateImageView(info.device, &view_info, nullptr, &entry.sampled); + if (result != VK_SUCCESS) { + log_once("sampled image view creation failed:", result); + return false; + } + } leonida::StorageViews views{}; if (storage) { VkImageViewCreateInfo storage_info = view_info; storage_info.components = {}; + storage_info.format = storage_format; VkImageViewUsageCreateInfo storage_usage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO}; - const VkFormat storage_format = r9g9b9e5_as_r32_uint ? VK_FORMAT_R32_UINT : view_format; - if (r9g9b9e5_as_r32_uint) { - storage_info.format = storage_format; - storage_usage.usage = VK_IMAGE_USAGE_STORAGE_BIT; - storage_info.pNext = &storage_usage; + storage_usage.usage = VK_IMAGE_USAGE_STORAGE_BIT; + VkImageViewSlicedCreateInfoEXT sliced{VK_STRUCTURE_TYPE_IMAGE_VIEW_SLICED_CREATE_INFO_EXT}; + if (slices.count) { + sliced.sliceOffset = slices.first; + sliced.sliceCount = slices.count; + storage_usage.pNext = &sliced; } - if (vk.vkCreateImageView(info.device, &storage_info, nullptr, &entry.storage) != VK_SUCCESS) { - vk.vkDestroyImageView(info.device, entry.sampled, nullptr); + storage_info.pNext = &storage_usage; + const VkResult result = vk.vkCreateImageView(info.device, &storage_info, nullptr, &entry.storage); + if (result != VK_SUCCESS) { + log_once("storage image view creation failed:", result); + if (entry.sampled) vk.vkDestroyImageView(info.device, entry.sampled, nullptr); return false; } const int numeric = numeric_class(storage_format); @@ -1082,7 +1099,7 @@ struct DeviceState { entry.index = bindless->add_image(dimension, entry.sampled, VK_IMAGE_LAYOUT_GENERAL, views, sampled_class); if (!entry.index) { log_once("a bindless image array is full; dimension", int(dimension)); - vk.vkDestroyImageView(info.device, entry.sampled, nullptr); + if (entry.sampled) vk.vkDestroyImageView(info.device, entry.sampled, nullptr); if (entry.storage) vk.vkDestroyImageView(info.device, entry.storage, nullptr); return false; } @@ -1791,7 +1808,15 @@ class Resource final const bool volume = desc_.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; const UINT depth = volume ? desc_.DepthOrArraySize : 1; const bool one_d = desc_.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D; - if (desc_.MipLevels == 0) desc_.MipLevels = full_mips(desc_.Width, desc_.Height, depth); + const UINT16 mips = full_mips(desc_.Width, desc_.Height, depth); + if (desc_.MipLevels == 0) desc_.MipLevels = mips; + if ((volume || one_d) && (desc_.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { + const UINT extent_limit = volume ? D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION : D3D12_REQ_TEXTURE1D_U_DIMENSION; + const UINT slice_limit = volume ? extent_limit : D3D12_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION; + if (!desc_.Width || desc_.Width > extent_limit || !desc_.Height || desc_.Height > extent_limit || + !desc_.DepthOrArraySize || desc_.DepthOrArraySize > slice_limit || desc_.MipLevels > mips) + return E_INVALIDARG; + } TextureCreateInfo create(desc_, format, device_.color_attachment_usable(format.format)); VkImageCreateInfo& info = create.info; if (!castable.empty()) { @@ -1895,6 +1920,7 @@ class Resource final } return desc; } + bool belongs_to(const DeviceState& device) const { return &device_ == &device; } // A reserved resource is a committed one underneath (docs/d3d12_vulkan.md section 4.2); it reports the layout it // was created with and has no heap of its own. @@ -3438,6 +3464,28 @@ struct TextureView { float min_lod = 0.0f; }; +// The existing mutable Vulkan formats come from these DXGI typeless families. A typed resource cannot be +// reinterpreted by the 1D/3D UAV path; equal texel sizes alone don't make a cast legal. +bool uav_format_compatible(DXGI_FORMAT resource, DXGI_FORMAT view) { + if (resource == view) return true; + switch (resource) { + case DXGI_FORMAT_R32G32B32A32_TYPELESS: + return view >= DXGI_FORMAT_R32G32B32A32_FLOAT && view <= DXGI_FORMAT_R32G32B32A32_SINT; + case DXGI_FORMAT_R16G16B16A16_TYPELESS: + return view >= DXGI_FORMAT_R16G16B16A16_FLOAT && view <= DXGI_FORMAT_R16G16B16A16_SINT; + case DXGI_FORMAT_R32G32_TYPELESS: return view >= DXGI_FORMAT_R32G32_FLOAT && view <= DXGI_FORMAT_R32G32_SINT; + case DXGI_FORMAT_R10G10B10A2_TYPELESS: return view == DXGI_FORMAT_R10G10B10A2_UNORM || + view == DXGI_FORMAT_R10G10B10A2_UINT; + case DXGI_FORMAT_R8G8B8A8_TYPELESS: return view >= DXGI_FORMAT_R8G8B8A8_UNORM && view <= DXGI_FORMAT_R8G8B8A8_SINT; + case DXGI_FORMAT_R16G16_TYPELESS: return view >= DXGI_FORMAT_R16G16_FLOAT && view <= DXGI_FORMAT_R16G16_SINT; + case DXGI_FORMAT_R8G8_TYPELESS: return view >= DXGI_FORMAT_R8G8_UNORM && view <= DXGI_FORMAT_R8G8_SINT; + case DXGI_FORMAT_R32_TYPELESS: return view >= DXGI_FORMAT_R32_FLOAT && view <= DXGI_FORMAT_R32_SINT; + case DXGI_FORMAT_R16_TYPELESS: return view >= DXGI_FORMAT_R16_FLOAT && view <= DXGI_FORMAT_R16_SINT; + case DXGI_FORMAT_B8G8R8A8_TYPELESS: return view == DXGI_FORMAT_B8G8R8A8_UNORM; + default: return false; + } +} + // In-memory pipeline library (docs/d3d12_vulkan.md sections 3.6 and 4). D3D12 cached blobs are driver-specific // and ignored across runs; Serialize writes a versioned header so CreatePipelineLibrary recognizes our own blobs // and returns D3D12_ERROR_DRIVER_VERSION_MISMATCH for foreign or corrupt ones. @@ -3858,9 +3906,14 @@ class ShaderCacheSession final // The T# of a view: what the shader gets to know about it, in the structure the console's shaders read. // False (with a log) for a view set 0 cannot show yet. -bool image_descriptor(const Resource& resource, const TextureView& view, leonida::gfx10::Image& out) { +bool image_descriptor(const Resource& resource, const TextureView& view, bool storage, leonida::gfx10::Image& out, + VkFormat& view_format, DeviceState::VolumeSlices& slices) { namespace g = leonida::gfx10; const D3D12_RESOURCE_DESC& desc = resource.desc(); + if (storage && (resource.aspects() & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT))) { + log_once("storage view not supported for depth-stencil texture:", int(desc.Format)); + return false; + } // Plane 1 of a depth-stencil texture is its stencil, viewed as X24_TYPELESS_G8_UINT (D24S8) or // X32_TYPELESS_G8X24_UINT (D32S8): eight unsigned bits in G, as D3D12 returns them. The T# is 8_UINT, the // format of the console's separate stencil surface, and bind_image views the stencil aspect for it. @@ -3880,13 +3933,15 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida log_once("a stencil-plane view needs its texture family's stencil view format; format", int(view.format)); return false; } - const bool volume = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; - const bool msaa = g::multisampled(view.type); + const bool volume = view.type == g::ImageType::image_3d; const bool line = view.type == g::ImageType::image_1d; - const auto dimension = line ? D3D12_RESOURCE_DIMENSION_TEXTURE1D : - view.type == g::ImageType::image_3d ? D3D12_RESOURCE_DIMENSION_TEXTURE3D : - D3D12_RESOURCE_DIMENSION_TEXTURE2D; - if (desc.Dimension != dimension || (line && view.layer_count != 1) || msaa != (desc.SampleDesc.Count > 1)) { + const bool line_array = view.type == g::ImageType::image_1d_array; + const bool one_d = line || line_array; + const bool msaa = g::multisampled(view.type); + const auto dimension = volume ? D3D12_RESOURCE_DIMENSION_TEXTURE3D + : one_d ? D3D12_RESOURCE_DIMENSION_TEXTURE1D : D3D12_RESOURCE_DIMENSION_TEXTURE2D; + if (desc.Dimension != dimension || (msaa ? desc.SampleDesc.Count <= 1 : desc.SampleDesc.Count != 1) || + (storage ? msaa : line_array) || (line && view.layer_count != 1)) { log_once("view type incompatible with texture dimension or sample count; view type", int(view.type)); return false; } @@ -3907,7 +3962,7 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida const VkFormat resource_format = resource.r9g9b9e5_as_r32_uint() ? VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 : resource.format(); VkFormat named = resource_format; - if (volume) { + if (volume && !storage) { const bool compatible = vulkan_format(desc.Format, false).typeless ? desc.Format == DXGI_FORMAT_R8G8B8A8_TYPELESS && (view.format == DXGI_FORMAT_R8G8B8A8_UNORM || view.format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB) @@ -3942,7 +3997,16 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida return false; } } - if (view.format != DXGI_FORMAT_UNKNOWN && !stencil && !depth_plane) { + const bool new_uav = storage && (volume || one_d); + if (new_uav) { + const DXGI_FORMAT dxgi = view.format == DXGI_FORMAT_UNKNOWN ? desc.Format : view.format; + const Format format = texture_storage_format(dxgi, false); + if (format.typeless || format.aspects != VK_IMAGE_ASPECT_COLOR_BIT || !uav_format_compatible(desc.Format, dxgi)) { + log_once("unordered-access view format is not compatible with the resource:", dxgi); + return false; + } + named = format.format; + } else if (view.format != DXGI_FORMAT_UNKNOWN && !stencil && !depth_plane) { if ((view.format == DXGI_FORMAT_A8_UNORM) != (desc.Format == DXGI_FORMAT_A8_UNORM)) { log_once("incompatible typed A8 view format:", int(view.format)); return false; @@ -3964,8 +4028,8 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida } } // A 96-bit texture takes views of its own family only (and a four-channel texture none of it), and only the - // TYPELESS one is cast between FLOAT, UINT and SINT. Its T# names the three-channel format: the swizzle below - // then reads alpha as one, and bind_image views the RGBA32 image accordingly. + // TYPELESS one is cast between FLOAT, UINT and SINT. Its T# names the three-channel format (alpha reads as + // one), but the format list and Vulkan view use the RGBA32 format that backs it. const bool rgb96 = resource.rgb96(); if (!stencil && !depth_plane) { const bool view_rgb96 = view.format != DXGI_FORMAT_UNKNOWN ? vulkan_format(view.format, false).rgb96 : rgb96; @@ -3974,31 +4038,43 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida log_once("view format outside the texture's 96-bit family:", int(view.format)); return false; } - if (rgb96) named = rgb96_named_format(named); } if (named == VK_FORMAT_UNDEFINED || !resource.allows_view_format(named)) { log_once("view format not in the resource's castable list:", int(view.format)); return false; } - const std::uint32_t code = stencil ? g::stencil_format : g::format_from_vulkan(named); - VkFormat view_format = VK_FORMAT_UNDEFINED; + const std::uint32_t code = stencil ? g::stencil_format + : g::format_from_vulkan(rgb96 ? rgb96_named_format(named) : named); + view_format = VK_FORMAT_UNDEFINED; if (stencil) { view_format = resource.format(); - } else if (code && rgb96) { - view_format = named; + } else if (code && (new_uav || rgb96)) { + view_format = rgb96 ? rgb96_view_format(resource.format(), code) : named; } else if (code) { view_format = g::vulkan_view_format(resource_format, code, resource.has_view_format_list()); } - if (view_format == VK_FORMAT_UNDEFINED) { + if (view_format == VK_FORMAT_UNDEFINED || !resource.allows_view_format(view_format)) { log_once("view format not supported for this texture:", int(view.format)); return false; } - const UINT layers = volume ? 1 : desc.DepthOrArraySize; - if (view.first_mip >= desc.MipLevels || view.first_layer >= layers) { + if (view.first_mip >= desc.MipLevels) { + log_once("view starts past the texture's mips; first mip", int(view.first_mip)); + return false; + } + // SRVs address an entire volume; only a UAV descriptor can specify a W range within its mip. + const UINT layers = volume ? (storage ? std::max(1u, UINT(desc.DepthOrArraySize) >> view.first_mip) : 1u) + : desc.DepthOrArraySize; + if (view.first_layer >= layers) { log_once("view starts past the texture's mips or layers; first mip", int(view.first_mip)); return false; } - if (msaa && view.layer_count != UINT_MAX && view.layer_count > UINT(desc.DepthOrArraySize) - view.first_layer) { + const UINT remaining = layers - view.first_layer; + const UINT layer_count = view.layer_count == ~0u ? remaining : view.layer_count; + if (new_uav && (!layer_count || layer_count > remaining)) { + log_once("unordered-access view slice count is outside the selected mip:", int(view.layer_count)); + return false; + } + if (msaa && layer_count > remaining) { log_once("multisample shader view ends past the texture array; layers", int(view.layer_count)); return false; } @@ -4012,8 +4088,13 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida out.samples = desc.SampleDesc.Count; out.first_mip = view.first_mip; out.mip_count = std::min(view.mip_count, desc.MipLevels - view.first_mip); - out.first_layer = view.first_layer; - out.layer_count = std::min(view.layer_count, layers - view.first_layer); + if (volume) { + if (storage && (view.first_layer != 0 || layer_count != layers)) + slices = {view.first_layer, layer_count}; + } else { + out.first_layer = view.first_layer; + out.layer_count = std::min(layer_count, remaining); + } if (view.type == g::ImageType::cube) out.layer_count -= out.layer_count % 6; // whole cubes out.resource_mips = desc.MipLevels; out.min_lod = view.min_lod; @@ -4031,7 +4112,8 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida // order, so then the view's own format places the channels. Depth images keep their own format's channels. const bool other_order = view.format != DXGI_FORMAT_UNKNOWN && !stencil && !depth_plane && !rgb96 && named != view_format && !g::is_depth_stencil_format(view_format); - g::Swizzle channels = g::format_swizzle(other_order ? named : view_format); + const VkFormat channels_format = rgb96 ? rgb96_named_format(view_format) : other_order ? named : view_format; + g::Swizzle channels = g::format_swizzle(channels_format); if (stencil) channels = {g::select_zero, g::select_x, g::select_zero, g::select_one}; else if (desc.Format == DXGI_FORMAT_A8_UNORM) channels = {g::select_zero, g::select_zero, g::select_zero, g::select_x}; else if (alpha_unused(view.format != DXGI_FORMAT_UNKNOWN ? view.format : desc.Format)) channels[3] = g::select_one; @@ -4215,6 +4297,8 @@ class Device final info.get_instance_proc(info.instance, "vkGetDeviceProcAddr")); state_.format_properties = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceFormatProperties")); + state_.format_properties2 = reinterpret_cast( + info.get_instance_proc(info.instance, "vkGetPhysicalDeviceFormatProperties2")); state_.image_format_properties = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceImageFormatProperties")); state_.image_format_properties2 = reinterpret_cast( @@ -5701,7 +5785,7 @@ class Device final if (!destination.ptr) return; std::memset(reinterpret_cast(destination.ptr), 0, kDescriptorSize); const Resource* r = Resource::from(resource); - if (!r) { + if (!r || !r->belongs_to(state_)) { if (resource) stub("ID3D12Device::CreateUnorderedAccessView(resource from another device)"); return; } @@ -5717,33 +5801,48 @@ class Device final } TextureView view{}; view.mip_count = 1; + namespace g = leonida::gfx10; if (!desc) { - const bool array = r->desc().DepthOrArraySize > 1; - if (r->desc().Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D && !array) { - view.type = leonida::gfx10::ImageType::image_1d; - view.layer_count = 1; - } else if (array) - view.type = leonida::gfx10::ImageType::image_2d_array; + const auto& shape = r->desc(); + if (shape.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D) + view.type = g::ImageType::image_3d; + else if (shape.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D) { + view.type = shape.DepthOrArraySize > 1 ? g::ImageType::image_1d_array : g::ImageType::image_1d; + if (view.type == g::ImageType::image_1d) view.layer_count = 1; + } else if (shape.DepthOrArraySize > 1) + view.type = g::ImageType::image_2d_array; } else { view.format = desc->Format; switch (desc->ViewDimension) { case D3D12_UAV_DIMENSION_TEXTURE1D: - view.type = leonida::gfx10::ImageType::image_1d; + view.type = g::ImageType::image_1d; view.first_mip = desc->Texture1D.MipSlice; view.layer_count = 1; break; + case D3D12_UAV_DIMENSION_TEXTURE1DARRAY: + view.type = g::ImageType::image_1d_array; + view.first_mip = desc->Texture1DArray.MipSlice; + view.first_layer = desc->Texture1DArray.FirstArraySlice; + view.layer_count = desc->Texture1DArray.ArraySize; + break; case D3D12_UAV_DIMENSION_TEXTURE2D: view.first_mip = desc->Texture2D.MipSlice; view.layer_count = 1; view.plane = desc->Texture2D.PlaneSlice; break; case D3D12_UAV_DIMENSION_TEXTURE2DARRAY: - view.type = leonida::gfx10::ImageType::image_2d_array; + view.type = g::ImageType::image_2d_array; view.first_mip = desc->Texture2DArray.MipSlice; view.first_layer = desc->Texture2DArray.FirstArraySlice; view.layer_count = desc->Texture2DArray.ArraySize; view.plane = desc->Texture2DArray.PlaneSlice; break; + case D3D12_UAV_DIMENSION_TEXTURE3D: + view.type = g::ImageType::image_3d; + view.first_mip = desc->Texture3D.MipSlice; + view.first_layer = desc->Texture3D.FirstWSlice; + view.layer_count = desc->Texture3D.WSize; + break; default: log_once("unordered-access view dimension not supported:", desc->ViewDimension); return; @@ -6725,7 +6824,7 @@ class Device final } if (optimal & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) { s1 |= D3D12_FORMAT_SUPPORT1_RENDER_TARGET; - // A D3D12 multisample resolve needs the same image usages as texture_create_info(): colour + // A D3D12 multisample resolve needs the same image usages as TextureCreateInfo: colour // attachment plus transfer source/destination (and the ordinary sampled usage). VkImageFormatProperties image_properties{}; const VkImageUsageFlags usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | @@ -7203,13 +7302,65 @@ class Device final // shown leaves the slot a null descriptor. void write_image_descriptor(const Resource& resource, const TextureView& view, D3D12_CPU_DESCRIPTOR_HANDLE destination, bool storage) { - leonida::gfx10::Image image{}; - if (!image_descriptor(resource, view, image)) return; - const leonida::gfx10::ImageWords words = leonida::gfx10::encode(image); - const bool registered = state_.bind_image(words, image, resource.image(), resource.format(), - resource.aspects(), storage, resource.has_view_format_list(), - resource.r9g9b9e5_as_r32_uint()); - if (leonida::gfx10::multisampled(image.type) && !registered) return; + namespace g = leonida::gfx10; + g::Image image{}; + VkFormat view_format{}; + DeviceState::VolumeSlices slices{}; + if (!image_descriptor(resource, view, storage, image, view_format, slices)) return; + const bool sampled = view.type != g::ImageType::image_1d_array && + !(resource.desc().Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE); + const bool new_uav = storage && (view.type == g::ImageType::image_3d || view.type == g::ImageType::image_1d || + view.type == g::ImageType::image_1d_array); + const bool packed_storage = storage && resource.r9g9b9e5_as_r32_uint(); + const VkFormat storage_format = packed_storage ? VK_FORMAT_R32_UINT : view_format; + if (storage) { + if (!state_.storage_usable(storage_format)) { + log_once("texture view format does not support storage images:", storage_format); + return; + } + if (new_uav && state_.info.robust_image_access) { + const bool storage_read = view.type == g::ImageType::image_1d_array; + if (sampled && !state_.sampled_usable(view_format)) { + log_once("texture view format does not support sampled access:", view_format); + return; + } + // Vulkan 1.3 allows formatless access based on the actual view's features, even on caller-owned + // devices. Packed RGB9E5 only exposes formatted raw R32_UINT storage, so it does not need these. + if (!packed_storage) { + const auto features = state_.optimal_features(storage_format); + if (!(features & VK_FORMAT_FEATURE_2_STORAGE_WRITE_WITHOUT_FORMAT_BIT) || + (storage_read && !(features & VK_FORMAT_FEATURE_2_STORAGE_READ_WITHOUT_FORMAT_BIT))) { + log_once("texture view format lacks the required formatless storage image access:", storage_format); + return; + } + } + } + } + if (slices.count && !(state_.info.sliced_3d_uav && state_.info.robust_image_access)) { + log_once("partial Texture3D UAV requires imageSlicedViewOf3D and robustImageAccess; mip", view.first_mip); + return; + } + g::ImageWords words = g::encode(image); + if (storage && view.type == g::ImageType::image_3d) { + words[4] |= g::volume_uav_flag; + const UINT mip_depth = std::max(1u, image.depth >> image.first_mip); + words[7] = g::volume_uav_word(slices.first, slices.count ? slices.count : mip_depth); + } + if (new_uav && packed_storage) { + words[4] |= g::volume_uav_flag; + if (view.type != g::ImageType::image_3d) words[7] = g::volume_uav_word(0, 1); + words[7] |= g::packed_uav_flag; + log_once("packed RGB9E5 UAV: translated storage operations are not implemented; type", int(view.type)); + } + const VkFormat channels_format = resource.rgb96() ? rgb96_named_format(view_format) : view_format; + if (new_uav && !state_.info.robust_image_access) { + log_once("shader access to 1D and 3D UAVs requires robustImageAccess; type", int(view.type)); + } else if (!state_.bind_image(words, image, resource.image(), view_format, channels_format, storage_format, + resource.aspects(), sampled, storage, slices) && g::multisampled(image.type)) { + // Unlike a CPU UAV, an MS SRV is usable only once its class and index are in set 0. + return; + } + // The CPU UAV used by ClearUnorderedAccessView is independent of set 0. std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); } @@ -7467,8 +7618,6 @@ class Device final const VkDevice dev = state_.info.device; const auto properties2 = reinterpret_cast( state_.info.get_instance_proc(state_.info.instance, "vkGetPhysicalDeviceProperties2")); - state_.format_properties2 = reinterpret_cast( - state_.info.get_instance_proc(state_.info.instance, "vkGetPhysicalDeviceFormatProperties2")); const auto to_image = reinterpret_cast(get_device(dev, "vkCopyMemoryToImageEXT")); const auto to_memory = reinterpret_cast(get_device(dev, "vkCopyImageToMemoryEXT")); const auto transition = @@ -8167,10 +8316,18 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) { // Subgroup size control: a pipeline stage asks for the size its shader was translated for (src/subgroup_size.h). leonida::query_subgroup_size_caps(vkGetPhysicalDeviceProperties2, info.physical, v13.subgroup_size_control, v13.compute_full_subgroups, info.subgroup); + void* v13_chain = v13.enable(ext_chain); + // D3D-78 uses the core robustness and format-feature flags. Leave the Vulkan 1.2 extension path unchanged. + if (v13.core) { + VkPhysicalDeviceVulkan13Features supported{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; + VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &supported}; + vkGetPhysicalDeviceFeatures2(info.physical, &query); + info.robust_image_access = supported.robustImageAccess == VK_TRUE; + static_cast(v13_chain)->robustImageAccess = supported.robustImageAccess; + } // Translated vertex shaders read BaseVertex / BaseInstance (SPIR-V DrawParameters) to give v0 / v3 the // hardware's zero-based vertex and instance ids (docs/design.md, Inputs and outputs). - VkPhysicalDeviceVulkan11Features enable11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, - v13.enable(ext_chain)}; + VkPhysicalDeviceVulkan11Features enable11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, v13_chain}; enable11.shaderDrawParameters = chosen_draw_params ? VK_TRUE : VK_FALSE; if (!chosen_draw_params) std::fprintf(stderr, "[rt] d3d12: the GPU has no shaderDrawParameters\n"); VkPhysicalDeviceVulkan12Features enable12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &enable11}; @@ -8336,12 +8493,25 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) { std::fprintf(stderr, "[rt] d3d12: no VK_EXT_host_image_copy; CPU texture copies use a staging submit\n"); } - // The pixel-shader extensions translated shaders can declare (VulkanDeviceInfo::fragment_shader_barycentric and - // the two after it). Each is queried, and enabled with its feature where the GPU has it. const auto has_device_extension = [&](const char* name) { return std::any_of(extensions.begin(), extensions.end(), [&](const auto& e) { return std::strcmp(e.extensionName, name) == 0; }); }; + const char* sliced_name = VK_EXT_IMAGE_SLICED_VIEW_OF_3D_EXTENSION_NAME; + VkPhysicalDeviceImageSlicedViewOf3DFeaturesEXT sliced{ + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_SLICED_VIEW_OF_3D_FEATURES_EXT}; + if (info.robust_image_access && has_device_extension(sliced_name)) { + VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &sliced}; + vkGetPhysicalDeviceFeatures2(info.physical, &query); + info.sliced_3d_uav = sliced.imageSlicedViewOf3D == VK_TRUE; + if (info.sliced_3d_uav) { + sliced.pNext = *v13.next(); + *v13.next() = &sliced; + } + } + + // The pixel-shader extensions translated shaders can declare (VulkanDeviceInfo::fragment_shader_barycentric and + // the two after it). Each is queried, and enabled with its feature where the GPU has it. VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR barycentric{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR}; if (has_device_extension(VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME)) { @@ -8417,10 +8587,10 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) { enable.depthClamp = chosen_features.depthClamp; enable.geometryShader = chosen_features.geometryShader; // translated geometry shaders (195 in the corpus) // What translated shaders declare (the index's `features`): 64-bit integers in most of the corpus (25,803 of - // 26,503 entries), doubles, 16-bit integers, clip and cull distances in a few vertex shaders, image stores - // without a format (StorageImageWriteWithoutFormat), gather offsets (ImageGatherExtended) and LOD-clamped samples - // (MinLod), and the layer or viewport a vertex shader writes (above, in Vulkan 1.2). Enabled where the GPU has - // them; without one, vkCreateShaderModule reports the capability (VUID-...-pCode-08740). + // 26,503 entries), doubles, 16-bit integers, clip and cull distances in a few vertex shaders, formatless image + // reads and writes, gather offsets (ImageGatherExtended), LOD-clamped samples (MinLod), and the layer or viewport + // a vertex shader writes (above, in Vulkan 1.2). Enabled where the GPU has them; without one, vkCreateShaderModule + // reports the capability (VUID-...-pCode-08740). enable.shaderInt64 = chosen_features.shaderInt64; enable.shaderFloat64 = chosen_features.shaderFloat64; enable.shaderInt16 = chosen_features.shaderInt16; @@ -8504,6 +8674,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) { if (info.vertex_attribute_divisor) device_extensions.push_back(divisor_extension); if (info.conditional_rendering) device_extensions.push_back(conditional_extension); if (info.host_image_copy) device_extensions.push_back(host_image_copy_name); + if (info.sliced_3d_uav) device_extensions.push_back(sliced_name); if (info.fragment_shader_barycentric) device_extensions.push_back(VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME); if (info.fragment_shader_interlock) device_extensions.push_back(VK_EXT_FRAGMENT_SHADER_INTERLOCK_EXTENSION_NAME); diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index 7e612e1eb0..cce075dc3b 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h @@ -512,6 +512,7 @@ struct UavView { std::uint32_t mip; // texture std::uint32_t first_layer; std::uint32_t layer_count; + bool exact_clear_format = false; // newly exposed 1D/3D UAVs: do not clear via a different backing format }; // ClearUnorderedAccessViewUint / ...Float; the resource must be in unordered_access state at execution. values are diff --git a/runtime/src/gfx10_descriptors.h b/runtime/src/gfx10_descriptors.h index b225cddef0..ac4b387452 100644 --- a/runtime/src/gfx10_descriptors.h +++ b/runtime/src/gfx10_descriptors.h @@ -146,6 +146,26 @@ inline ImageWords encode(const Image& image) { // TYPE names an image, so these eight dwords are a T# and not a V# followed by something else. inline constexpr bool is_image(const ImageWords& words) { return detail::get(words[3], 28, 4) >= 8; } +// Synthetic volume UAV metadata distinguishes the storage view from SRVs of the same mip, and distinct W +// ranges from one another. Sampled fetches use it because Vulkan only applies slicing to storage views. +// WORD4[31] is reserved on GFX10/GFX103; hardware uses WORD7 for metadata addresses. DEPTH and BASE_ARRAY +// stay unchanged. D3D12 depth is at most 2048, so count - 1 and offset fit 11 bits. +inline constexpr std::uint32_t volume_uav_flag = 0x80000000; +inline constexpr std::uint32_t volume_uav_tag = 0xD7800000; +inline constexpr std::uint32_t volume_uav_tag_mask = 0xff800000; +// RGB9E5 emulation uses R32_UINT storage, not the logical float format in T# word 1. The same tag marks packed +// 1D-family UAVs (without a W range). No ordinary SRV or raw hardware T# has this synthetic metadata. +inline constexpr std::uint32_t packed_uav_flag = 0x00400000; +inline constexpr std::uint32_t volume_uav_word(std::uint32_t offset, std::uint32_t count) { + return volume_uav_tag | ((count - 1) << 11) | offset; +} +inline constexpr bool partial_volume_uav(const ImageWords& words, const Image& image) { + const auto mip_depth = image.depth >> image.first_mip; + return image.type == ImageType::image_3d && (words[4] & volume_uav_flag) && + (words[7] & volume_uav_tag_mask) == volume_uav_tag && + (words[7] & ~packed_uav_flag) != volume_uav_word(0, mip_depth ? mip_depth : 1u); +} + inline constexpr float image_min_lod(const ImageWords& words) { return float(detail::get(words[1], 8, 12)) / 256.0f; } diff --git a/runtime/src/vulkan_bindless.h b/runtime/src/vulkan_bindless.h index d8a4c9846b..f855ead326 100644 --- a/runtime/src/vulkan_bindless.h +++ b/runtime/src/vulkan_bindless.h @@ -8,9 +8,10 @@ // 2 the descriptor hash table 1 7 3D r32ui storage images 256 // 3 sampled 2D-array images 1024 8 + 3 * dimension + class 256 each: // 4 2D r32ui storage images 1024 storage images by component class -// dimension: 0 = 2D, 1 = 2D array, 2 = 3D, 3 = 1D (the translator's STORE_DIMS); class: 0 = float, 1 = uint, 2 = sint. +// dimension: 0 = 2D, 1 = 2D array, 2 = 3D, 3 = 1D (the first four STORE_DIMS); class: 0 = float, 1 = uint, 2 = sint. // bindings 20/21: sampled multisample 2D images / 2D arrays, 256 each (runtime SRVs). // bindings 22/23 and 24/25 are their UINT and SINT equivalents on devices supporting those classes. +// bindings 26-28: storage-only 1D-array images by component class, 256 each (STORE_DIMS index 4). // These are the default counts (BindlessFeatures::counts). size_bindings() sizes the 2D, sampler and storage arrays // from the device's limits instead; the shaders declare runtime arrays, so any count works for them. // @@ -53,8 +54,8 @@ namespace leonida { -// The first four dimensions are the translator's STORE_DIMS indices. A cube is a 2D array of six layers. -enum class ImageDimension : std::uint32_t { dim_2d, dim_2d_array, dim_3d, dim_1d, dim_2d_ms, dim_2d_ms_array }; +// The first five dimensions are the translator's STORE_DIMS indices. A cube is a 2D array of six layers. +enum class ImageDimension : std::uint32_t { dim_2d, dim_2d_array, dim_3d, dim_1d, dim_1d_array, dim_2d_ms, dim_2d_ms_array }; // Storage views of one image by the component type a shader reads or writes it with (the translator picks by the // T# format at run time). r32ui is for the atomic instructions, whose image type is R32ui (2D and 3D only). @@ -67,7 +68,7 @@ struct StorageViews { }; namespace bindless { -inline constexpr std::uint32_t binding_count = 26; +inline constexpr std::uint32_t binding_count = 29; constexpr std::array default_counts(); } // namespace bindless @@ -91,10 +92,12 @@ struct Binding { inline constexpr std::uint32_t table_binding = 2; inline constexpr std::uint32_t sampler_binding = 1; inline constexpr std::uint32_t first_ms_binding = 20; +inline constexpr std::uint32_t ms_binding_count = 6; +inline constexpr std::uint32_t first_1d_array_storage_binding = first_ms_binding + ms_binding_count; inline constexpr std::uint32_t no_binding = 0xffffffffu; -// Indexed by binding number. -inline constexpr std::array bindings = {{ +// Indexed by binding number. Keep the literal extent for tools/spirv_metal_set0.py. +inline constexpr std::array bindings = {{ {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 4096}, {VK_DESCRIPTOR_TYPE_SAMPLER, 1024}, {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1024}, {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1024}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, @@ -108,6 +111,8 @@ inline constexpr std::array bindings = {{ {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, + {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256}, + {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256}, }}; static_assert(bindings.size() == binding_count); @@ -118,8 +123,12 @@ constexpr std::array default_counts() { return counts; } +constexpr bool ms_binding(std::uint32_t binding) { + return binding >= first_ms_binding && binding < first_ms_binding + ms_binding_count; +} + constexpr bool binding_enabled(std::uint32_t binding, const BindlessFeatures& features) { - return binding < first_ms_binding || features.ms_samples[(binding - first_ms_binding) / 2] != VK_SAMPLE_COUNT_1_BIT; + return !ms_binding(binding) || features.ms_samples[(binding - first_ms_binding) / 2] != VK_SAMPLE_COUNT_1_BIT; } // Every binding is visible to every shader stage. Preserve the single-sample layout on devices whose @@ -128,7 +137,8 @@ constexpr void limit_ms_bindings(BindlessFeatures& features, std::uint32_t sampl std::uint32_t resource_limit) { const auto& counts = features.counts; std::uint32_t sampled = 0, total = 0; - for (std::uint32_t b = 0; b < first_ms_binding; ++b) { + for (std::uint32_t b = 0; b < binding_count; ++b) { + if (ms_binding(b)) continue; if (bindings[b].type == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) sampled += counts[b]; if (bindings[b].type != VK_DESCRIPTOR_TYPE_SAMPLER) total += counts[b]; } @@ -150,12 +160,13 @@ constexpr bool multisampled(ImageDimension dimension) { } constexpr std::uint32_t sampled_binding(ImageDimension dimension, std::uint32_t component_class = 0) { - constexpr std::uint32_t by_dimension[] = {0, 3, 6, 5, first_ms_binding, first_ms_binding + 1}; + constexpr std::uint32_t by_dimension[] = {0, 3, 6, 5, no_binding, first_ms_binding, first_ms_binding + 1}; return by_dimension[std::uint32_t(dimension)] + (multisampled(dimension) ? component_class * 2 : 0); } // component_class: 0 = float, 1 = uint, 2 = sint. constexpr std::uint32_t storage_binding(ImageDimension dimension, std::uint32_t component_class) { + if (dimension == ImageDimension::dim_1d_array) return first_1d_array_storage_binding + component_class; return multisampled(dimension) ? no_binding : 8 + 3 * std::uint32_t(dimension) + component_class; } @@ -193,7 +204,7 @@ struct SetLayout { }; // What size_bindings() grows to where the device's limits allow. At 32-64 bytes a descriptor the whole set is then -// 3-6 MiB (93793 descriptors on an RTX 5070). +// 3-6 MiB (94561 descriptors on an RTX 5070 with all MS classes). inline constexpr std::uint32_t max_2d_images = 65536; inline constexpr std::uint32_t max_storage_indices = 4096; // in each storage array, at most its dimension's images // A full D3D12 shader-visible sampler heap (2048) and room for literal and static S#s, within what the device can @@ -211,8 +222,9 @@ inline constexpr std::uint32_t growth_headroom = 64; // 2. The MS pairs that fit beside them (limit_ms_bindings, which may turn classes off). // 3. Growth towards the maximums above, in the same order, within maxPerSetDescriptors. That limit only says // what is sure to work (vkGetDescriptorSetLayoutSupport may allow more), so it never shrinks step 1. -// A storage array holds the smaller of the storage count and its dimension's images: add_image never gives a -// storage view an index past the sampled array. The other bindings keep their default counts. +// A storage array holds the smaller of the storage count and its dimension's sampled count: add_image never +// gives a storage view an index past the sampled array. The storage-only 1D array is capped at its default of 256. +// The other bindings keep their default counts. // layout_supported, when given, answers vkGetDescriptorSetLayoutSupport for set 0 at the counts in its argument: // step 3 then also grows past maxPerSetDescriptors where the device says the layout works (Intel's Xe-LP reports // 6159 and supports the full sizes, D3D-219). It is asked only once the sum is above maxPerSetDescriptors. @@ -245,10 +257,13 @@ inline bool size_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimi const auto apply = [&](bool final) { counts[sampled_binding(ImageDimension::dim_2d)] = images; counts[sampler_binding] = samplers; - for (std::uint32_t d = 0; d < 4; ++d) { + for (std::uint32_t d = 0; d <= std::uint32_t(ImageDimension::dim_1d_array); ++d) { const auto dimension = ImageDimension(d); + const auto sampled_at = sampled_binding(dimension); + const auto capacity = sampled_at == no_binding ? bindings[storage_binding(dimension, 0)].count + : counts[sampled_at]; const bool capped = final || dimension != ImageDimension::dim_2d; - const std::uint32_t held = capped ? std::min(storage, counts[sampled_binding(dimension)]) : storage; + const std::uint32_t held = capped ? std::min(storage, capacity) : storage; for (std::uint32_t c = 0; c < 3; ++c) counts[storage_binding(dimension, c)] = held; if (r32ui_binding(dimension) != no_binding) counts[r32ui_binding(dimension)] = held; } @@ -339,7 +354,8 @@ class BindlessSet { // How many images of a dimension the set holds, the fallback included, and how many of the lowest of those // indices its storage arrays hold (0 for the MS dimensions, which have none). The same for samplers. std::uint32_t image_capacity(ImageDimension dimension) const { - return features_.counts[bindless::sampled_binding(dimension)]; + const auto binding = bindless::sampled_binding(dimension); + return binding == bindless::no_binding ? storage_capacity(dimension) : features_.counts[binding]; } std::uint32_t storage_capacity(ImageDimension dimension) const { return bindless::multisampled(dimension) ? 0 : features_.counts[bindless::storage_binding(dimension, 0)]; @@ -396,6 +412,7 @@ class BindlessSet { std::uint32_t add_image(ImageDimension dimension, VkImageView sampled, VkImageLayout sampled_layout, const StorageViews& storage = {}, std::uint32_t sampled_class = 0) { const bool stores = storage.as_float || storage.as_uint || storage.as_sint || storage.r32ui; + if (!stores && bindless::sampled_binding(dimension) == bindless::no_binding) return 0; if (bindless::multisampled(dimension) && (stores || !supports_ms_class(sampled_class))) return 0; auto& used = image_used_[std::uint32_t(dimension)]; const std::uint32_t low_end = std::min(std::uint32_t(used.size()), storage_capacity(dimension)); @@ -558,7 +575,7 @@ class BindlessSet { VkDescriptorImageInfo info; }; - static constexpr std::uint32_t dimensions = 6, classes = 3; + static constexpr std::uint32_t dimensions = 7, classes = 3; // The first free index in [begin, end), marked used; 0 when there is none. static std::uint32_t allocate(std::vector& used, std::uint32_t begin, std::uint32_t end) { @@ -612,10 +629,11 @@ class BindlessSet { constexpr std::uint32_t ms_type = 3; constexpr VkFormat formats[classes] = {VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R32_UINT, VK_FORMAT_R32_SINT}; // dimension -> (index into types, view type) - constexpr std::uint32_t type_of[dimensions] = {0, 0, 1, 2, ms_type, ms_type}; + constexpr std::uint32_t type_of[dimensions] = {0, 0, 1, 2, 2, ms_type, ms_type}; constexpr VkImageViewType view_types[dimensions] = {VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_VIEW_TYPE_2D_ARRAY, - VK_IMAGE_VIEW_TYPE_3D, VK_IMAGE_VIEW_TYPE_1D, - VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_VIEW_TYPE_2D_ARRAY}; + VK_IMAGE_VIEW_TYPE_3D, VK_IMAGE_VIEW_TYPE_1D, + VK_IMAGE_VIEW_TYPE_1D_ARRAY, + VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_VIEW_TYPE_2D_ARRAY}; for (std::uint32_t t = 0; t < std::size(types); ++t) { for (std::uint32_t c = 0; c < classes; ++c) { if (t == ms_type && !supports_ms_class(c)) continue; @@ -654,8 +672,9 @@ class BindlessSet { VkImageView view = VK_NULL_HANDLE; if (vk_.vkCreateImageView(device_, &info, nullptr, &view) != VK_SUCCESS) return false; fallback_views_.push_back(view); - if (c == 0 || bindless::multisampled(dimension)) - fallback_by_binding_[bindless::sampled_binding(dimension, c)] = view; + const auto sampled_at = bindless::sampled_binding(dimension, c); + if (sampled_at != bindless::no_binding && (c == 0 || bindless::multisampled(dimension))) + fallback_by_binding_[sampled_at] = view; const auto storage_at = bindless::storage_binding(dimension, c); if (storage_at != bindless::no_binding) fallback_by_binding_[storage_at] = view; const auto r32ui_at = bindless::r32ui_binding(dimension); @@ -906,8 +925,9 @@ class BindlessSet { return; } const std::uint32_t sampled_at = bindless::sampled_binding(dimension); - queue(sampled_at, index, - sampled ? VkDescriptorImageInfo{VK_NULL_HANDLE, sampled, sampled_layout} : fallback_info(sampled_at)); + if (sampled_at != bindless::no_binding) + queue(sampled_at, index, + sampled ? VkDescriptorImageInfo{VK_NULL_HANDLE, sampled, sampled_layout} : fallback_info(sampled_at)); const auto store = [&](std::uint32_t binding, VkImageView view) { if (binding == bindless::no_binding || index >= features_.counts[binding]) return; queue(binding, index, diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index d5effb8308..dd16664511 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -2488,16 +2488,22 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun // Emulated R9G9B9E5_SHAREDEXP images (backed by R32_UINT) lack COLOR_ATTACHMENT on E5B9G9R9 and keep the // bit-exact R32_UINT backing path. const VkFormat view_format = view.format ? VkFormat(view.format) : p.binding.format; + const bool packed_rgb9e5 = view_format == VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 && + p.binding.format == VK_FORMAT_R32_UINT; if (!uav_clear::encode(view_format, uav->is_float, uav->values, p.element)) return ReplayResult::unsupported; const auto* image_layout = uav_clear::layout(p.binding.format); if (!image_layout || image_layout->bytes != p.element.size) return ReplayResult::unsupported; - const bool attachment = p.binding.color_attachment && !p.binding.volume; + // The UAV attachment path creates a 2D-array view. 1D/3D UAVs can only use a transfer clear, which + // must not reinterpret bytes through a different numeric format (except packed RGB9E5 in R32_UINT). + const bool attachment = p.binding.color_attachment && !p.binding.volume && !view.exact_clear_format; const bool view_attachable = vk.color_attachment_format ? vk.color_attachment_format(view_format) : view_format != VK_FORMAT_E5B9G9R9_UFLOAT_PACK32; - const bool reinterpret = view_format != p.binding.format && attachment && view_attachable; + const bool reinterpret = view_format != p.binding.format && attachment && view_attachable && !packed_rgb9e5; + if (view.exact_clear_format && view_format != p.binding.format && !packed_rgb9e5) + return ReplayResult::unsupported; const VkFormat clear_format = reinterpret ? view_format : p.binding.format; if (!uav_clear::decode(clear_format, p.element, p.clear_color)) return ReplayResult::unsupported; diff --git a/runtime/test/bindless_sizing_test.cpp b/runtime/test/bindless_sizing_test.cpp index 4553f25b60..31a29b1df2 100644 --- a/runtime/test/bindless_sizing_test.cpp +++ b/runtime/test/bindless_sizing_test.cpp @@ -84,6 +84,13 @@ bool storage_consistent(const BindlessFeatures& f) { f.counts[bindless::r32ui_binding(dimension)] != held) return false; } + // 1D arrays have no sampled capacity, but all three storage classes are always present. + const auto array = ImageDimension::dim_1d_array; + const auto held = storage(f, array); + for (std::uint32_t c = 0; c < 3; ++c) { + const auto binding = bindless::storage_binding(array, c); + if (!held || !bindless::binding_enabled(binding, f) || f.counts[binding] != held) return false; + } return true; } @@ -93,6 +100,33 @@ int main() { using D = ImageDimension; constexpr auto defaults = bindless::default_counts(); static_assert(defaults[0] == 4096 && defaults[bindless::sampler_binding] == 1024 && defaults[8] == 256); + static_assert(bindless::sampled_binding(D::dim_1d_array) == bindless::no_binding); + static_assert(bindless::storage_binding(D::dim_1d_array, 0) == 26 && + bindless::storage_binding(D::dim_1d_array, 1) == 27 && + bindless::storage_binding(D::dim_1d_array, 2) == 28); + static_assert(bindless::sampled_binding(D::dim_2d_ms, 0) == 20 && + bindless::sampled_binding(D::dim_2d_ms_array, 0) == 21 && + bindless::sampled_binding(D::dim_2d_ms, 1) == 22 && + bindless::sampled_binding(D::dim_2d_ms_array, 1) == 23 && + bindless::sampled_binding(D::dim_2d_ms, 2) == 24 && + bindless::sampled_binding(D::dim_2d_ms_array, 2) == 25); + + // SetLayout compacts disabled MS pairs without renumbering either the enabled pair or the storage-only tail. + { + BindlessFeatures f{}; + f.update_after_bind = f.partially_bound = true; + f.ms_samples[1] = VK_SAMPLE_COUNT_4_BIT; + const bindless::SetLayout layout(f); + EXPECT(layout.info.bindingCount == 25 && layout.flags_info.bindingCount == 25); + EXPECT(layout.entries[20].binding == 22 && layout.entries[21].binding == 23); + for (std::uint32_t c = 0; c < 3; ++c) { + const auto& entry = layout.entries[22 + c]; + EXPECT(entry.binding == 26 + c && entry.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE && + entry.descriptorCount == 256); + EXPECT(layout.flags[22 + c] == + (VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT | VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT)); + } + } // An RTX 5070 (driver 621.24): 1048576 of each descriptor type, update-after-bind or not, 4000 samplers. for (const bool update_after_bind : {true, false}) { @@ -104,6 +138,7 @@ int main() { EXPECT(f.counts[bindless::sampler_binding] > 2048); // a full sampler heap and the fallback EXPECT(storage(f, D::dim_2d) == bindless::max_storage_indices); EXPECT(storage(f, D::dim_2d_array) == 1024 && storage(f, D::dim_3d) == 256 && storage(f, D::dim_1d) == 256); + EXPECT(storage(f, D::dim_1d_array) == 256 && totals(f).all == 94561); EXPECT(count(f, D::dim_2d_array) == 1024 && count(f, D::dim_3d) == 256 && count(f, D::dim_1d) == 256); EXPECT(f.ms_samples[0] == VK_SAMPLE_COUNT_4_BIT && f.ms_samples[2] == VK_SAMPLE_COUNT_4_BIT); EXPECT(storage_consistent(f)); @@ -112,12 +147,12 @@ int main() { count(f, D::dim_2d), f.counts[bindless::sampler_binding], storage(f, D::dim_2d), totals(f).all); } - // At today's sizes exactly (5632 sampled images, 1024 samplers, 3584 storage images): today's set, no MS pairs. + // At today's sizes exactly (5632 sampled images, 1024 samplers, 4352 storage images): no MS pairs. { Device d = uniform(1048576, 1048576); d.v12.maxPerStageDescriptorUpdateAfterBindSampledImages = 5632; d.v12.maxPerStageDescriptorUpdateAfterBindSamplers = 1024; - d.v12.maxPerStageDescriptorUpdateAfterBindStorageImages = 3584; + d.v12.maxPerStageDescriptorUpdateAfterBindStorageImages = 4352; BindlessFeatures f = with_ms(true); EXPECT(bindless::size_bindings(f, d.limits, d.v11, d.v12)); EXPECT(count(f, D::dim_2d) == 4096 && f.counts[bindless::sampler_binding] == 1024 && @@ -125,6 +160,7 @@ int main() { for (std::uint32_t b = 0; b < bindless::first_ms_binding; ++b) if (bindless::bindings[b].type != VK_DESCRIPTOR_TYPE_STORAGE_IMAGE) EXPECT(f.counts[b] == defaults[b]); EXPECT(f.ms_samples == (std::array{VK_SAMPLE_COUNT_1_BIT, VK_SAMPLE_COUNT_1_BIT, VK_SAMPLE_COUNT_1_BIT})); + EXPECT(totals(f).storage == 4352 && storage(f, D::dim_1d_array) == 256); EXPECT(storage_consistent(f)); } @@ -178,15 +214,19 @@ int main() { Device d = uniform(1048576, 1048576); d.v11.maxPerSetDescriptors = 6159; d.limits.maxSamplerAllocationCount = 4000; - unsigned asked = 0, asked_within = 0; + unsigned asked = 0, asked_within = 0, missing_storage = 0; const auto all_supported = [&](const BindlessFeatures& candidate) { ++asked; asked_within += totals(candidate).all <= 6159; + const bindless::SetLayout layout(candidate); + const auto& last = layout.entries[layout.info.bindingCount - 1]; + missing_storage += last.binding != 28 || last.descriptorType != VK_DESCRIPTOR_TYPE_STORAGE_IMAGE || + last.descriptorCount != storage(candidate, D::dim_1d_array); return true; }; BindlessFeatures f = with_ms(true); EXPECT(bindless::size_bindings(f, d.limits, d.v11, d.v12, all_supported)); - EXPECT(asked > 0 && asked_within == 0); + EXPECT(asked > 0 && asked_within == 0 && missing_storage == 0); EXPECT(count(f, D::dim_2d) == bindless::max_2d_images && f.counts[bindless::sampler_binding] == 4000 - bindless::reserved_samplers); EXPECT(storage(f, D::dim_2d) == bindless::max_storage_indices && storage_consistent(f)); diff --git a/runtime/test/d3d12_r9g9b9e5_uav_test.cpp b/runtime/test/d3d12_r9g9b9e5_uav_test.cpp index 71caaf6ac7..498d6cd261 100644 --- a/runtime/test/d3d12_r9g9b9e5_uav_test.cpp +++ b/runtime/test/d3d12_r9g9b9e5_uav_test.cpp @@ -204,14 +204,14 @@ struct ShaderParams { std::uint32_t mode; std::uint32_t width; std::uint32_t height; - std::uint32_t pad; + std::uint32_t slice; }; bool run_bindless_roundtrip(vktest::Device& d, VkDescriptorSet set0, VkDescriptorSetLayout set0_layout, const g::ImageWords& uav_words, const g::ImageWords& srv_words, const g::SamplerWords& sampler_words, bool do_uint_write, const std::array& input_words, - std::array& out_rgba) { + std::array& out_rgba, int z = -1, bool sliced = false) { std::vector code; if (!read_spirv(LEONIDA_TEST_CS_R9G9B9E5_UAV_SPV, code)) return false; @@ -319,7 +319,8 @@ bool run_bindless_roundtrip(vktest::Device& d, VkDescriptorSet set0, VkDescripto ShaderParams wp{}; std::memcpy(wp.tsharp, uav_words.data(), sizeof(wp.tsharp)); std::memcpy(wp.ssharp, sampler_words.data(), sizeof(wp.ssharp)); - wp.mode = 0; + wp.mode = z < 0 ? 0u : 2u; + wp.slice = sliced ? 1u : 0u; wp.width = 4; wp.height = 4; push(cb, pipe_layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(wp), &wp); @@ -335,7 +336,8 @@ bool run_bindless_roundtrip(vktest::Device& d, VkDescriptorSet set0, VkDescripto ShaderParams sp{}; std::memcpy(sp.tsharp, srv_words.data(), sizeof(sp.tsharp)); std::memcpy(sp.ssharp, sampler_words.data(), sizeof(sp.ssharp)); - sp.mode = 1; + sp.mode = z < 0 ? 1u : 3u; + sp.slice = z < 0 ? 0u : UINT(z); sp.width = 4; sp.height = 4; push(cb, pipe_layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(sp), &sp); @@ -357,7 +359,7 @@ bool run_bindless_roundtrip(vktest::Device& d, VkDescriptorSet set0, VkDescripto int main() { vktest::Device d; - const auto status = d.initialize(); + const auto status = d.initialize(true, true); // exercise sliced RGB9E5 volumes when the driver supports them if (status == vktest::DeviceStatus::unavailable) return 77; if (status != vktest::DeviceStatus::ready) return 1; @@ -380,6 +382,8 @@ int main() { info.bindless_partially_bound = d.partially_bound; info.image_view_min_lod = d.image_view_min_lod; info.host_image_copy = d.host_image_copy; + info.robust_image_access = d.robust_image_access; + info.sliced_3d_uav = d.sliced_3d_uav; Ref device; EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p)))); @@ -440,7 +444,7 @@ int main() { D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&tex_1d.p)))); - const auto desc_3d = tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE3D, 8, 8, 4, 2, + const auto desc_3d = tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE3D, 8, 8, 8, 2, DXGI_FORMAT_R9G9B9E5_SHAREDEXP, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); Ref tex_3d; EXPECT(SUCCEEDED(device->CreateCommittedResource(&def_heap, D3D12_HEAP_FLAG_NONE, &desc_3d, @@ -767,27 +771,77 @@ int main() { std::array sampled{}; EXPECT(run_bindless_roundtrip(d, set0, set0_layout, rt_uav_words, rt_srv_words, smp_words, !native_storage, input_words, sampled)); - for (UINT i = 0; i < 16; ++i) { - const std::uint32_t want_word = native_storage ? 0x94010040u : input_words[i]; - leonida::uav_clear::Element elem{}; - elem.size = 4; - std::memcpy(elem.bytes.data(), &want_word, 4); - VkClearColorValue want{}; - EXPECT(leonida::uav_clear::decode(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, elem, want)); - for (UINT c = 0; c < 4; ++c) { - const float got = sampled[i * 4 + c]; - const float exp_v = want.float32[c]; - const float tol = std::max(1e-6f, std::fabs(exp_v) * 1e-5f); - if (std::fabs(got - exp_v) > tol) { - std::fprintf(stderr, "bindless sample texel %u ch %u: got %g, want %g (word 0x%08x)\n", - i, c, got, exp_v, want_word); - return 1; + const auto check_samples = [&](bool seed_only) { + for (UINT i = 0; i < 16; ++i) { + const std::uint32_t want_word = seed_only ? 0x94010040u : input_words[i]; + leonida::uav_clear::Element elem{}; + elem.size = 4; + std::memcpy(elem.bytes.data(), &want_word, 4); + VkClearColorValue want{}; + if (!leonida::uav_clear::decode(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, elem, want)) return false; + for (UINT c = 0; c < 4; ++c) { + const float got = sampled[i * 4 + c]; + const float exp_v = want.float32[c]; + const float tol = std::max(1e-6f, std::fabs(exp_v) * 1e-5f); + if (!(std::fabs(got - exp_v) <= tol)) { + std::fprintf(stderr, "bindless sample texel %u ch %u: got %g, want %g (word 0x%08x)\n", + i, c, got, exp_v, want_word); + return false; + } } } - } + return true; + }; + EXPECT(check_samples(native_storage)); std::printf("Bindless set-0 GPU round-trip: 16/16 HDR RGB9E5 texels matched (%s)\n", native_storage ? "clear -> sampled E5B9G9R9" : "storage R32_UINT [bindings 9 & 4] -> sampled E5B9G9R9 [binding 0]"); + + if (!native_storage && d.robust_image_access) { + // Mip 1 of tex_3d is 4x4x4. Seed it through the logical RGB9E5 clear, then write packed data + // through R32_UINT. A sliced view selects only absolute Z=1; relative Z=1 must not write Z=2. + D3D12_UNORDERED_ACCESS_VIEW_DESC volume_uav{}; + volume_uav.Format = DXGI_FORMAT_R9G9B9E5_SHAREDEXP; + volume_uav.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; + volume_uav.Texture3D = {1, 0, ~0u}; + device->CreateUnorderedAccessView(tex_3d.p, nullptr, &volume_uav, slot(10)); + const auto whole = words_at(10); + EXPECT(g::decode(whole, decoded) && decoded.first_mip == 1 && decoded.format == 132 && + (whole[7] & g::packed_uav_flag) && !g::partial_volume_uav(whole, decoded)); + volume_uav.Texture3D.FirstWSlice = 1; + volume_uav.Texture3D.WSize = 1; + device->CreateUnorderedAccessView(tex_3d.p, nullptr, &volume_uav, slot(11)); + const auto partial = words_at(11); + if (d.sliced_3d_uav) { + EXPECT(g::decode(partial, decoded) && g::partial_volume_uav(partial, decoded)); + } else { + EXPECT(all_zero(partial.data(), sizeof(partial))); + } + D3D12_SHADER_RESOURCE_VIEW_DESC volume_srv{}; + volume_srv.Format = volume_uav.Format; + volume_srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; + volume_srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + volume_srv.Texture3D = {1, 1, 0}; + device->CreateShaderResourceView(tex_3d.p, &volume_srv, slot(12)); + const auto volume_sampled = words_at(12); + EXPECT(g::decode(volume_sampled, decoded) && decoded.format == 132 && volume_sampled[7] == 0); + + EXPECT(SUCCEEDED(alloc->Reset()) && SUCCEEDED(list->Reset(alloc.p, nullptr))); + list->ClearUnorderedAccessViewFloat({0}, slot(10), tex_3d.p, seed, 0, nullptr); + EXPECT(list->Close() == S_OK); + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(queue->Signal(fence.p, 2)) && SUCCEEDED(fence->SetEventOnCompletion(2, nullptr))); + const auto& write_key = d.sliced_3d_uav ? partial : whole; + EXPECT(run_bindless_roundtrip(d, set0, set0_layout, write_key, volume_sampled, smp_words, + true, input_words, sampled, d.sliced_3d_uav ? 1 : 0, d.sliced_3d_uav)); + EXPECT(check_samples(false)); + EXPECT(run_bindless_roundtrip(d, set0, set0_layout, write_key, volume_sampled, smp_words, + false, input_words, sampled, 2)); + EXPECT(check_samples(true)); + std::printf("RGB9E5 volume: 16/16 raw-store samples and 16/16 untouched neighbor texels (%s)\n", + d.sliced_3d_uav ? "sliced" : "whole-mip; partial view refused"); + } } #endif } diff --git a/runtime/test/d3d12_texture1d_test.cpp b/runtime/test/d3d12_texture1d_test.cpp index 007c513b4f..b32847a90c 100644 --- a/runtime/test/d3d12_texture1d_test.cpp +++ b/runtime/test/d3d12_texture1d_test.cpp @@ -116,7 +116,7 @@ int main() { uav1d.Texture1D.MipSlice = 1; dev->CreateUnorderedAccessView(tex1d, nullptr, &uav1d, {cbv_cpu.ptr + cbv_inc * 5}); - // Default (nullptr) SRV and UAV on a 1D array must write a null descriptor (set 0 has no 1D-array binding). + // Set 0 has storage-only 1D-array bindings: a default SRV is null, but a default UAV covers the whole array. std::memset(reinterpret_cast(cbv_cpu.ptr + cbv_inc * 6), 0x77, cbv_inc * 2); dev->CreateShaderResourceView(tex1d, nullptr, {cbv_cpu.ptr + cbv_inc * 6}); dev->CreateUnorderedAccessView(tex1d, nullptr, nullptr, {cbv_cpu.ptr + cbv_inc * 7}); @@ -147,11 +147,12 @@ int main() { if (!decode_and_lookup(5, img) || img.type != g::ImageType::image_1d || img.first_mip != 1 || img.mip_count != 1 || img.layer_count != 1) return fail("explicit 1D UAV on array T# or bindless lookup mismatch"); - for (UINT slot = 6; slot < 8; ++slot) { - const auto* bytes = reinterpret_cast(cbv_cpu.ptr + cbv_inc * slot); - for (UINT b = 0; b < 32; ++b) - if (bytes[b] != 0) return fail("default 1DArray view should write a null descriptor"); - } + const auto* srv_bytes = reinterpret_cast(cbv_cpu.ptr + cbv_inc * 6); + for (UINT b = 0; b < 32; ++b) + if (srv_bytes[b] != 0) return fail("default 1DArray SRV should write a null descriptor"); + if (!decode_and_lookup(7, img) || img.type != g::ImageType::image_1d_array || img.first_mip != 0 || + img.mip_count != 1 || img.first_layer != 0 || img.layer_count != tex1d_desc.DepthOrArraySize) + return fail("default 1DArray UAV T# or bindless lookup mismatch"); // RTV / DSV 1D bounds validation (out-of-bounds mip/slice must write a null TargetView) D3D12_RENDER_TARGET_VIEW_DESC bad_rtv{}; @@ -267,6 +268,6 @@ int main() { cbv_heap->Release(); dev->Release(); - std::printf("PASS: d3d12_texture1d_test (1D/1DArray SRV, UAV + CopyTextureRegion round-trip)\n"); + std::printf("PASS: d3d12_texture1d_test (1D views, 1DArray UAV + CopyTextureRegion round-trip)\n"); return 0; } diff --git a/runtime/test/glsl/cs_r9g9b9e5_uav.comp b/runtime/test/glsl/cs_r9g9b9e5_uav.comp index c9879064ac..41c986a412 100644 --- a/runtime/test/glsl/cs_r9g9b9e5_uav.comp +++ b/runtime/test/glsl/cs_r9g9b9e5_uav.comp @@ -10,10 +10,10 @@ layout(local_size_x = 16) in; layout(push_constant) uniform Params { uint tsharp[8]; uint ssharp[4]; - uint mode; // 0: write via binding 9 (first half) + binding 4 (second half); 1: sample via binding 0 + uint mode; // 0/1: 2D store/sample; 2/3: 3D store/sample uint width; uint height; - uint pad; + uint slice; // sample's absolute Z, or whether to probe relative Z=1 past a one-slice UAV } pc; layout(set = 0, binding = 0) uniform texture2D sampled_images[]; @@ -23,6 +23,9 @@ layout(set = 0, binding = 2, std430) readonly buffer DescriptorMap { }; layout(set = 0, binding = 4, r32ui) uniform writeonly uimage2D storage_r32ui_images[]; layout(set = 0, binding = 9, r32ui) uniform writeonly uimage2D storage_uint_images[]; +layout(set = 0, binding = 6) uniform texture3D sampled_volumes[]; +layout(set = 0, binding = 7, r32ui) uniform writeonly uimage3D storage_r32ui_volumes[]; +layout(set = 0, binding = 15, r32ui) uniform writeonly uimage3D storage_uint_volumes[]; layout(set = 1, binding = 0, std430) readonly buffer InputWords { uint packed_words[]; @@ -59,11 +62,23 @@ void main() { } else { imageStore(storage_r32ui_images[image], xy, uvec4(packed_words[i], 0u, 0u, 0u)); } + } else if (pc.mode == 2u) { + const uvec4 word = uvec4(packed_words[i], 0u, 0u, 0u); + if (i < total / 2u) { + imageStore(storage_uint_volumes[image], ivec3(xy, 0), word); + if (pc.slice != 0u) imageStore(storage_uint_volumes[image], ivec3(xy, 1), word); + } else { + imageStore(storage_r32ui_volumes[image], ivec3(xy, 0), word); + if (pc.slice != 0u) imageStore(storage_r32ui_volumes[image], ivec3(xy, 1), word); + } } else { uint sampler_key[8]; for (int k = 0; k < 8; ++k) sampler_key[k] = k < 4 ? pc.ssharp[k] : 0xffffffffu; const uint smp = lookup(sampler_key); const vec2 uv = (vec2(xy) + 0.5) / vec2(float(pc.width), float(pc.height)); - out_values[i] = textureLod(sampler2D(sampled_images[image], samplers[smp]), uv, 0.0); + if (pc.mode == 1u) + out_values[i] = textureLod(sampler2D(sampled_images[image], samplers[smp]), uv, 0.0); + else + out_values[i] = texelFetch(sampler3D(sampled_volumes[image], samplers[smp]), ivec3(xy, int(pc.slice)), 0); } } diff --git a/runtime/test/shaders/cs_imgatomic3d.asm b/runtime/test/shaders/cs_imgatomic3d.asm index 29f4477a4a..cd6b6a1130 100644 --- a/runtime/test/shaders/cs_imgatomic3d.asm +++ b/runtime/test/shaders/cs_imgatomic3d.asm @@ -18,10 +18,10 @@ s_mov_b32 s16, 0x5000 s_mov_b32 s17, 0x1400000 s_mov_b32 s18, 0x55 s_mov_b32 s19, 0x55 -s_mov_b32 s20, 0x55 +s_mov_b32 s20, 0x80000055 s_mov_b32 s21, 0x55 s_mov_b32 s22, 0x55 -s_mov_b32 s23, 0x55 +s_mov_b32 s23, 0xd7801800 s_mov_b32 s24, 0x3000 s_mov_b32 s25, 0x1500000 s_mov_b32 s26, 0x33 diff --git a/runtime/test/shaders/ps_imgatomic.asm b/runtime/test/shaders/ps_imgatomic.asm index b8f888c131..253cd2c9e7 100644 --- a/runtime/test/shaders/ps_imgatomic.asm +++ b/runtime/test/shaders/ps_imgatomic.asm @@ -1,8 +1,8 @@ ; Image atomics in a pixel shader, the forms the game uses (1,018 of its 1,038 image-atomic shaders are pixel shaders: ; image_atomic_or / umin / umax on a 2D image and umax on a 3D one), through the descriptor table and the set-0 ; r32ui storage arrays (binding 4 for 2D, 7 for 3D). User data s2:s3 is the console VA of a table of four T#s: -; +0x00 the 2D umax image, +0x20 the 2D umin image, +0x40 the 2D or image, +0x60 the 3D umax image (any 8 dwords: -; only the key matters). Each of the 64x64 pixels computes px, py from attr0 (vs_ids runs it 0..1 over the target), +; +0x00 the 2D umax image, +0x20 the 2D umin image, +0x40 the 2D or image, +0x60 the tagged R32_UINT 3D UAV. +; Each of the 64x64 pixels computes px, py from attr0 (vs_ids runs it 0..1 over the target), ; its id = px + 64 * py, and its texel tx = px >> 3, ty = py >> 3, so 64 pixels contend for each texel of the 8x8 ; images: ; umax2d[ty][tx] = max(id), umin2d[ty][tx] = min(id), or2d[ty][tx] |= 1 << (id & 31), diff --git a/runtime/test/vk_bindless_test.cpp b/runtime/test/vk_bindless_test.cpp index caa77be763..c9c0faf0a5 100644 --- a/runtime/test/vk_bindless_test.cpp +++ b/runtime/test/vk_bindless_test.cpp @@ -32,6 +32,7 @@ #include #include #include +#include #include #include #include @@ -285,6 +286,7 @@ int main(int argc, char** argv) { LD(vkDestroyCommandPool); LD(vkDestroyShaderModule); LD(vkDestroyFramebuffer); LD(vkDestroyRenderPass); LD(vkDestroySampler); LD(vkDestroyImageView); LD(vkDestroyImage); LD(vkDestroyBuffer); LD(vkFreeMemory); LD(vkDestroyDevice); LD(vkCmdClearColorImage); + LD(vkGetDescriptorSetLayoutSupport); VkQueue queue = VK_NULL_HANDLE; vkGetDeviceQueue(dev, qi, 0, &queue); VkPhysicalDeviceMemoryProperties mp; @@ -510,47 +512,60 @@ int main(int argc, char** argv) { } CHECK(submit()); - // An adapter at the original 5632 sampled-image limit must keep the original set. The per-stage - // resource budget can also leave room for just one class (9985 original resources + 512). + constexpr auto descriptors = [](VkDescriptorType type, const BindlessFeatures& f) { + std::uint32_t count = 0; + for (std::uint32_t b = 0; b < bindless::bindings.size(); ++b) + if (bindless::bindings[b].type == type && bindless::binding_enabled(b, f)) + count += f.counts[b]; + return count; + }; + + // An adapter at the single-sample limit must keep the original set. The stage resource budget + // can also leave room for just one MS class. Include the non-MS bindings after the MS pairs. + constexpr BindlessFeatures defaults{}; + constexpr auto base_sampled = descriptors(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, defaults); + constexpr auto base_resources = base_sampled + descriptors(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, defaults) + + descriptors(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, defaults); + constexpr auto ms_pair = + defaults.counts[bindless::first_ms_binding] + defaults.counts[bindless::first_ms_binding + 1]; constexpr auto ms_classes = [](std::uint32_t sampled, std::uint32_t total) { BindlessFeatures f{}; f.ms_samples.fill(VK_SAMPLE_COUNT_4_BIT); bindless::limit_ms_bindings(f, sampled, total); return f.ms_samples; }; - static_assert(ms_classes(5632, 20000) == + static_assert(ms_classes(base_sampled, base_resources + ms_pair) == std::array{VK_SAMPLE_COUNT_1_BIT, VK_SAMPLE_COUNT_1_BIT, VK_SAMPLE_COUNT_1_BIT}); - static_assert(ms_classes(7168, 10497) == + static_assert(ms_classes(base_sampled + 3 * ms_pair, base_resources + ms_pair) == std::array{VK_SAMPLE_COUNT_4_BIT, VK_SAMPLE_COUNT_1_BIT, VK_SAMPLE_COUNT_1_BIT}); - // Does a set with these flags fit the device? Every binding is visible to every stage. - const auto descriptors = [](VkDescriptorType type, const BindlessFeatures& f) { - std::uint32_t count = 0; - for (std::uint32_t b = 0; b < bindless::bindings.size(); ++b) - if (bindless::bindings[b].type == type && bindless::binding_enabled(b, f)) - count += f.counts[b]; - return count; - }; + // Check the sized layout against the device's limits. Standalone samplers count in the pool, + // but not towards the per-stage resource budget. const auto fits = [&](const BindlessFeatures& f) { const auto sampled_total = descriptors(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, f); const auto sampler_total = descriptors(VK_DESCRIPTOR_TYPE_SAMPLER, f); const auto storage_total = descriptors(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, f); - const auto stage_resources = sampled_total + storage_total + 2; // table buffer and fragment output + const auto buffer_total = descriptors(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, f); + const auto stage_resources = sampled_total + storage_total + buffer_total + 1; // fragment output + const auto pool_descriptors = sampled_total + sampler_total + storage_total + buffer_total; const VkPhysicalDeviceLimits& l = props.properties.limits; if (f.update_after_bind) return props12.maxPerStageDescriptorUpdateAfterBindSampledImages >= sampled_total && props12.maxPerStageDescriptorUpdateAfterBindSamplers >= sampler_total && props12.maxPerStageDescriptorUpdateAfterBindStorageImages >= storage_total && + props12.maxPerStageDescriptorUpdateAfterBindStorageBuffers >= buffer_total && props12.maxPerStageUpdateAfterBindResources >= stage_resources && - props12.maxUpdateAfterBindDescriptorsInAllPools >= sampled_total + sampler_total + storage_total + 1 && + props12.maxUpdateAfterBindDescriptorsInAllPools >= pool_descriptors && props12.maxDescriptorSetUpdateAfterBindSampledImages >= sampled_total && props12.maxDescriptorSetUpdateAfterBindSamplers >= sampler_total && - props12.maxDescriptorSetUpdateAfterBindStorageImages >= storage_total; + props12.maxDescriptorSetUpdateAfterBindStorageImages >= storage_total && + props12.maxDescriptorSetUpdateAfterBindStorageBuffers >= buffer_total; return l.maxPerStageDescriptorSampledImages >= sampled_total && l.maxPerStageDescriptorSamplers >= sampler_total && l.maxPerStageDescriptorStorageImages >= storage_total && + l.maxPerStageDescriptorStorageBuffers >= buffer_total && l.maxPerStageResources >= stage_resources && l.maxDescriptorSetSampledImages >= sampled_total && l.maxDescriptorSetSamplers >= sampler_total && - l.maxDescriptorSetStorageImages >= storage_total; + l.maxDescriptorSetStorageImages >= storage_total && l.maxDescriptorSetStorageBuffers >= buffer_total; }; unsigned mismatches = 0, runs = 0, readbacks = 0; @@ -576,11 +591,19 @@ int main(int argc, char** argv) { BindlessFeatures configurations[2] = {device_flags, {}}; const int configuration_count = (device_flags.update_after_bind || device_flags.partially_bound) ? 2 : 1; + std::function layout_supported; + if (vkGetDescriptorSetLayoutSupport) + layout_supported = [&](const BindlessFeatures& candidate) { + const bindless::SetLayout layout(candidate); + VkDescriptorSetLayoutSupport support{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_SUPPORT}; + vkGetDescriptorSetLayoutSupport(dev, &layout.info, &support); + return support.supported == VK_TRUE; + }; for (int configuration = 0; configuration < configuration_count; ++configuration) { BindlessFeatures flags = configurations[configuration]; flags.ms_samples[0] = VK_SAMPLE_COUNT_4_BIT; // A device below the default counts gets a smaller set; this test needs at least those. - const bool full = bindless::size_bindings(flags, props.properties.limits, props11, props12); + const bool full = bindless::size_bindings(flags, props.properties.limits, props11, props12, layout_supported); const char* name = flags.update_after_bind && flags.partially_bound ? "update after bind, partially bound" : flags.update_after_bind ? "update after bind" : flags.partially_bound ? "partially bound" : "no flags"; if (!full || !fits(flags)) { @@ -589,6 +612,8 @@ int main(int argc, char** argv) { } BindlessSet set(vkGetDeviceProcAddr, dev, mp, flags); EXPECT(set.ok() && set.layout() && set.set()); + EXPECT(set.image_capacity(ImageDimension::dim_1d_array) == set.storage_capacity(ImageDimension::dim_1d_array)); + EXPECT(set.add_image(ImageDimension::dim_1d_array, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL) == 0); const VkPushConstantRange push{VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, push_bytes}; const VkDescriptorSetLayout set_layout = set.layout(); @@ -718,7 +743,8 @@ int main(int argc, char** argv) { const std::array keys{{{0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8}, {0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8}, {0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8}, - {0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8}}}; + {0xd1, 20u << 20, 0xd3, 0xd4, 0x800000d5, 0xd6, 0xd7, + 0xd7801800}}}; for (std::uint32_t k = 0; k < 4; ++k) std::memcpy(static_cast(heap_map) + atomic_va + 32 * k, keys[k].data(), 32); const VkImageUsageFlags atomic_usage = diff --git a/runtime/test/vk_pipeline_check.cpp b/runtime/test/vk_pipeline_check.cpp index a3e886d51e..80f6432734 100644 --- a/runtime/test/vk_pipeline_check.cpp +++ b/runtime/test/vk_pipeline_check.cpp @@ -1,8 +1,8 @@ // Driver-level check of the translated corpus: vk_pipeline_check [pipeline_cache.bin] // Reads /index.json (written by tools/rdna2spirv.py), creates a VkShaderModule for every entry and a real // pipeline with the translator's resource contract (set 0: sampled images 0, 3, 5, 6; samplers 1; descriptor hash -// table 2; storage images 4, 7 and 8..19; set 1 binding 0 dynamic UBO for --pc-tail-ubo shaders; push constants -// sized from push_constant_bytes, default 144 or 128 with pc_tail): +// table 2; storage images 4, 7, 8..19 and 26..28; set 1 binding 0 dynamic UBO for --pc-tail-ubo shaders; +// push constants sized from push_constant_bytes, default 144 or 128 with pc_tail): // - cs: compute pipeline via vkCreateComputePipelines, using the runtime layout and subgroup request for // descriptor-free shaders with the standard push-constant range // - ps/vs/ms/gs: graphics pipeline via vkCreateGraphicsPipelines (Vulkan 1.3 dynamic rendering, no render pass) @@ -52,6 +52,7 @@ #include "large_module_gate.h" #include "../src/spirv_words.h" #include "../src/subgroup_size.h" +#include "../src/vulkan_bindless.h" #include #include @@ -68,6 +69,7 @@ #include #include #include +#include #include #include #include @@ -927,10 +929,13 @@ int main(int argc, char** argv) { } VkPhysicalDeviceProperties props; vkGetPhysicalDeviceProperties(pd, &props); VkPhysicalDeviceSubgroupSizeControlProperties sgProps{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_PROPERTIES}; - VkPhysicalDeviceFloatControlsProperties fcProps{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FLOAT_CONTROLS_PROPERTIES}; + VkPhysicalDeviceVulkan11Properties indexing_limits{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_PROPERTIES}; + // Vulkan12Properties already includes the float controls (do not chain both promoted structs). + VkPhysicalDeviceVulkan12Properties indexed{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_PROPERTIES}; VkPhysicalDeviceProperties2 props2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2}; + indexing_limits.pNext = &indexed; + sgProps.pNext = &indexing_limits; props2.pNext = &sgProps; - sgProps.pNext = &fcProps; vkGetPhysicalDeviceProperties2(pd, &props2); std::fprintf(stderr, "device: %s (subgroup %u..%u)\n", props.deviceName, sgProps.minSubgroupSize, sgProps.maxSubgroupSize); @@ -1062,6 +1067,7 @@ int main(int argc, char** argv) { } #define LOADD(name) auto name = reinterpret_cast(vkGetDeviceProcAddr(dev, #name)) LOADD(vkCreateShaderModule); LOADD(vkDestroyShaderModule); LOADD(vkCreateDescriptorSetLayout); + LOADD(vkGetDescriptorSetLayoutSupport); LOADD(vkCreatePipelineLayout); LOADD(vkCreateComputePipelines); LOADD(vkCreateGraphicsPipelines); LOADD(vkDestroyPipeline); LOADD(vkCreatePipelineCache); LOADD(vkGetPipelineCacheData); LOADD(vkGetPipelineExecutablePropertiesKHR); LOADD(vkGetPipelineExecutableStatisticsKHR); @@ -1089,13 +1095,14 @@ int main(int argc, char** argv) { // property, not a feature. for (const auto& fc : meta.float_controls) { if (fc == "shaderSignedZeroInfNanPreserveFloat32") { - if (!fcProps.shaderSignedZeroInfNanPreserveFloat32) return "no " + fc; + if (!indexed.shaderSignedZeroInfNanPreserveFloat32) return "no " + fc; } else if (fc == "shaderDenormPreserveFloat16") { - if (!fcProps.shaderDenormPreserveFloat16) return "no " + fc; + if (!indexed.shaderDenormPreserveFloat16) return "no " + fc; } else { return "unknown float control " + fc; } } + // Per-format read/write support for formatless storage is checked when the runtime binds the actual view. for (const auto& feat : meta.features) { if (feat == "meshShader" && !(ext_mesh && mesh.meshShader)) return "no VK_EXT_mesh_shader"; if (feat == "geometryShader" && !f2.features.geometryShader) return "no geometryShader"; @@ -1117,28 +1124,38 @@ int main(int argc, char** argv) { if (feat == "runtimeDescriptorArray" && !f12.runtimeDescriptorArray) return "no runtimeDescriptorArray"; if (feat == "shaderImageGatherExtended" && !f2.features.shaderImageGatherExtended) return "no shaderImageGatherExtended"; if (feat == "shaderResourceMinLod" && !f2.features.shaderResourceMinLod) return "no shaderResourceMinLod"; - if (feat == "shaderStorageImageWriteWithoutFormat" && !f2.features.shaderStorageImageWriteWithoutFormat) - return "no shaderStorageImageWriteWithoutFormat"; - if (feat == "shaderStorageImageReadWithoutFormat" && !f2.features.shaderStorageImageReadWithoutFormat) - return "no shaderStorageImageReadWithoutFormat"; + if (props.apiVersion < VK_API_VERSION_1_3) { + if (feat == "shaderStorageImageWriteWithoutFormat" && !f2.features.shaderStorageImageWriteWithoutFormat) + return "no shaderStorageImageWriteWithoutFormat"; + if (feat == "shaderStorageImageReadWithoutFormat" && !f2.features.shaderStorageImageReadWithoutFormat) + return "no shaderStorageImageReadWithoutFormat"; + } } return {}; }; - // Resource contract (docs/design.md): set 0, runtime-sized arrays as large bindless arrays. - std::vector b; - auto add = [&](uint32_t bind, VkDescriptorType t, uint32_t cnt) { - b.push_back({bind, t, cnt, VK_SHADER_STAGE_ALL, nullptr}); - }; - add(0, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 4096); add(1, VK_DESCRIPTOR_TYPE_SAMPLER, 1024); - add(2, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1); add(3, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1024); - add(4, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1024); add(5, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256); - add(6, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256); add(7, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256); - for (uint32_t i = 8; i <= 19; i++) add(i, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256); - VkDescriptorSetLayoutCreateInfo dli{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; - dli.bindingCount = uint32_t(b.size()); dli.pBindings = b.data(); + // Use the runtime's set-0 layout and sizing rules. The translator does not declare the runtime-only MS SRVs. + leonida::BindlessFeatures bindless{}; + std::function layout_supported; + if (vkGetDescriptorSetLayoutSupport) + layout_supported = [&](const leonida::BindlessFeatures& candidate) { + const leonida::bindless::SetLayout layout(candidate); + VkDescriptorSetLayoutSupport support{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_SUPPORT}; + vkGetDescriptorSetLayoutSupport(dev, &layout.info, &support); + return support.supported == VK_TRUE; + }; + if (!leonida::bindless::size_bindings(bindless, props2.properties.limits, indexing_limits, indexed, layout_supported) && + f12.descriptorBindingSampledImageUpdateAfterBind && f12.descriptorBindingStorageImageUpdateAfterBind && + f12.descriptorBindingStorageBufferUpdateAfterBind) { + bindless.update_after_bind = true; + leonida::bindless::size_bindings(bindless, props2.properties.limits, indexing_limits, indexed, layout_supported); + } + const leonida::bindless::SetLayout layout(bindless); VkDescriptorSetLayout dsl; - if (VkResult r = vkCreateDescriptorSetLayout(dev, &dli, nullptr, &dsl)) { std::fprintf(stderr, "layout %d\n", r); return 1; } + if (VkResult r = vkCreateDescriptorSetLayout(dev, &layout.info, nullptr, &dsl)) { + std::fprintf(stderr, "layout %d\n", r); + return 1; + } // Set 1 of --pc-tail-ubo shaders (docs/design.md): dynamic uniform block at binding 0 holding heap/code base. const VkDescriptorSetLayoutBinding tail_binding{0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1, VK_SHADER_STAGE_ALL, nullptr}; diff --git a/runtime/test/vk_store_test.cpp b/runtime/test/vk_store_test.cpp index 5612a7119f..28252290ff 100644 --- a/runtime/test/vk_store_test.cpp +++ b/runtime/test/vk_store_test.cpp @@ -1,6 +1,6 @@ // Headless Vulkan test for translated typed image stores and loads (runtime/test/shaders/cs_imgstore.asm and -// cs_imgload.asm). -// Usage: vk_store_test cs.spv [load|load-d16|words] +// cs_imgload*.asm). +// Usage: vk_store_test cs.spv [load|load-d16|load-mip|words] // The shader builds three T#s (word1 FORMAT = 56 rgba8 unorm, 20 r32 uint, 21 r32 sint) and stores to three 8x8 // images. The translator picks the float / uint / sint view (set 0, bindings 8 / 9 / 10 for 2D) from the FORMAT // field, and the bindless index from the descriptor hash table (binding 2). As in the runtime, each image has its @@ -9,6 +9,10 @@ // "load" (cs_imgload.asm): the uint and sint images are filled before the dispatch, and the shader loads both // texels with image_load and stores their sum into the sint image. The device is made without // shaderStorageImageReadWithoutFormat, and a module that declares StorageImageReadWithoutFormat fails (SHADER-151). +// "load-d16": check integer narrowing for packed image_load (cs_imgload_d16.asm) or image_sample_lz +// (cs_sample_lz_int_d16.asm), including saturation at the 16-bit boundaries. +// "load-mip": read level 1 through typed, two-level SRVs with both full-width and D16 fetches; write the checked +// results to level 0 through single-level storage views. The two mips start with different data. // "words" (cs_imgatomic.asm, cs_imgatomic3d.asm, cs_resinfo.asm): the uint and sint images are filled as for "load" // and a 4x4x4 r32 uint volume with 200 + i, and nothing is judged here: the 64 words of each are printed after the // dispatch (texel (x, y) at i = 8y + x, (x, y, z) at i = 16z + 4y + x) for check.py to compare. Three things are @@ -58,7 +62,7 @@ static void table_insert(std::vector& t, const uint32_t key[8], uint32 } int main(int argc, char** argv) { - if (argc < 2) { std::fprintf(stderr, "usage: vk_store_test cs.spv [load|load-d16|words]\n"); return 2; } + if (argc < 2) { std::fprintf(stderr, "usage: vk_store_test cs.spv [load|load-d16|load-mip|words]\n"); return 2; } gipa = load_vulkan(); if (!gipa) return 1; #define LOADI(name) auto name = reinterpret_cast(gipa(inst, #name)) @@ -111,8 +115,9 @@ int main(int argc, char** argv) { VkPhysicalDeviceFeatures2 f2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; f2.features.shaderStorageImageWriteWithoutFormat = VK_TRUE; // "load" mode (cs_imgload.asm): the sint image receives the sum of the two texels read back with image_load. + const bool load_mip = argc > 2 && !std::strcmp(argv[2], "load-mip"); const bool packed_load = argc > 2 && !std::strcmp(argv[2], "load-d16"); - const bool load_mode = packed_load || (argc > 2 && !std::strcmp(argv[2], "load")); + const bool load_mode = load_mip || packed_load || (argc > 2 && !std::strcmp(argv[2], "load")); // "words" mode: the two images filled as for "load"; the shader's results are whatever it leaves in them. const bool words_mode = argc > 2 && !std::strcmp(argv[2], "words"); const bool filled = load_mode || words_mode; @@ -200,7 +205,8 @@ int main(int argc, char** argv) { // The volume of the 3D atomics: index 1 of the 3D arrays, behind a T# of the 2D images' pattern (k = 4). const uint32_t VOL = 4; { - uint32_t t[8] = {0x5000, fmts[1] << 20, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55}; + // The volume uses the D3D12 layer's whole-mip UAV tag (FirstWSlice=0, WSize=4). + uint32_t t[8] = {0x5000, fmts[1] << 20, 0x55, 0x55, 0x80000055, 0x55, 0x55, 0xd7801800}; table_insert(table, t, 1); } VkBuffer tb; void* tbp; @@ -208,10 +214,12 @@ int main(int argc, char** argv) { std::memcpy(tbp, table.data(), table.size() * 4); const uint32_t W = 8; - VkImage img[3]; VkImageView view[3]; + const uint32_t base_width = load_mip ? 2 * W : W, mip_count = load_mip ? 2 : 1; + VkImage img[3]; VkImageView view[3], sampled[3]; for (int k = 0; k < 3; k++) { VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; - ii.imageType = VK_IMAGE_TYPE_2D; ii.format = vkf[k]; ii.extent = {W, W, 1}; ii.mipLevels = 1; ii.arrayLayers = 1; + ii.imageType = VK_IMAGE_TYPE_2D; ii.format = vkf[k]; ii.extent = {base_width, base_width, 1}; + ii.mipLevels = mip_count; ii.arrayLayers = 1; ii.samples = VK_SAMPLE_COUNT_1_BIT; ii.tiling = VK_IMAGE_TILING_OPTIMAL; ii.usage = VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; @@ -225,6 +233,14 @@ int main(int argc, char** argv) { vi.image = img[k]; vi.viewType = VK_IMAGE_VIEW_TYPE_2D; vi.format = vkf[k]; vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; CHECK(vkCreateImageView(dev, &vi, nullptr, &view[k])); + sampled[k] = view[k]; + if (load_mip) { + VkImageViewUsageCreateInfo usage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO}; + usage.usage = VK_IMAGE_USAGE_SAMPLED_BIT; + vi.pNext = &usage; + vi.subresourceRange.levelCount = mip_count; + CHECK(vkCreateImageView(dev, &vi, nullptr, &sampled[k])); + } } VkImage wide; VkImageView wide_view; { @@ -292,10 +308,10 @@ int main(int argc, char** argv) { dai.descriptorPool = dp; dai.descriptorSetCount = 1; dai.pSetLayouts = &dsl; VkDescriptorSet ds; CHECK(vkAllocateDescriptorSets(dev, &dai, &ds)); VkDescriptorBufferInfo tbi{tb, 0, VK_WHOLE_SIZE}; - VkDescriptorImageInfo sii[N] = {{VK_NULL_HANDLE, view[0], VK_IMAGE_LAYOUT_GENERAL}, - {VK_NULL_HANDLE, view[0], VK_IMAGE_LAYOUT_GENERAL}, - {VK_NULL_HANDLE, view[1], VK_IMAGE_LAYOUT_GENERAL}, - {VK_NULL_HANDLE, view[2], VK_IMAGE_LAYOUT_GENERAL}, + VkDescriptorImageInfo sii[N] = {{VK_NULL_HANDLE, sampled[0], VK_IMAGE_LAYOUT_GENERAL}, + {VK_NULL_HANDLE, sampled[0], VK_IMAGE_LAYOUT_GENERAL}, + {VK_NULL_HANDLE, sampled[1], VK_IMAGE_LAYOUT_GENERAL}, + {VK_NULL_HANDLE, sampled[2], VK_IMAGE_LAYOUT_GENERAL}, {VK_NULL_HANDLE, wide_view, VK_IMAGE_LAYOUT_GENERAL}}; VkDescriptorImageInfo smpi{sampler, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_UNDEFINED}; VkDescriptorImageInfo dii[3][N]; @@ -348,7 +364,10 @@ int main(int argc, char** argv) { VkBuffer rb[3]; void* rbp[3]; for (int k = 0; k < 3; k++) CHECK(make_buffer(W * W * 4, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &rb[k], &rbp[k])); - // Load and words modes: what the uint and sint images hold before the dispatch, texel (x, y) at i = 8y + x. + // Mip mode seeds level 0 with a decoy, and level 1 with the three typed inputs. Ordinary load mode + // and words mode seed only integer images. The high bits on the mip inputs force D16 saturation. + const int first_fill = load_mip ? 0 : 1; + const uint32_t mip_offset = load_mip ? base_width * base_width : 0; // The last row of the D16 fixture ("load-d16" only) exercises both sides of each 16-bit boundary. struct PackedLoad { uint32_t u; int32_t s, sum; }; constexpr PackedLoad boundary[] = { @@ -356,14 +375,20 @@ int main(int argc, char** argv) { {0, 32768, 32767}, {0, -32768, -32768}, {0, -32769, -32768}, {65536, -32769, 32767}, }; static_assert(sizeof(boundary) / sizeof(boundary[0]) == W); - VkBuffer fill[2]{}; void* fillp[2]{}; + VkBuffer fill[3]{}; if (filled) { - for (int j = 0; j < 2; j++) - CHECK(make_buffer(W * W * 4, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &fill[j], &fillp[j])); - for (uint32_t i = 0; i < W * W; i++) { - const bool edge = packed_load && i / W == W - 1; - static_cast(fillp[0])[i] = edge ? boundary[i % W].u : 100 + i; - static_cast(fillp[1])[i] = edge ? boundary[i % W].s : -2 * int32_t(i); + for (int k = first_fill; k < 3; k++) { + void* mapping; + CHECK(make_buffer((mip_offset + W * W) * 4, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &fill[k], &mapping)); + auto* words = static_cast(mapping); + for (uint32_t i = 0; i < mip_offset; i++) words[i] = 0x12345678u; + for (uint32_t i = 0; i < W * W; i++) { + const uint32_t rgba = (i & 1 ? 0xff : 0) | (i & W ? 0xff00 : 0) | 0xff000000u; + const bool edge = packed_load && i / W == W - 1; + const uint32_t u = edge ? boundary[i % W].u : (load_mip ? 0x100000 : 0) + 100 + i; + const int32_t s = edge ? boundary[i % W].s : -2 * int32_t(i) - (load_mip ? 0x10000 : 0); + words[mip_offset + i] = k == 0 ? rgba : k == 1 ? u : uint32_t(s); + } } } // The volume's fill and its read-back, used in words mode. @@ -387,8 +412,8 @@ int main(int argc, char** argv) { ib[k].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; ib[k].newLayout = VK_IMAGE_LAYOUT_GENERAL; ib[k].dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; ib[k].srcQueueFamilyIndex = ib[k].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - ib[k].subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - if (filled && k > 0) { // filled by a copy first + ib[k].subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, mip_count, 0, 1}; + if (filled && k >= first_fill) { // filled by a copy first ib[k].newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; ib[k].dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; } } @@ -403,6 +428,7 @@ int main(int argc, char** argv) { VkImageMemoryBarrier vol_ib = ib[0]; vol_ib.image = vol; vol_ib.newLayout = VK_IMAGE_LAYOUT_GENERAL; vol_ib.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + vol_ib.subresourceRange.levelCount = 1; const VkImageSubresourceLayers vol_layers{VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; if (words_mode) { // filled by a copy first vol_ib.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; vol_ib.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; @@ -421,16 +447,21 @@ int main(int argc, char** argv) { 0, nullptr, 1, &vol_ib); } if (filled) { - for (int k = 1; k < 3; k++) { - VkBufferImageCopy bic{}; - bic.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; bic.imageExtent = {W, W, 1}; - vkCmdCopyBufferToImage(cmd, fill[k - 1], img[k], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &bic); + VkBufferImageCopy copies[2]{}; + for (uint32_t level = 0; level < mip_count; level++) { + auto& copy = copies[level]; + copy.bufferOffset = level ? mip_offset * 4 : 0; + copy.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, level, 0, 1}; + copy.imageExtent = {base_width >> level, base_width >> level, 1}; + } + for (int k = first_fill; k < 3; k++) { + vkCmdCopyBufferToImage(cmd, fill[k], img[k], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, mip_count, copies); ib[k].oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; ib[k].newLayout = VK_IMAGE_LAYOUT_GENERAL; ib[k].srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; ib[k].dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; } vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, - nullptr, 0, nullptr, 2, ib + 1); + nullptr, 0, nullptr, 3 - first_fill, ib + first_fill); } vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pipe); vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pl, 0, 1, &ds, 0, nullptr); @@ -445,6 +476,7 @@ int main(int argc, char** argv) { for (int k = 0; k < 3; k++) { ib[k].oldLayout = VK_IMAGE_LAYOUT_GENERAL; ib[k].newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; ib[k].srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; ib[k].dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; + ib[k].subresourceRange.levelCount = 1; } vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 3, ib); for (int k = 0; k < 3; k++) { @@ -489,6 +521,18 @@ int main(int argc, char** argv) { for (uint32_t x = 0; x < W; x++) { uint32_t i = y * W + x; const uint8_t* c = static_cast(rbp[0]) + 4 * i; + if (load_mip) { + const bool red = x & 1, green = y & 1; + const uint32_t packed_float = (red ? 0x3c00u : 0) | (green ? 0x3c000000u : 0); + const uint32_t u = 0x100000u + 100 + i, s = uint32_t(-2 * int32_t(i) - 0x10000); + // D16 saturates red to 65535 (UINT) or -32768 (SINT); the high half holds alpha = 1. + const uint32_t want_u = u + 0x0001ffffu + packed_float; + const uint32_t want_s = s + 0x00018000u; + if (c[0] != (red ? 255 : 0) || c[1] != (green ? 255 : 0) || c[2] || c[3]) bad[0]++; + if (static_cast(rbp[1])[i] != want_u) bad[1]++; + if (static_cast(rbp[2])[i] != want_s) bad[2]++; + continue; + } int er = int(std::lround(x / 7.0 * 255)), eg = int(std::lround(y / 7.0 * 255)); if (std::abs(c[0] - er) > 1 || std::abs(c[1] - eg) > 1 || std::abs(c[2] - 128) > 1 || c[3] != 255) bad[0]++; const bool edge = packed_load && y == W - 1; diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h index 114ca187f1..f06718677d 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h @@ -106,6 +106,8 @@ class Device { bool storage_buffer_8bit = false; // storageBuffer8BitAccess enabled bool conditional_rendering = false; // VK_EXT_conditional_rendering enabled, where available bool host_image_copy = false; // VK_EXT_host_image_copy and hostImageCopy enabled + bool sliced_3d_uav = false; // imageSlicedViewOf3D and robustImageAccess enabled + bool robust_image_access = false; // create(true) only: VK_KHR (else EXT) swapchain_maintenance1 and its feature enabled, with the surface half on the // instance, so a vsync swapchain can switch to IMMEDIATE or FIFO_RELAXED per present. bool swapchain_maintenance1 = false; @@ -169,6 +171,17 @@ class Device { bool create(bool presentation = false) { return initialize(presentation) == DeviceStatus::ready; } DeviceStatus initialize(bool presentation = false) { + return initialize_device(presentation, false, true); + } + + // Headless UAV tests can request sliced views and opt out of legacy formatless storage image features. + DeviceStatus initialize(bool enable_sliced_3d_uav, bool enable_legacy_formatless_features) { + return initialize_device(false, enable_sliced_3d_uav, enable_legacy_formatless_features); + } + +private: + DeviceStatus initialize_device(bool presentation, bool enable_sliced_3d_uav, + bool enable_legacy_formatless_features) { const auto failure = [](const char* call, VkResult result) { std::fprintf(stderr, "%s failed (VkResult %d)\n", call, static_cast(result)); return DeviceStatus::failed; @@ -328,7 +341,9 @@ class Device { std::printf("device: %s%s%s\n", chosen.deviceName, v13_.core ? "" : " (Vulkan 1.2 + KHR extensions)", validation ? " (validation on)" : ""); - VkPhysicalDeviceVulkan11Features features11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES}; + VkPhysicalDeviceVulkan13Features features13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; + VkPhysicalDeviceVulkan11Features features11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, + v13_.core ? &features13 : nullptr}; VkPhysicalDeviceVulkan12Features features12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &features11}; VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &features12}; features2_of(physical, &features); @@ -370,6 +385,10 @@ class Device { // (zero-based VS ids) is in; harmless before. VkPhysicalDeviceVulkan11Features enable11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, v13_.enable(conditional_rendering ? &enable_conditional : nullptr)}; + if (v13_.core) { + robust_image_access = features13.robustImageAccess == VK_TRUE; + static_cast(enable11.pNext)->robustImageAccess = robust_image_access; + } enable11.shaderDrawParameters = features11.shaderDrawParameters; VkPhysicalDeviceVulkan12Features enable12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &enable11}; enable12.timelineSemaphore = VK_TRUE; @@ -428,9 +447,12 @@ class Device { bc = features.features.textureCompressionBC == VK_TRUE; enable.shaderSampledImageArrayDynamicIndexing = bindless; enable.shaderStorageImageArrayDynamicIndexing = bindless; + enable.shaderStorageImageReadWithoutFormat = + enable_legacy_formatless_features && features.features.shaderStorageImageReadWithoutFormat; + enable.shaderStorageImageWriteWithoutFormat = + enable_legacy_formatless_features && features.features.shaderStorageImageWriteWithoutFormat; enable.logicOp = features.features.logicOp; // d3d12_draw_test's logic-op draw, where available enable.geometryShader = features.features.geometryShader; // d3d12_geometry_test, where available - enable.shaderInt64 = features.features.shaderInt64; // translated shaders declare Int64 for their addresses const char* conditional_extension = VK_EXT_CONDITIONAL_RENDERING_EXTENSION_NAME; // VK_EXT_host_image_copy where the device has it, for the D3D12 layer's CPU texture copies. @@ -496,6 +518,22 @@ class Device { *v13_.next() = &host_copy; } + const char* sliced_name = VK_EXT_IMAGE_SLICED_VIEW_OF_3D_EXTENSION_NAME; + VkPhysicalDeviceImageSlicedViewOf3DFeaturesEXT sliced{ + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_SLICED_VIEW_OF_3D_FEATURES_EXT}; + if (enable_sliced_3d_uav && robust_image_access && + std::any_of(extensions.begin(), extensions.end(), [&](const auto& e) { + return std::strcmp(e.extensionName, sliced_name) == 0; + })) { + VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &sliced}; + instance_fn("vkGetPhysicalDeviceFeatures2")(physical, &query); + sliced_3d_uav = sliced.imageSlicedViewOf3D == VK_TRUE; + if (sliced_3d_uav) { + sliced.pNext = *v13_.next(); + *v13_.next() = &sliced; + } + } + #ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME // VK_KHR_shader_fma where the device has it: translated shaders built with --fma khr use OpFmaKHR. VkPhysicalDeviceShaderFmaFeaturesKHR fma_features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_FMA_FEATURES_KHR}; @@ -547,6 +585,7 @@ class Device { if (vertex_attribute_divisor) device_extensions.push_back(divisor_extension); if (conditional_rendering) device_extensions.push_back(conditional_extension); if (host_image_copy) device_extensions.push_back(host_image_copy_name); + if (sliced_3d_uav) device_extensions.push_back(sliced_name); const char* swapchain = "VK_KHR_swapchain"; if (presentation) device_extensions.push_back(swapchain); #if defined(VK_KHR_swapchain_maintenance1) @@ -596,6 +635,7 @@ class Device { return result == VK_SUCCESS ? DeviceStatus::ready : failure("vkCreateCommandPool", result); } +public: bool depth_format_usable(VkFormat format) const { VkFormatProperties properties{}; instance_fn("vkGetPhysicalDeviceFormatProperties")(physical, format, diff --git a/tests/test_image_load_typed.py b/tests/test_image_load_typed.py index 98c782749d..8e5ac1e057 100644 --- a/tests/test_image_load_typed.py +++ b/tests/test_image_load_typed.py @@ -99,8 +99,9 @@ def integer_coord_vgpr(self, operand): assert (op, ptr[1]) == ("OpAccessChain", "%vgpr"), (op, ptr) return self.value(ptr[2], 0, 0) - def value(self, x, word1, index): - """Evaluate the uint/bool id x given the T#'s word 1 and the bindless index of the lookup.""" + def value(self, x, word1, index, regs=None): + """Evaluate the format selection or volume guard, optionally supplying a test's SGPR/VGPR words.""" + get = lambda y: self.value(y, word1, index, regs) if x in ("%true", "%false"): return x == "%true" op, a = self.defs[x] @@ -113,18 +114,29 @@ def value(self, x, word1, index): if op == "OpLoad": ptr_op, p = self.defs[a[1]] assert ptr_op == "OpAccessChain", ptr_op - if p[1] == "%vgpr" and self.vgprs is not None: - return self.vgprs[self.value(p[2], word1, index)] - if p[1] == "%sgpr": - assert self.value(p[2], word1, index) == 1, "only T# word 1 is read" + if p[1] in ("%sgpr", "%vgpr"): + r = get(p[2]) + if regs is not None: + return regs[p[1], r] + if p[1] == "%vgpr" and self.vgprs is not None: + return self.vgprs[r] + assert (p[1], r) == ("%sgpr", 1), "only T# word 1 is read" return word1 var_op, v = self.defs[p[1]] assert var_op == "OpVariable" and v[1] == "Private", (var_op, v) words = self.defs[v[2]][1][1:] # OpConstantComposite %fmt_mask_arr - return self.value(words[self.value(p[2], word1, index)], word1, index) - if op == "OpGroupNonUniformBroadcastFirst": # desc_lookup makes the descriptor word uniform: one invocation - return self.value(a[2], word1, index) # here, so the value itself (a[1] is the Subgroup scope) - u = [self.value(y, word1, index) for y in a[1:]] + return get(words[get(p[2])]) + if op == "OpGroupNonUniformBroadcastFirst": # One invocation: return the value (a[1] is the Subgroup scope). + return get(a[2]) + if op == "OpCompositeExtract": + return get(a[1])[int(a[2])] + if op == "OpCompositeInsert": + result = list(get(a[2])) + result[int(a[3])] = get(a[1]) + return tuple(result) + u = [get(y) for y in a[1:]] + if op == "OpCompositeConstruct": + return tuple(u) if op == "OpBitcast": return u[0] if op == "OpBitFieldUExtract": @@ -135,8 +147,20 @@ def value(self, x, word1, index): return u[0] & u[1] if op == "OpINotEqual": return u[0] != u[1] + if op == "OpIEqual": + return u[0] == u[1] + if op == "OpIAdd": + return (u[0] + u[1]) & 0xffffffff + if op == "OpULessThanEqual": + return u[0] <= u[1] + if op == "OpSelect": + return u[1] if u[0] else u[2] if op == "OpLogicalAnd": return u[0] and u[1] + if op == "OpLogicalOr": + return u[0] or u[1] + if op == "OpLogicalNot": + return not u[0] raise AssertionError(f"unexpected {op} in the branch condition") def branch(self, word1, index): @@ -171,9 +195,15 @@ def test_volume_mip_fetch_uses_xyz_level_and_descriptor_type(self): self.assertEqual((m.binding[var], image[1]), (6, "3D")) _, _, xyz, mask, lod = m.defs[rid][1] self.assertEqual(mask, "Lod") - op, coords = m.defs[xyz] + # The sampled alias rebases only tagged UAVs; an ordinary SRV must use its original XYZ/LOD. + op, adjusted = m.defs[xyz] + self.assertEqual((op, adjusted[0], adjusted[3]), ("OpCompositeInsert", "%v3int", "2")) + op, coords = m.defs[adjusted[2]] self.assertEqual((op, coords[0]), ("OpCompositeConstruct", "%v3int")) self.assertEqual([m.integer_coord_vgpr(v) for v in [*coords[1:], lod]], [4, 5, 6, 7]) + regs = {("%vgpr", r): val for r, val in zip(range(4, 8), (11, 17, 23, 3))} + regs.update({("%sgpr", 4): 0, ("%sgpr", 7): 0}) + self.assertEqual((m.value(xyz, 0, 1, regs), m.value(lod, 0, 1, regs)), ((11, 17, 23), 3)) for fmt, kind in ((75, "uint"), (76, "sint"), (77, "float")): # RGBA32 formats self.assertEqual(m.branch(fmt << 20, 1), kind) self.assertEqual(m.branch(fmt << 20, 0), "float") @@ -508,15 +538,125 @@ def test_a_shader_that_also_stores_needs_only_the_write_feature(self): self.assertEqual(set(m.binding.values()), {0, 1, 2, 8, 9, 10}) +def uav_array_load(): + return translate(["v_mov_b32 v4, 1", "v_mov_b32 v5, 2", + "image_load v[0:3], v[4:5], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_1D_ARRAY unorm", + "s_waitcnt vmcnt(0)"]) + + +def volume_mip_load(): + return translate(["v_mov_b32 v4, 1", "v_mov_b32 v5, 2", "v_mov_b32 v6, 3", "v_mov_b32 v7, 1", + "image_load_mip v[0:3], v[4:7], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_3D unorm", + "s_waitcnt vmcnt(0)"]) + + +def mixed_d16_mip_loads(): + return translate(["image_load_mip v0, v[4:6], s[8:15] dmask:0x9 dim:SQ_RSRC_IMG_2D unorm d16", + "image_load_mip v3, v[8:11], s[16:23] dmask:0x9 dim:SQ_RSRC_IMG_3D unorm d16", + "s_waitcnt vmcnt(0)"]) + + +class TextureUavLoads(unittest.TestCase): + def test_1d_array_load_uses_only_storage_bindings_and_the_read_feature(self): + m = Module(uav_array_load()) + self.assertEqual(m.caps & STORAGE_IMAGE_CAPS, {"StorageImageReadWithoutFormat", "Image1D"}) + self.assertEqual(set(m.binding.values()), {0, 1, 2, 26, 27, 28}) + self.assertFalse(m.fetches()) + reads = {} + for _, op, args in m.order: + if op == "OpImageRead": + _, load = m.defs[args[1]] + _, chain = m.defs[load[1]] + reads[m.binding[chain[1]]] = m.defs[load[0]][1] + self.assertEqual(reads, {26: ["%float", "1D", "0", "1", "0", "2", "Unknown"], + 27: ["%uint", "1D", "0", "1", "0", "2", "Unknown"], + 28: ["%int", "1D", "0", "1", "0", "2", "Unknown"]}) + + def test_coherent_volume_load_and_1d_array_load_share_storage_dispatch(self): + m = Module(translate([ + "image_load v0, v[4:6], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm glc dlc", + "image_load v3, v[4:5], s[8:15] dmask:0x1 dim:SQ_RSRC_IMG_1D_ARRAY unorm", + "s_waitcnt vmcnt(0)", + ])) + self.assertEqual(m.caps & STORAGE_IMAGE_CAPS, {"StorageImageReadWithoutFormat", "Image1D"}) + self.assertFalse(m.fetches()) + self.assertEqual({b for v, b in m.binding.items() if v.startswith("%stv")}, {14, 15, 16, 26, 27, 28}) + self.assertTrue(all(f"OpDecorate {v} Coherent" in m.text for v in m.binding if v.startswith("%stv"))) + + def test_volume_mip_load_rebases_each_sampled_alias_without_storage(self): + m = Module(volume_mip_load()) + self.assertFalse(m.caps & STORAGE_IMAGE_CAPS) + fetches = m.fetches() + self.assertEqual({image[0] for _, _, image in fetches}, {"%int", "%uint", "%float"}) + for rid, var, _ in fetches: + self.assertEqual(m.binding[var], 6) + self.assertEqual(m.defs[m.defs[rid][1][2]][0], "OpCompositeInsert") + self.assertTrue(any(op == "OpPhi" and rid in args for _, op, args in m.order)) + + def test_volume_atomic_load_accepts_a_descriptor_register_list(self): + t = "[s100,s101,s102,s103,s104,s105,vcc_lo,vcc_hi]" + m = Module(translate([ + f"image_atomic_add v0, v[4:6], {t} dmask:0x1 dim:SQ_RSRC_IMG_3D unorm glc", + f"image_load v3, v[4:6], {t} dmask:0x1 dim:SQ_RSRC_IMG_3D unorm", + "s_waitcnt vmcnt(0)", + ])) + self.assertIn("OpAtomicIAdd", m.text) + self.assertIn("OpImageRead", m.text) + self.assertEqual(m.binding["%simages3d"], 7) + self.assertFalse(m.caps & STORAGE_IMAGE_CAPS) + + def test_mixed_d16_mips_keep_2d_lod_and_only_rebase_tagged_3d(self): + m = Module(mixed_d16_mip_loads()) + self.assertFalse(m.caps & STORAGE_IMAGE_CAPS) + self.assertNotIn("OpImageRead", m.text) + self.assertEqual(set(m.binding.values()), {0, 1, 2, 6}) + guards, last = {}, None + for rid, op, args in m.order: + if op == "OpBranchConditional": + last = args[0] + elif op == "OpImageFetch": + guards[rid] = last + regs = {("%vgpr", r): value for r, value in {4: 3, 5: 4, 6: 2, 8: 5, 9: 6, 10: 0, 11: 0}.items()} + types = {0: set(), 6: set()} + flag, tag = 0x80000000, 0xd7800000 | (1 << 11) | 3 # WSize=2, FirstWSlice=3 + for rid, var, image in m.fetches(): + binding = m.binding[var] + types[binding].add(image[0]) + _, (_, _, coords, operand, lod) = m.defs[rid] + self.assertEqual(operand, "Lod") + if binding == 0: + self.assertEqual(m.value(coords, 0, 1, regs), (3, 4)) + self.assertEqual(m.value(lod, 0, 1, regs), 2) + continue + for t4, t7, z, level, expected in ( + (flag, tag, 1, 0, 4), (flag, tag, 2, 0, None), (flag, tag, 0xffffffff, 0, None), + (flag, tag, 0, 1, None), (0, tag, 2, 1, 2), (flag, 0, 2, 1, 2), (0, 0, 2, 1, 2), + (flag, tag | 0x00400000, 1, 0, 4), (flag, tag | 0x00400000, 2, 0, None), + ): + with self.subTest(ty=image[0], t4=t4, t7=t7, z=z, level=level): + regs.update({("%sgpr", 20): t4, ("%sgpr", 23): t7, ("%vgpr", 10): z, ("%vgpr", 11): level}) + self.assertEqual(m.value(guards[rid], 0, 1, regs), expected is not None) + if expected is not None: + self.assertEqual(m.value(coords, 0, 1, regs), (5, 6, expected)) + self.assertEqual(m.value(lod, 0, 1, regs), level) + self.assertEqual(types, {0: {"%float", "%uint", "%int"}, 6: {"%float", "%uint", "%int"}}) + + @unittest.skipUnless(shutil.which("spirv-as") and shutil.which("spirv-val"), "needs spirv-as and spirv-val") class Validation(unittest.TestCase): def test_spirv_val_accepts_every_dimension(self): + shaders = {dim: load_shader(dim) for dim in DIMS} + shaders.update({"1D_ARRAY": uav_array_load(), "3D_MIP": volume_mip_load(), "MIXED_D16_MIP": mixed_d16_mip_loads()}) + shaders["GATHER_D16"] = translate([ + "image_gather4_lz v[0:1], v[4:5], s[0:7], s[8:11] dmask:0x2 dim:SQ_RSRC_IMG_2D d16", + "s_waitcnt vmcnt(0)", + ]) with tempfile.TemporaryDirectory() as tmp: - for dim in DIMS: + for dim, text in shaders.items(): with self.subTest(dim=dim): sa, sv = os.path.join(tmp, f"{dim}.spvasm"), os.path.join(tmp, f"{dim}.spv") with open(sa, "w", encoding="utf-8") as f: - f.write(load_shader(dim)) + f.write(text) result = rdna2spirv.assemble_spirv(sa, sv) self.assertEqual(result.returncode, 0, result.stderr + result.stdout) diff --git a/tests/test_spirv_metal_set0.py b/tests/test_spirv_metal_set0.py index e2ffe24a5d..6d25c66aa1 100644 --- a/tests/test_spirv_metal_set0.py +++ b/tests/test_spirv_metal_set0.py @@ -33,7 +33,7 @@ def test_capacities_match_vulkan_bindless(): counts = m.capacities() assert counts[:5] == [4096, 1024, 1, 1024, 1024] - assert len(counts) == 26 + assert counts[26:] == [256, 256, 256] # storage-only Texture1DArray UAVs def test_metal_ids_are_running_sums(): diff --git a/tests/test_spirv_metal_set0_aliases.py b/tests/test_spirv_metal_set0_aliases.py index 3793609302..0775197b06 100644 --- a/tests/test_spirv_metal_set0_aliases.py +++ b/tests/test_spirv_metal_set0_aliases.py @@ -83,7 +83,7 @@ def test_capacities_and_print_layout_emit_no_resource_warning(self): with warnings.catch_warnings(): warnings.simplefilter("error", ResourceWarning) counts = m.capacities() - self.assertEqual(len(counts), 26) + self.assertEqual(len(counts), 29) self.assertEqual(m.capacities(good_hdr), [16, 8]) with self.assertRaises(SystemExit): m.capacities(bad_hdr) diff --git a/tests/test_spirv_metal_set0_extra.py b/tests/test_spirv_metal_set0_extra.py index 5b03f429e0..f3a50b1f9b 100644 --- a/tests/test_spirv_metal_set0_extra.py +++ b/tests/test_spirv_metal_set0_extra.py @@ -1,7 +1,7 @@ """Expanded stdlib-only unit tests for tools/spirv_metal_set0.py. Covers bindless capacity parsing from vulkan_bindless.h and custom headers, -metal_ids() layout math, rewrite() across all 26 bindings, non-set-0 / +metal_ids() layout math, rewrite() across all set-0 bindings, non-set-0 / push-constant / non-runtime-array / pre-sized / raw-ID / error branches, synthetic SPIR-V binary word header/magic/endianness/bounds handling, out-of-place vs in-place CLI execution via mocked spirv-dis/spirv-as, @@ -376,17 +376,17 @@ def fake_run(cmd, check=False, capture_output=False, text=False, input=None): class TestCapacities(unittest.TestCase): - def test_default_bindless_header_all_26_entries_and_cross_check(self): + def test_default_bindless_header_all_entries_and_cross_check(self): counts = m.capacities() - expected = [4096, 1024, 1, 1024, 1024] + [256] * 21 + expected = [4096, 1024, 1, 1024, 1024] + [256] * 24 self.assertEqual(counts, expected) - self.assertEqual(len(counts), 26) - self.assertEqual(sum(counts), 12545) + self.assertEqual(len(counts), 29) + self.assertEqual(sum(counts), 13313) with open(m.BINDLESS_H, encoding="utf-8") as f: hdr = f.read() - self.assertIn("inline constexpr std::uint32_t binding_count = 26;", hdr) - self.assertIn("inline constexpr std::array bindings =", hdr) + self.assertIn("inline constexpr std::uint32_t binding_count = 29;", hdr) + self.assertIn("inline constexpr std::array bindings =", hdr) def test_custom_header_parsing_variants(self): cases = [ @@ -465,12 +465,13 @@ def test_empty_single_and_zero_capacities(self): def test_vulkan_bindless_ids_contiguous_and_non_overlapping(self): counts = m.capacities() ids = m.metal_ids(counts) - self.assertEqual(len(ids), 26) + self.assertEqual(len(ids), 29) self.assertEqual(ids[0], 0) self.assertEqual(ids[:6], [0, 4096, 5120, 5121, 6145, 7169]) self.assertEqual(ids[8], 7937) self.assertEqual(ids[20], 11009) self.assertEqual(ids[25], 12289) + self.assertEqual(ids[26:], [12545, 12801, 13057]) for b in range(len(counts) - 1): self.assertEqual(ids[b + 1], ids[b] + counts[b]) self.assertEqual(ids[-1] + counts[-1], sum(counts)) @@ -480,11 +481,11 @@ def test_vulkan_bindless_ids_contiguous_and_non_overlapping(self): if b > 0: self.assertGreater(ids[b], ids[b - 1] + counts[b - 1] - 1) seen_total += counts[b] - self.assertEqual(seen_total, 12545) + self.assertEqual(seen_total, 13313) class TestRewrite(unittest.TestCase): - def test_all_26_vulkan_bindless_bindings(self): + def test_all_vulkan_bindless_bindings(self): counts = m.capacities() ids = m.metal_ids(counts) lines = [ @@ -492,7 +493,7 @@ def test_all_26_vulkan_bindless_bindings(self): " OpCapability RuntimeDescriptorArray", " OpMemoryModel Logical GLSL450", ] - for b in range(26): + for b in range(len(counts)): lines.append(f" OpDecorate %v{b} DescriptorSet 0") lines.append(f" OpDecorate %v{b} Binding {b}") lines.extend([ @@ -504,13 +505,13 @@ def test_all_26_vulkan_bindless_bindings(self): " %map = OpTypeStruct %rt_map", " %ptr_map = OpTypePointer StorageBuffer %map", ]) - for b in range(26): + for b in range(len(counts)): if b == 2: continue elem = "%smp" if b == 1 else "%img2d" lines.append(f" %rt_b{b} = OpTypeRuntimeArray {elem}") lines.append(f" %ptr_b{b} = OpTypePointer UniformConstant %rt_b{b}") - for b in range(26): + for b in range(len(counts)): if b == 2: lines.append(" %v2 = OpVariable %ptr_map StorageBuffer") else: @@ -519,7 +520,7 @@ def test_all_26_vulkan_bindless_bindings(self): out = m.rewrite("\n".join(lines) + "\n", counts) out_lines = out.splitlines() - for b in range(26): + for b in range(len(counts)): self.assertIn(f" OpDecorate %v{b} Binding {ids[b]}", out_lines) if b == 2: self.assertIn(" %v2 = OpVariable %ptr_map StorageBuffer", out_lines) @@ -690,7 +691,7 @@ def test_empty_and_no_set0_modules(self): self.assertEqual(m.rewrite(plain, [4]), plain) def test_out_of_bounds_set0_binding_raises_system_exit(self): - for b, counts in ((2, [10, 20]), (26, m.capacities()), (100, m.capacities())): + for b, counts in ((2, [10, 20]), (29, m.capacities()), (100, m.capacities())): with self.subTest(binding=b, count_len=len(counts)): text = f"OpDecorate %bad DescriptorSet 0\nOpDecorate %bad Binding {b}\n" with self.assertRaises(SystemExit) as ctx: @@ -731,14 +732,14 @@ def _call_main(self, argv): code = m.main(argv) return code, out.getvalue(), err.getvalue() - def test_print_layout_outputs_26_formatted_ranges_without_subprocess(self): + def test_print_layout_outputs_all_formatted_ranges_without_subprocess(self): with mock.patch.object(m.subprocess, "run") as run_mock: code, out, err = self._call_main(["spirv_metal_set0.py", "--print-layout"]) run_mock.assert_not_called() self.assertEqual(code, 0) self.assertEqual(err, "") lines = out.splitlines() - self.assertEqual(len(lines), 26) + self.assertEqual(len(lines), 29) self.assertEqual(lines[0], "binding 0: 4096 descriptors at IDs 0..4095") self.assertEqual(lines[1], "binding 1: 1024 descriptors at IDs 4096..5119") self.assertEqual(lines[2], "binding 2: 1 descriptors at IDs 5120..5120") @@ -801,7 +802,7 @@ def test_cli_subprocess_isolated_print_layout_and_bad_args(self): ) self.assertEqual(r_layout.returncode, 0, r_layout.stderr) self.assertEqual(r_layout.stderr, "") - self.assertEqual(len(r_layout.stdout.splitlines()), 26) + self.assertEqual(len(r_layout.stdout.splitlines()), 29) self.assertEqual(r_layout.stdout.splitlines()[0], "binding 0: 4096 descriptors at IDs 0..4095") for args in ([], ["only_one.spv"], ["a.spv", "b.spv", "c.spv"]): @@ -1025,7 +1026,7 @@ def reconfigure(self, **_kwargs): runpy.run_path(TOOL_PATH, run_name="__main__") self.assertEqual(ctx.exception.code, 0) self.assertEqual(err_stream.getvalue(), "") - self.assertEqual(len(out_stream.getvalue().splitlines()), 26) + self.assertEqual(len(out_stream.getvalue().splitlines()), 29) err_stream = io.StringIO() with warnings.catch_warnings(): diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 001b98668c..a99ba4d056 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -248,7 +248,8 @@ def __init__(self, stage): self.uses_int_sampler = False # 2D typed sampled-image types for sampling and gathering self.uses_int_fetch = set() # typed image_load dims (index into STORE_DIMS): uint/sint sampled aliases self.uses_fmt_size = False # %fmt_size_tab: byte size of each 7-bit buffer FORMAT code (0 = not in FORMATS) - self.reads_store_views = False # a coherent image_load reads a storage view (StorageImageReadWithoutFormat) + self.uses_store_reads = set() # formatless loads for coherent accesses and storage-only dimensions + self.atomic_volume_tsharps = set() # T# register groups also used for 3D atomics self.coherent_images = False # a glc image_load/image_store: the storage views are decorated Coherent self.writes_depth = False self.uses_smul = False @@ -10703,6 +10704,9 @@ def image_op(self, op, a, mods): a16 = "a16" in mods d16 = "d16" in mods dim = next((m for m in mods if m.startswith("dim:")), "dim:SQ_RSRC_IMG_2D") + storage_only = dim == "dim:SQ_RSRC_IMG_1D_ARRAY" + if storage_only and (op != "image_load" or d16): + raise Unsupported(op + " 1D_ARRAY") kinds = {"dim:SQ_RSRC_IMG_2D": ("img2d", "%images", "simg2d", 2, "_ptr_UC_img"), "dim:SQ_RSRC_IMG_2D_ARRAY": ("img2da", "%images_arr", "simg2da", 3, "_ptr_UC_imga"), # Cube: the shader already did face selection (v_cube*), and cube_coords maps (s, t, face) onto a @@ -10710,17 +10714,20 @@ def image_op(self, op, a, mods): "dim:SQ_RSRC_IMG_CUBE": ("img2da", "%images_arr", "simg2da", 3, "_ptr_UC_imga"), "dim:SQ_RSRC_IMG_1D": ("img1d", "%images_1d", "simg1d", 1, "_ptr_UC_img1"), "dim:SQ_RSRC_IMG_3D": ("img3d", "%images_3d", "simg3d", -3, "_ptr_UC_img3")} - if dim not in kinds: + if not storage_only and dim not in kinds: raise Unsupported(op + " " + dim.split("SQ_RSRC_IMG_")[-1]) - itype, iarr, stype, ncoord, iptr = kinds[dim] - is3d = ncoord == -3 # 3D: three real coordinates (and 3-component gradients) - if is3d: - ncoord = 3 - self.uses_tex_3d = True - elif ncoord == 3: - self.uses_tex_array = True - if ncoord == 1: - self.uses_tex_1d = True + if storage_only: + ncoord, is3d = 2, False + else: + itype, iarr, stype, ncoord, iptr = kinds[dim] + is3d = ncoord == -3 # 3D: three real coordinates (and 3-component gradients) + if is3d: + ncoord = 3 + self.uses_tex_3d = True + elif ncoord == 3: + self.uses_tex_array = True + if ncoord == 1: + self.uses_tex_1d = True if is3d and op in ("image_sample_d", "image_sample_d_cl") and ("tfe" in mods or "lwe" in mods): raise Unsupported(op + " 3D gradient status") grad_width = 3 if is3d else min(ncoord, 2) # an array layer has no derivative @@ -10742,7 +10749,7 @@ def image_op(self, op, a, mods): raise Unsupported(op + " needs scalar 2D depth comparison") img_idx = self.desc_lookup_sgpr(a[2], 8) img = None # a coherent image_load reads the storage view, not this sampled one - if not coherent: + if not (coherent or storage_only): ip, img = self.tmp(), self.tmp() self.emit(f"{ip} = OpAccessChain %{iptr} {iarr} {img_idx}") self.emit(f"{img} = OpLoad %{itype} {ip}") @@ -10786,12 +10793,11 @@ def image_op(self, op, a, mods): iv = self.tmp() self.emit(f"{iv} = OpCompositeConstruct {'%v2int' if ncoord == 2 else '%v3int'} {' '.join(ints)}") if coherent: - self.image_load_coherent(dim, self.load_reg("sgpr", a[2]["r"] + 1), iv, img_idx, dmask, vdata, d16) + self.image_load_coherent(dim, a[2], iv, img_idx, dmask, vdata, d16) return # Cube loads use the same sampled 2D-array view and integer layer as array loads. view_dim = "dim:SQ_RSRC_IMG_2D_ARRAY" if dim == "dim:SQ_RSRC_IMG_CUBE" else dim - self.image_load_typed(view_dim, self.sgpr_word(a[2], 1), iv, img, img_idx, - dmask, vdata, self.cu(0), d16) + self.image_load_typed(view_dim, a[2], iv, img, img_idx, dmask, vdata, lod=self.cu(0), d16=d16) return else: smp_idx = self.desc_lookup_sgpr(a[3], 4) @@ -11133,13 +11139,15 @@ def opnd(mask, args): IMG_ATOMICS_EXTRA = ("image_atomic_swap", "image_atomic_inc", "image_atomic_dec", "image_atomic_fmin", "image_atomic_fmax", "image_atomic_fcmpswap") - # image_store views: dim -> (index, SPIR-V Dim, arrayed, coordinate count). Bindings 8 + 3 * index + class, - # class 0 = float, 1 = uint, 2 = sint (Vulkan needs the shader's component type to match the image format). + # image_store views: dim -> (index, SPIR-V Dim, arrayed, coordinate count). Class 0 = float, 1 = uint, 2 = sint + # (Vulkan needs the shader's component type to match the image format). STORE_DIMS = {"dim:SQ_RSRC_IMG_2D": (0, "2D", 0, 2), "dim:SQ_RSRC_IMG_2D_ARRAY": (1, "2D", 1, 3), - "dim:SQ_RSRC_IMG_3D": (2, "3D", 0, 3), "dim:SQ_RSRC_IMG_1D": (3, "1D", 0, 1)} + "dim:SQ_RSRC_IMG_3D": (2, "3D", 0, 3), "dim:SQ_RSRC_IMG_1D": (3, "1D", 0, 1), + "dim:SQ_RSRC_IMG_1D_ARRAY": (4, "1D", 1, 2)} # The sampled array of each STORE_DIMS index: its binding in set 0 (assemble declares %images, %images_arr, # %images_3d and %images_1d there). Typed image_load reads UINT/SINT images through uint/sint aliases of it. SAMPLED_BINDINGS = {0: 0, 1: 3, 2: 6, 3: 5} + R32_UINT = next(code for code, name in GFX10_FORMATS.items() if name == "GFX10_FORMAT_32_UINT") INT_FORMATS = None # (uint mask words, sint mask words) over the 512 GFX10 formats @classmethod @@ -11185,14 +11193,114 @@ def saturate_int16(self, bits: str, signed: bool) -> str: self.emit(f"{half} = OpExtInst %uint %glsl UMin {bits} {self.cu(0xFFFF)}") return half - def image_load_typed(self, dim, t1, iv, img, idx, dmask, vdata, lod, d16=False): - def fetch(image, _cls, ty): + @staticmethod + def tsharp_regs(tsharp): + """The same descriptor register group can be printed as a range or a list.""" + if tsharp["k"] == "slist": + return tuple(tsharp["r"][:8]) + if tsharp["k"] == "sgpr": + return tuple(range(tsharp["r"], tsharp["r"] + 8)) + return () + + def synthetic_uav(self, tsharp): + """Decode the private volume/packed UAV tag (gfx10_descriptors.h), not ordinary hardware metadata.""" + t4 = self.sgpr_word(tsharp, 4) + t7 = self.sgpr_word(tsharp, 7) + flag, flag_set, tag, tag_set, uav = (self.tmp() for _ in range(5)) + self.emit(f"{flag} = OpBitwiseAnd %uint {t4} {self.cu(0x80000000)}") + self.emit(f"{flag_set} = OpINotEqual %bool {flag} {self.cu(0)}") + self.emit(f"{tag} = OpBitwiseAnd %uint {t7} {self.cu(0xff800000)}") + self.emit(f"{tag_set} = OpIEqual %bool {tag} {self.cu(0xd7800000)}") + self.emit(f"{uav} = OpLogicalAnd %bool {flag_set} {tag_set}") + return uav, t7 + + def packed_uav(self, tsharp): + uav, t7 = self.synthetic_uav(tsharp) + return self.emit_land(uav, self.emit_ne0(self.emit_and(t7, 0x00400000))) + + def image_fetch(self, img, coords, lod, ty, volume=None): + """Vulkan applies Z slicing to storage views only. Rebase all sampled aliases of a volume UAV.""" + if volume is None: res = self.tmp() - self.emit(f"{res} = OpImageFetch {ty} {image} {iv} Lod {lod}") + self.emit(f"{res} = OpImageFetch {ty} {img} {coords} Lod {lod}") return res + uav, t7 = volume + offset, last, z, relative, absolute, coord = (self.tmp() for _ in range(6)) + self.emit(f"{offset} = OpBitFieldUExtract %uint {t7} {self.cu(0)} {self.cu(11)}") + self.emit(f"{last} = OpBitFieldUExtract %uint {t7} {self.cu(11)} {self.cu(11)}") + self.emit(f"{z} = OpCompositeExtract %int {coords} 2") + self.emit(f"{relative} = OpBitcast %uint {z}") + self.emit(f"{absolute} = OpIAdd %int {z} {self.as_int(offset)}") + self.emit(f"{coord} = OpSelect %int {uav} {absolute} {z}") + in_slice, not_uav, valid = (self.tmp() for _ in range(3)) + self.emit(f"{in_slice} = OpULessThanEqual %bool {relative} {last}") + in_view = in_slice + if lod != self.cu(0): + base_mip, in_view = self.tmp(), self.tmp() + self.emit(f"{base_mip} = OpIEqual %bool {lod} {self.as_int(self.cu(0))}") + self.emit(f"{in_view} = OpLogicalAnd %bool {in_slice} {base_mip}") + self.emit(f"{not_uav} = OpLogicalNot %bool {uav}") + self.emit(f"{valid} = OpLogicalOr %bool {not_uav} {in_view}") + body, miss, end = (self.tmp() + s for s in ("_fetch", "_oob", "_end")) + adjusted, texel, zero, result = (self.tmp() for _ in range(4)) + self.emit(f"OpSelectionMerge {end} None") + self.emit(f"OpBranchConditional {valid} {body} {miss}") + self.emit(f"{body} = OpLabel") + self.emit(f"{adjusted} = OpCompositeInsert %v3int {coord} {coords} 2") + self.emit(f"{texel} = OpImageFetch {ty} {img} {adjusted} Lod {lod}") + self.emit(f"OpBranch {end}") + self.emit(f"{miss} = OpLabel") + scalar = {"%v4float": "%f0", "%v4uint_st": self.cu(0), "%v4int_st": None}[ty] + if scalar is None: + scalar = self.as_int(self.cu(0)) + self.emit(f"{zero} = OpCompositeConstruct {ty} {' '.join([scalar] * 4)}") + self.emit(f"OpBranch {end}") + self.emit(f"{end} = OpLabel") + self.emit(f"{result} = OpPhi {ty} {texel} {body} {zero} {miss}") + return result + + def image_load_typed(self, dim, tsharp, iv, img, idx, dmask, vdata, *, lod, d16=False): + """Supply the fetch to the shared typed-image dispatch used by both loads and gathers.""" + t1 = self.sgpr_word(tsharp, 1) + di = self.STORE_DIMS[dim][0] + volume = self.synthetic_uav(tsharp) if di == 2 else None + atomic_read = (volume is not None and self.tsharp_regs(tsharp) in self.atomic_volume_tsharps and + lod == self.cu(0)) + if img is None: + return self.image_load_storage(dim, tsharp, iv, idx, dmask, vdata, d16) + + def fetch(image, cls, ty): + if cls != 1 or not atomic_read: + return self.image_fetch(image, iv, lod, ty, volume) + # Read a tagged logical R32_UINT volume UAV through the same formatted storage view as its atomics. + # Other uint descriptors (notably SRVs) must use the sampled alias, not a potentially shorter array. + self.uses_storage3d = True + fmt, r32, coherent = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{fmt} = OpBitFieldUExtract %uint {t1} {self.cu(20)} {self.cu(9)}") + self.emit(f"{r32} = OpIEqual %bool {fmt} {self.cu(self.R32_UINT)}") + self.emit(f"{coherent} = OpLogicalAnd %bool {r32} {volume[0]}") + storage, sampled, fetch_done, end = ( + self.tmp() + suffix for suffix in ("_storage", "_sampled", "_fetch_done", "_read_end")) + self.emit(f"OpSelectionMerge {end} None") + self.emit(f"OpBranchConditional {coherent} {storage} {sampled}") + self.emit(f"{storage} = OpLabel") + ip, im, raw, result = (self.tmp() for _ in range(4)) + self.emit(f"{ip} = OpAccessChain %_ptr_UC_simg3 %simages3d {idx}") + self.emit(f"{im} = OpLoad %simg3d_u {ip}") + self.emit(f"{raw} = OpImageRead {ty} {im} {iv}") + self.emit(f"OpBranch {end}") + self.emit(f"{sampled} = OpLabel") + texel = self.image_fetch(image, iv, lod, ty, volume) + self.emit(f"OpBranch {fetch_done}") + self.emit(f"{fetch_done} = OpLabel") + self.emit(f"OpBranch {end}") + self.emit(f"{end} = OpLabel") + self.emit(f"{result} = OpPhi {ty} {raw} {storage} {texel} {fetch_done}") + return result + self.image_read_typed(dim, t1, img, idx, dmask, vdata, d16, fetch) - def image_load_coherent(self, dim, t1, iv, idx, dmask, vdata, d16): + def image_load_coherent(self, dim, tsharp, iv, idx, dmask, vdata, d16): """image_load with glc: a coherent read. On GFX10 a device-scope load is glc + dlc and a device-scope store glc (Mesa ac_get_hw_cache_flags maps ACCESS_COHERENT to exactly these bits); the POPS pixel shaders read and write their ordered images that way. Through the sampled array (image_load_typed) the read could not see @@ -11200,10 +11308,25 @@ def image_load_coherent(self, dim, t1, iv, idx, dmask, vdata, d16): sections only makes Coherent memory visible (Vulkan memory model, fragment shader interlock). So the read goes through the storage view the stores write (OpImageRead, StorageImageReadWithoutFormat), and the storage views are decorated Coherent (assemble).""" - di = self.STORE_DIMS[dim][0] - self.uses_store_views.add(di) - self.reads_store_views = True self.coherent_images = True + self.image_load_storage(dim, tsharp, iv, idx, dmask, vdata, d16) + + def image_load_storage(self, dim, tsharp, iv, idx, dmask, vdata, d16): + di = self.STORE_DIMS[dim][0] + self.uses_store_reads.add(di) + if di >= 2: + # Packed RGB9E5 has no float storage view. Untagged 3D SRVs may also have an index beyond + # the shorter storage arrays; the coherent operation needs a UAV, not a sampled descriptor. + unsupported = self.packed_uav(tsharp) + if di == 2: + tagged, _ = self.synthetic_uav(tsharp) + untagged, reject = self.tmp(), self.tmp() + self.emit(f"{untagged} = OpLogicalNot %bool {tagged}") + self.emit(f"{reject} = OpLogicalOr %bool {untagged} {unsupported}") + unsupported = reject + safe = self.tmp() + self.emit(f"{safe} = OpSelect %uint {unsupported} {self.cu(0)} {idx}") + idx = safe def view(cls): ip, im = self.tmp(), self.tmp() @@ -11215,7 +11338,7 @@ def read(image, _cls, ty): res = self.tmp() self.emit(f"{res} = OpImageRead {ty} {image} {iv}") return res - self.image_read_typed(dim, t1, None, idx, dmask, vdata, d16, read, view) + self.image_read_typed(dim, self.sgpr_word(tsharp, 1), None, idx, dmask, vdata, d16, read, view) def image_read_typed(self, dim, t1, img, idx, dmask, vdata, d16, read, view=None): """Read an image using the component type selected by FORMAT in T# word 1. @@ -11271,29 +11394,25 @@ def write(v4u, numeric_class): self.emit(f"{w} = OpBitwiseOr %uint {xs[i]} {hi}") self.dst(dest, w) - def read_integer(cls, ty): - im = view(cls) + def read_view(cls, ty): + texel = read(view(cls), cls, ty) b = self.tmp() - r = read(im, cls, ty) - self.emit(f"{b} = OpBitcast %v4uint_st {r}") + self.emit(f"{b} = OpBitcast %v4uint_st {texel}") write(b, cls) self.emit(f"OpSelectionMerge {L['e2']} None") self.emit(f"OpBranchConditional {use_s} {L['s']} {L['rest']}") self.emit(f"{L['s']} = OpLabel") - read_integer(2, "%v4int_st") + read_view(2, "%v4int_st") self.emit(f"OpBranch {L['e2']}") self.emit(f"{L['rest']} = OpLabel") self.emit(f"OpSelectionMerge {L['e3']} None") self.emit(f"OpBranchConditional {use_u} {L['u']} {L['f']}") self.emit(f"{L['u']} = OpLabel") - read_integer(1, "%v4uint_st") + read_view(1, "%v4uint_st") self.emit(f"OpBranch {L['e3']}") self.emit(f"{L['f']} = OpLabel") - res = read(view(0), 0, "%v4float") - b = self.tmp() - self.emit(f"{b} = OpBitcast %v4uint_st {res}") - write(b, 0) + read_view(0, "%v4float") self.emit(f"OpBranch {L['e3']}") self.emit(f"{L['e3']} = OpLabel") self.emit(f"OpBranch {L['e2']}") @@ -11383,6 +11502,11 @@ def image_store(self, a, mods, dim): self.emit(f"{v4u} = OpCompositeConstruct %v4uint_st {' '.join(uv)}") self.emit(f"{v4s} = OpCompositeConstruct %v4int_st {' '.join(sv)}") act = self.active_b() + if di >= 2: # no writes to the shared fallback or to R32_UINT-backed logical RGB9E5 + found, unpacked = self.tmp(), self.tmp() + self.emit(f"{found} = OpINotEqual %bool {idx} {self.cu(0)}") + self.emit(f"{unpacked} = OpLogicalNot %bool {self.packed_uav(a[2])}") + act = self.emit_land(act, self.emit_land(found, unpacked)) L = {k: self.tmp() + "_" + k for k in ("do", "end", "s", "rest", "e2", "u", "f", "e3")} def write(cls, texel): @@ -11451,7 +11575,7 @@ def resinfo_words(self, img, level, array_query, word3): vals[i] = kept return vals + [lv] - def emit_image_atomic_extra(self, op, ip, iv, vdata, mods): + def emit_image_atomic_extra(self, op, idx, iv, vdata, mods, *, volume_active=None): """Lower 32-bit image_atomic_{swap,inc,dec,fmin,fmax,fcmpswap} on an r32ui storage image (2D or 3D). Inactive lanes skip the op and preserve vdata. CAS loops use OpAtomicLoad (valid on Image pointers) + OpAtomicCompareExchange, requiring no shader float atomic extension.""" @@ -11460,12 +11584,16 @@ def emit_image_atomic_extra(self, op, ip, iv, vdata, mods): raise Unsupported(op + " operands") val = self.load_reg("vgpr", vdata["r"]) cmpv = self.load_reg("vgpr", vdata["r"] + 1) if op == "image_atomic_fcmpswap" else None - act = self.active_b() + act = self.active_b() if volume_active is None else volume_active lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" self.emit(f"OpSelectionMerge {lbl_end} None") self.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}") self.emit(f"{lbl_do} = OpLabel") - tp = self.tmp() + ip, tp = self.tmp(), self.tmp() + if volume_active is None: + self.emit(f"{ip} = OpAccessChain %_ptr_UC_simg %simages {idx}") + else: + self.emit(f"{ip} = OpAccessChain %_ptr_UC_simg3 %simages3d {idx}") self.emit(f"{tp} = OpImageTexelPointer %_ptr_Image_uint {ip} {iv} {self.cu(0)}") sc, sem = self.cu(1), self.cu(0) if op == "image_atomic_swap": @@ -11565,31 +11693,42 @@ def image_misc(self, op, a, mods): if op == "image_store": self.image_store(a, mods, dim) return - if op == "image_load_mip" and "glc" in mods: - # A coherent read of one mip: image_load_coherent reads a storage view, which has one level. - raise Unsupported("image_load_mip glc") - if op == "image_load_mip" and dim == "dim:SQ_RSRC_IMG_3D" and "a16" not in mods: - # x, y, z, mip from a 3D sampled image (binding 6) - if "d16" in mods and ("tfe" in mods or "lwe" in mods): + if op == "image_load_mip": + if "glc" in mods: + raise Unsupported("image_load_mip glc") # the coherent storage view has only one mip + # x, y[, z], mip. All sampled aliases fetch that LOD; only a tagged volume UAV restricts it to zero. + is3d = dim == "dim:SQ_RSRC_IMG_3D" + ncoord = 3 if is3d else 2 + packed = "a16" in mods + status = "tfe" in mods or "lwe" in mods + if (not is3d and dim != "dim:SQ_RSRC_IMG_2D") or (packed and (is3d or status)): + raise Unsupported(op + " " + dim.split("SQ_RSRC_IMG_")[-1]) + if is3d and status and "d16" in mods: raise Unsupported("image_load_mip d16 status") vdata, addr = a[0], self.addr_regs(a[1]) - if len(addr) < 4: + words = 2 if packed else ncoord + 1 + if len(addr) < words: raise Unsupported("image_load_mip coords") idx = self.desc_lookup_sgpr(a[2], 8) - self.uses_tex_3d = True ip, img, iv = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{ip} = OpAccessChain %_ptr_UC_img3 %images_3d {idx}") - self.emit(f"{img} = OpLoad %img3d {ip}") - xs = [self.as_int(self.load_reg("vgpr", r)) for r in addr[:4]] - self.emit(f"{iv} = OpCompositeConstruct %v3int {xs[0]} {xs[1]} {xs[2]}") + if is3d: + self.uses_tex_3d = True + self.emit(f"{ip} = OpAccessChain %_ptr_UC_img3 %images_3d {idx}") + self.emit(f"{img} = OpLoad %img3d {ip}") + else: + self.emit(f"{ip} = OpAccessChain %_ptr_UC_img %images {idx}") + self.emit(f"{img} = OpLoad %img2d {ip}") + raw = [self.load_reg("vgpr", r) for r in addr[:words]] + if packed: + raw = self.unpack_image_a16_uints(raw) + *coords, lod = [self.as_int(c) for c in raw[:ncoord + 1]] + self.emit(f"{iv} = OpCompositeConstruct %v{ncoord}int {' '.join(coords)}") dm = next((m for m in mods if m.startswith("dmask:")), "dmask:0x1") - self.image_load_typed(dim, self.sgpr_word(a[2], 1), iv, img, idx, int(dm.split(":")[1], 0), - vdata, xs[3], d16="d16" in mods) + self.image_load_typed(dim, a[2], iv, img, idx, int(dm.split(":")[1], 0), vdata, + lod=lod, d16="d16" in mods) return - packed_mip = op == "image_load_mip" and "tfe" not in mods and "lwe" not in mods if ((dim != "dim:SQ_RSRC_IMG_2D" and not (is3d_atomic or array_query)) - or ("a16" in mods and not (is_atomic or packed_mip)) - or ("d16" in mods and op != "image_load_mip")): + or ("a16" in mods and not is_atomic) or "d16" in mods): raise Unsupported(op + " " + dim.split("SQ_RSRC_IMG_")[-1]) vdata, addr = a[0], self.addr_regs(a[1]) idx = self.desc_lookup_sgpr(a[2], 8) @@ -11613,34 +11752,39 @@ def atomic_coords(nc): # 3D r32ui storage image atomics (binding 7). self.uses_storage3d = True coords = atomic_coords(3) - iv, ip = self.tmp(), self.tmp() + iv, found, fmt, r32 = (self.tmp() for _ in range(4)) self.emit(f"{iv} = OpCompositeConstruct %v3int {coords[0]} {coords[1]} {coords[2]}") - self.emit(f"{ip} = OpAccessChain %_ptr_UC_simg3 %simages3d {idx}") + self.emit(f"{found} = OpINotEqual %bool {idx} {self.cu(0)}") + t1 = self.sgpr_word(a[2], 1) + self.emit(f"{fmt} = OpBitFieldUExtract %uint {t1} {self.cu(20)} {self.cu(9)}") + self.emit(f"{r32} = OpIEqual %bool {fmt} {self.cu(self.R32_UINT)}") + uav, _ = self.synthetic_uav(a[2]) + run = self.emit_land(self.active_b(), self.emit_land(found, self.emit_land(r32, uav))) if op in self.IMG_ATOMICS_EXTRA: - self.emit_image_atomic_extra(op, ip, iv, vdata, mods) + self.emit_image_atomic_extra(op, idx, iv, vdata, mods, volume_active=run) return - tp, old, safe = self.tmp(), self.tmp(), self.tmp() + ip, tp, old = self.tmp(), self.tmp(), self.tmp() val = self.load_reg("vgpr", vdata["r"]) + do, skip, end = (self.tmp() + suffix for suffix in ("_do", "_skip", "_end")) + self.emit(f"OpSelectionMerge {end} None") + self.emit(f"OpBranchConditional {run} {do} {skip}") + self.emit(f"{do} = OpLabel") + self.emit(f"{ip} = OpAccessChain %_ptr_UC_simg3 %simages3d {idx}") + self.emit(f"{tp} = OpImageTexelPointer %_ptr_Image_uint {ip} {iv} {self.cu(0)}") if op == "image_atomic_cmpswap": cmpv = self.load_reg("vgpr", vdata["r"] + 1) - act = self.active_b() - do, end = self.tmp() + "_do", self.tmp() + "_end" - self.emit(f"OpSelectionMerge {end} None") - self.emit(f"OpBranchConditional {act} {do} {end}") - self.emit(f"{do} = OpLabel") - self.emit(f"{tp} = OpImageTexelPointer %_ptr_Image_uint {ip} {iv} {self.cu(0)}") self.emit(f"{old} = OpAtomicCompareExchange %uint {tp} {self.cu(1)} {self.cu(0)} {self.cu(0)} {val} {cmpv}") - if "glc" in mods: - self.dst({"k": "vgpr", "r": vdata["r"], "n": 1}, old) - self.emit(f"OpBranch {end}") - self.emit(f"{end} = OpLabel") - return - spv, neutral = self.IMG_ATOMICS[op] - self.emit(f"{tp} = OpImageTexelPointer %_ptr_Image_uint {ip} {iv} {self.cu(0)}") - self.emit(f"{safe} = OpSelect %uint {self.active_b()} {val} {self.cu(neutral)}") - self.emit(f"{old} = {spv} %uint {tp} {self.cu(1)} {self.cu(0)} {safe}") + else: + spv, _ = self.IMG_ATOMICS[op] + self.emit(f"{old} = {spv} %uint {tp} {self.cu(1)} {self.cu(0)} {val}") + self.emit(f"OpBranch {end}") + self.emit(f"{skip} = OpLabel") + self.emit(f"OpBranch {end}") + self.emit(f"{end} = OpLabel") if "glc" in mods: - self.dst({"k": "vgpr", "r": vdata["r"], "n": 1}, old) + result = self.tmp() + self.emit(f"{result} = OpPhi %uint {old} {do} {self.cu(0)} {skip}") + self.dst({"k": "vgpr", "r": vdata["r"], "n": 1}, result) return if op == "image_store": self.image_store(a, mods, dim) @@ -11651,11 +11795,11 @@ def atomic_coords(nc): coords = atomic_coords(2) iv = self.tmp() self.emit(f"{iv} = OpCompositeConstruct %v2int {coords[0]} {coords[1]}") - ip = self.tmp() - self.emit(f"{ip} = OpAccessChain %_ptr_UC_simg %simages {idx}") if op in self.IMG_ATOMICS_EXTRA: - self.emit_image_atomic_extra(op, ip, iv, vdata, mods) + self.emit_image_atomic_extra(op, idx, iv, vdata, mods) return + ip = self.tmp() + self.emit(f"{ip} = OpAccessChain %_ptr_UC_simg %simages {idx}") val = self.load_reg("vgpr", vdata["r"]) if op == "image_store": # Writes dmask component 0 as r32ui; only active lanes store. @@ -11718,19 +11862,6 @@ def atomic_coords(nc): self.dst({"k": "vgpr", "r": vdata["r"] + out, "n": 1}, u) out += 1 return - # image_load_mip: x, y, mip, with the same typed SRV as image_load. - packed = "a16" in mods - if len(addr) < (2 if packed else 3): - raise Unsupported("image_load_mip coords") - if packed: - words = [self.load_reg("vgpr", r) for r in addr[:2]] - xs = [self.as_int(c) for c in self.unpack_image_a16_uints(words)[:3]] - else: - xs = [self.as_int(self.load_reg("vgpr", r)) for r in addr[:3]] - iv = self.tmp() - self.emit(f"{iv} = OpCompositeConstruct %v2int {xs[0]} {xs[1]}") - self.image_load_typed(dim, self.sgpr_word(a[2], 1), iv, img, idx, dmask, vdata, xs[2], d16="d16" in mods) - def interp_pair_src(self, op, a, ins): """SHADER-177: the VGPR source of a v_interp_p1/p2 is the barycentric coordinate that op interpolates @@ -12689,6 +12820,7 @@ def store_floats(base, values): def assemble(gen): + store_dims = gen.uses_store_views | gen.uses_store_reads vs = gen.stage == "vs" cs = gen.stage == "cs" ms = gen.stage == "ms" @@ -12741,9 +12873,10 @@ def assemble(gen): [f"%ms_out_f16h{n}_{h}" for n in ms_halves for h in (0, 1)])) if ms else []) + ( ["%x_buf"] if gen.emulate or gen.bar_rounds and not gen.bar_counts_in_lds() else []) + ( ([("%gs_in_pos" if sv == 1 else f"%gs_in{r}") for r, sv in gen.gs["in"]] + - [("%gs_out_pos" if sv == 1 else f"%gs_out{r}") for r, sv in gen.gs["out"]]) if gsx else []) + (["%fmt_uint_mask", "%fmt_sint_mask"] if gen.uses_store_views or gen.uses_int_fetch else []) + \ + [("%gs_out_pos" if sv == 1 else f"%gs_out{r}") for r, sv in gen.gs["out"]]) if gsx else []) + ( + ["%fmt_uint_mask", "%fmt_sint_mask"] if store_dims or gen.uses_int_fetch else []) + \ (["%fmt_size_tab"] if gen.uses_fmt_size else []) + \ - [f"%stv{c}_{d}" for d in sorted(gen.uses_store_views) for c in range(3)] + \ + [f"%stv{c}_{d}" for d in sorted(store_dims) for c in range(3)] + \ [f"%itx{c}_{d}" for d in sorted(gen.uses_int_fetch) for c in (1, 2)] psb = gen.uses_psb tex = gen.uses_tex @@ -12813,10 +12946,10 @@ def assemble(gen): caps.append("ShaderClockKHR") if gen.uses_store_views: caps.append("StorageImageWriteWithoutFormat") # shaderStorageImageWriteWithoutFormat - if gen.reads_store_views: - caps.append("StorageImageReadWithoutFormat") # shaderStorageImageReadWithoutFormat: coherent image_load - if 3 in gen.uses_store_views: - caps.append("Image1D") + if gen.uses_store_reads: + caps.append("StorageImageReadWithoutFormat") # shaderStorageImageReadWithoutFormat + if store_dims.intersection((3, 4)): + caps.append("Image1D") if vs: caps.append("DrawParameters") # BaseVertex / BaseInstance (shaderDrawParameters), see the seeding of v0 / v3 if gsx: @@ -13075,11 +13208,11 @@ def assemble(gen): sizes = [Gen.FORMATS[c][0] if c in Gen.FORMATS else 0 for c in range(128)] types += [f"%fmt_size_arr = OpTypeArray %uint {gen.cu(128)}", "%_ptr_Private_fmt_size = OpTypePointer Private %fmt_size_arr"] - if not (gen.uses_store_views or gen.uses_int_fetch): + if not (store_dims or gen.uses_int_fetch): types += ["%_ptr_Private_uint = OpTypePointer Private %uint"] types += ["%fmt_size_init = OpConstantComposite %fmt_size_arr " + " ".join(gen.cu(v) for v in sizes)] gvars += ["%fmt_size_tab = OpVariable %_ptr_Private_fmt_size Private %fmt_size_init"] - if gen.uses_store_views or gen.uses_int_fetch: + if store_dims or gen.uses_int_fetch: u, si = Gen.int_format_masks() types += ["%v4uint_st = OpTypeVector %uint 4", "%v4int_st = OpTypeVector %int 4", f"%fmt_mask_arr = OpTypeArray %uint {gen.cu(16)}", @@ -13104,14 +13237,16 @@ def assemble(gen): dec += [f"OpDecorate %itx{cls}_{di} DescriptorSet 0", f"OpDecorate %itx{cls}_{di} Binding {Gen.SAMPLED_BINDINGS[di]}"] gvars += [f"%itx{cls}_{di} = OpVariable %_ptr_UC_rt_itx{cls}_{di} UniformConstant"] - for di in sorted(gen.uses_store_views): + for di in sorted(store_dims): _, sdim, arr, _ = next(v for v in Gen.STORE_DIMS.values() if v[0] == di) + # Keep the runtime's multisample SRV bindings (20–25); 1D-array storage follows them. + base = 26 if di == 4 else 8 + 3 * di for cls, st in enumerate(("%float", "%uint", "%int")): types += [f"%stimg{cls}_{di} = OpTypeImage {st} {sdim} 0 {arr} 0 2 Unknown", f"%rt_stv{cls}_{di} = OpTypeRuntimeArray %stimg{cls}_{di}", f"%_ptr_UC_rt_stv{cls}_{di} = OpTypePointer UniformConstant %rt_stv{cls}_{di}", f"%_ptr_UC_stv{cls}_{di} = OpTypePointer UniformConstant %stimg{cls}_{di}"] - dec += [f"OpDecorate %stv{cls}_{di} DescriptorSet 0", f"OpDecorate %stv{cls}_{di} Binding {8 + 3 * di + cls}"] + dec += [f"OpDecorate %stv{cls}_{di} DescriptorSet 0", f"OpDecorate %stv{cls}_{di} Binding {base + cls}"] if gen.coherent_images: dec.append(f"OpDecorate %stv{cls}_{di} Coherent") gvars += [f"%stv{cls}_{di} = OpVariable %_ptr_UC_rt_stv{cls}_{di} UniformConstant"] @@ -14458,6 +14593,10 @@ def translate(path): else: check_printed_encodings(path, info) g = Gen(stage) + g.atomic_volume_tsharps = {g.tsharp_regs(i["args"][2]) for i in insns + if base_op(i["op"]) in (*Gen.IMG_ATOMICS, *Gen.IMG_ATOMICS_EXTRA, "image_atomic_cmpswap") + and "dim:SQ_RSRC_IMG_3D" in i["mods"] + and len(i["args"]) >= 3 and i["args"][2]["k"] in ("sgpr", "slist")} if stage in ("vs", "ms"): # --f16-interp-fallback places the decoded halves clear of every param g.param_max = max((int(t[5:]) for i in insns if base_op(i["op"]) == "exp" for t in (i["args"][0].get("t", ""),) if t.startswith("param") and t[5:].isdigit()), default=-1) From 1e63e096805a779a61f31715da5498d9864da116 Mon Sep 17 00:00:00 2001 From: Almogaver295 <133548141+guimsolutions@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:33:16 +0100 Subject: [PATCH 002/110] test(vulkan): exercise D3D-78 texture UAVs in the GPU runner Register the descriptor smoke test with CTest and run synthetic dispatches against the real bindless set and WARP. Cover sliced-volume atomics, typed mip loads, and runner failure/skip handling; document the ABI, limits, and test procedure. Reconstructs 6429d472, 8dc50af2, and the test and documentation resolutions through a56b8589. --- docs/d3d12_vulkan.md | 96 +++-- docs/design.md | 6 +- docs/testing.md | 24 +- runtime/CMakeLists.txt | 9 + runtime/test/d3d12_texture_uav_oracle.h | 279 +++++++++++++ runtime/test/d3d12_texture_uav_test.cpp | 533 ++++++++++++++++++++++++ runtime/test/shaders/check.py | 29 +- runtime/test/shaders/cs_imgload_mip.asm | 44 ++ runtime/test/shaders/cs_texture_uav.asm | 95 +++++ scripts/run_gpu_tests.py | 29 +- tests/test_run_gpu_tests.py | 70 ++++ tests/test_shader_checks.py | 26 +- 12 files changed, 1183 insertions(+), 57 deletions(-) create mode 100644 runtime/test/d3d12_texture_uav_oracle.h create mode 100644 runtime/test/d3d12_texture_uav_test.cpp create mode 100644 runtime/test/shaders/cs_imgload_mip.asm create mode 100644 runtime/test/shaders/cs_texture_uav.asm diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 9de1527b94..649b5bd30d 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -531,7 +531,8 @@ What is implemented (all of it testable without the game): Descriptors and the bindless set (milestone M2, without the pipelines that will bind the set), from the shader's side inwards: -- **`runtime/src/vulkan_bindless.h`**: set 0 includes the twenty bindings the translator declares, and +- **`runtime/src/vulkan_bindless.h`**: set 0 includes the single-sample bindings the translator declares, optional + multisample bindings, and `DescriptorTable` (`runtime/src/descriptor_table.h`, section 5.1) behind binding 2. One set for the device. The translator declares every array as a runtime array, so the counts are the runtime's choice. Details: - The device sizes the arrays once, when it creates the set. It does not recreate the set, because pipeline @@ -545,7 +546,7 @@ side inwards: - samplers: up to 4096, and at most `maxSamplerAllocationCount` less 64 for samplers outside the set. That covers a full 2048-sampler D3D12 heap plus room for literal and static S#s. - 2D images: up to 65536. - - storage arrays: up to 4096 each. + - storage arrays: up to 4096 each, capped by their dimension's sampled array or by 256 for storage-only 1D arrays. Growth leaves 64 descriptors of each limit to the other sets of a pipeline layout. It also stays within `maxPerSetDescriptors`, which never shrinks the default counts, because a layout past it may still be @@ -561,17 +562,19 @@ side inwards: shader reads the fallback. `d3d12_descriptor_test` then fills each short array to its last index and checks that the next view and sampler are refused. The other arrays keep their default counts. On an RTX 5070 (driver 621.24, 1048576 of each type - and 4000 samplers) the set has 65536 2D images, 3936 samplers and 4096 storage indices in 2D: 93793 - descriptors, 3-6 MiB at 32-64 bytes a descriptor. The device prints the counts it chose, and - `bindless_sizing_test` checks the rules on synthetic limits. - - An image has one index in its dimension (2D, 2D array, 3D, 1D, 2DMS or 2DMS array), shared by the + and 4000 samplers) the sizing rules give 65536 2D images, 3936 samplers and 4096 storage indices in 2D: + 94561 descriptors with all MS classes, 3-6 MiB at 32-64 bytes a descriptor. The device prints the counts + it chose, and `bindless_sizing_test` checks the rules on synthetic limits. + - An image view has one index in its dimension (2D, 2D array, 3D, 1D, 2DMS, 2DMS array or 1D array), shared by the bindings for that dimension. The runtime adds sampled-image bindings in pairs for 2DMS and 2DMS array: 20/21 for floating-point and normalized color, 22/23 for unsigned integers, and 24/25 for signed integers. The runtime enables pairs that fit the device's descriptor limits and have a multisampled zero fallback of the matching numeric class. A missed key reads zero at texel (0, 0), layer 0, sample 0. + The 1D-array dimension uses storage bindings 26–28 and has no sampled binding. - The storage arrays are shorter (`BindlessSet::storage_capacity`). Each array holds at most as many images as its dimension, and the 2D r32ui array is the same size as the other 2D storage arrays. So an image with a storage view gets an index the storage arrays hold, and a read-only one goes above where there is room. + Index 0 is reserved, so 256 descriptors hold 255 live views in each 1D-array storage binding. - Index 0 of every array is a fallback (a 1x1 image of zeros, a nearest clamping sampler), because a miss is index 0. - Changes are queued and written by `flush()`, one write a slot, so a view that is removed before the next @@ -583,8 +586,9 @@ side inwards: (every lookup, CPU and shader, compares all eight probe slots and never stops at an empty one), so it is uploaded like an add. Replacing a live key's index, an insert that relocates a live entry, and a table that has grown (a new buffer behind binding 2) change what running lookups see: `flush_needs_idle()` says when a - flush would do one of those, and the device waits for the queue before flushing in that case. Erasing used to - compact the probe cluster, which moved other keys and made every texture release wait for the whole GPU. + flush would do one of those, and the layer waits for the device to be idle before flushing in that case. + Erasing used to compact the probe cluster, which moved other keys and made every texture release wait for + the whole GPU. - **`runtime/src/gfx10_descriptors.h`**: the T#, S# and V# structures (section 5.3), encoded and decoded, with their mapping to Vulkan formats, view types, component mappings and samplers. Field positions are Mesa's (`src/amd/registers/gfx10-rsrc.json`) and agree with what the translator and the GPU tests already use. Bits @@ -592,8 +596,8 @@ side inwards: written as zero. - **Device**: `CreateShaderResourceView` and `CreateUnorderedAccessView` of textures write a T# into the slot, `CreateSampler` an S#; each then makes sure set 0 has the view or sampler and the table has the key. Details: - - The key is the descriptor's bytes, so a copied descriptor needs nothing more, and an unordered-access view - and a shader-resource view of the same mip are one entry. + - The key is the descriptor's bytes, so a copied descriptor needs nothing more. An SRV and UAV with identical + bytes can share an entry; a partial 3D UAV carries a W-range tag and remains separate from the unsliced SRV. - A D3D12 comparison sampler with function NEVER and an ordinary sampler both encode zero in the hardware depth comparison field. The layer marks the NEVER comparison in S# word 3, bit 12 (unused with DERIV_ADJUST_EN clear) to give it a separate lookup key and a comparison-enabled Vulkan sampler. @@ -609,7 +613,7 @@ side inwards: images and storage buffers. The standalone device enables them where the GPU has them. - Every `ExecuteCommandLists` flushes the set before its commands are written. - `rt::d3d12::bindless_set` and `bindless_set_layout` hand out the set and its layout: what a pipeline whose - shader declares set-0 bindings is created with and binds. Nothing in the layer creates such a pipeline yet. + shader declares set-0 bindings is created with and binds. - **Layouts.** A descriptor in set 0 has one image layout for as long as it lives, but D3D12 lets a texture be sampled in a shader-resource state and also while promoted from `COMMON`, which is `GENERAL` here (section 4.3). So with the bindless set, a texture's shader-resource states use `GENERAL` too @@ -630,7 +634,7 @@ volume, plus minimum-LOD clamped views (inside the mip range via `VK_EXT_image_v Known gaps in the descriptor path: buffer shader-resource views and constant-buffer views (the V# a shader would load for them; the structure is in `gfx10_descriptors.h`, the views are not written; buffer UAVs of every kind are, section 3.4 "Buffer UAVs", `d3d12_m4_compute_test` and `d3d12_buffer_uav_test`); -1D-array SRVs, 1D and 3D storage views, other typeless volume formats, multisampled depth/stencil and typeless +1D-array SRVs, other typeless volume formats, multisampled depth/stencil and typeless color SRVs, and shader-translator lowering for multisample loads. Single-sampled depth-plane views (`R24_UNORM_X8_TYPELESS`, `R32_FLOAT_X8X24_TYPELESS`) are a T# of the texture's depth format (8_24_UNORM, X24_8_32_FLOAT) through the depth aspect (the texture's backing format, so X24_8_32_FLOAT for a D24 texture where the layer stores it as @@ -642,17 +646,11 @@ the game writes itself, which need the execute-time scan of section 3.4 (only descriptors made through the device are registered); the literal S#s of shaders (`literal_samplers` in the index), which `rt::d3d12::register_samplers` registers without a heap slot but which nothing passes to it yet (the call at pipeline creation comes with the shader index, #291); -custom border colours without VK_EXT_custom_border_color, and minimum/maximum filters, anisotropy or mirror-once addressing without the Vulkan -feature, each logged and approximated (note: in Vulkan, `VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_MINMAX_BIT` is -per-format; because bindless set 0 hashes `T#` and `S#` independently in the shader, `bind_sampler` cannot know -which image format a sampler will be paired with — on Radeon iGPUs `BC*` formats lack `MINMAX` while uncompressed -formats support it, whereas RTX supports all queried formats); the storage arrays hold 255 images a dimension at the default counts, more -where the device has room (4095 2D and 1023 2D-array on an RTX 5070); nothing writes through a -storage view in a D3D12-level test yet (`vk_bindless_test` goes through the storage bindings at the Vulkan -level). The set is flushed at every `ExecuteCommandLists`; a flush that erases keys or moves the table to a larger -buffer (`BindlessSet::flush_needs_idle()`) first waits for the device to be idle and then frees the retired table -buffers, so no running lookup misses (D3D-76). That wait stalls every queue, which is correct but slow if the game -destroys textures every frame; a per-queue wait is open. +custom border colours without `VK_EXT_custom_border_color`, and minimum/maximum filters, anisotropy or mirror-once +addressing without the corresponding Vulkan feature, each logged and approximated. In Vulkan, +`VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_MINMAX_BIT` is per-format; because bindless set 0 hashes T# and S# +independently, `bind_sampler` cannot know which format the sampler will be paired with. On tested Radeon iGPUs +`BC*` formats lacked `MINMAX` while uncompressed formats supported it; RTX supported all queried formats. A typed 3D color target supports default and explicit RTVs. The default covers mip 0; `FirstWSlice` and `WSize` select the depth slices in an explicit view's mip. `d3d12_clear_test --volume` checks full and @@ -1112,13 +1110,19 @@ and any validation error fails them. - That set 0 holds them: a compute shader (`test/glsl/cs_sample.comp`, GLSL, compiled with `glslangValidator`; skipped without it) is handed a slot's T# and the sampler's S#, looks them up in the hash table as a translated shader does, and samples. The sampler wraps in U and the shader samples one tile to the right, - so a missed S# shows too: the fallback sampler clamps. The layer has no pipelines yet, so the test creates - this one in Vulkan and binds the device's set. It reads the texture through the view's own slot and through + so a missed S# shows too: the fallback sampler clamps. The test creates the pipeline in Vulkan and binds + the device's set. It reads the texture through the view's own slot and through a copy of it, and gets the fallback from a slot of bytes no view was made for and, after the texture is destroyed, from the view's own bytes. - Capacity: 5000 distinct SRVs of that texture and one more, and 2100 distinct wrapping samplers in two 2048-slot heaps. The last view through the last sampler reads the texture one tile to the right. With the sizes of before, both were past their arrays ("array is full") and the shader read the fallback. +- `d3d12_texture_uav_test` (D3D-78): creates 1D, 1D-array, 3D and 2D control UAVs through the D3D12 device, + checks rejected descriptors, copies descriptors between slots, and dispatches a translated hand-written + shader from a Vulkan compute pipeline on the actual set 0, not through D3D12 `Dispatch`. It reads back every + texel; the UINT read/modify/write cases (not atomics) also run on Windows WARP. The D3D12 command-list path + is used separately to flush the set and to test clears. + The tests dispatch past the selected array/W range, so writes to an adjacent layer or slice fail the check. - `d3d12_compute_test`: the compute path through the proxy. It creates a root signature from the PC serializer's blob, and a PSO through slot 62 from a container shaped like the game's, found in a translator-style index by its FSSM hash (an unknown program is refused). It sets root constants, a root UAV and a descriptor table whose @@ -1436,10 +1440,30 @@ The layer's descriptor model: If the logical device lacks the feature, the runtime logs the unsupported view and its descriptor resolves to the fallback. A clamp at or below the first mip needs no extension. Above the last mip, the view retains its dimensions and maps sampled channels to zero while preserving constant channels. +- D3D-78: a `Texture1DArray` UAV gets a 1D-array view with the requested array subrange and storage bindings + 26–28 (float, UINT, SINT); `ArraySize = UINT_MAX` selects the remaining layers. A non-array `Texture1D` + view of a 1D array selects layer 0, as checked on native D3D12. A `Texture3D` UAV gets a 3D view with a single mip + and Vulkan array range `{0, 1}`. + A partial W range requires `VK_EXT_image_sliced_view_of_3d` and `robustImageAccess` on the logical device: + `VkImageViewSlicedCreateInfoEXT` rebases storage-image Z to `FirstWSlice` and limits it to `WSize` (`UINT_MAX` + means the remaining mip depth). It does not slice the sampled view. The generated T# tags the W range for + whole-mip and partial UAVs, distinguishes them from SRVs in the hash table, and rebases typed sampled fetches; + see the contract in `docs/design.md`. + Without those features a partial W view is logged and left null, not made writable across the whole mip. + These new dimensions require storage-write-without-format support for the typed view format and, for the + storage-only 1D array bindings, storage-read-without-format as well. Vulkan 1.3 permits the + SPIR-V capabilities even when the legacy `shaderStorageImage{Read,Write}WithoutFormat` bits are not enabled; + the caller-owned device test leaves both bits off and checks the per-format path. + `ClearUnorderedAccessView*` refuses partial W ranges and 1D/3D format reinterprets: the transfer clear + cannot target a slice interval or guarantee preserving the reinterpreted bits. + Shader access to the new UAVs requires `robustImageAccess` (whole-mip CPU clears do not). + A separate native D3D12 probe on the RTX 4090 and UHD 770 clipped typed writes to the view's W range. + WARP 10.0.26100.9818 rebased the view but did not clip writes past a finite `WSize` in that probe. The + regression compares in-range writes with WARP and checks preservation of out-of-range slices independently. - Set 0 is a fixed bindless layout, sized once when the device creates it. The defaults are 4096 sampled 2D images, 1024 samplers, 1024 2D-array images, 256 1D, 256 3D and 256 per storage dimension/class. The 2D, sampler and - storage arrays grow to what the device's limits allow, up to 65536, 4096 and 4096 (see `vulkan_bindless.h` - above). The set is not recreated to grow, because recreating it would invalidate the pipeline + storage arrays grow to what the device's limits allow, up to 65536, 4096 and 4096 (1D-array storage stays + capped at 256; see `vulkan_bindless.h` above). The set is not recreated to grow, because recreating it would invalidate the pipeline layouts built on it. Use `UPDATE_AFTER_BIND` and `PARTIALLY_BOUND` so a new view does not require rewriting every descriptor; without those features, rebuild the set when it changes. - The command buffer binds set 0 once; descriptor-heap changes only update the arrays and the hash table. @@ -1774,13 +1798,13 @@ The trace will enumerate them. rules then apply, as native D3D12 reports them (RX 9070 XT, AMD 26.11.2, and WARP): - `MIP` wherever the image can have more than one level. - `SHADER_GATHER` with `SHADER_SAMPLE` (not `A8_UNORM`, whose swizzled view isn't verified for gathers). - - `UAV_TYPED_LOAD` with every typed UAV. Typed UAV texture reads use the sampled binding (`image_read_typed`), - not a storage-image read. Typed buffer UAVs: the layer now writes their V# (section 3.4, "Buffer UAVs"); the - gap left is `rdna2spirv.py` `FORMATS`, which decodes only some buffer formats (the 32-bit SINT ones, but no - 8/16-bit SINT/UINT other than the RGBA8 and RGBA16 UINT ones, and no 10_11_11). - - The UAV atomic bits other than exchange for `R32_UINT`, whose UAV views get the `r32ui` storage view. Today - that works on 2D UAVs only: the translator's image atomics and the `r32ui` slots cover 2D and 3D, and the - layer creates no 3D UAV views yet. There is no `image_atomic_swap`, and `R32_SINT` gets no `r32ui` view. + - `UAV_TYPED_LOAD` with every typed UAV. Typed UAV texture reads normally use the sampled binding + (`image_read_typed`); storage-only 1D arrays and loads that need storage visibility use storage-image reads. + Typed buffer UAVs: the layer writes their V# (section 3.4, "Buffer UAVs"); `rdna2spirv.py` `FORMATS` + determines which buffer formats the translator can decode. + - The UAV atomic bits other than exchange for `R32_UINT` where Vulkan reports storage image atomics. + The translator and set 0 use the formatted `r32ui` views for 2D and 3D. There is no `image_atomic_swap`, + and `R32_SINT` gets no `r32ui` view. - `MULTISAMPLE_RENDERTARGET` for depth formats, from the same usages `MULTISAMPLE_QUALITY_LEVELS` queries. - No integer resolve, no 1D block-compressed. Depth formats are 2D and cube only: no 3D, shader reads, UAVs, buffer or vertex use, and no 1D, which native D3D12 allows but the layer's resource creation refuses. @@ -2958,9 +2982,9 @@ store, load, mesh, geometry and BVH tests; this layer is the other half. | `heap_base` (dwords 32–33) | The arena's `vkGetBufferDeviceAddress`. One value per command buffer; updated only if the arena is recreated. | | `code_base` (dwords 34–35) | The console VA of the current shader's FSSM blob in the arena. Per-stage conflict: see below. | | Descriptor hash table (set 0, binding 2) | `uint mask` + entries of `key[8], index, pad`; FNV-1a over the 8 key dwords; linear probe up to 8; miss = index 0. Implemented in `runtime/src/descriptor_table.h` (`DescriptorTable`). The layer inserts every T#/S# it sees and keeps a fallback image/sampler at index 0. | -| Bindless images (bindings 0, 3, 5, 6) | 2D, 2D-array/cube, 1D, 3D sampled-image arrays; one `VkImageView` per distinct T#. Cube textures are 6-layer 2D arrays and cube arrays 6N-layer ones, as the translator expects. | +| Bindless images (bindings 0, 3, 5, 6) | 2D, 2D-array/cube, 1D, 3D sampled-image arrays; typed single-sample shader declarations alias the same binding numbers. Cube textures are 6-layer 2D arrays and cube arrays 6N-layer ones. The runtime also reserves optional MS SRV pairs at 20–25; the translator does not use them yet. | | Samplers (binding 1) | One `VkSampler` per distinct S#; literal S# values from shader constants are pre-registered. | -| Storage images (bindings 4, 7, 8–19) | r32ui/float/sint views by dimension and numeric class; the layer binds each storage image into the float/uint/sint arrays of its dimension (the translator picks by the T# format at run time), with all three arrays as the safe default. | +| Storage images (bindings 4, 7, 8–19, 26–28) | Bindings 4 and 7 are formatted `r32ui` for 2D and 3D atomics. Bindings 8–19 are float/UINT/SINT triples for 2D, 2D-array, 3D and 1D. Bindings 26–28 are the float/UINT/SINT triple for 1D arrays, which have no sampled binding. The translator picks the numeric class from the T# format; the arrays for a dimension share the same index. | | Buffer/image binding | Descriptors contain console VAs, never host BDAs. Buffers are in the arena at their VA; images are keyed by T# through the hash table. | | Vertex fetch | PSO input layout + ISG1 signature; location = D3D input register; format from `DXGI_FORMAT`; instance step rate from the layout. The fetch subroutine is already replaced by Vulkan inputs. | | PS system inputs | `FragCoord` (xy/z/w), `FrontFacing`, barycentrics; enable `fragmentShaderBarycentric` and `fragmentShaderPixelInterlock` when the index entry asks. | diff --git a/docs/design.md b/docs/design.md index d32503f1a8..6b04965c92 100644 --- a/docs/design.md +++ b/docs/design.md @@ -292,7 +292,7 @@ How the generated SPIR-V expects the runtime to work: | `v_med3_f32` output modifiers | The translator applies `mul:2`, `mul:4` or `div:2` to the median before clamping to [0, 1], following [LLVM’s modifier order](https://llvm.org/docs/AMDGPUModifierSyntax.html#omod). The finite-input fixture `ps_med3_mods.asm` produced 4,096 exact pixels on an Apple M3 Max with MoltenVK and on Mesa llvmpipe (software Vulkan); it also passes (4,096/4,096) on an NVIDIA RTX 4050 Laptop and an AMD Radeon 740M (RADV), both Linux, and on an RTX 2060 SUPER per #634. This uses the existing float MODE assumptions described above. | | `v_div_fmas_f32`, `v_div_fmas_f64` | Scaled FMA for IEEE-754 division (VOP3): `D = fma(S0, S1, S2)` when `VCC[lane] == 0`; when `VCC[lane] == 1`, `D = (exp(S2) > bias ? 2^+S : 2^-S) * fma_exact(S0, S1, S2)` where `(bias, S)` is `(127, 64)` for f32 and `(1023, 128)` for f64 (`OpCapability Float64`, no `Int64`), i.e. `\|S2\| >= 2.0` scales up and `\|S2\| < 2.0` scales down. Scale-up uses `fma(S0, S1, S2) * 2^S` (any non-zero cancellation residual against `\|S2\| >= 2.0` stays well above normal minimum). Scale-down pre-scales `S0`/`S1` only when `\|S0*S1\|` can overflow (`\|S0\| >= 2^S` and `\|S1\| >= 1`, symmetric, or both `>= 2^(S/2)`), with a raw-bit sticky value `copysign(min_normal, S2)` whenever `0 < \|S2\| < 2^(Emin + S)` so half-ULP tie-breaking stays exact; otherwise it post-scales `fma(S0, S1, S2) * 2^-S`, with a TwoSum + product-error half-ULP tie adjustment in f64 when `\|fma\|` falls in `[2^-947, 2^-894)` so f64 subnormal outputs single-round. For f32 under the game MODE (`denorm32=0`), subnormal inputs and intermediate products are kept while subnormal outputs flush to signed zero before (and after) output modifiers; for f64 (`denorm16_64=3`), subnormals are kept throughout. VOP3 input (`abs`/`neg`) and output (`mul:2`/`mul:4`/`div:2`, then `clamp`) modifiers apply via `clamp_mods` / `clamp_mods_f64`. **Until 2026-11-22 the translator scaled unconditionally by `2^32` (f32) / `2^64` (f64) whenever `VCC[lane] == 1`, omitting the `exp(S2) > bias` branch and using half the hardware exponent shift.** **Hardware-verified on RDNA2** (`gfx1036`, AMD Radeon Graphics, Windows driver 32.0.21042.62, `tools/hw_oracle`, wave32 and wave64, game MODE `ieee=0`/`dx10_clamp=1`/`denorm32=0`/`denorm16_64=3`): 150/150 f32 and 153/153 f64 stress cases match bit-for-bit, including the `\|S2\| = 2.0` vs `nextbelow(2.0)` threshold, scale-down overflow prevention, sticky-bit tie-breaking, f32 output denormal flushing, and f64 subnormal single rounding. Checked bit-for-bit on the CPU (`spirv_mini_interp` for f32, SSA `%double` evaluator for f64) and assembled with `tools/spirv_asm.py` (plus `spirv-val` when present) by `tests/semantic/test_alu_div_fmas.py`; not run on the shader corpus. | | POPS | Primitive-ordered pixel shading (10 PS, `src_pops_exiting_wave_id` wait loop, `s_sleep`, `MSG_ORDERED_PS_DONE`) becomes **fragment-shader interlock** (`PixelInterlockOrderedEXT`). It begins at the end of the entry block and ends at shader exit: a longer critical section with the same ordering. `src_pops_exiting_wave_id` reads 0, and **the runtime must put 0 (no collision, bit 31 clear) in the POPS collision SGPR**, so the hardware wait loop is skipped. Needs `VK_EXT_fragment_shader_interlock` (`fragmentShaderPixelInterlock`). | -| Coherent image accesses (`glc`) | On GFX10 a device-scope (coherent) load is `glc dlc` and a device-scope store `glc`: Mesa sets exactly these bits for `ACCESS_COHERENT` ([`ac_get_hw_cache_flags`](https://gitlab.freedesktop.org/mesa/mesa/-/blob/main/src/amd/common/ac_shader_util.c), GFX10–10.3 branch). In the corpus only the 10 POPS pixel shaders use them: 30 `image_load ... glc dlc` and 50 `image_store ... glc`, all 2D, and in each shader the 3 T#s it loads are the 3 it stores, a read-modify-write of its ordered images. A `glc` `image_load` therefore reads the **storage view the stores write** (`OpImageRead` on binding 8 + 3·dim + class, the class picked from the T# FORMAT as for stores), not the sampled array of "Typed image loads": a sampled read has no coherent form in SPIR-V, and between critical sections the fragment-shader interlock only makes coherent memory visible ([Vulkan memory model](https://docs.vulkan.org/spec/latest/appendices/memorymodel.html): non-atomic accesses are private unless `Coherent`; [ARB_fragment_shader_interlock](https://registry.khronos.org/OpenGL/extensions/ARB/ARB_fragment_shader_interlock.txt): stores to `coherent` memory in one critical section are visible to reads in the next). A shader with a `glc` image load or store decorates its storage views **`Coherent`**, as vkd3d-proton's dxil-spirv does for rasterizer-ordered views (`dxil_converter.cpp`: "ROV implies coherent"). These 10 modules need `shaderStorageImageReadWithoutFormat` (listed in their index features); every other `image_load` keeps the sampled path and needs no storage feature (SHADER-151). `dlc` alone is a CU-scope load and stays non-coherent; `glc` on a sampled read (`image_sample*`, `image_gather*`, `image_load_mip`) or on a dimension without storage views (cube) is `Unsupported`. Until 2026-11-22 the coherent loads read the sampled array and nothing was `Coherent`, so a POPS read could miss the previous fragment's store. Confirmed by these references, `tests/semantic/test_image_coherent.py` (each read and write's view and type, decorations, capabilities, index features; 7 of its 10 tests fail on the old translator) and a corpus count; **not GPU-checked**: a stale read is a cache race no deterministic test forces. | +| Coherent image accesses (`glc`) | On GFX10 a device-scope (coherent) load is `glc dlc` and a device-scope store `glc`: Mesa sets exactly these bits for `ACCESS_COHERENT` ([`ac_get_hw_cache_flags`](https://gitlab.freedesktop.org/mesa/mesa/-/blob/main/src/amd/common/ac_shader_util.c), GFX10-10.3 branch). In the corpus only the 10 POPS pixel shaders use them: 30 `image_load ... glc dlc` and 50 `image_store ... glc`, all 2D, and in each shader the 3 T#s it loads are the 3 it stores, a read-modify-write of its ordered images. A `glc` `image_load` therefore reads the **storage view the stores write** (`OpImageRead` on binding 8 + 3·dim + class for those 2D views, the class picked from the T# FORMAT as for stores), not the sampled array of "Typed image loads": a sampled read has no coherent form in SPIR-V, and between critical sections the fragment-shader interlock only makes coherent memory visible ([Vulkan memory model](https://docs.vulkan.org/spec/latest/appendices/memorymodel.html): non-atomic accesses are private unless `Coherent`; [ARB_fragment_shader_interlock](https://registry.khronos.org/OpenGL/extensions/ARB/ARB_fragment_shader_interlock.txt): stores to `coherent` memory in one critical section are visible to reads in the next). A shader with a `glc` image load or store decorates its storage views **`Coherent`**, as vkd3d-proton's dxil-spirv does for rasterizer-ordered views (`dxil_converter.cpp`: "ROV implies coherent"). These 10 modules need `shaderStorageImageReadWithoutFormat` (listed in their index features); other loads in the corpus keep the sampled path and need no storage feature (SHADER-151). The D3D-78 row below describes the storage-only and tagged atomic readback exceptions. `dlc` alone is a CU-scope load and stays non-coherent; `glc` on a sampled read (`image_sample*`, `image_gather*`, `image_load_mip`) or on a dimension without storage views (cube) is `Unsupported`. Until 2026-11-22 the coherent loads read the sampled array and nothing was `Coherent`, so a POPS read could miss the previous fragment's store. Confirmed by these references, `tests/semantic/test_image_coherent.py` (each read and write's view and type, decorations, capabilities, index features; 7 of its 10 tests fail on the old translator) and a corpus count; **not GPU-checked**: a stale read is a cache race no deterministic test forces. | | 2D `image_sample_lz` | The T# FORMAT selects the float, UINT or SINT sampled view at LOD zero. With nearest sampling, native gfx1036 returned the original 32-bit integer components. RTX 5080 and gfx1036 Vulkan readbacks matched all four channels on RGBA8 UINT, SINT and UNORM for full-width and D16 results. The R32 UINT/SINT saturation-boundary fixture also matched all 64 sampled sums on both adapters. | | 2D `image_sample_l` | The T# FORMAT selects the sampled image type, and every type uses the LOD following the two coordinates. Vulkan requires the sampled type and signedness to match the view. The CPU test in `tests/test_image_load_typed.py` checks the R32 UINT, SINT and FLOAT descriptor branches, the float fallback on a lookup miss and the LOD register with full-width and D16 results. [Vulkan sampling validation](https://docs.vulkan.org/spec/latest/chapters/textures.html#textures-input-validation) | | Implicit 2D pixel-shader integer samples | For `image_sample`, take the UV derivatives before branching on the T# format, then sample the matching float, UINT or SINT view with those gradients. In `ps_sample_implicit_sint` a 128×128 signed texture minifies onto 64×64 pixels. Clamping the sampler to level 0 returned four color quadrants; allowing level 1 returned cyan. All four signed D16 channels matched at every pixel on RTX 5080 and gfx1036. | @@ -380,7 +380,9 @@ How the generated SPIR-V expects the runtime to work: | Typed image stores | `image_store` (2D, 2D array, 3D) writes the dmask components (missing ones = 0). The image's numeric type lives in the T# (word 1 FORMAT [28:20], 512 GFX10 formats), so it is decided at run time. A 512-bit table built from `tools/gfx10_formats.json` (30 UINT and 15 SINT formats) picks a **sint**, **uint** or **float** view (bindings 8 + 3·dim + class; dim 0 = 2D, 1 = 2D array, 2 = 3D; class 0 float, 1 uint, 2 sint). Views have Unknown format (`shaderStorageImageWriteWithoutFormat`). **The runtime binds every storage image into all three arrays of its dimension, or at least the one matching its format.** The earlier path wrote only component 0 as `r32ui`, which was wrong for every other format. GPU-checked with `runtime/test/shaders/cs_imgstore.asm` through `runtime/test/vk_store_test.cpp`: rgba8 unorm, r32 uint and r32 sint images, every texel correct. | | Typed image loads | A noncoherent cube `image_load` reads the 2D-array sampled binding (3) with integer coordinates and layer. Its T# format selects the float, uint or sint alias, including for D16. The [RDNA2 ISA §8.2.1](https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture) assigns D16 conversion to the image format. The synthetic `cube_load_d16.asm` checks the generated views and format choices on the CPU. `image_load` on 1D/2D/2D-array/3D images uses the same T# FORMAT tables as stores, and fetches every format with `OpImageFetch` from the sampled array of its dimension (bindings 0, 3, 6, 5): UINT/SINT formats through **uint/sint aliases of that array** (same set and binding, an `OpTypeImage` of `%uint`/`%int`; Vulkan allows several variables on one binding when the descriptor type fits), everything else through the float array. A lookup miss (index 0) takes the float path, since the fallback there is RGBA8_UNORM. Results are the raw bits of the dmask components. **The runtime binds each image's view in its own format at its index of the sampled array** (what `bind_image` in `runtime/shims/d3d12_vulkan_device.cpp` already does for SRVs and UAVs), so the view's numeric type matches the alias that reads it. No storage image is read, so shaders that only load need neither `shaderStorageImageReadWithoutFormat` (missing on Intel Xe-LP, #619) nor `shaderStorageImageWriteWithoutFormat` (SHADER-151). Until 2026-11-22 integer formats were read with `OpImageRead` from the uint/sint storage arrays (bindings 8–19), which hold only unordered-access views and 256 entries: a read-only integer texture found the fallback there, or an index past the array's end. Like the float path, the fetch goes through the texture path, so it sees writes made before the dispatch, not ones made earlier in the same dispatch. **d16 loads take the same branch** (#1136) and pack the dmask components two per VGPR, low half first: f16 (round to nearest even, integer ops, no `PackHalf2x16`) from the float array, the low 16 bits of each value from the uint/sint aliases (truncated). **d16 loads take the same branch** (#1136) and pack the dmask components two per VGPR, low half first: f16 (round to nearest even, integer ops, no `PackHalf2x16`) from the float array, each value from the uint/sint aliases saturated to the 16-bit range of its signedness (`saturate_int16`). For odd component counts (1 or 3 in `dmask`), the trailing destination VGPR preserves its existing high 16 bits (`write_lo16`), matching native `gfx1036` hardware where a seeded `0x5a5a` high half survived 1-component UINT/SINT `image_load` and `image_load_mip`; until 2026-11-22 the unused high half was zeroed. Before #1136, a d16 load always read the float view, so a `Texture2D` `Load` returned garbage. CPU-checked by `tests/test_image_load_typed.py` (capabilities, bindings and component types for every dimension; the branch for all 512 FORMAT values, found and missed). GPU-checked with `runtime/test/shaders/cs_imgload.asm` through `vk_store_test load`, on a device made without `shaderStorageImageReadWithoutFormat`: r32 uint and r32 sint images filled before the dispatch, both read with `image_load` and their sum stored, every texel exact on an RTX 2080 Ti (NVIDIA 621.14, Windows 11), clean under the validation layer with GPU-assisted validation; the test fails a module that declares `StorageImageReadWithoutFormat`. d16: CPU-checked by `tests/test_image_load_d16_typed.py` (the uint/sint fetches go through the aliases, no storage image is read, the SPIR-V validates); GPU-checked with `runtime/test/shaders/cs_imgload_d16.asm` through `vk_store_test load`: both pre-filled texels read with d16 loads (the sint one sign-extended from bit 15 in the shader) and their sum stored, every texel exact on the RTX 2080 Ti with GPU-assisted validation (#1136 checked its first form, a store and d16 read-back in one dispatch, on an RTX 5070, and `cs_imgload_d16` passes unchanged on an AMD RX 7600 (gfx1102, RADV Mesa 27.0.0-devel) in `run_gpu_tests.py`). GPU-checked with `runtime/test/shaders/cs_imgload_d16.asm` through `vk_store_test load`: both pre-filled texels read with d16 loads (the sint one sign-extended from bit 15 in the shader) and their sum stored, every texel exact on the RTX 2080 Ti with GPU-assisted validation (#1136 checked its first form, a store and d16 read-back in one dispatch, on an RTX 5070). 2D `image_load_mip` uses the same numeric-type selection and passes the address register's mip to each fetch. Its D16 form packs the selected components in ascending order, two per VGPR. An RGBA8 two-level texture was checked on RTX 5080 and Radeon Graphics: all four exported halves matched the CPU reference for UINT, SINT and UNORM, and forcing level 0 changed every pixel. Checked on RTX 5080 and Radeon Graphics with R8G8B8A8 UINT, SINT and UNORM textures: level 1 matched the CPU reference at every pixel with GPU-assisted validation, and forcing level 0 changed all 4096 pixels for each format. Native gfx1036 saturated 32-bit UINT/SINT texels to the unsigned/signed 16-bit range in both D16 load forms; the translated 2D load matched both limits on RTX 5080 and Radeon Graphics. Native gfx1036 does the same on every dimension (SHADER-387, `tools/image_d16_probe.py`): 32_UINT and 32_32_UINT texels saturate to [0, 0xffff] and 32_SINT and 32_32_SINT texels to [-32768, 32767], never truncate, in 1D, 2D, 2D-array and 3D images, through `image_load` and `image_load_mip` alike; two-channel results pack x low and y high, and a one-channel result keeps the seeded high half. The translated d16 loads on 1D, 2D-array and 3D images still lack GPU checks. | | Packed 2D mip-load addresses | For `image_load_mip` with `a16`, the first VGPR holds unsigned X (low half) and Y (high half). The low half of the second VGPR selects the mip and its high half is unused. Both ordinary and D16 results use the same address. LLVM gfx1030 assembles both forms in `tests/semantic/fixtures/packed_mip_load_2d.asm`. `tests/test_image_load_typed.py` checks the texel and mip operands of the float, UINT and SINT fetches, including noncontiguous address registers. [AMD RDNA 2 ISA, MIMG A16 field](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) | -| 3D explicit-mip loads | `image_load_mip` reads x, y, z and mip from four address VGPRs. T# FORMAT selects the float, UINT or SINT 3D sampled view at binding 6. D16 narrows the selected components before packing them low half first. The synthetic translator tests check the four address registers and the RGBA32 format selection. Native gfx1036 measured UINT and SINT saturation for 3D `image_load_mip` at mip zero. [Volume load measurements](https://github.com/ItsNotRexed/Leonida/pull/2217) | +| 1D and 3D texture UAVs (D3D-78) | Storage bindings are 17–19 for 1D and 26–28 for 1D arrays (SPIR-V `1D`, arrayed), leaving multisample SRV bindings 20–25 unchanged. 1D arrays are storage-only: `image_load` and `image_store` use `(x, layer)` relative to the view. Ordinary 1D and 3D loads use sampled aliases; `image_load ... glc` in either dimension, or any `image_load` on a 1D array, reads the Unknown-format storage view. A layer-created 3D UAV sets reserved bit 31 of T# word 4; word 7 tagged with `0xd7800000` (mask `0xff800000`) holds `WSize - 1` in bits [21:11] and `FirstWSlice` in bits [10:0], including for whole-mip UAVs. Vulkan rebases/checks Z for storage operations. The typed sampled aliases below use the tag to rebase Z and return zero outside the range or for nonzero UAV LOD; an untagged SRV keeps its original coordinates and LOD. For non-`glc` `image_load` on a tagged R32_UINT T# whose SGPR group also feeds volume atomics in the shader, the read uses their formatted storage view (binding 7) so it can observe the atomic result in the same dispatch. Other sampled loads retain the visibility rule below. 3D atomics run only in active lanes with a resolved R32_UINT UAV; `glc` returns the old value and inactive lanes keep their destination. `cs_texture_uav.asm` and `d3d12_texture_uav_test` check coherent and sampled reads, dynamic `image_load_mip`, an untouched base mip, and active/inactive add and compare-and-swap with `glc` on an RTX 4090. | +| Packed RGB9E5 UAV backing (#1287 and D3D-78) | Emulated RGB9E5 still encodes the logical shared-exponent FORMAT in the T#. A sampled view reads E5B9G9R9; a raw storage view uses R32_UINT, with any selected W range applied only to that storage view. On 1D-family and 3D UAVs, bit 22 of the synthetic word 7 marks this backing (tag mask `0xff800000`, lower 22 W bits unchanged). The translator does not implement re-packing for generic `image_store` or unpacking for formatless storage loads: these operations respectively suppress writes or take the fallback, not a view of the wrong numeric type. R32_UINT atomics require a logical R32_UINT volume UAV. The packed bit does not affect slicing or untagged SRVs; `d3d12_r9g9b9e5_uav_test` checks raw stores and sampled readback with the real set 0. | +| 3D explicit-mip loads | `image_load_mip` reads x, y, z and mip from four address VGPRs. T# FORMAT selects the float, UINT or SINT 3D sampled view at binding 6. D16 narrows the selected components before packing them low half first. The synthetic translator tests check the four address registers and the RGBA32 format selection. Native gfx1036 measured UINT and SINT saturation for 3D `image_load_mip` at mip zero. [Volume load measurements](https://github.com/ItsNotRexed/Leonida/pull/2217) Only a tagged 3D UAV constrains the view-relative LOD to zero and rebases Z; an untagged 3D SRV keeps its explicit LOD and coordinates. The `cs_imgload_mip` GPU fixture separately checks both D16 halves and full-width reads against distinct 2D mips. | | Typed 2D gathers | `image_gather4_lz(_o)` takes one channel from four taps. For `image_gather4_l(_o)` the four manual fetches share the rounded, clamped mip and addressed footprint. The T# FORMAT selects the float, UINT or SINT sampled image at binding 0. For d16, integer taps are packed low half first, two per VGPR; float taps round to f16. \| AMD RDNA 2 ISA §8.2 (MIMG D16). RTX 5080 and Radeon Graphics matched a CPU clamp-to-edge gather over all 4096 RGBA32F pixels for 8-bit UINT, SINT and UNORM, both packed and unpacked, with zero offset and with (+1,-1). Selecting red in place of green changed all 4096 pixels. Explicit LOD 1 on two-level UINT, SINT and UNORM images also matched all 4096 pixels for both offset forms on both GPUs. Forcing mip 0 changed every pixel. Native gfx1036 saturates out-of-range integer taps as in the typed image loads below. | | Half-precision coordinates for LOD queries | For `image_get_lod a16` on 2D and 2D-array images, the low and high halves of the first address VGPR supply U and V. The array layer is excluded from `OpImageQueryLod`; the selected clamped and raw LOD outputs are f32. `tests/semantic/fixtures/get_lod_a16.asm` assembles for gfx1030 and checks the query operands and output components through `tests/test_image_load_typed.py`. [AMD RDNA2 ISA, MIMG](https://gpuopen.com/download/rdna2-shader-instruction-set-architecture.pdf) | | Image atomics, size and LOD queries | `image_atomic_add/sub/and/or/xor/smin/smax/umin/umax` are `OpAtomicIAdd/ISub/And/Or/Xor/SMin/SMax/UMin/UMax` on the texel (`OpImageTexelPointer`) of an r32ui storage image, binding 4 for 2D and 7 for 3D, at the T#'s index (the view `StorageViews::r32ui` of `runtime/src/vulkan_bindless.h`). The data VGPR is the operand; with `glc` it receives the texel's previous value, without it it is not written (RDNA2 ISA, MIMG: the previous value is returned if glc is 1). `image_atomic_cmpswap` takes two data VGPRs, the new value and then the comparand (`OpAtomicCompareExchange`). A lane that EXEC turns off leaves memory alone: cmpswap is skipped, the others run with the operand that changes nothing. `image_get_resinfo` (2D, no sampler) gives, for the mip level in its address VGPR, width, height, depth (0 for 2D; a 2D array's layers minified from BASE_LEVEL, T# word 3 [15:12]) and the level count in VGPRs 0..3, with width, height and depth 0 past the last level (the size isn't queried there) (ISA: {num_mip_levels, depth, height, width} in VGPRs 3..0; `image_get_resinfo` (2D, no sampler) gives, for the mip level in its address VGPR, width, height, depth (1) and the level count in VGPRs 0..3 (ISA: {num_mip_levels, depth, height, width} in VGPRs 3..0; `OpImageQuerySizeLod`, `OpImageQueryLevels`). `image_get_lod` (pixel shaders; 2D and 2D array, the slice ignored) gives the clamped LOD and the calculated LOD in VGPRs 0..1 (ISA: {rawLOD, clampedLOD} in VGPRs 1..0; `OpImageQueryLod`). In both, dmask keeps components and packs them into consecutive VGPRs. GPU-checked (TEST-184) on an RX 7900 XTX and a Ryzen 9 7950X3D integrated GPU (RADV, Mesa 26.3.1) and on Mesa llvmpipe, with the expected words derived by hand in each `.asm` header: `cs_imgatomic.asm` (every op on a 2D image: 0xfffffff0 tells the signed min/max from the unsigned ones, each with a case that goes the other way; cmpswap hit and miss; an op without `glc`; 63 lanes off; 64 threads adding to one texel) and `cs_imgatomic3d.asm` (six cases on a 4x4x4 volume, the three coordinates all different), through `vk_store_test words`; `cs_resinfo.asm` (a 16x4 image with five levels: levels 0, 1 and 3 in full, then dmask 0x3, 0xa and 0x8); `ps_get_lod.asm` and `ps_get_lod_array.asm` through `vk_texture_test` (calculated LOD 1 and 3 on the two-mip texture, the clamped LOD held at the last level, and at 0 by a sampler MAX_LOD of 0.25; 2 and -3 on the one-level array). Measured natively on RDNA2 (gfx1036, SHADER-388: `tools/image_query_probe.py`, 614 results in wave32 and wave64, all as follows). resinfo's depth word is 0 for a 2D image whatever T# WORD4 DEPTH holds; for a 2D array it is the layer count minified like a 3D depth, max(1, layers >> (BASE_LEVEL + level)). Past the last level, width, height and depth are 0. The level count is LAST_LEVEL - BASE_LEVEL + 1 and sizes count from BASE_LEVEL. The translator follows all three (`Gen.resinfo_words`; `cs_resinfo.asm` checks the 2D depth word and level 5 of five on RTX 5080 and Radeon Graphics, `tests/test_translate.py` the array rule). The translator still differs in the first three: it writes 1 for the 2D depth word and the full layer count for a 2D array, and `OpImageQuerySizeLod` past the last level is undefined. `image_get_lod`'s raw LOD includes the S#'s LOD_BIAS. Its clamped LOD is min(max(min(raw, MAX_LOD), MIN_LOD), levels - 1) under a linear mip filter (MIN_LOD wins when it is above MAX_LOD), that value rounded half up (the level read) under a point mip filter, and 0 with MIP_FILTER none: `OpImageQueryLod`'s definition. u is scaled by the width and v by the height (a 64x4 image). Unverified: resinfo's depth word on hardware (1 is what the T#'s DEPTH field says for a 2D image), the clamped LOD under a linear mip filter (the test's sampler is point-filtered, where 0.25 selects level 0), and the order of u and v in the LOD query (the test textures are square, where it makes no difference). `image_get_resinfo` on other dimensions is `Unsupported`. A host quirk the LOD test steps around: Mesa llvmpipe 26.3.1 does not apply a sampler's LOD range to `OpImageQueryLod` when its minimum and maximum are equal (0..0 gave level 1), so the second draw uses 0..0.25. | diff --git a/docs/testing.md b/docs/testing.md index 279eab0b24..47a9f4a22f 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -139,7 +139,29 @@ python -I runtime/test/shaders/build.py vs_ids ps_mullit python -I runtime/test/shaders/mullit_readback.py ``` -For D3D12/runtime tests, `LEONIDA_VK_VALIDATION=1` enables `VK_LAYER_KHRONOS_validation`. When running with validation, set `DISABLE_RTSS_LAYER=1` and `DISABLE_VULKAN_OBS_CAPTURE=1` if MSI Afterburner (RivaTuner) or OBS is installed: their overlay layers can add unsupported swapchain usage, and in an elevated (administrator) terminal the loader ignores `VK_LOADER_LAYERS_DISABLE=~implicit~` (see "Known problems"). +For D3D12/runtime tests, `LEONIDA_VK_VALIDATION=1` enables `VK_LAYER_KHRONOS_validation`. When running with +validation, set `DISABLE_RTSS_LAYER=1` and `DISABLE_VULKAN_OBS_CAPTURE=1` if MSI Afterburner (RivaTuner) or OBS is +installed: their overlay layers can add unsupported swapchain usage, and in an elevated (administrator) terminal +the loader ignores `VK_LOADER_LAYERS_DISABLE=~implicit~` (see "Known problems"). + +On Windows, `run_gpu_tests.py` assembles and translates the D3D-78 fixture and runs the UAV readback and WARP +comparison from the same build folder. Use `--filter cs_texture_uav` to run only this case: + +```powershell +$env:LEONIDA_VK_VALIDATION = "1" +python -I scripts/run_gpu_tests.py --build runtime/build --filter cs_texture_uav +``` + +Use the actual configuration subfolder for the executables with a multi-config generator. The native Windows +case reports SKIP without WARP or a sufficiently capable Vulkan device; failed translation, a missing test +executable on Windows, and readback mismatches fail the runner. Devices without sliced 3D views still run the 1D, +array and whole-mip cases and check that partial views are refused. + +CTest runs the same D3D-78 descriptor creation, copy, range/refusal and clear checks with `--descriptors-only`. +That mode requires Vulkan, but not a translated shader or WARP. The GPU runner still exercises dispatch and readback. + +Use `--filter cs_imgload_mip` to check 2D `image_load_mip` on FLOAT (UNORM), UINT and SINT sampled views with +both full-width and D16 loads; mip 0 contains decoy data and mip 1 holds the expected texels. The shader test programs (`vk_harness`, `vk_compute_test`, `vk_store_test`, `vk_texture_test`, `vk_bindless_test`, `vk_sampler_test`, `vk_image_fuzz`) don't read `LEONIDA_VK_VALIDATION`. To check one, load the layer through the diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 9dc2a7b66c..66e2987849 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -1513,6 +1513,15 @@ if(TARGET Vulkan::Headers) set_tests_properties(d3d12_indirect_dispatch_count PROPERTIES SKIP_RETURN_CODE 77) endif() + # Test descriptor creation and clears in CTest without shader tools. The GPU runner passes the translated + # cs_texture_uav.spv to also exercise dispatches through set 0 and compare texels with Windows WARP. + add_executable(d3d12_texture_uav_test test/d3d12_texture_uav_test.cpp) + target_link_libraries(d3d12_texture_uav_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_texture_uav_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_texture_uav_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_texture_uav COMMAND d3d12_texture_uav_test --descriptors-only) + set_tests_properties(d3d12_texture_uav PROPERTIES SKIP_RETURN_CODE 77) + # Differential regression: run explicitly (requires Vulkan hardware and Windows WARP). add_executable(d3d12_clear_test test/d3d12_clear_test.cpp) target_link_libraries(d3d12_clear_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) diff --git a/runtime/test/d3d12_texture_uav_oracle.h b/runtime/test/d3d12_texture_uav_oracle.h new file mode 100644 index 0000000000..d9d9dfaea1 --- /dev/null +++ b/runtime/test/d3d12_texture_uav_oracle.h @@ -0,0 +1,279 @@ +#pragma once + +// Native Windows D3D12/WARP reference for synthetic texture UAV dispatches. +// Link d3d12 and dxgi; the HLSL compiler is loaded from System32. +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace uav_oracle { +enum class Status { ready, unavailable, failed }; + +namespace detail { +using Microsoft::WRL::ComPtr; + +inline bool fail(const char* message) { + std::fprintf(stderr, "WARP texture UAV: %s\n", message); + return false; +} + +inline bool check(HRESULT hr, const char* action, ID3DBlob* errors = nullptr) { + if (SUCCEEDED(hr)) return true; + std::fprintf(stderr, "WARP texture UAV: %s failed (0x%08lx)\n", action, static_cast(hr)); + if (errors) std::fputs(static_cast(errors->GetBufferPointer()), stderr); + return false; +} + +struct View { + unsigned shader; + UINT mip; +}; + +inline View select_view(const D3D12_RESOURCE_DESC& resource, const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc) { + if (desc) { + switch (desc->ViewDimension) { + case D3D12_UAV_DIMENSION_TEXTURE1D: return {0, desc->Texture1D.MipSlice}; + case D3D12_UAV_DIMENSION_TEXTURE1DARRAY: return {1, desc->Texture1DArray.MipSlice}; + case D3D12_UAV_DIMENSION_TEXTURE2D: return {2, desc->Texture2D.MipSlice}; + case D3D12_UAV_DIMENSION_TEXTURE2DARRAY: return {3, desc->Texture2DArray.MipSlice}; + case D3D12_UAV_DIMENSION_TEXTURE3D: return {4, desc->Texture3D.MipSlice}; + default: return {5, 0}; + } + } + switch (resource.Dimension) { + case D3D12_RESOURCE_DIMENSION_TEXTURE1D: return {resource.DepthOrArraySize > 1 ? 1u : 0u, 0}; + case D3D12_RESOURCE_DIMENSION_TEXTURE2D: return {resource.DepthOrArraySize > 1 ? 3u : 2u, 0}; + case D3D12_RESOURCE_DIMENSION_TEXTURE3D: return {4, 0}; + default: return {5, 0}; + } +} + +inline D3D12_HEAP_PROPERTIES heap_properties(D3D12_HEAP_TYPE type) { + D3D12_HEAP_PROPERTIES heap{}; + heap.Type = type; + heap.CreationNodeMask = heap.VisibleNodeMask = 1; + return heap; +} + +struct Context { + ComPtr device; + ComPtr root; + std::array, 5> pipelines; + + Status prepare_device() { + if (device) return Status::ready; + ComPtr factory; + ComPtr warp; + HRESULT hr = CreateDXGIFactory1(IID_PPV_ARGS(factory.GetAddressOf())); + if (hr == E_NOINTERFACE || hr == DXGI_ERROR_UNSUPPORTED) return Status::unavailable; + if (!check(hr, "CreateDXGIFactory1")) return Status::failed; + hr = factory->EnumWarpAdapter(IID_PPV_ARGS(warp.GetAddressOf())); + if (hr == DXGI_ERROR_NOT_FOUND || hr == DXGI_ERROR_UNSUPPORTED || hr == E_NOTIMPL) + return Status::unavailable; + if (!check(hr, "EnumWarpAdapter")) return Status::failed; + hr = D3D12CreateDevice(warp.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(device.GetAddressOf())); + if (hr == DXGI_ERROR_UNSUPPORTED || hr == E_NOTIMPL) return Status::unavailable; + return check(hr, "D3D12CreateDevice") ? Status::ready : Status::failed; + } + + bool init() { + if (root) return true; + if (prepare_device() != Status::ready) return false; + const D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, 0, 0, 0}; + D3D12_ROOT_PARAMETER parameter{}; + parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + parameter.DescriptorTable = {1, &range}; + parameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + const D3D12_ROOT_SIGNATURE_DESC desc{1, ¶meter, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr blob, errors; + const HRESULT hr = D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1_0, + blob.GetAddressOf(), errors.GetAddressOf()); + return check(hr, "D3D12SerializeRootSignature", errors.Get()) && + check(device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), + IID_PPV_ARGS(root.GetAddressOf())), "CreateRootSignature"); + } + + bool create_pipeline(unsigned index) { + if (pipelines[index]) return true; + static constexpr const char* types[] = { + "RWTexture1D", "RWTexture1DArray", "RWTexture2D", "RWTexture2DArray", "RWTexture3D", + }; + static constexpr const char* coordinates[] = {"id.x", "id.xz", "id.xy", "id.xyz", "id.xyz"}; + static constexpr char source[] = + "UAV_TYPE dst : register(u0);\n" + "[numthreads(1, 1, 1)]\n" + "void main(uint3 id : SV_DispatchThreadID) {\n" + " dst[UAV_COORD] += 1000u + id.x + 16u * id.y + 256u * id.z;\n" + "}\n"; + struct Compiler { + HMODULE module = LoadLibraryExW(L"d3dcompiler_47.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); + ~Compiler() { if (module) FreeLibrary(module); } + } compiler; + if (!compiler.module) return check(HRESULT_FROM_WIN32(GetLastError()), "load d3dcompiler_47.dll"); + auto compile = std::bit_cast(GetProcAddress(compiler.module, "D3DCompile")); + if (!compile) return check(HRESULT_FROM_WIN32(GetLastError()), "find D3DCompile"); + const D3D_SHADER_MACRO macros[] = { + {"UAV_TYPE", types[index]}, {"UAV_COORD", coordinates[index]}, {nullptr, nullptr}, + }; + ComPtr blob, errors; + const HRESULT hr = compile(source, sizeof(source) - 1, "texture_uav_oracle.hlsl", macros, nullptr, "main", + "cs_5_1", D3DCOMPILE_ENABLE_STRICTNESS, 0, blob.GetAddressOf(), errors.GetAddressOf()); + if (!check(hr, "D3DCompile", errors.Get())) return false; + D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = root.Get(); + desc.CS = {blob->GetBufferPointer(), blob->GetBufferSize()}; + return check(device->CreateComputePipelineState(&desc, IID_PPV_ARGS(pipelines[index].GetAddressOf())), + "CreateComputePipelineState"); + } + + HRESULT create_buffer(UINT64 bytes, D3D12_HEAP_TYPE heap_type, D3D12_RESOURCE_STATES state, ID3D12Resource** out) { + const auto heap = heap_properties(heap_type); + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = bytes; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + return device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, IID_PPV_ARGS(out)); + } +}; + +inline Context& context() { + static thread_local Context ctx; + return ctx; +} +} // namespace detail + +inline Status prepare() { + return detail::context().prepare_device(); +} + +// Provide a valid R32_UINT or R32_TYPELESS texture descriptor and a valid UINT UAV view; a null view +// asks D3D12 to create the default view of a typed R32_UINT resource. Both spans cover the entire +// selected mip (x fastest, then y, then array layer or 3D depth). Other mips are neither read nor written. +inline bool run(const D3D12_RESOURCE_DESC& resource_desc, const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc, + std::span before, std::span after, UINT dispatch_depth = 0) { + using namespace detail; + const View view = select_view(resource_desc, desc); + auto& ctx = context(); + if (view.shader >= ctx.pipelines.size() || + (resource_desc.Format != DXGI_FORMAT_R32_UINT && resource_desc.Format != DXGI_FORMAT_R32_TYPELESS)) + return fail("expected an R32_UINT or R32_TYPELESS texture and a texture UAV"); + if (!ctx.init() || !ctx.create_pipeline(view.shader)) return false; + + ComPtr texture, upload, readback; + const auto heap = heap_properties(D3D12_HEAP_TYPE_DEFAULT); + if (!check(ctx.device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &resource_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(texture.GetAddressOf())), + "CreateCommittedResource (texture)")) return false; + + const auto actual_desc = texture->GetDesc(); // MipLevels = 0 in the input requests the full chain. + if (view.mip >= actual_desc.MipLevels) return fail("UAV mip slice is out of range"); + const bool volume = actual_desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; + const UINT subresources = volume ? 1 : actual_desc.DepthOrArraySize; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT64 bytes = 0; + ctx.device->GetCopyableFootprints(&actual_desc, view.mip, 1, 0, &footprint, nullptr, nullptr, &bytes); + if (bytes == (std::numeric_limits::max)()) return fail("GetCopyableFootprints rejected the texture"); + const auto& fp = footprint.Footprint; + const UINT depth = volume ? fp.Depth : subresources; + const std::uint64_t texels = std::uint64_t(fp.Width) * fp.Height * depth; + if (before.size() != texels || after.size() != texels) + return fail("input and output must span the whole selected mip"); + // Array layers are separate subresources; a 3D mip is one subresource with depth slices at rowPitch * height. + constexpr UINT64 alignment = D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT; + const UINT64 layer_pitch = (bytes + alignment - 1) & ~(alignment - 1); + const UINT64 total = bytes + (subresources - 1) * layer_pitch; + if (total > (std::numeric_limits::max)()) return fail("staging buffers exceed the host address space"); + const auto z_pitch = static_cast(volume ? UINT64(fp.RowPitch) * fp.Height : layer_pitch); + const SIZE_T row_bytes = SIZE_T(fp.Width) * sizeof(std::uint32_t); + if (!check(ctx.create_buffer(total, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, + upload.GetAddressOf()), "CreateCommittedResource (upload)") || + !check(ctx.create_buffer(total, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, + readback.GetAddressOf()), "CreateCommittedResource (readback)")) return false; + const auto each_row = [&](auto copy) { + for (UINT z = 0; z < depth; ++z) + for (UINT y = 0; y < fp.Height; ++y) + copy((SIZE_T(z) * fp.Height + y) * fp.Width, z * z_pitch + SIZE_T(y) * fp.RowPitch); + }; + const D3D12_RANGE none{}, all{0, static_cast(total)}; + void* mapped = nullptr; + if (!check(upload->Map(0, &none, &mapped), "Map upload")) return false; + each_row([&](SIZE_T word, SIZE_T offset) { + std::memcpy(static_cast(mapped) + offset, before.data() + word, row_bytes); + }); + upload->Unmap(0, &all); + + ComPtr uavs; + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{ + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0, + }; + if (!check(ctx.device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(uavs.GetAddressOf())), "CreateDescriptorHeap")) + return false; + ctx.device->CreateUnorderedAccessView(texture.Get(), nullptr, desc, uavs->GetCPUDescriptorHandleForHeapStart()); + + // Use fresh submission objects per run, so no allocator or descriptor heap is reset while in use. + ComPtr queue; + ComPtr allocator; + ComPtr list; + ComPtr fence; + constexpr auto direct = D3D12_COMMAND_LIST_TYPE_DIRECT; + const D3D12_COMMAND_QUEUE_DESC queue_desc{direct}; + if (!check(ctx.device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(queue.GetAddressOf())), "CreateCommandQueue") || + !check(ctx.device->CreateCommandAllocator(direct, IID_PPV_ARGS(allocator.GetAddressOf())), "CreateCommandAllocator") || + !check(ctx.device->CreateCommandList(0, direct, allocator.Get(), ctx.pipelines[view.shader].Get(), + IID_PPV_ARGS(list.GetAddressOf())), "CreateCommandList") || + !check(ctx.device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(fence.GetAddressOf())), "CreateFence")) + return false; + const auto copy_mip = [&](ID3D12Resource* buffer, bool to_texture) { + D3D12_TEXTURE_COPY_LOCATION tex{}, staging{}; + tex.pResource = texture.Get(); + tex.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + staging.pResource = buffer; + staging.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + staging.PlacedFootprint = footprint; + for (UINT layer = 0; layer < subresources; ++layer) { + tex.SubresourceIndex = view.mip + layer * actual_desc.MipLevels; + staging.PlacedFootprint.Offset = layer * layer_pitch; + list->CopyTextureRegion(to_texture ? &tex : &staging, 0, 0, 0, to_texture ? &staging : &tex, nullptr); + } + }; + const auto transition = [&](D3D12_RESOURCE_STATES from, D3D12_RESOURCE_STATES to) { + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Transition = {texture.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, from, to}; + list->ResourceBarrier(1, &barrier); + }; + copy_mip(upload.Get(), true); + transition(D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + ID3D12DescriptorHeap* heaps[] = {uavs.Get()}; + list->SetDescriptorHeaps(1, heaps); + list->SetComputeRootSignature(ctx.root.Get()); + list->SetComputeRootDescriptorTable(0, uavs->GetGPUDescriptorHandleForHeapStart()); + list->Dispatch(fp.Width, fp.Height, dispatch_depth ? dispatch_depth : depth); + transition(D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + copy_mip(readback.Get(), false); + if (!check(list->Close(), "Close command list")) return false; + ID3D12CommandList* lists[] = {list.Get()}; + queue->ExecuteCommandLists(1, lists); + if (!check(queue->Signal(fence.Get(), 1), "Signal queue fence") || + !check(fence->SetEventOnCompletion(1, nullptr), "wait for queue fence") || + !check(ctx.device->GetDeviceRemovedReason(), "D3D12 execution")) return false; + if (!check(readback->Map(0, &all, &mapped), "Map readback")) return false; + each_row([&](SIZE_T word, SIZE_T offset) { + std::memcpy(after.data() + word, static_cast(mapped) + offset, row_bytes); + }); + readback->Unmap(0, &none); + return true; +} +} // namespace uav_oracle diff --git a/runtime/test/d3d12_texture_uav_test.cpp b/runtime/test/d3d12_texture_uav_test.cpp new file mode 100644 index 0000000000..1b096b3995 --- /dev/null +++ b/runtime/test/d3d12_texture_uav_test.cpp @@ -0,0 +1,533 @@ +// Synthetic texture UAVs through the Vulkan D3D12 device. It has no compute PSOs yet, so dispatch the translated +// cs_texture_uav.asm through its actual Vulkan set 0. Non-atomic UINT cases also compare in-view writes with +// Windows WARP. Build the shader with runtime/test/shaders/build.py and pass the .spv as argv[1]. +// LEONIDA_VK_VALIDATION=1 enables the Khronos validation layer. No game files are used. +#include "vk_test_device.h" +#include "vk_pc_tail.h" +#include "../shims/d3d12_com.h" +#include "../src/gfx10_descriptors.h" +#include "d3d12_texture_uav_oracle.h" + +#include + +#include +#include +#include +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return false; } \ +} while (0) + +namespace { + +using Microsoft::WRL::ComPtr; +namespace g = leonida::gfx10; +constexpr auto uav_heap = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; + +// Numeric values are also the branches selected by cs_texture_uav.asm. +enum class Kind : UINT { one_d, array, volume, two_d, float_volume, float_array, atomic_volume }; + +D3D12_RESOURCE_DESC texture(Kind kind, UINT layers, DXGI_FORMAT format = DXGI_FORMAT_R32_UINT) { + using enum Kind; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = kind == one_d || kind == array || kind == float_array ? D3D12_RESOURCE_DIMENSION_TEXTURE1D : + kind == two_d ? D3D12_RESOURCE_DIMENSION_TEXTURE2D : D3D12_RESOURCE_DIMENSION_TEXTURE3D; + desc.Width = 8; + desc.Height = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D ? 1 : 4; + desc.DepthOrArraySize = UINT16(layers); + desc.MipLevels = 3; + desc.Format = format; + desc.SampleDesc.Count = 1; + desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + return desc; +} + +D3D12_UNORDERED_ACCESS_VIEW_DESC uav(Kind kind, UINT mip, UINT first, UINT count, + DXGI_FORMAT format = DXGI_FORMAT_R32_UINT) { + using enum Kind; + D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; + view.Format = format; + switch (kind) { + case one_d: view.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1D; view.Texture1D = {mip}; break; + case array: + case float_array: view.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1DARRAY; view.Texture1DArray = {mip, first, count}; break; + case two_d: view.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; view.Texture2D = {mip, 0}; break; + default: view.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; view.Texture3D = {mip, first, count}; break; + } + return view; +} + +struct Push { + g::ImageWords key; + UINT kind; +}; + +std::uint32_t push_bytes() { + return leonida::vk_test::pc_tail_requested() ? 128u : 144u; +} + +class Compute { +public: + explicit Compute(vktest::Device& vk) : vk_(vk) {} + ~Compute() { + if (pipeline_) vk_.fn("vkDestroyPipeline")(vk_.device, pipeline_, nullptr); + if (layout_) vk_.fn("vkDestroyPipelineLayout")(vk_.device, layout_, nullptr); + if (module_) vk_.fn("vkDestroyShaderModule")(vk_.device, module_, nullptr); + } + + bool create(ID3D12Device* device, const char* path) { + const auto set_layout = rt::d3d12::bindless_set_layout(device); + set_ = rt::d3d12::bindless_set(device); + EXPECT(set_layout && set_); + std::ifstream file(path, std::ios::binary | std::ios::ate); + EXPECT(file && file.tellg() > 0 && file.tellg() % 4 == 0); + std::vector code(std::size_t(file.tellg()) / 4); + file.seekg(0); + EXPECT(file.read(reinterpret_cast(code.data()), std::streamsize(code.size() * 4))); + // This fixture reads only the descriptor and case selector in s0..s8, not the heap/code-base tail. + EXPECT(!leonida::vk_test::spirv_declares_set(code.data(), code.size() * 4, leonida::vk_test::pc_tail_set)); + VkShaderModuleCreateInfo shader{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + shader.codeSize = code.size() * 4; + shader.pCode = code.data(); + EXPECT(vk_.fn("vkCreateShaderModule")(vk_.device, &shader, nullptr, &module_) == + VK_SUCCESS); + const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, push_bytes()}; + VkPipelineLayoutCreateInfo layout{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + layout.setLayoutCount = 1; + layout.pSetLayouts = &set_layout; + layout.pushConstantRangeCount = 1; + layout.pPushConstantRanges = &push; + EXPECT(vk_.fn("vkCreatePipelineLayout")(vk_.device, &layout, nullptr, &layout_) == + VK_SUCCESS); + VkComputePipelineCreateInfo pipeline{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; + pipeline.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; + pipeline.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; + pipeline.stage.module = module_; + pipeline.stage.pName = "main"; + pipeline.layout = layout_; + EXPECT(vk_.fn("vkCreateComputePipelines")( + vk_.device, VK_NULL_HANDLE, 1, &pipeline, nullptr, &pipeline_) == VK_SUCCESS); + return true; + } + + bool run(ID3D12Resource* resource, UINT mip, VkExtent3D extent, const Push& push, + std::span input, std::span output) { + const auto desc = resource->GetDesc(); + const bool volume = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; + const bool check_base_mip = push.kind == UINT(Kind::float_volume) && mip != 0; + const std::size_t base_texels = check_base_mip ? std::size_t(desc.Width) * desc.Height * desc.DepthOrArraySize : 0; + constexpr std::uint32_t base_marker = std::bit_cast(4096.0f); + const VkDeviceSize bytes = input.size_bytes() + base_texels * sizeof(base_marker); + const VkImage image = rt::d3d12::vulkan_image(resource); + EXPECT(image); + void *src = nullptr, *dst = nullptr; + const VkBuffer upload = vk_.buffer(bytes, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &src); + const VkBuffer readback = vk_.buffer(bytes, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &dst); + EXPECT(upload && readback); + std::memcpy(src, input.data(), input.size_bytes()); + std::fill_n(static_cast(src) + input.size(), base_texels, base_marker); + + EXPECT(vk_.run([&](VkCommandBuffer cb) { + const auto barrier = vk_.fn("vkCmdPipelineBarrier"); + VkImageMemoryBarrier texture_barrier{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; + texture_barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; + texture_barrier.newLayout = VK_IMAGE_LAYOUT_GENERAL; + texture_barrier.srcQueueFamilyIndex = texture_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + texture_barrier.image = image; + texture_barrier.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, check_base_mip ? 0u : mip, + check_base_mip ? mip + 1 : 1, 0, volume ? 1 : extent.depth}; + texture_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + barrier(cb, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, + 1, &texture_barrier); + VkBufferImageCopy copies[2]{}; + copies[0].imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, mip, 0, volume ? 1 : extent.depth}; + copies[0].imageExtent = {extent.width, extent.height, volume ? extent.depth : 1}; + copies[1].bufferOffset = input.size_bytes(); + copies[1].imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; + copies[1].imageExtent = {UINT(desc.Width), desc.Height, desc.DepthOrArraySize}; + const UINT copy_count = check_base_mip ? 2 : 1; + vk_.fn("vkCmdCopyBufferToImage")(cb, upload, image, VK_IMAGE_LAYOUT_GENERAL, + copy_count, copies); + texture_barrier.oldLayout = VK_IMAGE_LAYOUT_GENERAL; + texture_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + texture_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + barrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, + nullptr, 1, &texture_barrier); + vk_.fn("vkCmdBindPipeline")(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_); + vk_.fn("vkCmdBindDescriptorSets")(cb, VK_PIPELINE_BIND_POINT_COMPUTE, layout_, + 0, 1, &set_, 0, nullptr); + std::array sgprs{}; + std::memcpy(sgprs.data(), &push, sizeof(push)); + vk_.fn("vkCmdPushConstants")(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, + push_bytes(), sgprs.data()); + const UINT dispatch_depth = push.kind == UINT(Kind::one_d) ? 1 : extent.depth; + vk_.fn("vkCmdDispatch")(cb, extent.width, extent.height, dispatch_depth); + texture_barrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT; + texture_barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; + barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &texture_barrier); + vk_.fn("vkCmdCopyImageToBuffer")(cb, image, VK_IMAGE_LAYOUT_GENERAL, readback, + copy_count, copies); + VkMemoryBarrier host{VK_STRUCTURE_TYPE_MEMORY_BARRIER, nullptr, VK_ACCESS_TRANSFER_WRITE_BIT, + VK_ACCESS_HOST_READ_BIT}; + barrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &host, 0, nullptr, 0, + nullptr); + return true; + })); + std::memcpy(output.data(), dst, output.size_bytes()); + const auto* base = static_cast(dst) + output.size(); + EXPECT(std::all_of(base, base + base_texels, [&](std::uint32_t word) { return word == base_marker; })); + return true; + } + +private: + vktest::Device& vk_; + VkShaderModule module_ = VK_NULL_HANDLE; + VkPipelineLayout layout_ = VK_NULL_HANDLE; + VkPipeline pipeline_ = VK_NULL_HANDLE; + VkDescriptorSet set_ = VK_NULL_HANDLE; +}; + +bool create_texture(ID3D12Device* device, const D3D12_RESOURCE_DESC& desc, ID3D12Resource** resource) { + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + // The refusal test needs a valid read-only resource; only a UAV-capable resource can start in UAV state. + const auto state = desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS ? D3D12_RESOURCE_STATE_UNORDERED_ACCESS + : D3D12_RESOURCE_STATE_COMMON; + return SUCCEEDED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, + state, nullptr, IID_PPV_ARGS(resource))); +} + +auto read_slot(D3D12_CPU_DESCRIPTOR_HANDLE h) { + g::ImageWords words{}; + std::memcpy(words.data(), reinterpret_cast(h.ptr), sizeof(words)); + return words; +} + +bool flush_descriptors(ID3D12Device* device) { + ComPtr queue; + ComPtr allocator; + ComPtr list; + const D3D12_COMMAND_QUEUE_DESC desc{}; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&desc, IID_PPV_ARGS(&queue)))); + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, + IID_PPV_ARGS(&list)))); + EXPECT(SUCCEEDED(list->Close())); + ID3D12CommandList* lists[] = {list.Get()}; + queue->ExecuteCommandLists(1, lists); + // Queue destruction waits for the device-local descriptor upload before the raw Vulkan dispatch. + return rt::d3d12::last_execute_result(queue.Get()) == leonida::ReplayResult::success; +} + +bool rejects_partial_clear(ID3D12Device* device, ID3D12Resource* resource, D3D12_CPU_DESCRIPTOR_HANDLE view) { + ComPtr allocator; + ComPtr list; + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, + IID_PPV_ARGS(&list)))); + const UINT colors[4] = {42, 0, 0, 0}; + list->ClearUnorderedAccessViewUint({}, view, resource, colors, 0, nullptr); + return list->Close() == E_INVALIDARG; +} + +bool check_case(ID3D12Device* device, Compute* compute, Kind kind, const D3D12_RESOURCE_DESC& shape, + D3D12_CPU_DESCRIPTOR_HANDLE source, D3D12_CPU_DESCRIPTOR_HANDLE copy, bool sliced, + UINT mip, UINT first, UINT count, bool use_default = false) { + const bool volume = kind == Kind::volume || kind == Kind::float_volume || kind == Kind::atomic_volume; + const bool floating = kind == Kind::float_volume || kind == Kind::float_array; + const VkExtent3D extent{UINT(shape.Width) >> mip, std::max(1u, shape.Height >> mip), + volume ? std::max(1u, UINT(shape.DepthOrArraySize) >> mip) : shape.DepthOrArraySize}; + const UINT writable = count == ~0u ? extent.depth - first : count; + const auto desc = uav(kind, mip, first, count, floating ? DXGI_FORMAT_R32_FLOAT : DXGI_FORMAT_R32_UINT); + ComPtr resource; + EXPECT(create_texture(device, shape, &resource)); + device->CreateUnorderedAccessView(resource.Get(), nullptr, use_default ? nullptr : &desc, source); + const auto key = read_slot(source); + const bool partial = volume && (first || writable != extent.depth); + if (partial && !sliced) { + EXPECT(key == g::ImageWords{}); + return true; + } + g::Image decoded{}; + EXPECT(g::decode(key, decoded) && decoded.first_mip == mip && decoded.mip_count == 1); + EXPECT(bool(key[4] & g::volume_uav_flag) == volume); + EXPECT(key[7] == (volume ? g::volume_uav_word(first, writable) : 0)); + EXPECT(g::partial_volume_uav(key, decoded) == partial); + EXPECT(!volume || (decoded.depth == shape.DepthOrArraySize && decoded.first_layer == 0 && decoded.layer_count == 1)); + EXPECT((kind != Kind::array && kind != Kind::float_array) || + (decoded.first_layer == first && decoded.layer_count == writable)); + device->CopyDescriptorsSimple(1, copy, source, uav_heap); + EXPECT(read_slot(copy) == key); + if (partial) EXPECT(rejects_partial_clear(device, resource.Get(), copy)); + if (partial && first > 0) { + // A second view of the same volume and mip must not collide with the copied T#. + auto other = desc; + other.Texture3D.FirstWSlice = 0; + device->CreateUnorderedAccessView(resource.Get(), nullptr, &other, source); + EXPECT(read_slot(source) != key && g::is_image(read_slot(source))); + } + if (partial && kind == Kind::float_volume && shape.Format == DXGI_FORMAT_R32_FLOAT) { + // The typed SRV of this same mip must remain unsliced and must not replace the live partial UAV. + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = shape.Format; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Texture3D = {mip, 1, 0.0f}; + device->CreateShaderResourceView(resource.Get(), &srv, source); + const auto srv_key = read_slot(source); + g::Image sampled{}; + EXPECT(g::decode(srv_key, sampled) && sampled.type == g::ImageType::image_3d && + sampled.address == decoded.address && sampled.first_mip == mip && sampled.mip_count == 1 && + sampled.depth == decoded.depth && sampled.first_layer == 0 && sampled.layer_count == 1); + EXPECT(!(srv_key[4] & g::volume_uav_flag) && srv_key[7] == 0 && srv_key != read_slot(copy)); + } + EXPECT(flush_descriptors(device)); + if (!compute) return true; // CTest exercises the complete descriptor setup, without translated SPIR-V. + + std::vector input(extent.width * extent.height * extent.depth); + auto bits = [&](UINT value) { return floating ? std::bit_cast(float(value)) : value; }; + for (UINT i = 0; i < input.size(); ++i) input[i] = bits(17 + i); + std::vector expected = input, output(input.size()), host(input.size()); + for (UINT z = first; z < first + writable; ++z) + for (UINT y = 0; y < extent.height; ++y) + for (UINT x = 0; x < extent.width; ++x) { + const UINT i = (z * extent.height + y) * extent.width + x; + const UINT initial = 17 + i; + const UINT add = 1000 + x + 16 * y + 256 * (z - first); + if (kind == Kind::atomic_volume) + expected[i] = add + (initial << 16) + ((initial + 5) << 8) + 7 + 99; + else + expected[i] = bits(initial + add + (kind == Kind::float_volume && x % 2 == 0 ? initial : 0)); + } + EXPECT(compute->run(resource.Get(), mip, extent, {read_slot(copy), UINT(kind)}, input, output)); + for (UINT i = 0; i < output.size(); ++i) { + if (output[i] == expected[i]) continue; + std::fprintf(stderr, "kind %u mip %u first %u count %u texel %u: got %#x, expected %#x\n", + UINT(kind), mip, first, count, i, output[i], expected[i]); + return false; + } + if (!floating && kind != Kind::atomic_volume) { + // WARP did not clip out-of-range W accesses to WSize in the native probe. Compare documented in-view + // D3D12 accesses and independently require Vulkan to preserve every non-view slice, even under overdispatch. + EXPECT(uav_oracle::run(shape, use_default ? nullptr : &desc, input, host, + volume ? writable : kind == Kind::one_d ? 1 : 0)); + EXPECT(output == host); + } + return true; +} + +bool check_refusals(ID3D12Device* device, D3D12_CPU_DESCRIPTOR_HANDLE slot) { + using enum Kind; + const auto bad = [&](ID3D12Resource* resource, const D3D12_UNORDERED_ACCESS_VIEW_DESC* view) { + std::memset(reinterpret_cast(slot.ptr), 0x55, sizeof(g::ImageWords)); + device->CreateUnorderedAccessView(resource, nullptr, view, slot); + return read_slot(slot) == g::ImageWords{}; + }; + ComPtr line, layers, depth, typeless, read_only; + EXPECT(create_texture(device, texture(one_d, 1), &line)); + EXPECT(create_texture(device, texture(array, 4), &layers)); + EXPECT(create_texture(device, texture(volume, 8), &depth)); + EXPECT(create_texture(device, texture(volume, 8, DXGI_FORMAT_R32_TYPELESS), &typeless)); + auto shape = texture(one_d, 1); + shape.Flags = D3D12_RESOURCE_FLAG_NONE; + EXPECT(create_texture(device, shape, &read_only)); + EXPECT(bad(read_only.Get(), nullptr) && bad(typeless.Get(), nullptr)); + const auto good = uav(one_d, 0, 0, 1); + EXPECT(bad(nullptr, &good) && bad(depth.Get(), &good)); + for (const auto view : {uav(one_d, 3, 0, 1), uav(one_d, 0, 0, 1, DXGI_FORMAT_R16_FLOAT)}) + EXPECT(bad(line.Get(), &view)); + for (const auto view : {uav(array, 0, 4, 1), uav(array, 0, 1, 0), uav(array, 0, 2, 3), uav(array, 3, 0, 1)}) + EXPECT(bad(layers.Get(), &view)); + for (const auto view : {uav(volume, 3, 0, 1), uav(volume, 2, 2, 1), uav(volume, 1, 1, 0), uav(volume, 1, 2, 3)}) + EXPECT(bad(depth.Get(), &view)); + auto rgba = texture(volume, 4, DXGI_FORMAT_R8G8B8A8_TYPELESS); + ComPtr srgb; + EXPECT(create_texture(device, rgba, &srgb)); + const auto srgb_view = uav(volume, 0, 0, ~0u, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB); + EXPECT(bad(srgb.Get(), &srgb_view)); + ComPtr refused; + const auto unsupported = texture(volume, 4, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB); + EXPECT(!create_texture(device, unsupported, &refused) && !refused); + auto invalid_shape = texture(volume, 4); + invalid_shape.MipLevels = 8; + EXPECT(!create_texture(device, invalid_shape, &refused) && !refused); + invalid_shape = texture(one_d, 1); + invalid_shape.Width = (1ull << 32) + 8; + EXPECT(!create_texture(device, invalid_shape, &refused) && !refused); + return true; +} + +bool check_standalone(bool sliced) { + ComPtr device; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&device)))); + ComPtr volume; + EXPECT(create_texture(device.Get(), texture(Kind::volume, 8), &volume)); + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{uav_heap, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + ComPtr heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap)))); + const auto slot = heap->GetCPUDescriptorHandleForHeapStart(); + device->CreateUnorderedAccessView(volume.Get(), nullptr, nullptr, slot); + EXPECT(g::is_image(read_slot(slot))); + const auto view = uav(Kind::volume, 1, 1, 2); + device->CreateUnorderedAccessView(volume.Get(), nullptr, &view, slot); + EXPECT(read_slot(slot)[7] == (sliced ? g::volume_uav_word(1, 2) : 0)); + return true; +} + +bool check_cpu_clear(ID3D12Device* device, vktest::Device& vk, D3D12_CPU_DESCRIPTOR_HANDLE slot) { + EXPECT(!rt::d3d12::bindless_set(device)); + ComPtr queue; + ComPtr allocator; + ComPtr list; + const D3D12_COMMAND_QUEUE_DESC queue_desc{}; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue)))); + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, + IID_PPV_ARGS(&list)))); + ComPtr image; + EXPECT(create_texture(device, texture(Kind::two_d, 1), &image)); + device->CreateUnorderedAccessView(image.Get(), nullptr, nullptr, slot); + EXPECT(g::is_image(read_slot(slot))); + const UINT value[] = {42, 0, 0, 0}; + list->ClearUnorderedAccessViewUint({}, slot, image.Get(), value, 0, nullptr); + EXPECT(SUCCEEDED(list->Close())); + ID3D12CommandList* lists[] = {list.Get()}; + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue.Get()) == leonida::ReplayResult::success); + void* mapped = nullptr; + const VkBuffer output = vk.buffer(32 * sizeof(UINT), VK_BUFFER_USAGE_TRANSFER_DST_BIT, &mapped); + EXPECT(output); + EXPECT(vk.run([&](VkCommandBuffer cb) { + const VkMemoryBarrier memory{VK_STRUCTURE_TYPE_MEMORY_BARRIER, nullptr, VK_ACCESS_TRANSFER_WRITE_BIT, + VK_ACCESS_TRANSFER_READ_BIT}; + vk.fn("vkCmdPipelineBarrier")(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &memory, 0, nullptr, 0, nullptr); + vk.read_back(cb, rt::d3d12::vulkan_image(image.Get()), VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_ASPECT_COLOR_BIT, + 8, 4, 1, output, 0); + return true; + })); + const auto* pixels = static_cast(mapped); + EXPECT(std::all_of(pixels, pixels + 32, [](UINT pixel) { return pixel == 42; })); + + // A typeless backing may reinterpret bits in a transfer clear; an unsupported clear must not be submitted. + EXPECT(SUCCEEDED(allocator->Reset())); + EXPECT(SUCCEEDED(list->Reset(allocator.Get(), nullptr))); + ComPtr volume; + EXPECT(create_texture(device, texture(Kind::volume, 4, DXGI_FORMAT_R32_TYPELESS), &volume)); + const auto view = uav(Kind::volume, 0, 0, ~0u); + device->CreateUnorderedAccessView(volume.Get(), nullptr, &view, slot); + EXPECT(g::is_image(read_slot(slot))); + list->ClearUnorderedAccessViewUint({}, slot, volume.Get(), value, 0, nullptr); + EXPECT(SUCCEEDED(list->Close())); + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue.Get()) == leonida::ReplayResult::unsupported); + return true; +} + +bool test(vktest::Device& vk, const char* shader, bool enable_slices) { + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = vk.instance_proc; + info.instance = vk.instance; + info.physical = vk.physical; + info.device = vk.device; + info.queue = vk.queue; + info.queue_family = vk.family; + info.bindless = vk.bindless; + info.bindless_partially_bound = vk.partially_bound; + info.robust_image_access = vk.robust_image_access; + info.sliced_3d_uav = enable_slices && vk.sliced_3d_uav; + ComPtr device; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device)))); + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{uav_heap, 2, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + ComPtr heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap)))); + const auto source = heap->GetCPUDescriptorHandleForHeapStart(); + const D3D12_CPU_DESCRIPTOR_HANDLE copy{source.ptr + device->GetDescriptorHandleIncrementSize(uav_heap)}; + if (!enable_slices) { + ComPtr volume; + EXPECT(create_texture(device.Get(), texture(Kind::volume, 8), &volume)); + device->CreateUnorderedAccessView(volume.Get(), nullptr, nullptr, source); + EXPECT(g::is_image(read_slot(source))); + const auto view = uav(Kind::volume, 1, 1, 2); + device->CreateUnorderedAccessView(volume.Get(), nullptr, &view, source); + EXPECT(read_slot(source) == g::ImageWords{}); + info.bindless = false; + ComPtr cpu_only; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&cpu_only)))); + ComPtr cpu_heap; + EXPECT(SUCCEEDED(cpu_only->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&cpu_heap)))); + return check_cpu_clear(cpu_only.Get(), vk, cpu_heap->GetCPUDescriptorHandleForHeapStart()); + } + + using enum Kind; + EXPECT(check_refusals(device.Get(), source)); + Compute compute(vk); + if (shader) EXPECT(compute.create(device.Get(), shader)); + auto* dispatch = shader ? &compute : nullptr; + EXPECT(check_case(device.Get(), dispatch, one_d, texture(one_d, 1), source, copy, false, 0, 0, 1, true)); + EXPECT(check_case(device.Get(), dispatch, one_d, texture(one_d, 1), source, copy, false, 2, 0, 1)); + EXPECT(check_case(device.Get(), dispatch, one_d, texture(array, 4), source, copy, false, 1, 0, 1)); + EXPECT(check_case(device.Get(), dispatch, array, texture(array, 4), source, copy, false, 0, 0, 4, true)); + EXPECT(check_case(device.Get(), dispatch, array, texture(array, 4), source, copy, false, 1, 1, 2)); + EXPECT(check_case(device.Get(), dispatch, array, texture(array, 4), source, copy, false, 1, 1, ~0u)); + EXPECT(check_case(device.Get(), dispatch, float_array, texture(float_array, 4, DXGI_FORMAT_R32_FLOAT), + source, copy, false, 1, 1, 2)); + EXPECT(check_case(device.Get(), dispatch, volume, texture(volume, 8), source, copy, vk.sliced_3d_uav, 0, 0, 8, true)); + EXPECT(check_case(device.Get(), dispatch, volume, texture(volume, 8, DXGI_FORMAT_R32_TYPELESS), source, copy, + vk.sliced_3d_uav, 1, 1, 2)); + EXPECT(check_case(device.Get(), dispatch, volume, texture(volume, 8), source, copy, vk.sliced_3d_uav, 1, 2, ~0u)); + EXPECT(check_case(device.Get(), dispatch, float_volume, texture(float_volume, 8, DXGI_FORMAT_R32_FLOAT), + source, copy, vk.sliced_3d_uav, 1, 1, 2)); + EXPECT(check_case(device.Get(), dispatch, atomic_volume, texture(atomic_volume, 8), + source, copy, vk.sliced_3d_uav, 1, 0, 4)); + EXPECT(check_case(device.Get(), dispatch, atomic_volume, texture(atomic_volume, 8), + source, copy, vk.sliced_3d_uav, 1, 1, 2)); + EXPECT(check_case(device.Get(), dispatch, two_d, texture(two_d, 1), source, copy, false, 1, 0, 1)); + return true; +} + +} // namespace + +int main(int argc, char** argv) { + if (argc != 2) { + std::fprintf(stderr, "usage: d3d12_texture_uav_test |--descriptors-only\n"); + return 2; + } + vktest::Device vk; + // Exercise Vulkan 1.3 per-format access even on a logical device without the legacy feature bits. + const auto status = vk.initialize(true, false); + if (status == vktest::DeviceStatus::unavailable && !vk.validation_errors()) { + std::printf("SKIP: no Vulkan 1.3 device with a graphics queue\n"); + return 77; + } + if (status != vktest::DeviceStatus::ready) return 1; + const char* shader = std::strcmp(argv[1], "--descriptors-only") == 0 ? nullptr : argv[1]; + VkPhysicalDeviceProperties props{}; + vk.instance_fn("vkGetPhysicalDeviceProperties")(vk.physical, &props); + if (!vk.bindless || !vk.robust_image_access || (shader && props.limits.maxPushConstantsSize < push_bytes())) { + std::printf("SKIP: requires bindless descriptors and robustImageAccess%s\n", + shader ? " and 144 bytes of push constants" : ""); + return vk.validation_errors() ? 1 : 77; + } + if (shader) { + const auto warp = uav_oracle::prepare(); + if (warp == uav_oracle::Status::unavailable) { + std::printf("SKIP: no D3D12 WARP adapter\n"); + return vk.validation_errors() ? 1 : 77; + } + if (warp != uav_oracle::Status::ready) return 1; + } + if (!test(vk, shader, false) || !test(vk, shader, true) || !check_standalone(vk.sliced_3d_uav) || + vk.validation_errors()) + return 1; + if (!shader) { + std::puts("texture UAV descriptors: creation, copy, range/refusal and clear checks passed"); + return 0; + } + if (!vk.sliced_3d_uav) std::printf("SKIP: sliced 3D UAV GPU writes (feature unavailable); rejection verified\n"); + std::printf("texture UAVs: %u GPU cases (%u compared with WARP), format/range/refusal checks passed\n", + vk.sliced_3d_uav ? 14u : 10u, vk.sliced_3d_uav ? 10u : 8u); + return 0; +} diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py index de286fa770..5eba736b2f 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py @@ -1520,6 +1520,29 @@ def clip_test(tools, spirv, name): return "" +def texture_uav_test(tools, spv): + """The Windows D3D12 test compares every texel itself, through both Vulkan and WARP.""" + if os.name != "nt": + return Skip("SKIP (needs the Windows D3D12 runtime)") + exe = os.path.join(tools, "d3d12_texture_uav_test" + EXE) + if not os.path.isfile(exe): + return f"missing {exe}" + code, out = run(exe, spv) + if code == UNSUPPORTED: + reason = next((line for line in out.splitlines() if line.startswith("SKIP:")), "unsupported device") + return Skip(reason) + return "" if code == 0 else failure(code, out, 8) + + +IMAGE_STORE_CASES = { + "cs_imgstore": (), + "cs_imgload": ("load",), + "cs_imgload_d16": ("load-d16",), + "cs_sample_lz_int_d16": ("load-d16",), + "cs_imgload_mip": ("load-mip",), +} + + def main(): if len(sys.argv) < 2: sys.exit(__doc__) @@ -1564,8 +1587,7 @@ def main(): results.append(("ms_wave_info_s3", mesh_w64x_test(tools, spirv, "ms_wave_info_s3"))) with tempfile.TemporaryDirectory(prefix="leonida-mesh-") as tmp: results.append(("ms_v5_workgroup", mesh_v5_test(tools, spirv, Path(tmp) / "groups.raw"))) - for name, args in (("cs_imgstore", []), ("cs_imgload", ["load"]), ("cs_imgload_d16", ["load-d16"]), - ("cs_sample_lz_int_d16", ["load-d16"])): + for name, args in IMAGE_STORE_CASES.items(): code, out = run(os.path.join(tools, "vk_store_test" + EXE), os.path.join(spirv, name + ".spv"), *args) if code == UNSUPPORTED: # vk_store_test: the device lacks a feature this test needs m = re.search(r"unsupported: .*", out) @@ -1573,6 +1595,9 @@ def main(): continue bad = re.findall(r"(\d+) bad", out) results.append((name, "" if code == 0 and len(bad) == 3 and set(bad) == {"0"} else failure(code, out, 3))) + texture_uav_spv = os.path.join(spirv, "cs_texture_uav.spv") + if os.path.isfile(texture_uav_spv): + results.append(("cs_texture_uav", texture_uav_test(tools, texture_uav_spv))) for name in STORE_WORDS: # TEST-184: image atomics and image_get_resinfo results.append((name, store_words_test(tools, spirv, name))) for name in GET_LOD_TESTS: # TEST-184: image_get_lod, 2D and 2D array diff --git a/runtime/test/shaders/cs_imgload_mip.asm b/runtime/test/shaders/cs_imgload_mip.asm new file mode 100644 index 0000000000..c9d4d33067 --- /dev/null +++ b/runtime/test/shaders/cs_imgload_mip.asm @@ -0,0 +1,44 @@ +; vk_store_test load-mip: x/y are a texel in the 8x8 mip 1. The 16x16 mip 0 has decoy data and receives +; the results. Fetch each mip-1 format twice: full-width and D16 (RG for UNORM, RA for R32 UINT/SINT). +; Store the float RG bits, and check both packed halves (including integer saturation) in the integer outputs. +v_and_b32_e32 v1, 7, v0 +v_lshrrev_b32_e32 v2, 3, v0 +v_mov_b32_e32 v3, 1 +s_mov_b32 s8, 0x1000 +s_mov_b32 s9, 0x3800000 +s_mov_b32 s10, 0x11 +s_mov_b32 s11, 0x11 +s_mov_b32 s12, 0x11 +s_mov_b32 s13, 0x11 +s_mov_b32 s14, 0x11 +s_mov_b32 s15, 0x11 +image_load_mip v[4:5], v[1:3], s[8:15] dmask:0x3 dim:SQ_RSRC_IMG_2D unorm +image_load_mip v6, v[1:3], s[8:15] dmask:0x3 dim:SQ_RSRC_IMG_2D unorm d16 +s_mov_b32 s16, 0x2000 +s_mov_b32 s17, 0x1400000 +s_mov_b32 s18, 0x22 +s_mov_b32 s19, 0x22 +s_mov_b32 s20, 0x22 +s_mov_b32 s21, 0x22 +s_mov_b32 s22, 0x22 +s_mov_b32 s23, 0x22 +image_load_mip v7, v[1:3], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm +image_load_mip v8, v[1:3], s[16:23] dmask:0x9 dim:SQ_RSRC_IMG_2D unorm d16 +s_mov_b32 s24, 0x3000 +s_mov_b32 s25, 0x1500000 +s_mov_b32 s26, 0x33 +s_mov_b32 s27, 0x33 +s_mov_b32 s28, 0x33 +s_mov_b32 s29, 0x33 +s_mov_b32 s30, 0x33 +s_mov_b32 s31, 0x33 +image_load_mip v9, v[1:3], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm +image_load_mip v10, v[1:3], s[24:31] dmask:0x9 dim:SQ_RSRC_IMG_2D unorm d16 +s_waitcnt vmcnt(0) +v_add_nc_u32_e32 v7, v7, v8 +v_add_nc_u32_e32 v7, v7, v6 +v_add_nc_u32_e32 v9, v9, v10 +image_store v[4:5], v[1:2], s[8:15] dmask:0x3 dim:SQ_RSRC_IMG_2D unorm +image_store v7, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm +image_store v9, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm +s_endpgm diff --git a/runtime/test/shaders/cs_texture_uav.asm b/runtime/test/shaders/cs_texture_uav.asm new file mode 100644 index 0000000000..4c1a7c8fc2 --- /dev/null +++ b/runtime/test/shaders/cs_texture_uav.asm @@ -0,0 +1,95 @@ +; group: 1,1,1 +; rsrc2: 0x392 +; s[0:7] = UAV T#, s8 = case (0: 1D, 1: 1D array, 2: 3D UINT, 3: 2D, 4: 3D FLOAT, 5: 1D array FLOAT, 6: 3D atomics). +; s[9:11] = workgroup XYZ. Add 1000 + x + 16*y + 256*z to each existing texel (z is the array +; layer for 1D arrays). d3d12_texture_uav_test pushes production heap descriptors and compares +; every texel against the CPU expectation and, for non-atomic UINT, against Windows WARP. +; The float volume adds the texel twice at even x (LOD 0), once at odd x (LOD 1 reads zero). +; The atomic volume stores the coordinate increment + (initial << 16) + ((initial + 5) << 8) + 7 + 99. +v_mov_b32_e32 v0, s9 +v_mov_b32_e32 v1, s10 +v_mov_b32_e32 v2, s11 +v_lshlrev_b32_e32 v3, 8, v2 +v_lshl_add_u32 v3, v1, 4, v3 +v_add_nc_u32_e32 v3, v0, v3 +v_add_nc_u32_e32 v3, 1000, v3 +s_cmp_eq_u32 s8, 0 +s_cbranch_scc0 6 +image_load v4, v0, s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_1D unorm +v_add_nc_u32_e32 v3, v3, v4 +image_store v3, v0, s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_1D unorm +s_endpgm +s_cmp_eq_u32 s8, 1 +s_cbranch_scc0 7 +v_mov_b32_e32 v1, v2 +image_load v4, v[0:1], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_1D_ARRAY unorm +v_add_nc_u32_e32 v3, v3, v4 +image_store v3, v[0:1], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_1D_ARRAY unorm +s_endpgm +s_cmp_eq_u32 s8, 2 +s_cbranch_scc0 6 +image_load v4, v[0:2], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm +v_add_nc_u32_e32 v3, v3, v4 +image_store v3, v[0:2], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm +s_endpgm +s_cmp_eq_u32 s8, 3 +s_cbranch_scc0 6 +image_load v4, v[0:1], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm +v_add_nc_u32_e32 v3, v3, v4 +image_store v3, v[0:1], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm +s_endpgm +s_cmp_eq_u32 s8, 5 +s_cbranch_scc0 13 +v_mov_b32_e32 v1, v2 +image_load v4, v[0:1], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_1D_ARRAY unorm +v_cvt_f32_u32_e32 v3, v3 +v_add_f32_e32 v3, v3, v4 +; Float array view covers two layers. Verify that the next-layer read does not contribute. +v_add_nc_u32_e32 v1, 2, v1 +image_load v4, v[0:1], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_1D_ARRAY unorm +v_add_f32_e32 v3, v3, v4 +v_mov_b32_e32 v1, v2 +image_store v3, v[0:1], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_1D_ARRAY unorm +s_endpgm +s_cmp_eq_u32 s8, 6 +s_cbranch_scc0 31 +; Use a separate T# SGPR group so the non-atomic UINT volume case exercises the sampled alias. +s_mov_b64 s[12:13], s[0:1] +s_mov_b64 s[14:15], s[2:3] +s_mov_b64 s[16:17], s[4:5] +s_mov_b64 s[18:19], s[6:7] +; Inactive add and CAS must neither write nor change their glc destinations. The active add returns +; the initial texel, the active CAS returns that texel + 5, and the following load reads 99. +v_mov_b32_e32 v4, 7 +v_mov_b32_e32 v5, 0 +s_mov_b32 exec_lo, 0 +image_atomic_add v4, v[0:2], s[12:19] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm glc +image_atomic_cmpswap v[4:5], v[0:2], s[12:19] dmask:0x3 dim:SQ_RSRC_IMG_3D unorm glc +s_mov_b32 exec_lo, 1 +v_mov_b32_e32 v6, 5 +image_atomic_add v6, v[0:2], s[12:19] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm glc +v_mov_b32_e32 v8, 99 +v_add_nc_u32_e32 v9, 5, v6 +image_atomic_cmpswap v[8:9], v[0:2], s[12:19] dmask:0x3 dim:SQ_RSRC_IMG_3D unorm glc +image_load v7, v[0:2], s[12:19] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm +v_lshl_add_u32 v3, v6, 16, v3 +v_lshl_add_u32 v3, v8, 8, v3 +v_add_nc_u32_e32 v3, v4, v3 +v_add_nc_u32_e32 v3, v7, v3 +image_store v3, v[0:2], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm +s_endpgm +image_load v4, v[0:2], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm +v_cvt_f32_u32_e32 v3, v3 +v_add_f32_e32 v3, v3, v4 +; Relative LOD 0 reuses the physical mip selected by the view; LOD 1 is outside the single-mip view. +v_mov_b32_e32 v6, v3 +v_and_b32_e32 v3, 1, v0 +image_load_mip v5, v[0:3], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm +v_add_f32_e32 v3, v6, v5 +; Float test uses WSize=2: an outside-Z fetch must be zero even if still inside the image. +v_add_nc_u32_e32 v2, 2, v2 +image_load v4, v[0:2], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm +v_add_f32_e32 v3, v3, v4 +v_mov_b32_e32 v2, s11 +image_store v3, v[0:2], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm +s_endpgm diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index 66400b57af..1a0bab1d59 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -25,14 +25,15 @@ import mc_command # noqa: E402 sys.path.insert(0, SHADER_DIR) from build import CLIP_CASES, clip_container, shader_source -from check import (Skip, clip_test, fmt_1010102_test, fmt_d16_xyz_test, fmt_int_narrow_test, fmt_sint32_test, - fmt_xy_xyz_test, tbuffer_store_test) +from check import (Skip, clip_test, fmt_1010102_test, fmt_int_narrow_test, fmt_sint32_test, fmt_xy_xyz_test, + tbuffer_store_test) from compute_fixture import compute_header from check import SAMPLER_CASES, sampler_test # ps_ssharp: the S#/T# mip fields (vk_sampler_test) -from check import (CMPX_CLASS_WORDS, CVT_F32_SAT_CASES, CVT_PK_U8_WORDS, GRADIENT_TESTS, TEST_PROGRAMS, TEXTURE_MIP_DEPENDENCIES, - TEXTURE_MIP_TEST, GATHER_LOD_TEST, MIP_TEST_PASSES, TEXTURE_CONSTANTS, USER_SGPRS_ENV, USER_SGPRS_WORDS, Skip, mesh_v5_test, not_found_message, - pick_build_dir, start_failure, texture_gradient_a16_test, texture_mip_test) -from check import SIGNED_MIP_TEST +from check import (CMPX_CLASS_WORDS, CVT_F32_SAT_CASES, CVT_PK_U8_WORDS, GATHER_LOD_TEST, GRADIENT_TESTS, + IMAGE_STORE_CASES, MIP_TEST_PASSES, SIGNED_MIP_TEST, TEST_PROGRAMS, TEXTURE_CONSTANTS, + TEXTURE_MIP_DEPENDENCIES, TEXTURE_MIP_TEST, USER_SGPRS_ENV, USER_SGPRS_WORDS, mesh_v5_test, + not_found_message, pick_build_dir, start_failure, texture_gradient_a16_test, texture_mip_test, + texture_uav_test) from check import HEAP_INIT_EXPECTED, heap_init_env # cs_heap_init: vk_compute_test's VKC_HEAP_INIT from check import judged_words, words_match # dump words not judged on some devices (cs_signed_zero_nan) from check import TEXOFF_ARGS, texoff_problem # ps_texoff's expected words and arguments live in check.py @@ -1120,12 +1121,16 @@ def run_suite(a, work: str) -> int: unjudged = ", ".join(str(i) for i, w in enumerate(want) if w is None) detail += f" (words {unjudged} not judged on this device: UNJUDGED_WORDS in check.py)" results.append((name, ok, detail)) - elif name == "cs_imgstore": - rc, msg = run_cmd([vk_store, spv]) - results.append((name, rc == 0, msg.splitlines()[-1] if msg else "")) - elif name in ("cs_imgload", "cs_imgload_d16", "cs_sample_lz_int_d16"): - rc, msg = run_cmd([vk_store, spv, "load" if name == "cs_imgload" else "load-d16"]) - results.append((name, rc == 0, msg.splitlines()[-1] if msg else "")) + elif name in IMAGE_STORE_CASES: + rc, msg = run_cmd([vk_store, spv, *IMAGE_STORE_CASES[name]]) + if rc == UNSUPPORTED: + results.append((name, None, unsupported_skip(msg))) + else: + results.append((name, rc == 0, msg.splitlines()[-1] if msg else "")) + elif name == "cs_texture_uav": + problem = texture_uav_test(a.build, spv) + results.append((name, None if isinstance(problem, Skip) else not problem, + problem or "D3D12/Vulkan storage-image readback matched")) elif name in MIP_TEST_PASSES: problem = texture_mip_test(a.build, spirv_dir, name) ok = None if isinstance(problem, Skip) else not problem diff --git a/tests/test_run_gpu_tests.py b/tests/test_run_gpu_tests.py index da69c1ee34..9af86f0d19 100644 --- a/tests/test_run_gpu_tests.py +++ b/tests/test_run_gpu_tests.py @@ -169,6 +169,76 @@ def test_other_failures_still_fail(self): self.assertNotIn("skipped", out) +class TextureUavFixture(unittest.TestCase): + """Run the real filtered suite and checker, substituting only the external tools.""" + def run_uav(self, code=0, message="", *, windows=True, compiled=True, executable=True): + import check + + name = "cs_texture_uav" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + args = SimpleNamespace(filter=name, build=str(root / "build"), llvm_mc="unused") + exe = Path(args.build) / "d3d12_texture_uav_test.exe" + exe.parent.mkdir() + if executable: + exe.touch() + spv = root / "spirv" / f"{name}.spv" + spv.parent.mkdir() + spv.write_bytes(b"stale fixture") + + def translate(cmd, env=None, gpu=True): + self.assertFalse(gpu) + self.assertEqual(cmd[2], rgt.TRANSLATOR) + self.assertEqual([p.name for p in Path(cmd[3]).iterdir()], [f"{name}.s"]) + self.assertEqual(Path(cmd[cmd.index("--out") + 1]), spv.parent) + self.assertFalse(spv.exists(), "an old SPIR-V must not mask a failed translation") + if compiled: + spv.touch() + return 0, "" + + result = SimpleNamespace(returncode=code, stdout=message, stderr="") + output = io.StringIO() + with (patch.object(rgt, "assemble_to_s", side_effect=lambda _mc, _src, dst, _name: Path(dst).touch()), + patch.object(rgt, "spirv_as"), + patch.object(rgt, "run_cmd", side_effect=translate), + patch.object(check, "os", SimpleNamespace(name="nt" if windows else "posix", path=check.os.path, + environ=check.os.environ)), + patch.object(check, "EXE", ".exe"), + patch.object(check.subprocess, "run", return_value=result) as launch, + contextlib.redirect_stdout(output)): + rc = rgt.run_suite(args, tmp) + if windows and compiled and executable: + launch.assert_called_once() + self.assertEqual(tuple(launch.call_args.args[0]), (str(exe), str(spv))) + else: + launch.assert_not_called() + return rc, output.getvalue() + + def test_translates_and_runs_the_windows_uav_fixture(self): + rc, out = self.run_uav() + self.assertEqual(rc, 0, out) + self.assertIn("1/1 passed", out) + + def test_unavailable_warp_and_non_windows_are_skips(self): + for options in (dict(code=77, message="SKIP: no D3D12 WARP adapter"), dict(windows=False)): + with self.subTest(options=options): + rc, out = self.run_uav(**options) + self.assertEqual(rc, 0, out) + self.assertIn("SKIP cs_texture_uav", out) + self.assertIn("0/1 passed, 1 skipped", out) + + def test_failed_gpu_run_missing_translation_and_missing_executable_fail(self): + for options, detail in ((dict(code=1, message="bad texel"), "bad texel"), + (dict(compiled=False), "missing .spv"), + (dict(executable=False), "missing ")): + with self.subTest(options=options): + rc, out = self.run_uav(**options) + self.assertEqual(rc, 1, out) + self.assertIn(detail, out) + self.assertIn("0/1 passed", out) + self.assertNotIn("skipped", out) + + class FilterWithoutRunnableCases(unittest.TestCase): """A filter selecting only an input shader (cs_bench_mix) must not report 0/0 passed with exit 0.""" diff --git a/tests/test_shader_checks.py b/tests/test_shader_checks.py index 025794d6d0..9d280d213c 100644 --- a/tests/test_shader_checks.py +++ b/tests/test_shader_checks.py @@ -29,9 +29,9 @@ WAVE32_WORDS = {n: w for n, w in check.CS_DUMPS if n in check.WAVE32_DUMPS and n not in ("cs_store", "cs_smem_soffset_imm")} -# All check.py cases, including the four vk_store_test shaders and the three mesh fixtures, and TEST-184's -# vk_store_test "words" fixtures and image_get_lod draws. -TOTAL = (len(check.COMPUTE) + 7 + len(check.CS_DUMPS) + len(check.W64X_DUMPS) + len(check.W64X_PARTIAL) + 4 +# All check.py cases except the optional Windows UAV fixture (no SPIR-V is staged for it here). +TOTAL = (len(check.COMPUTE) + 7 + len(check.CS_DUMPS) + len(check.W64X_DUMPS) + len(check.W64X_PARTIAL) + + len(check.IMAGE_STORE_CASES) + len(check.PIXEL_TESTS) + len(check.CLIP_TESTS) + len(check.BOUNDS) + len(check.GLOBAL_OFFSET) + len(check.MIP_TEST_PASSES) + len(check.GRADIENT_TESTS) + len(check.STORE_WORDS) + len(check.GET_LOD_TESTS) @@ -57,6 +57,23 @@ def cvt_answer(env, wrong_for=None): return 0, "out[0..7] = " + " ".join(map(str, words + [0xEEEEEEEE] * 6)) + "\n" +class TextureUavCheck(unittest.TestCase): + def test_windows_requires_a_real_successful_executable(self): + with tempfile.TemporaryDirectory() as tmp, patch.object(check.os, "name", "nt"): + exe = check.os.path.join(tmp, "d3d12_texture_uav_test" + check.EXE) + spv = check.os.path.join(tmp, "cs_texture_uav.spv") + self.assertIn("missing", check.texture_uav_test(tmp, spv)) + with open(exe, "wb"): + pass + with patch.object(check, "run", return_value=(0, "matched")) as run: + self.assertEqual(check.texture_uav_test(tmp, spv), "") + run.assert_called_once_with(exe, spv) + with patch.object(check, "run", return_value=(77, "SKIP: missing features")): + self.assertIsInstance(check.texture_uav_test(tmp, spv), check.Skip) + with patch.object(check, "run", return_value=(1, "bad texel")): + self.assertIn("bad texel", check.texture_uav_test(tmp, spv)) + + class Wave64Checks(unittest.TestCase): def run_checks(self, wavemask, ballot, *, missing_ballot=False, emulated=False, fmt=(0, GOOD_FMT)): def harness(_tool, shader, *args, env=None): @@ -151,7 +168,8 @@ def harness(_tool, shader, *args, env=None): return 0, "out[0..7] = " + " ".join(map(str, (WAVE32_WORDS[name] + [0] * 8)[:8])) + "\n" if name == "cs_workgroup_yz": # #186: vk_compute_test's 2x3x4 Y/Z histogram line return 0, "2x3x4 workgroup Y/Z: 0 mismatches\n" - if name in ("cs_imgstore", "cs_imgload", "cs_imgload_d16", "cs_sample_lz_int_d16"): # vk_store_test checks + if name in check.IMAGE_STORE_CASES: + self.assertEqual(args, check.IMAGE_STORE_CASES[name]) return 0, "0 bad\n0 bad\n0 bad\n" if name in check.STORE_WORDS: # vk_store_test "words": the three images, judged by check.py self.assertEqual(args, ("words",)) From 57cb669f52ba6ca4bb58bf2e09492ffbe2b8ee60 Mon Sep 17 00:00:00 2001 From: Almogaver295 <133548141+guimsolutions@users.noreply.github.com> Date: Mon, 23 Nov 2026 09:31:12 +0100 Subject: [PATCH 003/110] fix(vulkan): require formatless reads for all D3D-78 UAVs Coherent 1D and 3D loads and all 1D-array loads can issue OpImageRead on Unknown-format storage views. Require both per-format access bits before registering the view or writing its descriptor, while preserving the formatted RGB9E5 exception. AI-assisted. Verified the synthetic UAV readback and format refusals with Vulkan validation on RTX 4090 (621.01) and UHD 770 (101.7088). --- docs/d3d12_vulkan.md | 12 ++-- runtime/shims/d3d12_vulkan_device.cpp | 12 ++-- runtime/test/d3d12_texture_uav_test.cpp | 89 ++++++++++++++++++++++++- runtime/test/shaders/cs_texture_uav.asm | 14 +++- 4 files changed, 112 insertions(+), 15 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 649b5bd30d..b644000762 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1450,10 +1450,11 @@ The layer's descriptor model: whole-mip and partial UAVs, distinguishes them from SRVs in the hash table, and rebases typed sampled fetches; see the contract in `docs/design.md`. Without those features a partial W view is logged and left null, not made writable across the whole mip. - These new dimensions require storage-write-without-format support for the typed view format and, for the - storage-only 1D array bindings, storage-read-without-format as well. Vulkan 1.3 permits the - SPIR-V capabilities even when the legacy `shaderStorageImage{Read,Write}WithoutFormat` bits are not enabled; - the caller-owned device test leaves both bits off and checks the per-format path. + Shader-visible 1D, 1D-array and 3D UAVs require both formatless storage read and write support for the actual + Vulkan view format. `image_load ... glc` uses the storage view for 1D and 3D, and 1D-array loads always use it. + The emulated RGB9E5 raw `R32_UINT` storage view is formatted and is exempt. Vulkan 1.3 permits these SPIR-V + capabilities even without the legacy `shaderStorageImage{Read,Write}WithoutFormat` feature bits. The + caller-owned device test leaves both legacy bits off and masks each per-format bit to verify safe rejection. `ClearUnorderedAccessView*` refuses partial W ranges and 1D/3D format reinterprets: the transfer clear cannot target a slice interval or guarantee preserving the reinterpreted bits. Shader access to the new UAVs requires `robustImageAccess` (whole-mip CPU clears do not). @@ -1803,8 +1804,7 @@ The trace will enumerate them. Typed buffer UAVs: the layer writes their V# (section 3.4, "Buffer UAVs"); `rdna2spirv.py` `FORMATS` determines which buffer formats the translator can decode. - The UAV atomic bits other than exchange for `R32_UINT` where Vulkan reports storage image atomics. - The translator and set 0 use the formatted `r32ui` views for 2D and 3D. There is no `image_atomic_swap`, - and `R32_SINT` gets no `r32ui` view. + The translator and set 0 use the formatted `r32ui` views for 2D and 3D; `R32_SINT` gets no `r32ui` view. - `MULTISAMPLE_RENDERTARGET` for depth formats, from the same usages `MULTISAMPLE_QUALITY_LEVELS` queries. - No integer resolve, no 1D block-compressed. Depth formats are 2D and cube only: no 3D, shader reads, UAVs, buffer or vertex use, and no 1D, which native D3D12 allows but the layer's resource creation refuses. diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 1af93b4067..f8ba8d1add 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -7319,17 +7319,17 @@ class Device final return; } if (new_uav && state_.info.robust_image_access) { - const bool storage_read = view.type == g::ImageType::image_1d_array; if (sampled && !state_.sampled_usable(view_format)) { log_once("texture view format does not support sampled access:", view_format); return; } - // Vulkan 1.3 allows formatless access based on the actual view's features, even on caller-owned - // devices. Packed RGB9E5 only exposes formatted raw R32_UINT storage, so it does not need these. + // All three dimensions use Unknown-format storage writes and can use Unknown-format reads + // (image_load glc, or any image_load on a 1D array). Check the actual storage view's format. + // Packed RGB9E5 only exposes formatted raw R32_UINT storage, so it does not need these bits. if (!packed_storage) { - const auto features = state_.optimal_features(storage_format); - if (!(features & VK_FORMAT_FEATURE_2_STORAGE_WRITE_WITHOUT_FORMAT_BIT) || - (storage_read && !(features & VK_FORMAT_FEATURE_2_STORAGE_READ_WITHOUT_FORMAT_BIT))) { + constexpr auto required = VK_FORMAT_FEATURE_2_STORAGE_READ_WITHOUT_FORMAT_BIT | + VK_FORMAT_FEATURE_2_STORAGE_WRITE_WITHOUT_FORMAT_BIT; + if ((state_.optimal_features(storage_format) & required) != required) { log_once("texture view format lacks the required formatless storage image access:", storage_format); return; } diff --git a/runtime/test/d3d12_texture_uav_test.cpp b/runtime/test/d3d12_texture_uav_test.cpp index 1b096b3995..08092f5697 100644 --- a/runtime/test/d3d12_texture_uav_test.cpp +++ b/runtime/test/d3d12_texture_uav_test.cpp @@ -25,6 +25,28 @@ namespace { using Microsoft::WRL::ComPtr; namespace g = leonida::gfx10; constexpr auto uav_heap = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; +constexpr auto formatless_read = VK_FORMAT_FEATURE_2_STORAGE_READ_WITHOUT_FORMAT_BIT; +constexpr auto formatless_write = VK_FORMAT_FEATURE_2_STORAGE_WRITE_WITHOUT_FORMAT_BIT; + +// Only the layer sees the masked capabilities. The real device and validation layer see the unmodified driver. +PFN_vkGetInstanceProcAddr real_instance_proc = nullptr; +PFN_vkGetPhysicalDeviceFormatProperties2 real_format_properties = nullptr; +VkFormatFeatureFlags2 missing_format_features = 0; + +VKAPI_ATTR void VKAPI_CALL masked_format_properties(VkPhysicalDevice physical, VkFormat format, + VkFormatProperties2* properties) { + real_format_properties(physical, format, properties); + if (format != VK_FORMAT_R32_UINT) return; + for (auto* next = static_cast(properties->pNext); next; next = next->pNext) + if (next->sType == VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_3) + reinterpret_cast(next)->optimalTilingFeatures &= ~missing_format_features; +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL masked_instance_proc(VkInstance instance, const char* name) { + if (std::strcmp(name, "vkGetPhysicalDeviceFormatProperties2") == 0) + return reinterpret_cast(masked_format_properties); + return real_instance_proc(instance, name); +} // Numeric values are also the branches selected by cs_texture_uav.asm. enum class Kind : UINT { one_d, array, volume, two_d, float_volume, float_array, atomic_volume }; @@ -359,6 +381,65 @@ bool check_refusals(ID3D12Device* device, D3D12_CPU_DESCRIPTOR_HANDLE slot) { return true; } +bool check_formatless_features(ID3D12Device* device, D3D12_CPU_DESCRIPTOR_HANDLE slot, bool sliced) { + using enum Kind; + const auto check = [&](Kind kind, const D3D12_RESOURCE_DESC& shape, UINT first, UINT count) { + ComPtr resource; + EXPECT(create_texture(device, shape, &resource)); + const auto view = uav(kind, 1, first, count); + device->CreateUnorderedAccessView(resource.Get(), nullptr, &view, slot); + const auto valid = read_slot(slot); + g::Image decoded{}; + EXPECT(g::decode(valid, decoded) && decoded.first_mip == 1 && decoded.mip_count == 1); + for (const auto missing : {formatless_read, formatless_write, formatless_read | formatless_write}) { + std::memcpy(reinterpret_cast(slot.ptr), valid.data(), sizeof(valid)); + missing_format_features = missing; + device->CreateUnorderedAccessView(resource.Get(), nullptr, &view, slot); + missing_format_features = 0; + if (read_slot(slot) != g::ImageWords{}) { + std::fprintf(stderr, "kind %u first slice %u: accepted mip 1 UAV without format features %#llx\n", + UINT(kind), first, static_cast(missing)); + return false; + } + } + return true; + }; + EXPECT(check(one_d, texture(one_d, 1), 0, 1)); + EXPECT(check(array, texture(array, 4), 1, 2)); + // The mask applies to the R32_UINT view, not its typeless resource's backing format. + const auto volume_shape = texture(volume, 8, DXGI_FORMAT_R32_TYPELESS); + EXPECT(check(volume, volume_shape, 0, ~0u)); + if (sliced) EXPECT(check(volume, volume_shape, 1, 2)); + return true; +} + +bool check_packed_formatless_exemption(ID3D12Device* device, vktest::Device& vk, + D3D12_CPU_DESCRIPTOR_HANDLE slot, bool sliced) { + VkFormatProperties features{}; + vk.instance_fn("vkGetPhysicalDeviceFormatProperties")( + vk.physical, VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, &features); + if (features.optimalTilingFeatures & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) { + std::puts("Packed R32_UINT exemption not exercised: native RGB9E5 storage"); + return true; + } + constexpr auto format = DXGI_FORMAT_R9G9B9E5_SHAREDEXP; + ComPtr resource; + if (!create_texture(device, texture(Kind::volume, 8, format), &resource)) { + std::puts("Packed R32_UINT exemption not exercised: no emulated RGB9E5 3D storage"); + return true; + } + const UINT first = sliced ? 1 : 0, count = sliced ? 2 : 4; + const auto view = uav(Kind::volume, 1, first, count, format); + missing_format_features = formatless_read | formatless_write; + device->CreateUnorderedAccessView(resource.Get(), nullptr, &view, slot); + missing_format_features = 0; + const auto key = read_slot(slot); + g::Image decoded{}; + EXPECT(g::decode(key, decoded) && decoded.first_mip == 1 && (key[4] & g::volume_uav_flag)); + EXPECT(key[7] == (g::volume_uav_word(first, count) | g::packed_uav_flag)); + return true; +} + bool check_standalone(bool sliced) { ComPtr device; EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&device)))); @@ -428,7 +509,11 @@ bool check_cpu_clear(ID3D12Device* device, vktest::Device& vk, D3D12_CPU_DESCRIP bool test(vktest::Device& vk, const char* shader, bool enable_slices) { rt::d3d12::VulkanDeviceInfo info{}; - info.get_instance_proc = vk.instance_proc; + real_instance_proc = vk.instance_proc; + real_format_properties = vk.instance_fn( + "vkGetPhysicalDeviceFormatProperties2"); + EXPECT(real_format_properties); + info.get_instance_proc = masked_instance_proc; info.instance = vk.instance; info.physical = vk.physical; info.device = vk.device; @@ -463,6 +548,8 @@ bool test(vktest::Device& vk, const char* shader, bool enable_slices) { using enum Kind; EXPECT(check_refusals(device.Get(), source)); + EXPECT(check_formatless_features(device.Get(), source, info.sliced_3d_uav)); + EXPECT(check_packed_formatless_exemption(device.Get(), vk, source, info.sliced_3d_uav)); Compute compute(vk); if (shader) EXPECT(compute.create(device.Get(), shader)); auto* dispatch = shader ? &compute : nullptr; diff --git a/runtime/test/shaders/cs_texture_uav.asm b/runtime/test/shaders/cs_texture_uav.asm index 4c1a7c8fc2..b5180a881a 100644 --- a/runtime/test/shaders/cs_texture_uav.asm +++ b/runtime/test/shaders/cs_texture_uav.asm @@ -14,8 +14,13 @@ v_lshl_add_u32 v3, v1, 4, v3 v_add_nc_u32_e32 v3, v0, v3 v_add_nc_u32_e32 v3, 1000, v3 s_cmp_eq_u32 s8, 0 -s_cbranch_scc0 6 +s_cbranch_scc0 11 image_load v4, v0, s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_1D unorm +; The sampled and formatless coherent reads must agree; a mismatch changes the result. +image_load v5, v0, s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_1D unorm glc dlc +s_waitcnt vmcnt(0) +v_xor_b32_e32 v5, v4, v5 +v_add_nc_u32_e32 v3, v3, v5 v_add_nc_u32_e32 v3, v3, v4 image_store v3, v0, s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_1D unorm s_endpgm @@ -27,8 +32,13 @@ v_add_nc_u32_e32 v3, v3, v4 image_store v3, v[0:1], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_1D_ARRAY unorm s_endpgm s_cmp_eq_u32 s8, 2 -s_cbranch_scc0 6 +s_cbranch_scc0 11 image_load v4, v[0:2], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm +; A sliced UAV must see the same texel via the rebased sampled alias and the sliced storage view. +image_load v5, v[0:2], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm glc dlc +s_waitcnt vmcnt(0) +v_xor_b32_e32 v5, v4, v5 +v_add_nc_u32_e32 v3, v3, v5 v_add_nc_u32_e32 v3, v3, v4 image_store v3, v[0:2], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm s_endpgm From e925b634551ed96d1ed097dfe17d7dfca0cdbe4d Mon Sep 17 00:00:00 2001 From: Vadson159 Date: Mon, 23 Nov 2026 17:24:09 +0100 Subject: [PATCH 004/110] d3d12_xs: route command queue slot 35 to ExecuteCommandLists --- runtime/shims/d3d12_xs_device.cpp | 26 +++++++++++ runtime/shims/d3d12_xs_device.h | 14 ++++-- runtime/test/queue_proxy_test.cpp | 72 +++++++++++++++++++++++------ runtime/test/xs_proxy_mock_test.cpp | 37 ++++++++++++++- 4 files changed, 129 insertions(+), 20 deletions(-) diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index e17a80353b..daa2af795c 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -674,7 +674,11 @@ static_assert(kQueueSlots * sizeof(void*) <= 4096 && kFenceSlots * sizeof(void*) kAllocatorSlots * sizeof(void*) <= 4096, "a table must fit in the first page of its reservation"); +constexpr unsigned kQueueExecuteCommandLists = 10; // (UINT, ID3D12CommandList* const*) constexpr unsigned kQueueSignal = 14, kQueueWait = 15; // (ID3D12Fence*, UINT64) +constexpr unsigned kQueueExecuteCommandListsX = 35; // console ExecuteCommandLists(count, lists) variant +static_assert(kQueueExecuteCommandLists < kQueuePublicSlots && kQueueExecuteCommandListsX < kQueueSlots, + "queue execution slots must stay within their respective tables"); struct ChildProxy { void** vtable; // offset 0: the caller's ID3D12CommandQueue* / ID3D12Fence* points here @@ -715,6 +719,7 @@ const char* child_public_name(unsigned slot) { if (slot < 8) return object[slot]; if constexpr (K == ChildKind::queue) { if (slot < kQueuePublicSlots) return queue[slot - 8]; + if (slot == kQueueExecuteCommandListsX) return "ExecuteCommandListsX"; } else if constexpr (K == ChildKind::fence) { if (slot < kFence1PublicSlots) return fence[slot - 8]; } else { @@ -970,6 +975,15 @@ LONG CALLBACK table_overrun_handler(EXCEPTION_POINTERS* info) { return EXCEPTION_CONTINUE_SEARCH; // diagnostics only: the fault goes on to the title's handlers or the crash } +std::uint64_t queue_execute_command_lists(ChildProxy* self, std::uint64_t count_word, std::uint64_t lists_word) { + // Pass zero-extended UINT in 64-bit RDX so both 32-bit PC implementations and 64-bit mock thunks see clean count. + using ExecuteFn = void(WINAPI*)(void*, std::uint64_t, ID3D12CommandList* const*); + reinterpret_cast(self->real_vtable[kQueueExecuteCommandLists])( + self->real, static_cast(static_cast(count_word)), + reinterpret_cast(lists_word)); + return 0; +} + template std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7, @@ -989,6 +1003,10 @@ std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_ reinterpret_cast(a2))); } else { note_child_slot(Slot); + if constexpr (K == ChildKind::queue && Slot == kQueueExecuteCommandListsX) { + d3d12_trace::record(child_trace_name(Slot)); + return queue_execute_command_lists(self, a1, a2); + } if (Slot >= self->slot_count) { bool expected = false; if (ChildStats::beyond_warned[Slot].compare_exchange_strong(expected, true, @@ -1004,6 +1022,9 @@ std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_ return hr_to_u64(E_NOTIMPL); } d3d12_trace::record(child_trace_name(Slot)); // "called": the real object's result is not inspected + if constexpr (K == ChildKind::queue && Slot == kQueueExecuteCommandLists) { + return queue_execute_command_lists(self, a1, a2); + } if constexpr (K == ChildKind::queue && (Slot == kQueueSignal || Slot == kQueueWait)) a1 = unwrap_object(a1); // The PC vtable entry with the real object as `this`; integer/pointer arguments, the hidden struct-return @@ -1742,6 +1763,11 @@ unsigned fence_proxy_slot_count(const void* fence) { unsigned queue_proxy_table_size() { return kQueueSlots; } unsigned fence_proxy_table_size() { return kFenceSlots; } + +bool queue_slot_overridden(unsigned slot) { + return slot <= 2 || slot == 7 || slot == kQueueSignal || slot == kQueueWait || + slot == kQueueExecuteCommandListsX; +} unsigned allocator_proxy_table_size() { return kAllocatorSlots; } unsigned allocator_proxy_slot_count(const void* allocator) { return is_allocator_proxy(allocator) ? static_cast(allocator)->slot_count : 0; diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index 0019ec5069..2bf25000ac 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -35,11 +35,12 @@ // // Command queues and fences (device slots 8, 75, 36, and 32 for a shared fence) come back wrapped in queue and fence // proxies of the same kind: the public chain (19 queue slots, 11 or 12 fence slots in SDK 10.0.26100) is forwarded -// in PC order, and a slot past it, up to the end of the proxy's table (128 queue, 64 fence slots), is logged with its -// first four argument words and refused with E_NOTIMPL. A slot past the table faults on the vtable read inside a -// reserved, never-committed region, and the fault is logged with the slot. That is where the console's queue methods -// (PresentX, SuspendX, ResumeX) will show up; their slots are not known and are not guessed, and that the console -// keeps the public slots is an assumption (docs/d3d12_command_objects.md §5.2). Heap, queue and fence proxies are +// in PC order. Queue slot 35 is the console ExecuteCommandLists(count, lists) variant and forwards to PC slot 10; +// every other slot past the public chain, up to the end of the proxy's table (128 queue, 64 fence slots), is logged +// with its first four argument words and refused with E_NOTIMPL. A slot past the table faults on the vtable read inside a +// reserved, never-committed region, and the fault is logged with the slot. PresentX, SuspendX and ResumeX slots past +// the public chain remain refused until measured and implemented, and that the console keeps the public slots is an +// assumption (docs/d3d12_command_objects.md §5.2). Heap, queue and fence proxies are // unwrapped wherever a device or queue method hands them to the real runtime: queue Signal/Wait (14/15), device // CreateSharedHandle (31), MakeResident/Evict (34/35), SetEventOnMultipleFenceCompletion (45), SetResidencyPriority // (46) and EnqueueMakeResident (50). Command lists are not wrapped, so ExecuteCommandLists passes them through and a @@ -107,6 +108,9 @@ unsigned queue_proxy_slot_count(const void* queue); unsigned fence_proxy_slot_count(const void* fence); unsigned queue_proxy_table_size(); unsigned fence_proxy_table_size(); +// True for queue slots handled by the proxy instead of forwarded verbatim past IUnknown: 0-2 (IUnknown), +// 7 (GetDevice), 14/15 (Signal/Wait unwrap fences), and 35 (Xbox ExecuteCommandLists variant -> PC slot 10). +bool queue_slot_overridden(unsigned slot); // Live references on a queue, fence or allocator proxy (0 for anything else). Test helper. unsigned long command_object_proxy_ref_count(const void* object); // Per-slot call counters and first-call flags, shared by all queue proxies and all fence proxies. diff --git a/runtime/test/queue_proxy_test.cpp b/runtime/test/queue_proxy_test.cpp index 3f46567f85..967313d53a 100644 --- a/runtime/test/queue_proxy_test.cpp +++ b/runtime/test/queue_proxy_test.cpp @@ -257,7 +257,9 @@ int check_slots(const Backend& b) { } } - // 10: ExecuteCommandLists passes the (real, not wrapped) command lists through. + // 10 and console slot 35: ExecuteCommandLists passes the (real, not wrapped) command lists through. + EXPECT(xs::queue_slot_overridden(35) && xs::queue_slot_overridden(14) && xs::queue_slot_overridden(15)); + EXPECT(!xs::queue_slot_overridden(10) && !xs::queue_slot_overridden(34)); { Ref allocator; EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, @@ -272,6 +274,11 @@ int check_slots(const Backend& b) { EXPECT(qhits(10) == before + 1); EXPECT(SUCCEEDED(queue->Signal(fence.p, 6))); if (wait_for(label, fence.p, 6)) return 1; + const std::uint64_t before35 = qhits(35); + EXPECT(raw_call(queue.p, 35, 1, reinterpret_cast(lists)) == 0); + EXPECT(qhits(35) == before35 + 1 && xs::queue_slot_first_call_seen(35)); + EXPECT(SUCCEEDED(queue->Signal(fence.p, 7))); + if (wait_for(label, fence.p, 7)) return 1; if (b.vulkan) { // The layer's own helpers find their queue behind the proxy. EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); @@ -293,17 +300,17 @@ int check_slots(const Backend& b) { // 14/15: Signal and Wait take fence proxies; the real queue gets the real fences. before = qhits(14); - EXPECT(SUCCEEDED(queue->Signal(fence.p, 7))); + EXPECT(SUCCEEDED(queue->Signal(fence.p, 8))); EXPECT(qhits(14) == before + 1); - if (wait_for(label, fence.p, 7)) return 1; + if (wait_for(label, fence.p, 8)) return 1; before = qhits(15); - EXPECT(SUCCEEDED(queue->Wait(fence.p, 8))); // the queue waits until the CPU signals 8 + EXPECT(SUCCEEDED(queue->Wait(fence.p, 9))); // the queue waits until the CPU signals 9 EXPECT(qhits(15) == before + 1); EXPECT(SUCCEEDED(queue->Signal(second.p, 1))); Sleep(50); EXPECT(second->GetCompletedValue() == 0); // still held by the Wait before = fhits(10); - EXPECT(SUCCEEDED(fence->Signal(8))); // fence 10, from the CPU + EXPECT(SUCCEEDED(fence->Signal(9))); // fence 10, from the CPU EXPECT(fhits(10) == before + 1); if (wait_for(label, second.p, 1)) return 1; @@ -359,12 +366,12 @@ int check_slots(const Backend& b) { EXPECT(fhits(7) == before + 1); } before = fhits(8); - EXPECT(fence->GetCompletedValue() == 8); + EXPECT(fence->GetCompletedValue() == 9); EXPECT(fhits(8) == before + 1); { Event done; before = fhits(9); - EXPECT(SUCCEEDED(fence->SetEventOnCompletion(8, done.h)) && done.set_within(5000)); + EXPECT(SUCCEEDED(fence->SetEventOnCompletion(9, done.h)) && done.set_within(5000)); EXPECT(fhits(9) == before + 1); } if (fence_slots == 12) { @@ -389,8 +396,9 @@ int check_slots(const Backend& b) { } } - // The refused tail: every slot from the end of the public chain to the end of the table. + // The refused tail: every unmodelled slot from the end of the public chain to the end of the table. for (unsigned slot = 19; slot < xs::queue_proxy_table_size(); ++slot) { + if (xs::queue_slot_overridden(slot)) continue; before = qhits(slot); EXPECT(as_hr(call_slot(queue.p, slot)) == E_NOTIMPL); EXPECT(qhits(slot) == before + 1 && xs::queue_slot_first_call_seen(slot)); @@ -1460,18 +1468,56 @@ int check_xbox_client(const Backend& b) { EXPECT(same); // the GPU really ran the list the queue proxy submitted } - // Device slot 50: EnqueueMakeResident with the objects and a fence proxy to signal. - EXPECT(SUCCEEDED(as_hr(raw(device, 50, D3D12_RESIDENCY_FLAG_NONE, 4, word(pageables), word(fence.p), 2)))); + // Second copy with fresh bytes, submitted through console ExecuteCommandLists slot 35. + { + std::uint8_t* bytes = nullptr; + EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast(&bytes)))); + for (UINT64 i = 0; i < kBytes; ++i) bytes[i] = static_cast(i * 11 + 5); + upload->Unmap(0, nullptr); + } + EXPECT(SUCCEEDED(allocator->Reset())); + EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr))); + D3D12_RESOURCE_BARRIER to_dest{}; + to_dest.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + to_dest.Transition.pResource = gpu.p; + to_dest.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + to_dest.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_SOURCE; + to_dest.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST; + list->ResourceBarrier(1, &to_dest); + list->CopyBufferRegion(gpu.p, 0, upload.p, 0, kBytes); + D3D12_RESOURCE_BARRIER to_source = to_dest; + to_source.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST; + to_source.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; + list->ResourceBarrier(1, &to_source); + list->CopyBufferRegion(readback.p, 0, gpu.p, 0, kBytes); + EXPECT(SUCCEEDED(list->Close())); + EXPECT(raw(queue.p, 35, 1, word(lists)) == 0); + EXPECT(SUCCEEDED(as_hr(raw(queue.p, 14, word(fence.p), 2)))); EXPECT(SUCCEEDED(as_hr(raw(fence.p, 9, 2, word(done.h)))) && done.set_within(5000)); + EXPECT(raw(fence.p, 8) >= 2); + { + std::uint8_t* bytes = nullptr; + const D3D12_RANGE read_range{0, kBytes}; + EXPECT(SUCCEEDED(readback->Map(0, &read_range, reinterpret_cast(&bytes)))); + bool same = true; + for (UINT64 i = 0; i < kBytes; ++i) same = same && bytes[i] == static_cast(i * 11 + 5); + const D3D12_RANGE nothing{0, 0}; + readback->Unmap(0, ¬hing); + EXPECT(same); // the GPU really ran the list submitted via queue slot 35 + } + + // Device slot 50: EnqueueMakeResident with the objects and a fence proxy to signal. + EXPECT(SUCCEEDED(as_hr(raw(device, 50, D3D12_RESIDENCY_FLAG_NONE, 4, word(pageables), word(fence.p), 3)))); + EXPECT(SUCCEEDED(as_hr(raw(fence.p, 9, 3, word(done.h)))) && done.set_within(5000)); // Queue slot 15 holds the queue until the CPU (fence slot 10) signals; device slot 45 then sees both fences. - EXPECT(SUCCEEDED(as_hr(raw(queue.p, 15, word(fence.p), 3)))); + EXPECT(SUCCEEDED(as_hr(raw(queue.p, 15, word(fence.p), 4)))); EXPECT(SUCCEEDED(as_hr(raw(queue.p, 14, word(second.p), 1)))); Sleep(50); EXPECT(raw(second.p, 8) == 0); - EXPECT(SUCCEEDED(as_hr(raw(fence.p, 10, 3)))); + EXPECT(SUCCEEDED(as_hr(raw(fence.p, 10, 4)))); ID3D12Fence* both[] = {fence.p, second.p}; - const UINT64 values[] = {3, 1}; + const UINT64 values[] = {4, 1}; EXPECT(SUCCEEDED(as_hr(raw(device, 45, word(both), word(values), 2, D3D12_MULTIPLE_FENCE_WAIT_FLAG_ALL, word(done.h)))) && done.set_within(5000)); diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index f0030116bd..c916402e42 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -767,6 +767,37 @@ int check_xbox_slots() { #endif } +// ---- 7b. Xbox queue ExecuteCommandLists variant (queue slot 35 -> PC slot 10) ---- + +int check_xbox_queue_slots() { + Mock* mock = nullptr; + void* device = make_device(mock, 9, true); + EXPECT(device); + void* queue = make_queue(device); + EXPECT(queue); + Mock* const queue_mock = reinterpret_cast(xs::queue_proxy_real_queue(queue)); + xs::reset_device_proxy_stats(); + + EXPECT(xs::queue_slot_overridden(35) && xs::queue_slot_overridden(14) && xs::queue_slot_overridden(15)); + EXPECT(!xs::queue_slot_overridden(10) && !xs::queue_slot_overridden(34) && !xs::queue_slot_overridden(36)); + + void* fake_lists[2] = {reinterpret_cast(0x12340000), reinterpret_cast(0x56780000)}; + EXPECT(raw(queue, 35, (0xdeadbeefull << 32) | 2ull, word(fake_lists)) == 0); + EXPECT(xs::queue_slot_hits(35) == 1 && xs::queue_slot_first_call_seen(35)); + EXPECT(xs::queue_slot_hits(10) == 0); + EXPECT(queue_mock->calls[35] == 0 && queue_mock->calls[10] == 1); + EXPECT(queue_mock->args[10][0] == 2 && queue_mock->args[10][1] == word(fake_lists)); + + EXPECT(raw(queue, 35, 0, 0) == 0); + EXPECT(xs::queue_slot_hits(35) == 2 && queue_mock->calls[35] == 0 && queue_mock->calls[10] == 2); + EXPECT(queue_mock->args[10][0] == 0 && queue_mock->args[10][1] == 0); + + EXPECT(release(queue) == 0 && release(device) == 0 && mock->refs == 0); + std::printf("%s: queue slot 35 routes ExecuteCommandLists(count, lists) to PC slot 10 with UINT count masking\n", + g_label); + return 0; +} + // ---- 8. Environment overrides for the Xbox device slots (one process each, read once) ---- int run_env_slots(bool valid) { @@ -835,8 +866,10 @@ int check_tail(bool want_guarded) { // Signal (14) still reaches the real queue, with the real fence. EXPECT(hr_of(raw(queue, 14, word(fence), 5)) == S_OK && queue_mock->calls[14] == 1 && queue_mock->args[14][0] == word(xs::fence_proxy_real_fence(fence)) && queue_mock->args[14][1] == 5); - for (unsigned slot = 19; slot < xs::queue_proxy_table_size(); ++slot) + for (unsigned slot = 19; slot < xs::queue_proxy_table_size(); ++slot) { + if (xs::queue_slot_overridden(slot)) continue; EXPECT(hr_of(raw(queue, slot)) == E_NOTIMPL && queue_mock->calls[slot] == 0); + } for (unsigned slot = 12; slot < xs::fence_proxy_table_size(); ++slot) EXPECT(hr_of(raw(fence, slot)) == E_NOTIMPL); EXPECT(xs::queue_table_overruns() == 0 && xs::fence_table_overruns() == 0); EXPECT(release(queue) == 0 && release(fence) == 0 && release(device) == 0 && mock->refs == 0); @@ -948,7 +981,7 @@ int main(int argc, char** argv) { } if (argc != 1) return 2; if (check_tail(true) || check_levels() || check_fence1() || check_create_failures() || check_open_shared() || - check_alloc_failures() || check_allocators() || check_xbox_slots()) + check_alloc_failures() || check_allocators() || check_xbox_slots() || check_xbox_queue_slots()) return 1; std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news); return 0; From d3a1c290b5738694e4d3b78a66350e70e0eb5846 Mon Sep 17 00:00:00 2001 From: Daiko Date: Mon, 23 Nov 2026 17:39:20 +0100 Subject: [PATCH 005/110] d3d12: persist the pipeline cache across launches (D3D-704) PSOs a session built were compiled again by the next one. The layer already read the `pipelines` stage's pipeline_cache.bin beside gta6rt.exe (#367), but never wrote anything back. Now the runtime keeps its own cache in pipeline_cache.session.bin beside it: vkGetPipelineCacheData on device teardown, then vkMergePipelineCaches into the cache at the next launch. Vulkan takes one blob per create, so the offline seed and the session file are two caches merged together rather than one file. They are deliberately separate files, so a run can never replace the multi-GB corpus cache with the handful of pipelines it compiled. The write is capped at 256 MiB (LEONIDA_PIPELINE_CACHE_BYTES=, 0 turns it off): a cache seeded from the corpus comes back as the whole union, which is not worth rewriting at every exit; past the cap the previous session file is left alone. A foreign or truncated session file is ignored with one line, and so is a failed write (a read-only install directory). The header check moves to runtime/src/pipeline_cache_store.h, shared with the offline seed and tested without Vulkan (runtime/test/pipeline_cache_store_test.cpp: the limit parser and the 32-byte VkPipelineCacheHeaderVersionOne comparison). write_pipeline_cache_file moves from runtime/test to runtime/src so the runtime and vk_pipeline_check use the same staged write. Not run: this machine has neither MSVC nor the Windows SDK, so the shim itself is compiled by the Windows job. The portable test passes here (23/23 ctest on Linux). The end-to-end check needs a Vulkan GPU: run d3d12_vulkan_device_test twice and look for "wrote N bytes to pipeline_cache.session.bin", then "merged N bytes" on the second run. --- docs/d3d12_vulkan.md | 8 ++ runtime/CMakeLists.txt | 4 + runtime/shims/d3d12_vulkan_device.cpp | 130 ++++++++++++++++++-- runtime/{test => src}/pipeline_cache_file.h | 3 + runtime/src/pipeline_cache_store.h | 69 +++++++++++ runtime/src/vulkan_backend.h | 2 +- runtime/test/pipeline_cache_file_test.cpp | 2 +- runtime/test/pipeline_cache_store_test.cpp | 93 ++++++++++++++ runtime/test/vk_pipeline_check.cpp | 2 +- 9 files changed, 298 insertions(+), 15 deletions(-) rename runtime/{test => src}/pipeline_cache_file.h (90%) create mode 100644 runtime/src/pipeline_cache_store.h create mode 100644 runtime/test/pipeline_cache_store_test.cpp diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index a14d67bcc3..02846e4298 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2023,6 +2023,14 @@ Pipeline creation: and pipeline-cache UUID. When the file is absent or incompatible, the runtime starts with an empty cache. The offline checker matches the runtime's layout and subgroup request for compute shaders with no descriptor bindings and the standard 144-byte push-constant range. + The runtime also keeps what it compiled itself: `pipeline_cache.session.bin`, written from + `vkGetPipelineCacheData` on device teardown and merged into the cache at the next launch with + `vkMergePipelineCaches` (the offline seed and the session file cannot be passed together as one + `VkPipelineCacheCreateInfo`). The two files are separate so a run never replaces the multi-GB corpus cache with + the handful of pipelines it happened to compile. The session write is capped at 256 MiB + (`LEONIDA_PIPELINE_CACHE_BYTES=`, `0` turns it off): a cache seeded with the corpus file returns the whole + union, which is not worth rewriting at every exit. A session file from another device, driver or pipeline-cache + UUID is ignored with one line, and a write that fails (a read-only install directory) leaves the previous file. `GetCachedBlob` records the vendor, device, driver version, `pipelineCacheUUID` and a SHA-256 of the description without `Flags`, sealed by a checksum (`runtime/src/cached_pso.h`). The answers are the host's, measured on an RTX 3060 and WARP: the same description is accepted; another diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index b801320744..1afb3837bd 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -440,6 +440,10 @@ if(BUILD_TESTING) add_executable(pipeline_cache_file_test test/pipeline_cache_file_test.cpp) add_test(NAME pipeline_cache_file COMMAND pipeline_cache_file_test) + # D3D-704's session-cache limit and header check: pure stdlib, no Vulkan headers. + add_executable(pipeline_cache_store_test test/pipeline_cache_store_test.cpp) + add_test(NAME pipeline_cache_store COMMAND pipeline_cache_store_test) + add_executable(xdxr_build_output_test test/xdxr_build_output_test.cpp) add_test(NAME xdxr_build_output COMMAND xdxr_build_output_test) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index c7e3d99942..018c751364 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -23,6 +23,8 @@ #include "../src/vulkan_memory.h" #include "../src/resource_tiling.h" #include "../src/cached_pso.h" +#include "../src/pipeline_cache_file.h" +#include "../src/pipeline_cache_store.h" #include "../src/conservative_raster.h" #include "../src/resource_detile.h" #include "../src/shader_library.h" @@ -50,6 +52,7 @@ #include #include #include +#include #include #include #include @@ -66,6 +69,8 @@ constexpr UINT kDescriptorSize = descriptor_size; // for unbound vertex and index buffers to read (D3D12 reads zeros there). constexpr VkDeviceSize kArenaReserved = 64 * 1024; static_assert(sizeof(leonida::TargetView) <= kDescriptorSize); +// pipeline_cache_store.h reads this layout without vulkan.h (D3D-704); remember the two. +static_assert(sizeof(VkPipelineCacheHeaderVersionOne) == leonida::pipeline_cache_store::header_bytes); // The shader model and root signature version this layer can honour. Nothing in the runtime compiles DXIL: the // game's shaders arrive as SPIR-V from the offline translator, and the only DXIL path (the BVH builder) is lowered @@ -133,6 +138,25 @@ std::filesystem::path pipeline_cache_path() { return std::filesystem::path(path).parent_path() / L"pipeline_cache.bin"; } +// What the runtime itself compiled, kept next to the offline seed and never written over it (D3D-704). +std::filesystem::path pipeline_cache_session_path() { + std::filesystem::path path = pipeline_cache_path(); + if (!path.empty()) path.replace_filename(L"pipeline_cache.session.bin"); + return path; +} + +// LEONIDA_PIPELINE_CACHE_BYTES, in bytes; 0 turns the session file off. One line for a value that is not a number. +std::size_t pipeline_cache_save_limit() { + char text[32] = {}; + size_t length = 0; + const bool present = getenv_s(&length, text, "LEONIDA_PIPELINE_CACHE_BYTES") == 0 && length > 1; + const auto limit = leonida::pipeline_cache_store::parse_save_limit(present ? text : ""); + if (!limit.valid) + std::fprintf(stderr, "[rt] d3d12: LEONIDA_PIPELINE_CACHE_BYTES=%s is not a byte count; using %zu\n", text, + limit.bytes); + return limit.bytes; +} + // A corpus cache may be several GiB. Keep the read-only view alive through vkCreatePipelineCache // and deny writers while the view is in use. class PipelineCacheSeed { @@ -165,13 +189,7 @@ class PipelineCacheSeed { std::size_t size() const { return size_; } bool compatible(const leonida::cached_pso::Identity& identity) const { - static_assert(sizeof(VkPipelineCacheHeaderVersionOne) == 32); - VkPipelineCacheHeaderVersionOne header{}; - // The header is little-endian, like the host. The driver interprets the opaque payload. - std::memcpy(&header, data_, sizeof(header)); - return header.headerSize == sizeof(header) && header.headerVersion == VK_PIPELINE_CACHE_HEADER_VERSION_ONE && - header.vendorID == identity.vendor && header.deviceID == identity.device && - std::memcmp(header.pipelineCacheUUID, identity.cache_uuid, VK_UUID_SIZE) == 0; + return leonida::pipeline_cache_store::header_matches(data_, size_, identity); } private: @@ -199,6 +217,90 @@ VkPipelineCache create_seeded_pipeline_cache(PFN_vkCreatePipelineCache create_ca return cache; } +// D3D-704: merges what earlier launches compiled into the cache the pipelines are created against. The offline seed +// and the session file cannot be handed over as one VkPipelineCacheCreateInfo -- Vulkan reads a single blob -- so the +// session cache is created on its own and merged in. A missing, foreign or corrupt session file leaves the cache as +// it was, and so does a driver that does not expose vkMergePipelineCaches. +void merge_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache, + const leonida::cached_pso::Identity& identity) { + if (!cache || !vk.vkCreatePipelineCache || !vk.vkDestroyPipelineCache || !vk.vkMergePipelineCaches) return; + if (!pipeline_cache_save_limit()) return; // LEONIDA_PIPELINE_CACHE_BYTES=0 turns the session file off + const PipelineCacheSeed seed(pipeline_cache_session_path()); + if (!seed.data()) return; + if (!seed.compatible(identity)) { + std::fprintf(stderr, "[rt] d3d12: pipeline_cache.session.bin does not match this Vulkan device\n"); + return; + } + const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, nullptr, 0, seed.size(), + seed.data()}; + VkPipelineCache session = VK_NULL_HANDLE; + if (vk.vkCreatePipelineCache(device, &create, nullptr, &session) != VK_SUCCESS) { + std::fprintf(stderr, "[rt] d3d12: Vulkan declined pipeline_cache.session.bin\n"); + return; + } + const VkResult result = vk.vkMergePipelineCaches(device, cache, 1, &session); + vk.vkDestroyPipelineCache(device, session, nullptr); + if (result == VK_SUCCESS) + std::fprintf(stderr, "[rt] d3d12: merged %zu bytes from pipeline_cache.session.bin\n", seed.size()); + else + std::fprintf(stderr, "[rt] d3d12: vkMergePipelineCaches on pipeline_cache.session.bin returned %d; ignored\n", + static_cast(result)); +} + +// Writes what this device compiled for the next launch (D3D-704). Called once the device is idle, before the cache +// is destroyed. Past the cap nothing is written: the blob from an earlier, smaller session stays, which is better +// than replacing it with one the next launch would keep refusing to save. +void save_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache) { + if (!cache || !vk.vkGetPipelineCacheData) return; + const std::size_t limit = pipeline_cache_save_limit(); + if (!limit) return; // LEONIDA_PIPELINE_CACHE_BYTES=0 turns the session file off + const auto over_limit = [limit](std::size_t size) { + std::fprintf(stderr, + "[rt] d3d12: pipeline cache is %zu bytes, over the %zu-byte session limit " + "(LEONIDA_PIPELINE_CACHE_BYTES); pipeline_cache.session.bin left as it was\n", + size, limit); + }; + std::size_t size = 0; + if (vk.vkGetPipelineCacheData(device, cache, &size, nullptr) != VK_SUCCESS || + size <= sizeof(VkPipelineCacheHeaderVersionOne)) + return; + if (size > limit) { + over_limit(size); + return; + } + std::vector data; + try { + // Room to spare in case the driver counts the blob short between the query and the read. Nothing creates + // pipelines while the device is torn down, so this is a belt-and-braces margin, not a retry loop. + data.resize(size + (size >> 4)); + } catch (const std::bad_alloc&) { + std::fprintf(stderr, + "[rt] d3d12: no memory for the %zu-byte pipeline cache; pipeline_cache.session.bin not " + "written\n", + size); + return; + } + std::size_t written = data.size(); + const VkResult result = vk.vkGetPipelineCacheData(device, cache, &written, data.data()); + if (result != VK_SUCCESS || written < sizeof(VkPipelineCacheHeaderVersionOne) || written > data.size()) { + std::fprintf(stderr, + "[rt] d3d12: could not read the pipeline cache (%d); pipeline_cache.session.bin not written\n", + static_cast(result)); + return; + } + if (written > limit) { + over_limit(written); + return; + } + const std::filesystem::path path = pipeline_cache_session_path(); + if (path.empty()) return; + if (const std::error_code error = write_pipeline_cache_file(path, data.data(), written)) { + std::fprintf(stderr, "[rt] d3d12: pipeline_cache.session.bin not written: %s\n", error.message().c_str()); + return; + } + std::fprintf(stderr, "[rt] d3d12: wrote %zu bytes to pipeline_cache.session.bin\n", written); +} + // A shader whose subgroup size cannot be had runs at the device's: inexact if it crosses the halves of a wave64 (or, // for a wave32 shader on a 64-wide default, reads lanes that are not its own). Logged once per stage with the first // shader's name, then again at 10, 100, 1000... of that stage so a whole corpus stays readable. @@ -609,10 +711,12 @@ struct DeviceState { const auto& vk = context->vk; if (!vk.vkCreatePipelineCache || !vk.vkDestroyPipelineCache) return; pipeline_cache_handle = create_seeded_pipeline_cache(vk.vkCreatePipelineCache, info.device, pso_identity); - if (pipeline_cache_handle) return; - const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO}; - if (vk.vkCreatePipelineCache(info.device, &create, nullptr, &pipeline_cache_handle) != VK_SUCCESS) - pipeline_cache_handle = VK_NULL_HANDLE; + if (!pipeline_cache_handle) { + const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO}; + if (vk.vkCreatePipelineCache(info.device, &create, nullptr, &pipeline_cache_handle) != VK_SUCCESS) + pipeline_cache_handle = VK_NULL_HANDLE; + } + merge_session_pipeline_cache(vk, info.device, pipeline_cache_handle, pso_identity); }); // Without EXTERNALLY_SYNCHRONIZED_BIT the driver synchronizes concurrent pipeline creation using this cache. return pipeline_cache_handle; @@ -5208,8 +5312,10 @@ class Device final vk.vkDestroyBuffer(state_.info.device, state_.arena.buffer, nullptr); if (state_.arena.memory) vk.vkFreeMemory(state_.info.device, state_.arena.memory, nullptr); } - if (state_.pipeline_cache_handle) + if (state_.pipeline_cache_handle) { + save_session_pipeline_cache(state_.context->vk, state_.info.device, state_.pipeline_cache_handle); state_.context->vk.vkDestroyPipelineCache(state_.info.device, state_.pipeline_cache_handle, nullptr); + } state_.context.reset(); if (owned_.device) owned_.destroy_device(owned_.device, nullptr); if (owned_.instance) owned_.destroy_instance(owned_.instance, nullptr); diff --git a/runtime/test/pipeline_cache_file.h b/runtime/src/pipeline_cache_file.h similarity index 90% rename from runtime/test/pipeline_cache_file.h rename to runtime/src/pipeline_cache_file.h index 400138ef7d..95afbd10ad 100644 --- a/runtime/test/pipeline_cache_file.h +++ b/runtime/src/pipeline_cache_file.h @@ -1,4 +1,7 @@ // Publish a checkpoint only after every byte has reached a closed, same-directory staging file. +// +// Used by vk_pipeline_check (its corpus checkpoints) and by the runtime itself, which writes the session cache on +// device teardown (pipeline_cache_store.h). A reader of the old file keeps it open until its rename completes. #pragma once #include diff --git a/runtime/src/pipeline_cache_store.h b/runtime/src/pipeline_cache_store.h new file mode 100644 index 0000000000..6d519d99b1 --- /dev/null +++ b/runtime/src/pipeline_cache_store.h @@ -0,0 +1,69 @@ +// Persisting the runtime's VkPipelineCache across launches (D3D-704). +// +// Two files sit beside gta6rt.exe, and they are not interchangeable: +// +// pipeline_cache.bin the offline corpus seed the `pipelines` build stage writes (#367). Read only. +// pipeline_cache.session.bin what the runtime compiled last time. Written on device teardown. +// +// Keeping them apart means a run can never replace the multi-GB corpus cache with the handful of pipelines it +// happened to compile. On the next launch both are loaded and merged, so the offline entries and the previous +// session's entries are available together. +// +// This header is pure stdlib on purpose (it does not include vulkan.h): pipeline_cache_store_test builds on hosts +// where CMake has no Vulkan headers. The byte layout below is VkPipelineCacheHeaderVersionOne, whose 32 bytes are +// part of Vulkan's ABI, not something a driver chooses. +#pragma once + +#include +#include +#include +#include + +#include "cached_pso.h" + +namespace leonida::pipeline_cache_store { + +// A session cache normally holds what one boot compiled (a few MB to a few hundred MB). The cap is what keeps a +// cache seeded from the multi-GB corpus file -- whose data comes back as the whole union -- from being rewritten +// at every exit. Past it the previous session file is left alone; raise the limit with +// LEONIDA_PIPELINE_CACHE_BYTES when a session really compiles that much. +inline constexpr std::size_t default_save_limit = std::size_t{256} << 20; // 256 MiB + +struct SaveLimit { + std::size_t bytes = default_save_limit; + bool valid = true; // false when the text was not a byte count; bytes then stays at the default +}; + +// LEONIDA_PIPELINE_CACHE_BYTES: a decimal byte count, 0 turning the session file off entirely. Empty or absent +// means the default; stray text, a sign or an overflow is reported by the caller and the default is used. +inline SaveLimit parse_save_limit(const char* text) { + if (!text || !*text) return {}; + std::size_t value = 0; + for (const char* p = text; *p; ++p) { + if (*p < '0' || *p > '9') return {default_save_limit, false}; + const std::size_t digit = static_cast(*p - '0'); + if (value > (std::numeric_limits::max() - digit) / 10) return {default_save_limit, false}; + value = value * 10 + digit; + } + return {value, true}; +} + +inline constexpr std::size_t header_bytes = 32; +inline constexpr std::uint32_t header_version_one = 1; + +inline std::uint32_t read_u32(const std::uint8_t* p) { + return std::uint32_t(p[0]) | (std::uint32_t(p[1]) << 8) | (std::uint32_t(p[2]) << 16) | + (std::uint32_t(p[3]) << 24); +} + +// True when the blob's header names this physical device and pipeline-cache UUID, which is what a driver requires +// before it will read the opaque payload. The header is little-endian, like the host. +inline bool header_matches(const void* data, std::size_t size, const cached_pso::Identity& identity) { + if (!data || size < header_bytes) return false; + const auto* bytes = static_cast(data); + return read_u32(bytes) == header_bytes && read_u32(bytes + 4) == header_version_one && + read_u32(bytes + 8) == identity.vendor && read_u32(bytes + 12) == identity.device && + std::memcmp(bytes + 16, identity.cache_uuid, sizeof(identity.cache_uuid)) == 0; +} + +} // namespace leonida::pipeline_cache_store diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index e659a762dc..4303b55ef7 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -95,7 +95,7 @@ struct VulkanDeviceFunctions { X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \ X(vkCmdSetBlendConstants) X(vkCmdDraw) \ X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) X(vkGetImageSparseMemoryRequirements) \ - X(vkCreatePipelineCache) X(vkDestroyPipelineCache) \ + X(vkCreatePipelineCache) X(vkDestroyPipelineCache) X(vkGetPipelineCacheData) X(vkMergePipelineCaches) \ X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) X(vkCmdDrawMeshTasksEXT) \ X(vkCreateRenderPass2) X(vkDestroyRenderPass) X(vkCreateFramebuffer) X(vkDestroyFramebuffer) \ X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass) diff --git a/runtime/test/pipeline_cache_file_test.cpp b/runtime/test/pipeline_cache_file_test.cpp index 73dad65de8..f24694a56d 100644 --- a/runtime/test/pipeline_cache_file_test.cpp +++ b/runtime/test/pipeline_cache_file_test.cpp @@ -1,5 +1,5 @@ // Exercise checkpoint replacement and real filesystem errors without a Vulkan device. -#include "pipeline_cache_file.h" +#include "../src/pipeline_cache_file.h" #include #include diff --git a/runtime/test/pipeline_cache_store_test.cpp b/runtime/test/pipeline_cache_store_test.cpp new file mode 100644 index 0000000000..dbf174768b --- /dev/null +++ b/runtime/test/pipeline_cache_store_test.cpp @@ -0,0 +1,93 @@ +// The two pure decisions behind D3D-704: how large a session cache may be (LEONIDA_PIPELINE_CACHE_BYTES) and +// whether a blob's VkPipelineCacheHeaderVersionOne names this device. No Vulkan, no GPU, no files. +#include "../src/pipeline_cache_store.h" + +#include +#include +#include +#include +#include + +#define CHECK(condition) do { \ + if (!(condition)) { \ + std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \ + return 1; \ + } \ +} while (0) + +namespace store = leonida::pipeline_cache_store; + +static void put32(std::uint8_t* p, std::uint32_t value) { + for (int i = 0; i < 4; ++i) p[i] = static_cast(value >> (8 * i)); +} + +static int test_limit() { + using store::default_save_limit; + // Absent, empty and the default knob. + CHECK(store::parse_save_limit(nullptr).bytes == default_save_limit); + CHECK(store::parse_save_limit(nullptr).valid); + CHECK(store::parse_save_limit("").bytes == default_save_limit); + // 0 is the documented "off", not a typo, and leading zeros are still a number. + CHECK(store::parse_save_limit("0").bytes == 0); + CHECK(store::parse_save_limit("0").valid); + CHECK(store::parse_save_limit("007").bytes == 7); + CHECK(store::parse_save_limit("1048576").bytes == 1048576); + const std::string largest = std::to_string(std::numeric_limits::max()); + CHECK(store::parse_save_limit(largest.c_str()).bytes == std::numeric_limits::max()); + // Anything that is not a plain byte count falls back to the default and says the value was rejected. + for (const char* text : {"-1", "+1", " 1", "1 ", "12x", "0x10", "1.5", "99999999999999999999999999"}) { + const auto limit = store::parse_save_limit(text); + CHECK(!limit.valid); + CHECK(limit.bytes == default_save_limit); + } + return 0; +} + +static int test_header() { + leonida::cached_pso::Identity identity; + identity.vendor = 0x1002; + identity.device = 0x73ff; + identity.driver = 0x02000d0b; + + std::uint8_t header[store::header_bytes] = {}; + put32(header, store::header_bytes); + put32(header + 4, store::header_version_one); + put32(header + 8, identity.vendor); + put32(header + 12, identity.device); + for (int i = 0; i < 16; ++i) header[16 + i] = identity.cache_uuid[i] = static_cast(i + 1); + CHECK(store::header_matches(header, sizeof(header), identity)); + // Extra payload past the header does not matter: the driver reads the header and then its own data. + std::uint8_t blob[store::header_bytes + 8] = {}; + std::memcpy(blob, header, sizeof(header)); + CHECK(store::header_matches(blob, sizeof(blob), identity)); + + // Too short and null are "no cache", never a read past the end. + CHECK(!store::header_matches(header, store::header_bytes - 1, identity)); + CHECK(!store::header_matches(nullptr, store::header_bytes, identity)); + + // The four fields a driver checks before trusting a blob from another device, driver or header version. + auto differs = [&](int offset, std::uint32_t value) { + std::uint8_t changed[store::header_bytes]; + std::memcpy(changed, header, sizeof(changed)); + put32(changed + offset, value); + return !store::header_matches(changed, sizeof(changed), identity); + }; + CHECK(differs(0, store::header_bytes + 4)); + CHECK(differs(4, store::header_version_one + 1)); + CHECK(differs(8, identity.vendor + 1)); + CHECK(differs(12, identity.device + 1)); + std::uint8_t uuid[store::header_bytes]; + std::memcpy(uuid, header, sizeof(uuid)); + uuid[16] ^= 0xff; + CHECK(!store::header_matches(uuid, sizeof(uuid), identity)); + // vendorID/deviceID are u32s little-endian; the same bytes read the other way name another device. + leonida::cached_pso::Identity swapped = identity; + swapped.vendor = 0x02100000; + CHECK(!store::header_matches(header, sizeof(header), swapped)); + return 0; +} + +int main() { + if (const int failed = test_limit()) return failed; + return test_header(); +} diff --git a/runtime/test/vk_pipeline_check.cpp b/runtime/test/vk_pipeline_check.cpp index 00b58901b4..12260b1bef 100644 --- a/runtime/test/vk_pipeline_check.cpp +++ b/runtime/test/vk_pipeline_check.cpp @@ -47,7 +47,7 @@ // pipelines stage's retry. #include "vulkan_loader.h" #include "vk_device_pick.h" -#include "pipeline_cache_file.h" +#include "../src/pipeline_cache_file.h" #include "pipeline_cache_snapshot.h" #include "large_module_gate.h" #include "pipeline_summary.h" From 86cd0c5f2a392f6637ff5724d2786b12084b28b7 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Mon, 23 Nov 2026 17:45:10 +0100 Subject: [PATCH 006/110] d3d12: draw the console's rectangle lists (17, PSO type 19) and quad lists (19) as triangles A rectangle list is three corners; the fourth is v2 + v3 - v1 for the position and every interpolant, after the vertex stage. A quad list is four vertices per quad. Vulkan has neither. A PSO with topology type 19 was refused (E_INVALIDARG) and the two list topologies drew as a plain triangle list. Rectangle list: the PSO becomes a triangle-list pipeline with a generated geometry stage (src/rect_list_geometry.h), built from the vertex shader's own SPIR-V outputs, that emits the strip v1 v2 v3 v4. Quad list: one triangle fan per quad (0 1 2, 0 2 3), drawn with the index values 4q..4q+3 so the translated vertex id (VertexIndex - BaseVertex) is right; non-indexed draws read a shared 0, 1, 2, ... buffer reserved in the arena. Facts from xvalkyrie (GPL-3.0, commit 53af7df77c10); no code copied. --- docs/d3d12_vulkan.md | 8 +- runtime/CMakeLists.txt | 9 + runtime/shims/d3d12_vulkan_device.cpp | 45 +++- runtime/src/rect_list_geometry.h | 214 ++++++++++++++++ runtime/src/vulkan_backend.h | 8 + runtime/src/vulkan_replay.h | 29 +++ runtime/test/d3d12_rect_list_test.cpp | 341 ++++++++++++++++++++++++++ 7 files changed, 649 insertions(+), 5 deletions(-) create mode 100644 runtime/src/rect_list_geometry.h create mode 100644 runtime/test/d3d12_rect_list_test.cpp diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 33b52d422f..76a8b16a7d 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -169,7 +169,7 @@ The command-list surface maps to the IR as follows: | `SetGraphicsRootSignature` / `SetComputeRootSignature` | state; select the pipeline layout and root map | | `Set*Root32BitConstant(s)` / `Set*Root*View` / `Set*RootDescriptorTable` | update root args; build the push-constant block at the draw/dispatch | | `SetDescriptorHeaps` | state; scan/populate the bindless arrays and hash table at execute | -| `IASetVertexBuffers` / `IASetIndexBuffer` / `IASetPrimitiveTopology` | state; bind arena buffer + offset, dynamic topology | +| `IASetVertexBuffers` / `IASetIndexBuffer` / `IASetPrimitiveTopology` | state; bind arena buffer + offset, dynamic topology. The console's rectangle list (17, PSO topology type 19) and quad list (19) are drawn as triangles, see *Console rectangle and quad lists* below | | `RSSetViewports` / `RSSetScissorRects` | state; dynamic viewport/scissor | | `OMSetRenderTargets` / `OMSetBlendFactor` / `OMSetStencilRef` | state; rendering scope and dynamic state | | `DrawInstanced` / `DrawIndexedInstanced` | command with a state snapshot | @@ -2080,6 +2080,12 @@ The trace will enumerate them. - **What it doesn't cover:** whether the console flattens a 3D `DispatchMesh` grid the same way. That is an open question in `docs/design.md`, "Mesh shaders"; the test shader reads the workgroup ID directly. +### Console rectangle and quad lists + +The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiveTopology(17)`, with a PSO whose topology type is 19) and quad list (`IASetPrimitiveTopology(19)`). The facts are from xvalkyrie (GPL-3.0, commit `53af7df77c10`; no code taken): a rectangle is three corners and the fourth is v2 + v3 - v1 for the position and every interpolant, after the vertex stage; a quad is four vertices. The layer draws both as triangles (`d3d12_rect_list_test`, RTX 4090: 4096 of 4096 pixels, the colour plane exact, quad list bit-exact). +- **Rectangle list**: PSO type 19 builds a triangle-list pipeline plus a generated geometry stage (`src/rect_list_geometry.h`, written from the vertex shader's own outputs) that takes the three corners and emits the strip v1 v2 v3 v4 (same winding). It has to be post-vertex-stage: the translated vertex shaders fetch by V# themselves, and the fourth corner is a function of what they write. A corner value with the same bits at all three corners (a flat attribute) is copied. Needs `geometryShader` (else `E_NOTIMPL`), no application GS, and a vertex shader with no ClipDistance, CullDistance, Layer or ViewportIndex output. +- **Quad list**: one four-vertex triangle fan per quad (the pattern 0 1 2, 0 2 3). The translated vertex id is `VertexIndex - BaseVertex`, so each fan reads the index values 4q..4q+3: from the application's index buffer when the draw is indexed, else from a shared 0, 1, 2, ... buffer in the arena's reserved pages (16384 quads per draw at most), with the draw's first vertex as the vertex offset. The PSO type is the ordinary triangle type. + ## 4. Object model mapping | D3D12 / Xbox object | Vulkan / layer object | Notes | diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 2ab8c7bc84..3be2911a9e 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2099,6 +2099,15 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_translated_draw COMMAND d3d12_translated_draw_test) set_tests_properties(d3d12_translated_draw PROPERTIES SKIP_RETURN_CODE 77) + # The console's rectangle and quad lists (src/rect_list_geometry.h), through the same translated vs_m15 / ps_m15. + add_executable(d3d12_rect_list_test test/d3d12_rect_list_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_M15_FILES}) + target_link_libraries(d3d12_rect_list_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_rect_list_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_M15_DIR="${LEONIDA_M15_DIR}") + target_compile_options(d3d12_rect_list_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_rect_list COMMAND d3d12_rect_list_test) + set_tests_properties(d3d12_rect_list PROPERTIES SKIP_RETURN_CODE 77) + # vk_bindless_test (the bindless set and its table at the Vulkan level, no D3D12) takes the translated vs_ids, # ps_tex and ps_imgatomic; it was only run by scripts/run_gpu_tests.py and check.py until D3D-314 needed it. set(LEONIDA_BINDLESS_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/bindless_shaders) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index c7e3d99942..fbeccc3d34 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -18,6 +18,7 @@ #include "../src/arena_size.h" #include "../src/gfx10_descriptors.h" #include "../src/depth24_fragment.h" +#include "../src/rect_list_geometry.h" #include "../src/uav_clear.h" #include "../src/vulkan_bindless.h" #include "../src/vulkan_memory.h" @@ -64,7 +65,9 @@ namespace { constexpr UINT kDescriptorSize = descriptor_size; // The first 64 KiB of the GPU address arena are never handed out: VA 0 stays invalid, and the page is kept zero // for unbound vertex and index buffers to read (D3D12 reads zeros there). -constexpr VkDeviceSize kArenaReserved = 64 * 1024; +constexpr VkDeviceSize kZeroPage = 64 * 1024; // zeroed: what unbound vertex and index buffers read +constexpr std::uint32_t kQuadIndexCount = 64 * 1024; // 0, 1, 2, ... that non-indexed quad lists draw with (16384 quads) +constexpr VkDeviceSize kArenaReserved = kZeroPage + VkDeviceSize(kQuadIndexCount) * sizeof(std::uint32_t); static_assert(sizeof(leonida::TargetView) <= kDescriptorSize); // The shader model and root signature version this layer can honour. Nothing in the runtime compiles DXIL: the @@ -3189,6 +3192,14 @@ class PipelineState final log_once("geometry shaders need the Vulkan geometryShader feature; stage", 0); return E_NOTIMPL; } + // The console's rectangle topology type (19) draws as triangles through a generated geometry stage that adds + // each rectangle's fourth corner (src/rect_list_geometry.h); it needs the same device feature, and no GS of + // the application's own. + const bool rect_list = !mesh && desc.PrimitiveTopologyType == leonida::topology_type_rect_list; + if (rect_list && (geometry || !device_.info.features.geometryShader)) { + log_once("a rectangle-list pipeline needs the geometryShader feature and no geometry shader; stage", 0); + return geometry ? E_INVALIDARG : E_NOTIMPL; + } if (geometry && desc.PrimitiveTopologyType != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) { log_once("a translated geometry shader takes triangles; topology type", desc.PrimitiveTopologyType); return E_INVALIDARG; @@ -3378,6 +3389,26 @@ class PipelineState final subgroup_size_for(*stage.entry, required_sizes[stage_infos.size()], info); stage_infos.push_back(info); } + if (rect_list) { // the stage that adds each rectangle's fourth corner, from the vertex shader's outputs + std::string why; + const std::vector words = leonida::rect_list_geometry(vs_stage.words, why); + if (words.empty()) { + std::fprintf(stderr, "[rt] d3d12: %s cannot be drawn as a rectangle list: %s\n", + vs_stage.entry->name.c_str(), why.c_str()); + return E_NOTIMPL; + } + VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + module_info.codeSize = words.size() * 4; + module_info.pCode = words.data(); + VkShaderModule module = VK_NULL_HANDLE; + if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) return E_FAIL; + modules_.push_back(module); + VkPipelineShaderStageCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; + info.stage = VK_SHADER_STAGE_GEOMETRY_BIT; + info.module = module; + info.pName = "main"; + stage_infos.push_back(info); + } if (depth24_fragment && !ps_stage.entry) { // no pixel shader: a built-in one writes the depth const std::vector words = leonida::depth24_depth_only_fragment(depth24_bias); VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; @@ -3452,7 +3483,8 @@ class PipelineState final } } VkPipelineInputAssemblyStateCreateInfo assembly{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; - switch (mesh ? D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE : desc.PrimitiveTopologyType) { // mesh: not used + // Type 19 is the console's rectangles, drawn as triangle lists through the geometry stage added above. + switch (mesh || rect_list ? D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE : desc.PrimitiveTopologyType) { // mesh: not used case D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT: assembly.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST; break; case D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_LINE_LIST; break; case D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; break; @@ -5168,7 +5200,11 @@ class Device final return false; } arena.mapped = static_cast(mapped); - std::memset(arena.mapped, 0, kArenaReserved); // the zero page unbound vertex and index buffers read + std::memset(arena.mapped, 0, kZeroPage); // the zero page unbound vertex and index buffers read + { + auto* iota = reinterpret_cast(arena.mapped + kZeroPage); + for (std::uint32_t i = 0; i < kQuadIndexCount; ++i) iota[i] = i; + } VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; address.buffer = arena.buffer; arena.address = vk.vkGetBufferDeviceAddress(state_.info.device, &address); @@ -5179,7 +5215,8 @@ class Device final length = 0; arena.log = getenv_s(&length, log, "LEONIDA_ARENA_LOG") == 0 && length > 1 && log[0] != '0'; state_.context->set_heap_base(arena.address); - state_.context->set_zero_page(arena.buffer, 0, kArenaReserved); + state_.context->set_zero_page(arena.buffer, 0, kZeroPage); + state_.context->set_quad_indices(arena.buffer, kZeroPage, kQuadIndexCount); return true; } diff --git a/runtime/src/rect_list_geometry.h b/runtime/src/rect_list_geometry.h new file mode 100644 index 0000000000..ee7d69905c --- /dev/null +++ b/runtime/src/rect_list_geometry.h @@ -0,0 +1,214 @@ +#pragma once + +// Console rectangle lists on Vulkan, which has no such primitive. +// +// A rectangle is three corners (v1, v2, v3) and the hardware makes the fourth, v2 + v3 - v1, for the position and for +// every interpolant, after the vertex stage. A list topology of rectangles (D3D_PRIMITIVE_TOPOLOGY 17) and a pipeline +// whose topology type is 19 are console-only. The fact comes from xvalkyrie (GPL-3.0, commit 53af7df77c10, notes in +// its backlog); no code is taken from it. +// +// The fourth vertex depends on what the vertex stage wrote, not on what it read, so the expansion has to sit after +// the vertex stage: a pre-pass over the vertex buffers is wrong for any shader that is not linear in its inputs (and +// the translated vertex shaders fetch by V# themselves, so there is no vertex buffer to expand). The pipeline gets a +// small geometry stage instead, built here from the vertex shader's own SPIR-V: it takes the triangle (v1, v2, v3) +// the list draws, and emits the strip v1, v2, v3, v4, which is the two triangles (v1, v2, v3) and (v3, v2, v4) of the +// parallelogram with the same winding. Every Location output of the vertex stage is a vec4 float in the translator's +// output (rdna2spirv.py), and so is the stage's Position; the generated stage reads and writes exactly those. A value +// that is the same bit pattern at all three corners (a flat attribute, which may hold integer bits) is copied rather +// than computed, so it cannot turn into a NaN. +// +// Not covered, and refused with a reason: a vertex stage that writes ClipDistance, CullDistance, Layer or +// ViewportIndex, or a Location output that is not a vec4 float. +// +// Plain word editing, standard library only. + +#include +#include +#include +#include +#include +#include +#include + +namespace leonida { + +// D3D_PRIMITIVE_TOPOLOGY values and the PSO topology type of the console's rectangle and quad lists. +constexpr std::uint32_t topology_rect_list = 17; +constexpr std::uint32_t topology_quad_list = 19; +constexpr std::uint32_t topology_type_rect_list = 19; + +// The geometry stage for `vertex_words`' outputs; empty, with `why` set, when the vertex stage cannot be expanded. +inline std::vector rect_list_geometry(const std::vector& vertex_words, std::string& why) { + enum : std::uint32_t { + op_entry_point = 15, op_type_void = 19, op_type_bool = 20, op_type_int = 21, op_type_float = 22, + op_type_vector = 23, op_type_array = 28, op_type_pointer = 32, op_type_function = 33, op_constant = 43, + op_function = 54, op_function_end = 56, op_variable = 59, op_load = 61, op_store = 62, op_access_chain = 65, + op_decorate = 71, op_bitcast = 124, op_fadd = 129, op_fsub = 131, op_logical_and = 167, op_select = 169, + op_iequal = 170, op_emit_vertex = 218, op_end_primitive = 219, op_label = 248, op_return = 253, + op_capability = 17, op_memory_model = 14, op_execution_mode = 16, + deco_builtin = 11, deco_location = 30, builtin_position = 0, builtin_point_size = 1, + storage_input = 1, storage_output = 3 + }; + why.clear(); + if (vertex_words.size() < 6 || vertex_words[0] != 0x07230203u) { + why = "the vertex shader is not a SPIR-V module"; + return {}; + } + // What the vertex stage declares: types, Output variables, and the decorations that name them. + struct Type { std::uint32_t op = 0, component = 0, count = 0, width = 0; }; + std::map types; + std::map variable_type; // Output variable -> its pointer type + std::map location, builtin; // variable id -> value + std::set outputs; + for (std::size_t i = 5; i < vertex_words.size();) { + const std::uint32_t op = vertex_words[i] & 0xffffu, n = vertex_words[i] >> 16; + if (!n || i + n > vertex_words.size()) { + why = "the vertex shader's SPIR-V is cut short"; + return {}; + } + const std::uint32_t* w = &vertex_words[i]; + if (op == op_type_float && n >= 3) types[w[1]] = {op, 0, 0, w[2]}; + else if (op == op_type_vector && n >= 4) types[w[1]] = {op, w[2], w[3], 0}; + else if (op == op_type_pointer && n >= 4) types[w[1]] = {op, w[3], w[2], 0}; + else if (op == op_variable && n >= 4 && w[3] == storage_output) outputs.insert(w[2]), variable_type[w[2]] = w[1]; + else if (op == op_decorate && n >= 4 && w[2] == deco_location) location[w[1]] = w[3]; + else if (op == op_decorate && n >= 4 && w[2] == deco_builtin) builtin[w[1]] = w[3]; + i += n; + } + std::uint32_t position = 0; + std::vector params; // Location values, ascending + for (std::uint32_t id : outputs) { + const auto b = builtin.find(id); + if (b != builtin.end()) { + if (b->second == builtin_position) position = id; + else if (b->second != builtin_point_size) { + why = "the vertex shader writes ClipDistance, CullDistance, Layer or ViewportIndex"; + return {}; + } + continue; + } + const auto l = location.find(id); + if (l == location.end()) continue; + const Type& ptr = types[variable_type[id]]; + const Type& vec = types[ptr.component]; + const Type& scalar = types[vec.component]; + if (vec.op != op_type_vector || vec.count != 4 || scalar.op != op_type_float || scalar.width != 32) { + why = "a vertex output is not a vec4 float"; + return {}; + } + params.push_back(l->second); + } + if (!position) { + why = "the vertex shader writes no Position"; + return {}; + } + std::sort(params.begin(), params.end()); + params.erase(std::unique(params.begin(), params.end()), params.end()); + + // The module: a fixed prelude, then per variable ids, then the body. Ids count up from 1. + std::uint32_t next = 1; + const auto id = [&] { return next++; }; + std::vector head, annotations, globals, body; + const auto emit = [](std::vector& to, std::uint32_t op, std::initializer_list args) { + to.push_back((std::uint32_t(args.size()) + 1) << 16 | op); + to.insert(to.end(), args.begin(), args.end()); + }; + const std::uint32_t t_void = id(), t_fn = id(), t_uint = id(), t_float = id(), t_v4 = id(), t_bool = id(), + t_v4bool = id(), t_v4uint = id(), c3 = id(), t_arr = id(), t_pin_arr = id(), t_pin_v4 = id(), + t_pout_v4 = id(), c0 = id(), c1 = id(), c2 = id(); + emit(globals, op_type_void, {t_void}); + emit(globals, op_type_function, {t_fn, t_void}); + emit(globals, op_type_int, {t_uint, 32, 0}); + emit(globals, op_type_float, {t_float, 32}); + emit(globals, op_type_vector, {t_v4, t_float, 4}); + emit(globals, op_type_bool, {t_bool}); + emit(globals, op_type_vector, {t_v4bool, t_bool, 4}); + emit(globals, op_type_vector, {t_v4uint, t_uint, 4}); + emit(globals, op_constant, {t_uint, c3, 3}); + emit(globals, op_constant, {t_uint, c0, 0}); + emit(globals, op_constant, {t_uint, c1, 1}); + emit(globals, op_constant, {t_uint, c2, 2}); + emit(globals, op_type_array, {t_arr, t_v4, c3}); + emit(globals, op_type_pointer, {t_pin_arr, storage_input, t_arr}); + emit(globals, op_type_pointer, {t_pin_v4, storage_input, t_v4}); + emit(globals, op_type_pointer, {t_pout_v4, storage_output, t_v4}); + + struct Var { std::uint32_t in, out; bool is_position; }; + std::vector vars; + vars.push_back({id(), id(), true}); + for (std::size_t i = 0; i < params.size(); ++i) vars.push_back({id(), id(), false}); + std::vector io_vars; + emit(annotations, op_decorate, {vars[0].in, deco_builtin, builtin_position}); + emit(annotations, op_decorate, {vars[0].out, deco_builtin, builtin_position}); + for (std::size_t i = 0; i < params.size(); ++i) { + emit(annotations, op_decorate, {vars[i + 1].in, deco_location, params[i]}); + emit(annotations, op_decorate, {vars[i + 1].out, deco_location, params[i]}); + } + for (const Var& v : vars) { + emit(globals, op_variable, {t_pin_arr, v.in, storage_input}); + emit(globals, op_variable, {t_pout_v4, v.out, storage_output}); + io_vars.push_back(v.in); + io_vars.push_back(v.out); + } + + const std::uint32_t main_fn = id(), entry_label = id(); + emit(body, op_function, {t_void, main_fn, 0, t_fn}); + emit(body, op_label, {entry_label}); + // Per variable: the three corners, and the fourth. The fourth is v2 + v3 - v1, except where all three corners + // have the same bits (a flat value), where it is v1. + struct Corners { std::uint32_t v[4]; }; + std::vector corners; + const std::uint32_t cs[3] = {c0, c1, c2}; + for (const Var& v : vars) { + Corners c{}; + for (int k = 0; k < 3; ++k) { + const std::uint32_t ptr = id(); + c.v[k] = id(); + emit(body, op_access_chain, {t_pin_v4, ptr, v.in, cs[k]}); + emit(body, op_load, {t_v4, c.v[k], ptr}); + } + const std::uint32_t sum = id(), diff = id(); + emit(body, op_fadd, {t_v4, sum, c.v[1], c.v[2]}); + emit(body, op_fsub, {t_v4, diff, sum, c.v[0]}); + if (v.is_position) { + c.v[3] = diff; + } else { + const std::uint32_t b0 = id(), b1 = id(), b2 = id(), e1 = id(), e2 = id(), same = id(), pick = id(); + emit(body, op_bitcast, {t_v4uint, b0, c.v[0]}); + emit(body, op_bitcast, {t_v4uint, b1, c.v[1]}); + emit(body, op_bitcast, {t_v4uint, b2, c.v[2]}); + emit(body, op_iequal, {t_v4bool, e1, b1, b0}); + emit(body, op_iequal, {t_v4bool, e2, b2, b0}); + emit(body, op_logical_and, {t_v4bool, same, e1, e2}); + emit(body, op_select, {t_v4, pick, same, c.v[0], diff}); + c.v[3] = pick; + } + corners.push_back(c); + } + // The strip v1, v2, v3, v4. + for (int k = 0; k < 4; ++k) { + for (std::size_t i = 0; i < vars.size(); ++i) emit(body, op_store, {vars[i].out, corners[i].v[k]}); + emit(body, op_emit_vertex, {}); + } + emit(body, op_end_primitive, {}); + emit(body, op_return, {}); + emit(body, op_function_end, {}); + + std::vector out{0x07230203u, 0x00010000u, 0, next, 0}; + emit(out, op_capability, {19}); // Geometry + emit(out, op_memory_model, {0, 1}); // Logical, GLSL450 + std::vector entry{3, main_fn, 0x6e69616du, 0}; // Geometry, %main, "main" + entry.insert(entry.end(), io_vars.begin(), io_vars.end()); + out.push_back((std::uint32_t(entry.size()) + 1) << 16 | op_entry_point); + out.insert(out.end(), entry.begin(), entry.end()); + emit(out, op_execution_mode, {main_fn, 22}); // Triangles + emit(out, op_execution_mode, {main_fn, 0, 1}); // Invocations 1 + emit(out, op_execution_mode, {main_fn, 29}); // OutputTriangleStrip + emit(out, op_execution_mode, {main_fn, 26, 4}); // OutputVertices 4 + out.insert(out.end(), annotations.begin(), annotations.end()); + out.insert(out.end(), globals.begin(), globals.end()); + out.insert(out.end(), body.begin(), body.end()); + return out; +} + +} // namespace leonida diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index e659a762dc..b05f5fc1ad 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -1247,6 +1247,14 @@ class VulkanContext { replay_.zero_size = size; } + // 0, 1, 2, ... as 32-bit indices, for non-indexed quad lists (ReplayFunctions::quad_indices). + void set_quad_indices(VkBuffer buffer, VkDeviceSize offset, std::uint32_t count) { + std::unique_lock lock(resource_mutex_); + replay_.quad_indices = buffer; + replay_.quad_indices_offset = offset; + replay_.quad_index_count = count; + } + // Physical-device COLOR_ATTACHMENT format check for reinterpreted UAV clears. void set_color_attachment_format(std::function check) { std::unique_lock lock(resource_mutex_); diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 1e0e598c7f..d519fe822e 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -32,6 +32,7 @@ #include "command_list.h" #include "depth24.h" +#include "rect_list_geometry.h" #include "uav_clear.h" #include @@ -866,6 +867,10 @@ struct ReplayFunctions { VkBuffer zero_buffer = VK_NULL_HANDLE; VkDeviceSize zero_offset = 0; VkDeviceSize zero_size = 0; + // 0, 1, 2, ... as 32-bit indices: what a non-indexed quad list is drawn with (quad_index_count of them). + VkBuffer quad_indices = VK_NULL_HANDLE; + VkDeviceSize quad_indices_offset = 0; + std::uint32_t quad_index_count = 0; std::uint64_t heap_base = 0; // device address of the GPU address arena (push-constant dwords 32-33) // Resolves available binary-occlusion queries to 64-bit 0/1 values, outside conditional rendering. std::functionzero_step_slots & (1u << slot)) ? 0 : view.stride; } + // A non-indexed quad list is drawn from the shared 0, 1, 2, ... index buffer (emit). + if (!draw.indexed && !draw.mesh && draw.topology == topology_quad_list && !vk.quad_indices) + return ReplayResult::unresolved_resource; if (draw.indexed) { if (draw.index.format == 57) p.index_type = VK_INDEX_TYPE_UINT16; else if (draw.index.format == 42) p.index_type = VK_INDEX_TYPE_UINT32; @@ -2210,6 +2218,11 @@ inline VkPrimitiveTopology vulkan_topology(std::uint32_t topology) { case 11: return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY; case 12: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY; case 13: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY; + // The console's lists (rect_list_geometry.h). A rectangle list is drawn as the triangle list of its three + // corners, the pipeline's geometry stage adds the fourth. A quad (v0 v1 v2 v3) is the fan (v0 v1 v2) (v0 v2 v3), + // which is the index pattern 0 1 2, 0 2 3; the draw below issues one fan per quad. + case topology_rect_list: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + case topology_quad_list: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN; default: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; } } @@ -4106,6 +4119,22 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c } if (draw->mesh) { vk.draw_mesh_tasks(command_buffer, draw->count, draw->instances, draw->first); + } else if (draw->topology == topology_quad_list) { + // One four-vertex fan per quad. The translated vertex shaders take their vertex id from the index + // value (VertexIndex - BaseVertex), so a fan must be drawn with the index values 4q..4q+3: an + // indexed draw reads them from the application's index buffer, a non-indexed one from the + // shared 0, 1, 2, ... buffer (quad_indices), with the draw's first vertex as the vertex offset, as + // VertexIndex is first + i for a plain draw. + const bool generated = !draw->indexed; // prepare() has checked that quad_indices is there + if (generated) + vk.bind_index_buffer(command_buffer, vk.quad_indices, vk.quad_indices_offset, VK_INDEX_TYPE_UINT32); + else + vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); + const std::uint32_t quads = std::min(draw->count / 4, generated ? vk.quad_index_count / 4 : UINT32_MAX); + const std::int32_t vertex_offset = generated ? std::int32_t(draw->first) : draw->base_vertex; + for (std::uint32_t quad = 0; quad < quads; ++quad) + vk.draw_indexed(command_buffer, 4, draw->instances, (generated ? 0 : draw->first) + 4 * quad, + vertex_offset, draw->first_instance); } else if (draw->indexed) { vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); vk.draw_indexed(command_buffer, draw->count, draw->instances, draw->first, draw->base_vertex, diff --git a/runtime/test/d3d12_rect_list_test.cpp b/runtime/test/d3d12_rect_list_test.cpp new file mode 100644 index 0000000000..05b90a81c8 --- /dev/null +++ b/runtime/test/d3d12_rect_list_test.cpp @@ -0,0 +1,341 @@ +// The console's rectangle and quad lists drawn through the D3D12-on-Vulkan layer (src/rect_list_geometry.h). +// +// Built like d3d12_translated_draw_test.cpp, from the same translated vs_m15 / ps_m15 (the VS fetches its vertices +// through a V#; the PS multiplies the colour by (0.5, 2, 1, 1) and adds the bias, 0 here), so the shaders are real +// translator output found by the SHA-256 of their FSSM programs. +// frame 1, rectangle list: PSO topology type 19, IASetPrimitiveTopology(17), DrawInstanced(3). The three corners +// v1 (-1, 1), v2 (1, 1), v3 (-1, -1) cover the top-left, top-right and bottom-left of the 64x64 target; the fourth +// corner, v2 + v3 - v1 = (1, -1) with colour c2 + c3 - c1, is made by the layer. Every pixel must carry the plane +// through the three corner colours; the bottom-right quadrant is only right when the fourth corner is. +// frame 2, quad list: PSO topology type TRIANGLE, IASetPrimitiveTopology(19), DrawInstanced(8): two quads (corners +// in order around the quad), the top-left and bottom-right quadrants, each one colour. These pixels are exact. +// Pixels are read back and compared; the other two quadrants of frame 2 stay the clear colour. LEONIDA_VK_VALIDATION=1 +// runs it under the validation layer. +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/gfx10_descriptors.h" +#include "../src/shader_library.h" + +#include +#include +#include +#include +#include +#include + +#ifndef LEONIDA_TEST_M15_DIR +#error "LEONIDA_TEST_M15_DIR must name the folder build.py wrote (spirv/index.json, fssm/*.fssm)" +#endif + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +using namespace d3d12test; +using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX + +namespace { + +std::vector read_file(const std::filesystem::path& path) { + std::ifstream in(path, std::ios::binary); + return {std::istreambuf_iterator(in), std::istreambuf_iterator()}; +} + +struct Vertex { // 32 bytes, as vs_m15.asm reads it + float position[4]; + float color[4]; +}; + +using Pixel = std::array; +constexpr UINT target_extent = 64; +constexpr UINT pitch = target_extent * sizeof(Pixel); +constexpr D3D_PRIMITIVE_TOPOLOGY rect_list = D3D_PRIMITIVE_TOPOLOGY(17), quad_list = D3D_PRIMITIVE_TOPOLOGY(19); +const std::uint32_t rect_type_value = 19; // not an enumerator of D3D12_PRIMITIVE_TOPOLOGY_TYPE + +std::array make_vsharp(std::uint64_t base, std::uint32_t records) { + leonida::gfx10::Buffer buffer; + buffer.address = base; + buffer.stride = 32; + buffer.num_records = records; + buffer.format = 77; // GFX10_FORMAT_32_32_32_32_FLOAT + buffer.oob_select = leonida::gfx10::OobSelect::structured; + return leonida::gfx10::encode(buffer); +} + +Vertex vertex(float x, float y, const float* c) { return Vertex{{x, y, 0.0f, 1.0f}, {c[0], c[1], c[2], c[3]}}; } + +} // namespace + +int main() { + vktest::Device d; + const auto device_status = d.initialize(); + if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips + EXPECT(device_status == vktest::DeviceStatus::ready); + if (!d.enabled.geometryShader) { + std::printf("SKIP: no geometryShader on this GPU\n"); + return 77; + } + const std::filesystem::path root_dir = LEONIDA_TEST_M15_DIR; + const auto vs_program = read_file(root_dir / "fssm" / "vs_m15.fssm"); + const auto ps_program = read_file(root_dir / "fssm" / "ps_m15.fssm"); + EXPECT(vs_program.size() >= 4 && ps_program.size() == 0x110); + const auto vs_container = shader_container(vs_program), ps_container = shader_container(ps_program); + + // Frame 1: the rectangle's three corners. Vertices 0..2. Frame 2: two quads, vertices 3..10. + const float ca[4] = {0.0f, 0.0f, 0.0f, 1.0f}, cb[4] = {1.0f, 0.0f, 0.5f, 1.0f}, cc[4] = {0.0f, 0.5f, 1.0f, 1.0f}; + const float q1[4] = {0.25f, 0.5f, 0.75f, 1.0f}, q2[4] = {1.0f, 0.0f, 0.5f, 1.0f}; + const Vertex vertices[11] = {vertex(-1, 1, ca), vertex(1, 1, cb), vertex(-1, -1, cc), + vertex(-1, 1, q1), vertex(0, 1, q1), vertex(0, 0, q1), vertex(-1, 0, q1), + vertex(0, 0, q2), vertex(1, 0, q2), vertex(1, -1, q2), vertex(0, -1, q2)}; + static_assert(sizeof(Vertex) == 32 && sizeof(vertices) == 352); + + std::vector rect_pixels(target_extent * target_extent), quad_pixels(target_extent * target_extent); + { + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = d.instance_proc; + info.instance = d.instance; + info.physical = d.physical; + info.device = d.device; + info.queue = d.queue; + info.queue_family = d.family; + info.buffer_device_address = true; + info.features = d.enabled; // geometryShader: the rectangle stage needs it + info.shader_dir = (root_dir / "spirv").string(); + ID3D12Device* inner = nullptr; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); + Ref device; + EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), + reinterpret_cast(&device.p)))); + rt::d3d12::set_device_outer(inner, device.p); + + D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + D3D12_ROOT_PARAMETER params[2] = {}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[0].DescriptorTable = {1, &range}; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[1].Constants = {0, 0, 4}; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + root_desc.Desc_1_0 = {2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + const auto root_blob = serialize_root_signature(root_desc); + EXPECT(!root_blob.empty()); + Ref root; + EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p)))); + + D3D12_GRAPHICS_PIPELINE_STATE_DESC pso_desc{}; + pso_desc.pRootSignature = root.p; + pso_desc.VS = {vs_container.data(), vs_container.size()}; + pso_desc.PS = {ps_container.data(), ps_container.size()}; + pso_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + pso_desc.SampleMask = 0xffffffff; + pso_desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pso_desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pso_desc.RasterizerState.DepthClipEnable = TRUE; + pso_desc.NumRenderTargets = 1; + pso_desc.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT; + pso_desc.SampleDesc.Count = 1; + Ref rect_pso, quad_pso; + std::memcpy(&pso_desc.PrimitiveTopologyType, &rect_type_value, sizeof(rect_type_value)); // 19: rectangles + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&rect_pso.p)))); + pso_desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&quad_pso.p)))); + + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; + const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + Ref vertex_buffer, upload, readback, target; + const auto vb_desc = buffer_desc(sizeof(vertices)); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &vb_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&vertex_buffer.p)))); + const auto upload_desc = buffer_desc(1024); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &upload_desc, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&upload.p)))); + const auto readback_desc = buffer_desc(pitch * target_extent); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + D3D12_RESOURCE_DESC rt_desc{}; + rt_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + rt_desc.Width = rt_desc.Height = target_extent; + rt_desc.DepthOrArraySize = 1; + rt_desc.MipLevels = 1; + rt_desc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + rt_desc.SampleDesc.Count = 1; + rt_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &rt_desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&target.p)))); + std::uint8_t* up = nullptr; + EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast(&up)))); + std::memcpy(up, vertices, sizeof(vertices)); + + // Two V#s over the one vertex buffer: slot 0 the rectangle's three corners, slot 1 the eight quad corners. + const D3D12_DESCRIPTOR_HEAP_DESC srv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + Ref srv_heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&srv_heap_desc, IID_PPV_ARGS(&srv_heap.p)))); + const std::uint64_t cpu = reinterpret_cast(slot(srv_heap.p, 9))(srv_heap.p); + const std::uint64_t gpu = reinterpret_cast(slot(srv_heap.p, 10))(srv_heap.p); + const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + EXPECT(cpu && gpu >= 0x10000 && gpu < (1ull << 32) && step >= 16); + const std::uint64_t buffer_va = vertex_buffer->GetGPUVirtualAddress(); + EXPECT(buffer_va >= 0x10000); + const std::array vsharps[2] = {make_vsharp(buffer_va, 3), + make_vsharp(buffer_va + 3 * sizeof(Vertex), 8)}; + for (unsigned i = 0; i < 2; ++i) + std::memcpy(reinterpret_cast(cpu + std::uint64_t(i) * step), vsharps[i].data(), 16); + + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + Ref rtv_heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&rtv_heap.p)))); + const D3D12_CPU_DESCRIPTOR_HANDLE rtv{ + SIZE_T(reinterpret_cast(slot(rtv_heap.p, 9))(rtv_heap.p))}; + device->CreateRenderTargetView(target.p, nullptr, rtv); + + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + Ref queue; + Ref allocator; + Ref list; + Ref fence; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, rect_pso.p, + IID_PPV_ARGS(&list.p)))); + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + + list->CopyBufferRegion(vertex_buffer.p, 0, upload.p, 0, sizeof(vertices)); + D3D12_RESOURCE_BARRIER barriers[2] = { + transition(vertex_buffer.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE), + transition(target.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET)}; + list->ResourceBarrier(2, barriers); + + const auto render_frame = [&](UINT64 frame, ID3D12PipelineState* pso, D3D_PRIMITIVE_TOPOLOGY topology, + unsigned vsharp_slot, UINT vertex_count, std::vector& out) -> int { + if (frame > 1) { + EXPECT(SUCCEEDED(allocator->Reset())); + EXPECT(SUCCEEDED(list->Reset(allocator.p, pso))); + auto to_target = transition(target.p, D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_RENDER_TARGET); + list->ResourceBarrier(1, &to_target); + } else { + list->SetPipelineState(pso); + } + const FLOAT clear[4] = {0.5f, 0.125f, 0.25f, 0.5f}; + list->ClearRenderTargetView(rtv, clear, 0, nullptr); + list->SetGraphicsRootSignature(root.p); + ID3D12DescriptorHeap* heaps[] = {srv_heap.p}; + list->SetDescriptorHeaps(1, heaps); + list->IASetPrimitiveTopology(topology); + const D3D12_VIEWPORT viewport{0, 0, float(target_extent), float(target_extent), 0, 1}; + const D3D12_RECT scissor{0, 0, LONG(target_extent), LONG(target_extent)}; + list->RSSetViewports(1, &viewport); + list->RSSetScissorRects(1, &scissor); + list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); + const float constants[4] = {0, 0, 0, 0}; // no offset, no bias + list->SetGraphicsRootDescriptorTable(0, D3D12_GPU_DESCRIPTOR_HANDLE{gpu + std::uint64_t(vsharp_slot) * step}); + list->SetGraphicsRoot32BitConstants(1, 4, constants, 0); + list->DrawInstanced(vertex_count, 1, 0, 0); + D3D12_RESOURCE_BARRIER to_copy = transition(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &to_copy); + D3D12_TEXTURE_COPY_LOCATION dst{}; + dst.pResource = readback.p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = {0, {DXGI_FORMAT_R32G32B32A32_FLOAT, target_extent, target_extent, 1, pitch}}; + D3D12_TEXTURE_COPY_LOCATION src{}; + src.pResource = target.p; + src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + EXPECT(list->Close() == S_OK); + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(queue->Signal(fence.p, frame))); + EXPECT(SUCCEEDED(fence->SetEventOnCompletion(frame, nullptr))); + void* mapped = nullptr; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); + std::memcpy(out.data(), mapped, out.size() * sizeof(Pixel)); + readback->Unmap(0, nullptr); + return 0; + }; + EXPECT(render_frame(1, rect_pso.p, rect_list, 0, 3, rect_pixels) == 0); + EXPECT(render_frame(2, quad_pso.p, quad_list, 1, 8, quad_pixels) == 0); + for (auto* r : {&vertex_buffer, &upload, &readback, &target}) r->reset(); + rect_pso.reset(); + quad_pso.reset(); + root.reset(); + srv_heap.reset(); + rtv_heap.reset(); + list.reset(); + allocator.reset(); + queue.reset(); + fence.reset(); + EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); + } + + // Rectangle: the plane through the three corner colours, at each pixel centre, through the PS's scale. + const float scale[4] = {0.5f, 2.0f, 1.0f, 1.0f}; + unsigned covered = 0, off = 0; + float worst = 0.0f; + for (UINT row = 0; row < target_extent; ++row) { + for (UINT col = 0; col < target_extent; ++col) { + const float u = (float(col) + 0.5f) / target_extent, v = (float(row) + 0.5f) / target_extent; + const Pixel& got = rect_pixels[row * target_extent + col]; + bool pixel_ok = true; + for (int c = 0; c < 4; ++c) { + const float want = (ca[c] + u * (cb[c] - ca[c]) + v * (cc[c] - ca[c])) * scale[c]; + const float error = std::fabs(got[c] - want); + worst = std::fmax(worst, error); + if (!(error <= 2e-5f)) pixel_ok = false; + } + covered += pixel_ok; + if (!pixel_ok && off++ < 8) + std::fprintf(stderr, "rect pixel (%u, %u): got %g,%g,%g,%g\n", col, row, got[0], got[1], got[2], got[3]); + } + } + // The four quadrant centres on their own, so a wrong fourth corner is named by quadrant. + const char* names[4] = {"top left", "top right", "bottom left", "bottom right"}; + for (int quadrant = 0; quadrant < 4; ++quadrant) { + const UINT col = (quadrant & 1 ? 48 : 16), row = (quadrant & 2 ? 48 : 16); + const Pixel& got = rect_pixels[row * target_extent + col]; + const float u = (float(col) + 0.5f) / target_extent, v = (float(row) + 0.5f) / target_extent; + for (int c = 0; c < 4; ++c) { + const float want = (ca[c] + u * (cb[c] - ca[c]) + v * (cc[c] - ca[c])) * scale[c]; + if (!(std::fabs(got[c] - want) <= 2e-5f)) { + std::fprintf(stderr, "rect %s quadrant: channel %d got %g want %g\n", names[quadrant], c, got[c], want); + return 1; + } + } + } + EXPECT(covered == target_extent * target_extent); + + // Quad list: whole-bit comparison; two quadrants one colour each, the rest the clear colour. + const Pixel clear_color = {0.5f, 0.125f, 0.25f, 0.5f}; + const Pixel top_left = {q1[0] * scale[0], q1[1] * scale[1], q1[2], q1[3]}; + const Pixel bottom_right = {q2[0] * scale[0], q2[1] * scale[1], q2[2], q2[3]}; + unsigned quad_wrong = 0; + for (UINT row = 0; row < target_extent; ++row) { + for (UINT col = 0; col < target_extent; ++col) { + const bool top = row < target_extent / 2, left = col < target_extent / 2; + const Pixel& want = top && left ? top_left : (!top && !left ? bottom_right : clear_color); + const Pixel& got = quad_pixels[row * target_extent + col]; + if (std::memcmp(&got, &want, sizeof(Pixel)) == 0) continue; + if (quad_wrong++ < 8) + std::fprintf(stderr, "quad pixel (%u, %u): got %g,%g,%g,%g want %g,%g,%g,%g\n", col, row, got[0], got[1], + got[2], got[3], want[0], want[1], want[2], want[3]); + } + } + EXPECT(!quad_wrong); + if (d.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); + return 1; + } + std::printf("rect list: %u of %u pixels on the colour plane (worst error %g), all four quadrants; quad list: " + "%u of %u pixels exact\n", + covered, target_extent * target_extent, double(worst), target_extent * target_extent - quad_wrong, + target_extent * target_extent); + return 0; +} From a6b31d51ac5d4ea43e965539fd1793f7d995d6db Mon Sep 17 00:00:00 2001 From: tedin7 Date: Mon, 23 Nov 2026 17:48:05 +0100 Subject: [PATCH 007/110] d3d12: rectangle list stage emits (v1 v2 v4) (v1 v4 v3) with capability Geometry, log cut-off quads (review fixes) --- docs/d3d12_vulkan.md | 2 +- runtime/src/rect_list_geometry.h | 57 ++++++++++++-------------------- runtime/src/vulkan_replay.h | 11 +++++- 3 files changed, 33 insertions(+), 37 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 76a8b16a7d..3233715169 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2084,7 +2084,7 @@ The trace will enumerate them. The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiveTopology(17)`, with a PSO whose topology type is 19) and quad list (`IASetPrimitiveTopology(19)`). The facts are from xvalkyrie (GPL-3.0, commit `53af7df77c10`; no code taken): a rectangle is three corners and the fourth is v2 + v3 - v1 for the position and every interpolant, after the vertex stage; a quad is four vertices. The layer draws both as triangles (`d3d12_rect_list_test`, RTX 4090: 4096 of 4096 pixels, the colour plane exact, quad list bit-exact). - **Rectangle list**: PSO type 19 builds a triangle-list pipeline plus a generated geometry stage (`src/rect_list_geometry.h`, written from the vertex shader's own outputs) that takes the three corners and emits the strip v1 v2 v3 v4 (same winding). It has to be post-vertex-stage: the translated vertex shaders fetch by V# themselves, and the fourth corner is a function of what they write. A corner value with the same bits at all three corners (a flat attribute) is copied. Needs `geometryShader` (else `E_NOTIMPL`), no application GS, and a vertex shader with no ClipDistance, CullDistance, Layer or ViewportIndex output. -- **Quad list**: one four-vertex triangle fan per quad (the pattern 0 1 2, 0 2 3). The translated vertex id is `VertexIndex - BaseVertex`, so each fan reads the index values 4q..4q+3: from the application's index buffer when the draw is indexed, else from a shared 0, 1, 2, ... buffer in the arena's reserved pages (16384 quads per draw at most), with the draw's first vertex as the vertex offset. The PSO type is the ordinary triangle type. +- **Quad list**: one four-vertex triangle fan per quad (the pattern 0 1 2, 0 2 3). The translated vertex id is `VertexIndex - BaseVertex`, so each fan reads the index values 4q..4q+3: from the application's index buffer when the draw is indexed, else from a shared 0, 1, 2, ... buffer in the arena's reserved pages (16384 quads per draw at most, more are cut off with a log line), with the draw's first vertex as the vertex offset. A quad's instances are drawn together, so several overlapping blended instances rasterize quad by quad rather than instance by instance. The PSO type is the ordinary triangle type. ## 4. Object model mapping diff --git a/runtime/src/rect_list_geometry.h b/runtime/src/rect_list_geometry.h index ee7d69905c..335e4db00e 100644 --- a/runtime/src/rect_list_geometry.h +++ b/runtime/src/rect_list_geometry.h @@ -11,11 +11,10 @@ // the vertex stage: a pre-pass over the vertex buffers is wrong for any shader that is not linear in its inputs (and // the translated vertex shaders fetch by V# themselves, so there is no vertex buffer to expand). The pipeline gets a // small geometry stage instead, built here from the vertex shader's own SPIR-V: it takes the triangle (v1, v2, v3) -// the list draws, and emits the strip v1, v2, v3, v4, which is the two triangles (v1, v2, v3) and (v3, v2, v4) of the -// parallelogram with the same winding. Every Location output of the vertex stage is a vec4 float in the translator's -// output (rdna2spirv.py), and so is the stage's Position; the generated stage reads and writes exactly those. A value -// that is the same bit pattern at all three corners (a flat attribute, which may hold integer bits) is copied rather -// than computed, so it cannot turn into a NaN. +// the list draws and emits the parallelogram as the two triangles (v1, v2, v4) and (v1, v4, v3), with the winding of +// (v1, v2, v3). Both start at v1, so a flat input (taken from a triangle's first vertex) is v1's over the whole +// rectangle. Every Location output of the vertex stage is a vec4 float in the translator's output (rdna2spirv.py), +// and so is the stage's Position; the generated stage reads and writes exactly those. // // Not covered, and refused with a reason: a vertex stage that writes ClipDistance, CullDistance, Layer or // ViewportIndex, or a Location output that is not a vec4 float. @@ -40,11 +39,10 @@ constexpr std::uint32_t topology_type_rect_list = 19; // The geometry stage for `vertex_words`' outputs; empty, with `why` set, when the vertex stage cannot be expanded. inline std::vector rect_list_geometry(const std::vector& vertex_words, std::string& why) { enum : std::uint32_t { - op_entry_point = 15, op_type_void = 19, op_type_bool = 20, op_type_int = 21, op_type_float = 22, + op_entry_point = 15, op_type_void = 19, op_type_int = 21, op_type_float = 22, op_type_vector = 23, op_type_array = 28, op_type_pointer = 32, op_type_function = 33, op_constant = 43, op_function = 54, op_function_end = 56, op_variable = 59, op_load = 61, op_store = 62, op_access_chain = 65, - op_decorate = 71, op_bitcast = 124, op_fadd = 129, op_fsub = 131, op_logical_and = 167, op_select = 169, - op_iequal = 170, op_emit_vertex = 218, op_end_primitive = 219, op_label = 248, op_return = 253, + op_decorate = 71, op_fadd = 129, op_fsub = 131, op_emit_vertex = 218, op_end_primitive = 219, op_label = 248, op_return = 253, op_capability = 17, op_memory_model = 14, op_execution_mode = 16, deco_builtin = 11, deco_location = 30, builtin_position = 0, builtin_point_size = 1, storage_input = 1, storage_output = 3 @@ -113,17 +111,14 @@ inline std::vector rect_list_geometry(const std::vector rect_list_geometry(const std::vector corners; const std::uint32_t cs[3] = {c0, c1, c2}; @@ -170,32 +164,25 @@ inline std::vector rect_list_geometry(const std::vector out{0x07230203u, 0x00010000u, 0, next, 0}; - emit(out, op_capability, {19}); // Geometry + emit(out, op_capability, {2}); // Geometry emit(out, op_memory_model, {0, 1}); // Logical, GLSL450 std::vector entry{3, main_fn, 0x6e69616du, 0}; // Geometry, %main, "main" entry.insert(entry.end(), io_vars.begin(), io_vars.end()); @@ -204,7 +191,7 @@ inline std::vector rect_list_geometry(const std::vector #include #include +#include #include #include #include @@ -4130,8 +4131,16 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c vk.bind_index_buffer(command_buffer, vk.quad_indices, vk.quad_indices_offset, VK_INDEX_TYPE_UINT32); else vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); - const std::uint32_t quads = std::min(draw->count / 4, generated ? vk.quad_index_count / 4 : UINT32_MAX); + // The shared buffer holds quad_index_count / 4 quads: more are cut off here and said so. + const std::uint32_t wanted = draw->count / 4, room = generated ? vk.quad_index_count / 4 : UINT32_MAX; + const std::uint32_t quads = std::min(wanted, room); + if (quads < wanted) + std::fprintf(stderr, "[rt] d3d12: a non-indexed quad list of %u quads draws only the first %u\n", + wanted, quads); const std::int32_t vertex_offset = generated ? std::int32_t(draw->first) : draw->base_vertex; + // All the instances of a quad are drawn together (a split by instance would zero the translated + // instance id, InstanceIndex - BaseInstance), so with several instances the primitive order is quad + // by quad, not instance by instance: only overlapping blended instances can tell. for (std::uint32_t quad = 0; quad < quads; ++quad) vk.draw_indexed(command_buffer, 4, draw->instances, (generated ? 0 : draw->first) + 4 * quad, vertex_offset, draw->first_instance); From a3da5122fdb1d4d9db8c5c2cdb89e9f04f46671b Mon Sep 17 00:00:00 2001 From: P2GR <26923358+P2GR@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:59:05 +0100 Subject: [PATCH 008/110] d3d12: checkpoint slow compute pipeline compiles Depends on: #7384 AI-assisted: yes (Codex) --- docs/d3d12_vulkan.md | 3 +++ runtime/shims/d3d12_vulkan_device.cpp | 32 +++++++++++++++++++++------ 2 files changed, 28 insertions(+), 7 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 02846e4298..4bc67346ed 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2031,6 +2031,9 @@ Pipeline creation: (`LEONIDA_PIPELINE_CACHE_BYTES=`, `0` turns it off): a cache seeded with the corpus file returns the whole union, which is not worth rewriting at every exit. A session file from another device, driver or pipeline-cache UUID is ignored with one line, and a write that fails (a read-only install directory) leaves the previous file. + Set `LEONIDA_STARTUP_CACHE_CHECKPOINTS=1` to write the session file after a successful compute pipeline + compile that took at least 500 ms. A later launch can reuse the completed work if the process exits before device + teardown. The session file keeps the same size cap and atomic replacement. `GetCachedBlob` records the vendor, device, driver version, `pipelineCacheUUID` and a SHA-256 of the description without `Flags`, sealed by a checksum (`runtime/src/cached_pso.h`). The answers are the host's, measured on an RTX 3060 and WARP: the same description is accepted; another diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 018c751364..14d6085a6c 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -247,9 +247,15 @@ void merge_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDe static_cast(result)); } -// Writes what this device compiled for the next launch (D3D-704). Called once the device is idle, before the cache -// is destroyed. Past the cap nothing is written: the blob from an earlier, smaller session stays, which is better -// than replacing it with one the next launch would keep refusing to save. +bool startup_cache_checkpoints_enabled() { + static const bool enabled = [] { + wchar_t value[2]{}; + return GetEnvironmentVariableW(L"LEONIDA_STARTUP_CACHE_CHECKPOINTS", value, 2) == 1 && value[0] == L'1'; + }(); + return enabled; +} + +// Writes the session cache at a startup checkpoint or during device teardown. The size cap applies to either write. void save_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache) { if (!cache || !vk.vkGetPipelineCacheData) return; const std::size_t limit = pipeline_cache_save_limit(); @@ -270,8 +276,7 @@ void save_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDev } std::vector data; try { - // Room to spare in case the driver counts the blob short between the query and the read. Nothing creates - // pipelines while the device is torn down, so this is a belt-and-braces margin, not a retry loop. + // Leave room in case another thread grows the cache between the size query and the read. data.resize(size + (size >> 4)); } catch (const std::bad_alloc&) { std::fprintf(stderr, @@ -705,6 +710,7 @@ struct DeviceState { leonida::cached_pso::Identity pso_identity; // what GetCachedBlob records and CachedPSO is checked against std::once_flag pipeline_cache_once; VkPipelineCache pipeline_cache_handle = VK_NULL_HANDLE; + std::mutex startup_cache_checkpoint_mutex; VkPipelineCache pipeline_cache() { std::call_once(pipeline_cache_once, [this] { @@ -3903,9 +3909,21 @@ class PipelineState final VkPipelineShaderStageRequiredSubgroupSizeCreateInfo required_size{}; subgroup_size_for(*entry, required_size, pipeline_info.stage); pipeline_info.layout = pipeline_.layout; - if (vk.vkCreateComputePipelines(dev, device_.pipeline_cache(), 1, &pipeline_info, nullptr, &pipeline_.pipeline) != - VK_SUCCESS) + const VkPipelineCache cache = device_.pipeline_cache(); + const bool checkpoint = cache && startup_cache_checkpoints_enabled(); + const ULONGLONG started = checkpoint ? GetTickCount64() : 0; + if (vk.vkCreateComputePipelines(dev, cache, 1, &pipeline_info, nullptr, &pipeline_.pipeline) != VK_SUCCESS) return E_FAIL; + if (checkpoint && GetTickCount64() - started >= 500) { + const std::unique_lock lock(device_.startup_cache_checkpoint_mutex, std::try_to_lock); + if (lock.owns_lock()) { + try { + save_session_pipeline_cache(vk, dev, cache); + } catch (const std::exception& error) { + std::fprintf(stderr, "[rt] d3d12: pipeline cache checkpoint failed (%s)\n", error.what()); + } + } + } // The code base: shaders read constant tables embedded in their own program through s_getpc_b64. The // translator's code offsets are into the bytes the key hashes (the FSSM blob, or the kind-6 program). From 49410a52fc6684f09692d551815fd385c73be7fc Mon Sep 17 00:00:00 2001 From: thibaut Date: Mon, 23 Nov 2026 19:13:41 +0100 Subject: [PATCH 009/110] d3d12: a slot-133 buffer whose pages are not imported is a shadow at the title's VA When VK_EXT_external_memory_host refuses the title's pages (write-combined or uncached pages, pages not committed yet, no extension, or the driver's import budget: about 64 MiB on an RTX 3070 Ti), the fallback was an ordinary DEFAULT buffer with neither the title's VA nor its data, so the title's descriptors resolved to nothing (slot 70 wrote a null SRV) and UI draws sampled nothing. The fallback is now a host-visible buffer (VRAM through Resizable BAR where upload buffers use it) whose console VA is the title's address, filled from the title's pages at creation and again before every submission of command lists (VulkanContext::set_before_execute, called from VulkanQueue::execute_now). Only committed, readable pages are read; the rest is zero. GPU writes to the shadow are not copied back. The first per-submission copy of each buffer size is timed and logged. Write-combined pages are read with MOVNTDQA: memcpy read 64 MiB of them in 253 ms on a Core i9-13900K, MOVNTDQA in 13 to 17 ms. Tests: write-combined, uncached, 64 MiB write-combined and half-committed ranges in d3d12_existing_heap_test, two patterns over two submissions each, 0 validation errors on an RTX 4090. Co-Authored-By: Claude Opus 5.5 --- runtime/shims/d3d12_vulkan_device.cpp | 180 +++++++++++++++++++++- runtime/src/vulkan_backend.h | 7 + runtime/test/d3d12_existing_heap_test.cpp | 130 ++++++++++++---- 3 files changed, 281 insertions(+), 36 deletions(-) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 2a463e1f83..d34419a010 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -41,6 +41,7 @@ #include #include #include +#include #include #include #include @@ -54,6 +55,7 @@ #include #include #include +#include #include namespace rt::d3d12 { @@ -84,6 +86,53 @@ void log_once(const char* what, int value) { if (seen.insert({what, value}).second) std::fprintf(stderr, "[rt] d3d12: %s %d\n", what, value); } +// memcpy that a page fault ends instead of killing the process: the title may decommit a page between the +// VirtualQuery that saw it committed and the read. No C++ objects here: it is a __try frame. +// `streaming` reads with MOVNTDQA, for write-combined pages: ordinary loads from them are not cached, and memcpy +// read 64 MiB of them in 253 ms on a Core i9-13900K (253 MiB/s), MOVNTDQA in 13 to 17 ms (4 to 5 GiB/s). Paid at every submission. +bool copy_guarded(std::uint8_t* to, const std::uint8_t* from, std::size_t bytes, bool streaming) { + __try { + if (streaming) { + const std::size_t head = std::min(bytes, (0 - reinterpret_cast(from)) & 63); + std::memcpy(to, from, head); + to += head, from += head, bytes -= head; + for (; bytes >= 64; to += 64, from += 64, bytes -= 64) { + const auto* in = reinterpret_cast(from); + const __m128i a = _mm_stream_load_si128(in), b = _mm_stream_load_si128(in + 1); + const __m128i c = _mm_stream_load_si128(in + 2), d = _mm_stream_load_si128(in + 3); + auto* out = reinterpret_cast<__m128i*>(to); + _mm_storeu_si128(out, a), _mm_storeu_si128(out + 1, b); + _mm_storeu_si128(out + 2, c), _mm_storeu_si128(out + 3, d); + } + } + std::memcpy(to, from, bytes); + return true; + } __except (EXCEPTION_EXECUTE_HANDLER) { + return false; + } +} + +// Copies [from, from + bytes) of the title's address space to `to`, for a slot-133 shadow buffer. Only committed, +// readable pages are read (xmem commits on first touch, and a read of a reserved page faults); the rest is zero. +void copy_title_pages(std::uint8_t* to, const std::uint8_t* from, std::size_t bytes) { + constexpr DWORD readable = PAGE_READONLY | PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READ | + PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY; + for (std::size_t at = 0; at < bytes;) { + MEMORY_BASIC_INFORMATION region{}; + std::size_t run = bytes - at; + bool read = false; + if (VirtualQuery(from + at, ®ion, sizeof(region))) { + const auto end = reinterpret_cast(region.BaseAddress) + region.RegionSize; + run = std::min(run, end - reinterpret_cast(from + at)); + read = region.State == MEM_COMMIT && (region.Protect & readable) && + !(region.Protect & (PAGE_GUARD | PAGE_NOACCESS)); + } + if (!read || !copy_guarded(to + at, from + at, run, (region.Protect & PAGE_WRITECOMBINE) != 0)) + std::memset(to + at, 0, run); + at += run; + } +} + // Two test settings that make the standalone device look like a GPU with fewer Vulkan queues, so the path where D3D12 // queues share a VkQueue runs on any GPU; both together give the Intel UHD 770 on Windows and lavapipe (one family, // one queue). LEONIDA_VK_MAX_QUEUES_PER_FAMILY=N (1 to 16): at most N VkQueues per queue family (unset, or not a @@ -640,6 +689,45 @@ struct DeviceState { // VK_EXT_external_memory_host; null unless info.host_pointer_alignment is set and the entry point loaded. PFN_vkGetMemoryHostPointerPropertiesEXT get_host_pointer_properties = nullptr; + // The live shadow buffers of Xbox device slot 133 (Resource::create_shadow_buffer): title-placed buffers whose + // pages the driver would not import. Each is re-copied from the title's pages before every submission of + // command lists (VulkanContext::set_before_execute), since nothing says which pages the title wrote. The first + // per-submission copy of each buffer size is timed and logged, so the cost shows in a run's log. + struct Shadow { + const std::uint8_t* pages; // the title's + std::uint8_t* mapped; // the shadow's memory + std::size_t size; + }; + std::mutex shadow_mutex; // a leaf: nothing else is taken under it + std::vector shadows; + std::set shadow_sizes_logged; + + void add_shadow(const Shadow& shadow) { + std::lock_guard lock(shadow_mutex); + shadows.push_back(shadow); + } + void remove_shadow(const std::uint8_t* mapped) { + std::lock_guard lock(shadow_mutex); + std::erase_if(shadows, [mapped](const Shadow& s) { return s.mapped == mapped; }); + } + void refresh_shadows() { + std::lock_guard lock(shadow_mutex); + for (const Shadow& s : shadows) { + if (!shadow_sizes_logged.insert(s.size).second) { + copy_title_pages(s.mapped, s.pages, s.size); + continue; + } + const auto start = std::chrono::steady_clock::now(); + copy_title_pages(s.mapped, s.pages, s.size); + const double ms = + std::chrono::duration(std::chrono::steady_clock::now() - start).count(); + std::fprintf(stderr, "[rt] d3d12: slot-133 shadow buffer of %llu KiB: copied from the title's pages in " + "%.3f ms (%.0f MiB/s), paid at every submission\n", + static_cast(s.size / 1024), ms, + ms > 0 ? double(s.size) / (1024.0 * 1024.0) / (ms / 1000.0) : 0.0); + } + } + // WriteToSubresource/ReadFromSubresource without host image copy: one staging copy at a time, submitted to // the device's VkQueue and waited for. Created on first use. std::mutex staging_mutex; @@ -1726,6 +1814,8 @@ class Resource final } if (image_address_) device_.forget_image(image_address_); device_.context->remove_resource(id()); + // Before the memory goes to the deferred queue: no submission copies into it after this. + if (shadow_) device_.remove_shadow(shadow_); if (host_import_) { // VK_EXT_external_memory_host needs the caller's pages to stay valid for the imported memory's whole // lifetime, and a title may free them right after releasing the resource. So the memory is not left to @@ -2001,6 +2091,69 @@ class Resource final return S_OK; } + // The fallback of create_host_buffer, for pages the driver will not import: write-combined or uncached ones (in + // retail 74 MiB of the title's 182 MiB range), pages not committed yet, a device without + // VK_EXT_external_memory_host, or a driver past its import budget (an RTX 3070 Ti answers + // VK_ERROR_OUT_OF_DEVICE_MEMORY after about 64 MiB of imports). The buffer has its own host-visible memory, a + // shadow of the title's pages, but keeps the title's VA as its console VA, so the descriptors and views the title + // builds from that VA still find it (an ordinary buffer here had another VA and none of the data: slot 70 wrote + // a null SRV and the UI draws sampled nothing). It is filled from the pages now and again before every + // submission of command lists (DeviceState::refresh_shadows). + // One way only: what the GPU writes to the shadow is NOT copied back to the title's pages, and the next + // submission's copy overwrites it. A title that reads GPU output at `address` needs the import. + HRESULT create_shadow_buffer(void* address) { + auto& vk = device_.context->vk; + if (!address || !desc_.Width || desc_.Width > ~UINT64(0) - D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT) + return E_INVALIDARG; + const bool need_bda = device_.info.buffer_device_address || device_.arena.buffer != VK_NULL_HANDLE; + VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + info.size = desc_.Width; + info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | + VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT | + VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | + VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT; + if (device_.info.conditional_rendering) info.usage |= VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT; + if (need_bda) info.usage |= VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + device_.share(info); + if (vk.vkCreateBuffer(device_.info.device, &info, nullptr, &buffer_) != VK_SUCCESS) return E_OUTOFMEMORY; + VkMemoryRequirements requirements{}; + vk.vkGetBufferMemoryRequirements(device_.info.device, buffer_, &requirements); + // As an upload buffer (D3D-96): the CPU writes it at every submission and the GPU reads it, so VRAM through + // Resizable BAR where there is one, system memory otherwise. + memory_ = device_.allocate(requirements, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, + device_.upload_in_vram ? VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT : 0, &memory_flags_, + need_bda); + void* shadow = nullptr; + if (!memory_ || vk.vkBindBufferMemory(device_.info.device, buffer_, memory_, 0) != VK_SUCCESS || + vk.vkMapMemory(device_.info.device, memory_, 0, VK_WHOLE_SIZE, 0, &shadow) != VK_SUCCESS) + return E_OUTOFMEMORY; + shadow_ = static_cast(shadow); + const auto* pages = static_cast(address); + copy_title_pages(shadow_, pages, std::size_t(desc_.Width)); + // Map() answers the title's own pages, as the imported buffer does: a write to the shadow's memory would be + // overwritten by the next copy. + mapped_ = address; + va_ = reinterpret_cast(address); + if (need_bda && vk.vkGetBufferDeviceAddress) { + VkBufferDeviceAddressInfo bda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; + bda.buffer = buffer_; + buffer_va_ = vk.vkGetBufferDeviceAddress(device_.info.device, &bda); + gpu_va_ = buffer_va_; + } + device_.log_va("title-placed buffer (shadow)", va_, desc_.Width); + leonida::ResourceBinding binding{}; + binding.buffer = buffer_; + binding.size = desc_.Width; + // CPU-side reads take the shadow, not the title's pages: it is as fresh as what the GPU reads and every byte + // of it can be read, which the pages do not promise. Not host_readable: GPU writes are not handed back. + binding.host = shadow_; + binding.va = va_; + device_.context->add_resource(id(), binding); + device_.add_shadow({pages, shadow_, std::size_t(desc_.Width)}); + return S_OK; + } + HRESULT create_sparse_buffer() { constexpr std::uint64_t tile_bytes = leonida::tile_size_in_bytes; if (!desc_.Width || desc_.Width > UINT64_MAX - tile_bytes || @@ -2533,6 +2686,7 @@ class Resource final std::uint64_t buffer_va_ = 0; std::uint64_t gpu_va_ = 0; bool host_import_ = false; // memory_ is the caller's pages (create_host_buffer): freed at once, not deferred + std::uint8_t* shadow_ = nullptr; // create_shadow_buffer: memory_ mapped, in DeviceState::shadows bool reserved_ = false; bool sparse_image_ = false; bool placed_ = false; @@ -4985,6 +5139,7 @@ class Device final info.conditional_rendering, info.ray_tracing, info.xdxr_acceleration_structures && info.buffer_device_address); + state_.context->set_before_execute([this] { state_.refresh_shadows(); }); if (info.physical && state_.format_properties) { state_.context->set_color_attachment_format( [physical = info.physical, get_props = state_.format_properties](VkFormat format) { @@ -6996,13 +7151,26 @@ class Device final if (FAILED(hr)) { // The driver would not import these pages: RADV refuses a view of a pagefile-backed section, the form // xmem's physical pages take (found in review on an RX 9070 XT under Wine), and a device without - // VK_EXT_external_memory_host has no import at all. The boot goes on with an ordinary DEFAULT buffer - // of the same description, as #6915's stand-in did: the title gets a resource, but its writes at - // `address` do not reach it. + // VK_EXT_external_memory_host has no import at all; write-combined and uncommitted pages are not tried, + // and some drivers stop importing after a budget (create_shadow_buffer). The title then gets a shadow + // buffer at its VA, copied from its pages before every submission. + resource->Release(); + resource = new Resource(state_, desc, heap, D3D12_HEAP_FLAG_NONE); + resource->attach_device(identity()); + const HRESULT shadow = resource->create_shadow_buffer(address); + if (SUCCEEDED(shadow)) { + log_once("a title-placed buffer (device slot 133) could not import its pages, so it is a shadow " + "copied from them before every submission; HRESULT", + int(hr)); + return d3d12_trace::result(method, hand_out(resource, riid, out)); + } + // No memory for the shadow either: the boot goes on with an ordinary DEFAULT buffer of the same + // description, as #6915's stand-in did. The title gets a resource, but neither its VA nor its writes at + // `address` reach it. resource->Release(); - log_once("a title-placed buffer (device slot 133) could not import its pages, so it is an ordinary buffer " - "the title's writes do not reach; HRESULT", - int(hr)); + log_once("a title-placed buffer (device slot 133) could neither import its pages nor get a shadow, so it " + "is an ordinary buffer the title's writes do not reach; HRESULT", + int(shadow)); const D3D12_HEAP_PROPERTIES fallback{D3D12_HEAP_TYPE_DEFAULT}; return d3d12_trace::result(method, create_committed(&fallback, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, 0, nullptr, riid, out)); diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index e659a762dc..77e43b90cf 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -1362,6 +1362,11 @@ class VulkanContext { // and records what the set needs first. When it fails, nothing of that call is executed. void set_transfer_only_family(std::uint32_t family) { transfer_only_family_ = family; } + // `before` is called at the start of every submission of command lists (a held batch: when it is released), + // before any lock here is taken: the device re-copies its slot-133 shadow buffers from the title's pages there. + // Set once, before the first queue exists. + void set_before_execute(std::function before) { before_execute_ = std::move(before); } + void set_bindless_prepare(std::function prepare) { std::unique_lock lock(resource_mutex_); bindless_prepare_ = std::move(prepare); @@ -1666,6 +1671,7 @@ class VulkanContext { std::map, VkRenderPass> resolve_passes_; std::map, VkFramebuffer> resolve_framebuffers_; + std::function before_execute_; std::function bindless_prepare_; std::function bindless_current_; bool bindless_upload_pending_ = false; // tracker_mutex_ @@ -2154,6 +2160,7 @@ class VulkanQueue : private QueueHolds::Holder { ReplayResult execute_now(std::span lists) { if (context_.is_device_lost() || !wait_for_room()) return ReplayResult::unsupported; + if (context_.before_execute_) context_.before_execute_(); if (kind_ != QueueKind::direct) for (const auto* list : lists) for (const auto& command : list->commands()) diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index 04900226a1..94dc94cf17 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -226,15 +226,89 @@ int check_title_placed(ID3D12Device* device, const char* kind, void* pages, UINT Ref placed_texture; EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, texture, 0x6u, IID_PPV_ARGS(&placed_texture.p)), S_OK); EXPECT(placed_texture.p != nullptr && placed_texture->GetDesc().Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D); - // An address off the buffer alignment can't be bound inside the import: the ordinary-buffer fallback answers. + // An address off the buffer alignment can't be bound inside the import: a shadow buffer answers, at the same VA + // (a driver whose buffer alignment is 1 imports it; the VA is the address either way). Ref fallback; + desc.Width = size - 1; EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, bytes + 1, desc, 0xFFFFFFFFu, IID_PPV_ARGS(&fallback.p)), S_OK); - EXPECT(fallback->GetGPUVirtualAddress() != reinterpret_cast(bytes + 1)); + EXPECT(fallback->GetGPUVirtualAddress() == reinterpret_cast(bytes + 1)); std::printf("%s: %s, %llu bytes: GPU VA is the address, a GPU copy reads the CPU's writes\n", who, kind, static_cast(size)); return 0; } +std::uint8_t pattern_byte(UINT64 i, unsigned seed) { + return static_cast(i * 131u + (i >> 8) * 7u + seed); +} + +// The shadow fallback of slot 133: pages the driver does not import (write-combined, uncached, not all committed) +// still give a buffer whose GPU VA is the address. It is a copy of the pages, made again before every submission: +// a pattern written to the first `committed` bytes after the buffer exists is what a GPU copy in the next +// ExecuteCommandLists reads, and so is a second pattern in the submission after. Bytes past `committed` are not +// committed: they are never read, and the GPU sees zeros there. The same holds where the range was imported after +// all (a Wine that drops the cache modifier), so the caller need not know which path answered. +int check_title_placed_shadow(ID3D12Device* device, const char* kind, void* pages, UINT64 committed, UINT64 size) { + const char* who = "vulkan slot-133 shadow"; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = size; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + Ref buffer; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, 0xFFFFFFFFu, IID_PPV_ARGS(&buffer.p)), S_OK); + EXPECT(buffer->GetGPUVirtualAddress() == reinterpret_cast(pages)); + D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + Ref readback; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + Ref queue; + Ref allocator; + Ref list; + Ref fence; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, + IID_PPV_ARGS(&list.p)))); + EXPECT(SUCCEEDED(list->Close())); + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr); + EXPECT(done != nullptr); + auto* bytes = static_cast(pages); + UINT64 fence_value = 0; + for (const unsigned seed : {7u, 93u}) { + // Written after the buffer exists (and, the second time, after a submission read the first pattern). + for (UINT64 i = 0; i < committed; ++i) bytes[i] = pattern_byte(i, seed); + EXPECT(SUCCEEDED(allocator->Reset())); + EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr))); + list->CopyBufferRegion(readback.p, 0, buffer.p, 0, size); + EXPECT(SUCCEEDED(list->Close())); + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + EXPECT(SUCCEEDED(queue->Signal(fence.p, ++fence_value))); + EXPECT(SUCCEEDED(fence->SetEventOnCompletion(fence_value, done))); + EXPECT(WaitForSingleObject(done, 30000) == WAIT_OBJECT_0); + void* mapped = nullptr; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); + const auto* got = static_cast(mapped); + UINT64 wrong = size; + for (UINT64 i = 0; i < size && wrong == size; ++i) + if (got[i] != (i < committed ? pattern_byte(i, seed) : 0)) wrong = i; + readback->Unmap(0, nullptr); + if (wrong != size) + std::fprintf(stderr, "%s: %s: pattern %u: first wrong byte at %llu\n", who, kind, seed, + static_cast(wrong)); + EXPECT(wrong == size); + } + CloseHandle(done); + std::printf("%s: %s, %llu bytes (%llu committed): GPU VA is the address, each submission reads the pages' " + "latest bytes\n", + who, kind, static_cast(size), static_cast(committed)); + return 0; +} + int check_title_placed_all(ID3D12Device* device) { constexpr SIZE_T size = 4 * 0x10000; int failures = 0; @@ -252,47 +326,43 @@ int check_title_placed_all(ID3D12Device* device) { UnmapViewOfFile(view); CloseHandle(section); - // Cache-modified ranges are not imported (WC imports read wrong bytes on an RTX 5090 in review). Some Wine - // versions report a requested WC allocation as plain read-write memory; check the protection actually supplied. - // PAGE_NOCACHE also exercises the fallback on those hosts, rather than dropping the cache-protection check. + // Cache-modified ranges are not imported (WC imports read wrong bytes on an RTX 5090 in review): a shadow buffer + // answers at the same VA. Some Wine versions report a requested WC allocation as plain read-write memory; check + // the protection actually supplied. PAGE_NOCACHE also exercises the fallback on those hosts, rather than + // dropping the cache-protection check. const char* who = "vulkan slot-133 buffer"; - D3D12_RESOURCE_DESC desc{}; - desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - desc.Width = size; - desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1; - desc.SampleDesc.Count = 1; - desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; for (DWORD modifier : {DWORD(PAGE_WRITECOMBINE), DWORD(PAGE_NOCACHE)}) { void* pages = VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE | modifier); EXPECT(pages != nullptr); MEMORY_BASIC_INFORMATION region{}; EXPECT(VirtualQuery(pages, ®ion, sizeof(region)) == sizeof(region)); const bool cache_modified = (region.Protect & (PAGE_WRITECOMBINE | PAGE_NOCACHE)) != 0; - { - Ref buffer; - EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, 0xFFFFFFFFu, IID_PPV_ARGS(&buffer.p)), S_OK); - if (cache_modified) { - EXPECT(buffer->GetGPUVirtualAddress() != reinterpret_cast(pages)); - } else { - EXPECT(region.Protect == PAGE_READWRITE); - EXPECT(buffer->GetGPUVirtualAddress() == reinterpret_cast(pages)); - } - } + if (!cache_modified) EXPECT(region.Protect == PAGE_READWRITE); + const int failed = check_title_placed_shadow(device, modifier == PAGE_WRITECOMBINE ? "write-combined range" + : "uncached range", + pages, size, size); std::printf("%s: cache modifier 0x%lx, reported protection 0x%lx: %s\n", who, modifier, region.Protect, - cache_modified ? "ordinary-buffer fallback verified" - : "modifier not reported; read-write import verified"); + failed ? "FAILED" + : cache_modified ? "shadow buffer verified" + : "modifier not reported; read-write import verified"); + failures += failed; VirtualFree(pages, 0, MEM_RELEASE); } - char* partial = static_cast(VirtualAlloc(nullptr, size, MEM_RESERVE, PAGE_READWRITE)); - EXPECT(partial != nullptr && VirtualAlloc(partial, size / 2, MEM_COMMIT, PAGE_READWRITE) == partial); { - // Pages not committed yet (xmem commits on first touch) are not imported either: the fallback answers. - Ref fallback; - EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, partial, desc, 0xFFFFFFFFu, IID_PPV_ARGS(&fallback.p)), S_OK); - EXPECT(fallback->GetGPUVirtualAddress() != reinterpret_cast(partial)); + // A larger write-combined range, so the per-submission copy the layer logs is measured on more than a few + // pages (retail places 182 MiB, 74 MiB of it write-combined). + constexpr SIZE_T large = 64u << 20; + void* pages = VirtualAlloc(nullptr, large, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE | PAGE_WRITECOMBINE); + EXPECT(pages != nullptr); + failures += check_title_placed_shadow(device, "64 MiB write-combined range", pages, large, large); + VirtualFree(pages, 0, MEM_RELEASE); } + char* partial = static_cast(VirtualAlloc(nullptr, size, MEM_RESERVE, PAGE_READWRITE)); + EXPECT(partial != nullptr && VirtualAlloc(partial, size / 2, MEM_COMMIT, PAGE_READWRITE) == partial); + // Pages not committed yet (xmem commits on first touch) are not imported either: the shadow copies the committed + // half and never reads the other, which a GPU copy sees as zeros. + failures += check_title_placed_shadow(device, "half-committed range", partial, size / 2, size); VirtualFree(partial, 0, MEM_RELEASE); - std::printf("%s: a partly committed range falls back to an ordinary buffer\n", who); return failures; } From 14dc9af525c5e54f9edbde43ccb2bbe499007852 Mon Sep 17 00:00:00 2001 From: Giovanni Lion Date: Tue, 24 Nov 2026 02:32:51 +0800 Subject: [PATCH 010/110] d3d12: enable SSE4.1 for Clang's slot-133 streaming copy Clang's baseline x64 target cannot inline _mm_stream_load_si128 into copy_guarded. Give only that function the target feature the existing intrinsic requires; keep the MSVC path and global build flags unchanged. Depends on: #8225. Claimed in #8186, comment7110252121. AI-assisted: yes (Codex). --- runtime/shims/d3d12_vulkan_device.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index d34419a010..0660b95130 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -90,6 +90,9 @@ void log_once(const char* what, int value) { // VirtualQuery that saw it committed and the read. No C++ objects here: it is a __try frame. // `streaming` reads with MOVNTDQA, for write-combined pages: ordinary loads from them are not cached, and memcpy // read 64 MiB of them in 253 ms on a Core i9-13900K (253 MiB/s), MOVNTDQA in 13 to 17 ms (4 to 5 GiB/s). Paid at every submission. +#if defined(__clang__) && defined(_M_X64) +__attribute__((target("sse4.1"))) +#endif bool copy_guarded(std::uint8_t* to, const std::uint8_t* from, std::size_t bytes, bool streaming) { __try { if (streaming) { From 8c5ce53d123c58f7b1219b4007489e44036b0afe Mon Sep 17 00:00:00 2001 From: Mumogg <104529023+Mumogg@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:35:55 -0600 Subject: [PATCH 011/110] local: wire #8591 into present_state_for --- runtime/shims/d3d12_xs_device.cpp | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 68f3700546..72b7a0692c 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -24,6 +24,7 @@ // 78 SetFrameIntervalX, 79 ScheduleFrameEventX and 80 WaitFrameEventX. The slots can be moved with LEONIDA_XS_*_SLOT // for a trace that disagrees. The frame-event calls answer from a per-device token counter: there is no vblank source // behind the device before a presenter exists, so WaitFrameEventX returns at once with a fresh non-zero token. +#include "title_window.h" #include "d3d12_xs_device.h" #include "d3d12_trace.h" #include "d3d12_xs_alloc_size.h" @@ -1337,7 +1338,15 @@ PresentState* present_state_for(DeviceProxy* device) { std::fprintf(stderr, "[rt] d3d12_xs: PresentX window failed (error %lu)\n", GetLastError()); return state; } - auto presenter = rt::d3d12::create_window_presenter(device->real, state->window); + // LOCAL (wiring of #8591): present into the title's own window when it has one; else show the fallback window. + HWND target = rt::d3d12::find_title_window(GetCurrentProcessId(), state->window); + if (target) { + std::fprintf(stderr, "[rt] d3d12_xs: PresentX uses the title's own window %p\n", static_cast(target)); + } else { + target = state->window; + ShowWindow(target, SW_SHOWNOACTIVATE); + } + auto presenter = rt::d3d12::create_window_presenter(device->real, target); if (!presenter) { std::fprintf(stderr, "[rt] d3d12_xs: no window presenter on this device; PresentX is a no-op\n"); return state; From ab1fbff95dbd8becb9866f2a26fafac80ed1f6a4 Mon Sep 17 00:00:00 2001 From: Etr0p <216035314+Etr0p@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:38:42 +0100 Subject: [PATCH 012/110] d3d12: shaders reach a title-placed buffer through the root views and buffer V#s the layer writes Xbox device slot 133 places a buffer at the title's own VA, about 1.5 TiB on Windows, while a translated shader computes heap_base + console VA with heap_base the arena's device address. A root view or V# naming that VA missed the buffer. The layer now translates an address inside a title-placed buffer where it writes it (root CBV/SRV/UAV, CBV and buffer SRV/UAV V#s): to the arena offset of the slot-133 shadow, which now lives in the GPU address arena when it fits, or to an import's device address minus heap_base. New tests: title_va_alias_test, d3d12_title_va_test. Co-Authored-By: Claude Opus 5.5 --- runtime/CMakeLists.txt | 11 + runtime/shims/d3d12_com.cpp | 5 + runtime/shims/d3d12_vulkan_device.cpp | 63 +++- runtime/src/title_va_alias.h | 89 ++++++ runtime/test/d3d12_title_va_test.cpp | 398 ++++++++++++++++++++++++++ runtime/test/glsl/cs_user_data.comp | 8 +- runtime/test/title_va_alias_test.cpp | 47 +++ 7 files changed, 618 insertions(+), 3 deletions(-) create mode 100644 runtime/src/title_va_alias.h create mode 100644 runtime/test/d3d12_title_va_test.cpp create mode 100644 runtime/test/title_va_alias_test.cpp diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 3d0bb02022..3fd8525d0d 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2438,6 +2438,14 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_compute_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_compute COMMAND d3d12_compute_test) set_tests_properties(d3d12_compute PROPERTIES SKIP_RETURN_CODE 77) + # A buffer at the title's own VA (device slot 133) read by the same shader through a root view and a V#. + add_executable(d3d12_title_va_test test/d3d12_title_va_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_CS}) + target_link_libraries(d3d12_title_va_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_title_va_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_CS_SPV="${LEONIDA_TEST_CS}") + target_compile_options(d3d12_title_va_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_title_va COMMAND d3d12_title_va_test) + set_tests_properties(d3d12_title_va PROPERTIES SKIP_RETURN_CODE 77) # Compute PSOs from FSPX programs (docs/fspx.md): an ACCC container at slot 62 and a bare kind-6 program. add_executable(d3d12_fspx_compute_test test/d3d12_fspx_compute_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_CS}) target_link_libraries(d3d12_fspx_compute_test PRIVATE gta6rt_d3d12_com) @@ -2997,6 +3005,9 @@ if(TARGET Vulkan::Headers) add_executable(arena_size_test test/arena_size_test.cpp) target_link_libraries(arena_size_test PRIVATE Vulkan::Headers) add_test(NAME arena_size COMMAND arena_size_test) + # Title-placed buffer VAs (device slot 133) and the console VA shaders reach them by (src/title_va_alias.h). + add_executable(title_va_alias_test test/title_va_alias_test.cpp) + add_test(NAME title_va_alias COMMAND title_va_alias_test) endif() else() include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/vulkan_headers_missing.cmake") diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index e33769c580..2d7d6de713 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -6,6 +6,7 @@ #include "d3d12_trace.h" #include "d3d12_xs_device.h" #include "../src/gfx10_descriptors.h" +#include "../src/title_va_alias.h" #include #include @@ -1167,6 +1168,10 @@ class GraphicsCommandList final return; const RootArgumentLayout::Parameter* p = parameter(state, index, type); if (!p) return; + // A root view inside a buffer the title placed at its own VA (device slot 133) gets the console VA of the + // buffer's GPU copy, so the shader's heap_base + VA reaches it (src/title_va_alias.h). Descriptor tables are + // the layer's own heaps: never translated. + if (type == rt::rootsig::ParamType::Descriptor) va = leonida::title_va_aliases().shader_va(va); const std::uint32_t first = first_dword(state, *p); write(state, first, std::uint32_t(va)); // In the compute layout a descriptor table is one dword, the 32-bit VA of its first descriptor (the heaps diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 0660b95130..ff794dc05f 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -28,6 +28,7 @@ #include "../src/shader_library.h" #include "../src/spirv_f16_halves.h" #include "../src/spirv_stores.h" +#include "../src/title_va_alias.h" #include "../src/vulkan_present.h" #include "../src/vulkan_device_filter.h" #include "../src/vulkan13_features.h" @@ -86,6 +87,19 @@ void log_once(const char* what, int value) { if (seen.insert({what, value}).second) std::fprintf(stderr, "[rt] d3d12: %s %d\n", what, value); } +// The base address a V# gets for a buffer address: inside a buffer the title placed at its own VA (device slot +// 133), the console VA of the buffer's GPU copy (src/title_va_alias.h, docs/d3d12_vulkan.md section 3.3); anything +// else unchanged. A V# keeps 48 address bits. An arena copy always fits; an imported buffer's address is its device +// address minus heap_base, which wraps when the driver put it below the arena: logged, and written as before. +std::uint64_t vsharp_address(std::uint64_t va) { + const std::uint64_t to = leonida::title_va_aliases().shader_va(va); + if (to != va && (to >> 48)) + log_once("a V# names a title-placed buffer whose GPU copy lies below heap_base, out of a V#'s 48 bits; " + "address bits 48-63:", + int(to >> 48)); + return to; +} + // memcpy that a page fault ends instead of killing the process: the title may decommit a page between the // VirtualQuery that saw it committed and the read. No C++ objects here: it is a __try frame. // `streaming` reads with MOVNTDQA, for write-combined pages: ordinary loads from them are not cached, and memcpy @@ -1810,6 +1824,7 @@ class Resource final : device_(device), desc_(desc), heap_(heap), heap_flags_(heap_flags), placed_(true), va_(placed_va) {} ~Resource() override { + if (aliased_) leonida::title_va_aliases().remove(va_, title_alias_); if (accel_) { device_.context->unregister_acceleration_structure(gpu_va_); if (buffer_va_ && buffer_va_ != gpu_va_) device_.context->unregister_acceleration_structure(buffer_va_); @@ -2091,9 +2106,19 @@ class Resource final binding.host_readable = true; binding.va = va_; device_.context->add_resource(id(), binding); + // Shaders reach the imported pages by their device address (src/title_va_alias.h). + if (buffer_va_) alias_title_va(buffer_va_ - device_.arena.address); return S_OK; } + // Registers [va_, va_ + width) as reached by shaders at `shader_va` (src/title_va_alias.h): the root views and + // buffer V#s the layer writes for an address in it get the matching address of the buffer's GPU copy. + void alias_title_va(std::uint64_t shader_va) { + if (!leonida::title_va_aliases().add(va_, desc_.Width, shader_va)) return; + title_alias_ = shader_va; + aliased_ = true; + } + // The fallback of create_host_buffer, for pages the driver will not import: write-combined or uncached ones (in // retail 74 MiB of the title's 182 MiB range), pages not committed yet, a device without // VK_EXT_external_memory_host, or a driver past its import budget (an RTX 3070 Ti answers @@ -2108,6 +2133,35 @@ class Resource final auto& vk = device_.context->vk; if (!address || !desc_.Width || desc_.Width > ~UINT64(0) - D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT) return E_INVALIDARG; + const auto* pages = static_cast(address); + // The shadow is a range of the GPU address arena when it fits there (docs/d3d12_vulkan.md section 3.3). + // The title's VA is about 1.5 TiB on Windows, far past the arena, so a shader's heap_base + VA would miss + // any buffer of the layer's; the root views and V#s the layer writes for that VA name the arena offset + // instead (src/title_va_alias.h), a VA below 4 GiB that a root view and a V#'s 48 bits both hold. The arena + // is host-visible, so the per-submission copy writes it in place. + if (device_.arena.mapped && device_.arena_allocate(desc_.Width, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT, + arena_offset_, DeviceState::arena_buffer)) { + in_arena_ = true; + shadow_ = device_.arena.mapped + arena_offset_; + copy_title_pages(shadow_, pages, std::size_t(desc_.Width)); + mapped_ = address; + va_ = reinterpret_cast(address); + buffer_va_ = gpu_va_ = device_.arena.address + arena_offset_; + device_.log_va("title-placed buffer (arena shadow)", va_, desc_.Width); + leonida::ResourceBinding binding{}; + binding.buffer = device_.arena.buffer; + binding.buffer_offset = arena_offset_; + binding.size = desc_.Width; + binding.host = shadow_; + binding.va = va_; + device_.context->add_resource(id(), binding); + device_.add_shadow({pages, shadow_, std::size_t(desc_.Width)}); + alias_title_va(arena_offset_); + return S_OK; + } + log_once("a title-placed shadow buffer does not fit the GPU address arena (raise LEONIDA_ARENA_MB), so it " + "has its own memory; size in KiB:", + int(desc_.Width / 1024)); const bool need_bda = device_.info.buffer_device_address || device_.arena.buffer != VK_NULL_HANDLE; VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; info.size = desc_.Width; @@ -2132,7 +2186,6 @@ class Resource final vk.vkMapMemory(device_.info.device, memory_, 0, VK_WHOLE_SIZE, 0, &shadow) != VK_SUCCESS) return E_OUTOFMEMORY; shadow_ = static_cast(shadow); - const auto* pages = static_cast(address); copy_title_pages(shadow_, pages, std::size_t(desc_.Width)); // Map() answers the title's own pages, as the imported buffer does: a write to the shadow's memory would be // overwritten by the next copy. @@ -2154,6 +2207,7 @@ class Resource final binding.va = va_; device_.context->add_resource(id(), binding); device_.add_shadow({pages, shadow_, std::size_t(desc_.Width)}); + if (buffer_va_) alias_title_va(buffer_va_ - device_.arena.address); return S_OK; } @@ -2690,6 +2744,8 @@ class Resource final std::uint64_t gpu_va_ = 0; bool host_import_ = false; // memory_ is the caller's pages (create_host_buffer): freed at once, not deferred std::uint8_t* shadow_ = nullptr; // create_shadow_buffer: memory_ mapped, in DeviceState::shadows + bool aliased_ = false; // va_ is in leonida::title_va_aliases(), reached at title_alias_ + std::uint64_t title_alias_ = 0; bool reserved_ = false; bool sparse_image_ = false; bool placed_ = false; @@ -6403,6 +6459,7 @@ class Device final buffer.num_records = desc->SizeInBytes; buffer.format = leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT); buffer.oob_select = leonida::gfx10::OobSelect::raw; + buffer.address = vsharp_address(buffer.address); const leonida::gfx10::BufferWords words = leonida::gfx10::encode(buffer); std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); } @@ -6494,6 +6551,7 @@ class Device final } buffer.oob_select = leonida::gfx10::OobSelect::structured; } + buffer.address = vsharp_address(buffer.address); const leonida::gfx10::BufferWords words = leonida::gfx10::encode(buffer); std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); return; @@ -6651,11 +6709,12 @@ class Device final buffer.swizzle = channels; buffer.oob_select = typed ? g::OobSelect::structured : structured ? g::OobSelect::structured_with_offset : g::OobSelect::raw; + buffer.address = vsharp_address(buffer.address); const g::BufferWords words = g::encode(buffer); std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); if (counter) { g::Buffer counter_buffer{}; - counter_buffer.address = counter_va + view.CounterOffsetInBytes; + counter_buffer.address = vsharp_address(counter_va + view.CounterOffsetInBytes); counter_buffer.num_records = 4; counter_buffer.oob_select = g::OobSelect::raw; const g::BufferWords counter_words = g::encode(counter_buffer); diff --git a/runtime/src/title_va_alias.h b/runtime/src/title_va_alias.h new file mode 100644 index 0000000000..66739f7c13 --- /dev/null +++ b/runtime/src/title_va_alias.h @@ -0,0 +1,89 @@ +#pragma once +// Title-chosen buffer VAs (Xbox device slot 133) and the console VA a translated shader reaches them by +// (docs/d3d12_vulkan.md section 3.3, "Title-placed buffers"). +// +// A translated shader computes heap_base + console_va, with heap_base the GPU address arena's device address. The +// layer chooses every console VA it hands out, so they all land in the arena, but slot 133 places a buffer at a VA +// the title chose: the CPU address of its own pages (about 1.5 TiB on Windows), far past the arena. A shader that +// adds heap_base to that VA reads nothing the layer made. So where the layer itself writes an address a shader will +// dereference (a root CBV/SRV/UAV, and the V# of a CBV or a buffer SRV/UAV), an address inside a title-placed +// buffer is replaced by the console VA of the buffer's GPU copy: its arena offset when the copy is an arena range +// (the slot-133 shadow), or its device address minus heap_base (mod 2^64) when it has its own memory (an imported +// buffer). Everything else is passed through unchanged. Addresses the title writes into memory itself (a V# it +// builds in its own constant data) are not seen by the layer and keep the title's VA. +// +// The table is process-wide, like the title's address space: a title VA names one buffer at a time. It depends only +// on the standard library, so it is tested without a GPU (title_va_alias_test). +#include +#include +#include +#include +#include +#include +#include + +namespace leonida { + +class TitleVaAliases { +public: + // [title_va, title_va + bytes) is reached as [shader_va, shader_va + bytes). A range that overlaps a live one + // replaces it (the title has placed a new buffer over pages it released). False for an empty or wrapping range. + bool add(std::uint64_t title_va, std::uint64_t bytes, std::uint64_t shader_va) { + if (!bytes || title_va > UINT64_MAX - bytes) return false; + std::unique_lock lock(mutex_); + erase_overlapping(title_va, title_va + bytes); + ranges_[title_va] = {title_va + bytes, shader_va}; + count_.store(ranges_.size(), std::memory_order_release); + return true; + } + + // Forgets the range that starts at title_va, if it still maps to shader_va (a newer buffer at the same VA keeps + // its own entry). + void remove(std::uint64_t title_va, std::uint64_t shader_va) { + std::unique_lock lock(mutex_); + const auto it = ranges_.find(title_va); + if (it != ranges_.end() && it->second.shader_va == shader_va) ranges_.erase(it); + count_.store(ranges_.size(), std::memory_order_release); + } + + // The address a shader must be given for `va`: translated inside a title-placed buffer, unchanged elsewhere. + std::uint64_t shader_va(std::uint64_t va) const { + if (!count_.load(std::memory_order_acquire)) return va; // the common case: no title-placed buffer + std::shared_lock lock(mutex_); + auto it = ranges_.upper_bound(va); + if (it == ranges_.begin()) return va; + --it; + if (va >= it->second.end) return va; + return it->second.shader_va + (va - it->first); + } + + std::size_t size() const { return count_.load(std::memory_order_acquire); } + +private: + struct Range { + std::uint64_t end; // exclusive + std::uint64_t shader_va; // what title_va becomes + }; + + void erase_overlapping(std::uint64_t begin, std::uint64_t end) { + auto it = ranges_.lower_bound(begin); + if (it != ranges_.begin()) { + auto previous = std::prev(it); + if (previous->second.end > begin) it = previous; + } + while (it != ranges_.end() && it->first < end) it = ranges_.erase(it); + } + + mutable std::shared_mutex mutex_; + std::map ranges_; // by title VA + std::atomic count_{0}; +}; + +// The process's table: the slot-133 buffers add and remove their ranges, the command lists and descriptor writers +// read it. +inline TitleVaAliases& title_va_aliases() { + static TitleVaAliases aliases; + return aliases; +} + +} // namespace leonida diff --git a/runtime/test/d3d12_title_va_test.cpp b/runtime/test/d3d12_title_va_test.cpp new file mode 100644 index 0000000000..73447964b5 --- /dev/null +++ b/runtime/test/d3d12_title_va_test.cpp @@ -0,0 +1,398 @@ +// A buffer the title places at its own VA (Xbox device slot 133, rt::d3d12::create_buffer_at_host_address) is read +// by a shader written to the translator's address contract (heap_base + console VA, docs/d3d12_vulkan.md section +// 3.3), through the two kinds of address the layer writes for it: +// - a root view (SetComputeRootUnorderedAccessView with the title's VA): read 256 bytes past its base and written +// at its base, then copied to a READBACK buffer; +// - a buffer V# (CreateShaderResourceView of the title's buffer), the way translated vertex shaders fetch their +// vertices: read and written to an arena buffer. +// The title's VA is a VirtualAlloc address, far past the 4 GiB arena. Both page kinds are covered: read-write pages +// (imported with VK_EXT_external_memory_host where the driver takes them) and write-combined pages (refused by the +// import, so a shadow copy in the arena, the retail case on an RTX 5070 Ti). The data is written after the buffer +// exists, so the shadow's copy before the submission is what the GPU reads. +// Negative controls: a second title buffer with other data must not be what the first one's V# reads; an address +// one byte past the title range, an arena buffer's VA, and the title's VA after the buffer is released are written +// to a V# unchanged. The shader is test/glsl/cs_user_data.comp. No game data. LEONIDA_VK_VALIDATION=1 for the +// Khronos validation layer. +#include "shader_fixture_path.h" +#include "test_temp_dir.h" +#include "vk_test_device.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/shader_library.h" +#include "../src/title_va_alias.h" + +#include +#include +#include +#include +#include + +#ifndef LEONIDA_TEST_CS_SPV +#error "LEONIDA_TEST_CS_SPV must name the compiled test shader" +#endif + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX +using XboxComputePipelineFn = HRESULT(WINAPI*)(void* device, const D3D12_COMPUTE_PIPELINE_STATE_DESC*, std::uint64_t, + std::uint64_t, const IID*, void**); +using SerializeFn = HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**); + +template +struct Ref { + T* p = nullptr; + ~Ref() { reset(); } + void reset() { + if (p) p->Release(); + p = nullptr; + } + T* operator->() const { return p; } +}; + +void* slot(void* object, unsigned index) { return (*reinterpret_cast(object))[index]; } + +void put32(std::vector& out, std::uint32_t v) { + for (int i = 0; i < 4; ++i) out.push_back(std::uint8_t(v >> (8 * i))); +} + +std::vector zlib_stored(const std::vector& data) { + std::vector out = {0x78, 0x01, 0x01}; + const auto length = std::uint16_t(data.size()); + out.insert(out.end(), {std::uint8_t(length), std::uint8_t(length >> 8), std::uint8_t(~length), + std::uint8_t(~length >> 8)}); + out.insert(out.end(), data.begin(), data.end()); + std::uint32_t a = 1, b = 0; + for (const std::uint8_t x : data) { + a = (a + x) % 65521; + b = (b + a) % 65521; + } + const std::uint32_t adler = (b << 16) | a; + out.insert(out.end(), {std::uint8_t(adler >> 24), std::uint8_t(adler >> 16), std::uint8_t(adler >> 8), + std::uint8_t(adler)}); + return out; +} + +// The game's shader container shape (DXBC > DXIL > XDAT 0x0D > XBCH > zlib > FSSM), as d3d12_compute_test builds it. +std::vector shader_container(const std::vector& fssm) { + const auto stream = zlib_stored(fssm); + std::vector xbch = {'X', 'B', 'C', 'H'}; + for (const std::uint32_t v : {1u, std::uint32_t(stream.size()), 0u, std::uint32_t(fssm.size()), 0u}) put32(xbch, v); + xbch.insert(xbch.end(), stream.begin(), stream.end()); + std::vector dxil(16, 0); + dxil.insert(dxil.end(), {'X', 'D', 'A', 'T'}); + put32(dxil, 1); + put32(dxil, 12); + put32(dxil, 0x0d); + put32(dxil, 16 + 12 + 12); + put32(dxil, std::uint32_t(xbch.size())); + dxil.insert(dxil.end(), xbch.begin(), xbch.end()); + std::vector out = {'D', 'X', 'B', 'C'}; + out.resize(28, 0); + put32(out, 1); + put32(out, 36); + out.insert(out.end(), {'D', 'X', 'I', 'L'}); + put32(out, std::uint32_t(dxil.size())); + out.insert(out.end(), dxil.begin(), dxil.end()); + return out; +} + +std::vector serialize(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& desc) { + const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); + const auto fn = d3d12 ? reinterpret_cast( + reinterpret_cast(GetProcAddress(d3d12, "D3D12SerializeVersionedRootSignature"))) + : nullptr; + std::vector out; + ID3DBlob* blob = nullptr; + if (fn && SUCCEEDED(fn(&desc, &blob, nullptr)) && blob) { + const auto* p = static_cast(blob->GetBufferPointer()); + out.assign(p, p + blob->GetBufferSize()); + blob->Release(); + } + return out; +} + +D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) { + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = bytes; + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + desc.Flags = flags; + return desc; +} + +// The 48-bit base address of the 16-byte GFX10 buffer V# at `cpu` (dword 0, and dword 1 bits 0-15). +std::uint64_t vsharp_base(std::uint64_t cpu) { + std::uint32_t w[2]; + std::memcpy(w, reinterpret_cast(cpu), sizeof(w)); + return std::uint64_t(w[0]) | (std::uint64_t(w[1] & 0xFFFFu) << 32); +} + +D3D12_SHADER_RESOURCE_VIEW_DESC raw_srv(UINT first_word, UINT words) { + D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; + desc.Format = DXGI_FORMAT_R32_TYPELESS; + desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + desc.Buffer.FirstElement = first_word; + desc.Buffer.NumElements = words; + desc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + return desc; +} + +constexpr UINT kElements = 64, kBytes = kElements * 4; +constexpr UINT64 kPages = 64 * 1024; +constexpr UINT kSrvWord = 256; // the V# reads title words 256..319 +constexpr UINT kRootAdd = 7; // root view mode: title word i = title word 64 + i + 7 + +struct Context { + ID3D12Device* inner = nullptr; // the Vulkan device (slot 133's backend takes it) + ID3D12Device* device = nullptr; // the Xbox-ABI proxy over it + ID3D12RootSignature* root = nullptr; + ID3D12PipelineState* pso = nullptr; + ID3D12CommandQueue* queue = nullptr; + ID3D12Fence* fence = nullptr; + UINT64 fence_value = 0; + std::uint64_t arena = 0; +}; + +// One kind of title pages: `protect` is PAGE_READWRITE, or with PAGE_WRITECOMBINE. +int check_kind(Context& c, const char* kind, DWORD protect, int& checks) { + void* pages = VirtualAlloc(nullptr, kPages, MEM_RESERVE | MEM_COMMIT, protect); + void* other_pages = VirtualAlloc(nullptr, kPages, MEM_RESERVE | MEM_COMMIT, protect); + EXPECT(pages && other_pages); + const auto title_va = reinterpret_cast(pages); + EXPECT(title_va >= c.arena); // outside the arena: heap_base + title_va names nothing of the layer's + const D3D12_RESOURCE_DESC desc = buffer_desc(kPages); + Ref title, other; + EXPECT(SUCCEEDED(rt::d3d12::create_buffer_at_host_address(c.inner, pages, desc, 0xFFFFFFFFu, + IID_PPV_ARGS(&title.p)))); + EXPECT(SUCCEEDED(rt::d3d12::create_buffer_at_host_address(c.inner, other_pages, desc, 0xFFFFFFFFu, + IID_PPV_ARGS(&other.p)))); + EXPECT(title->GetGPUVirtualAddress() == title_va); // the title keeps its own VA + const std::uint64_t shader_va = leonida::title_va_aliases().shader_va(title_va); + EXPECT(shader_va != title_va); + const bool arena_copy = shader_va < c.arena; + const bool vsharp_fits = (shader_va >> 48) == 0; + + // The data, written after the buffers exist. + auto* words = static_cast(pages); + auto* other_words = static_cast(other_pages); + for (UINT i = 0; i < kPages / 4; ++i) { + words[i] = 0xA0000000u + i * 3u; + other_words[i] = 0xB0000000u + i * 5u; + } + + // Descriptors: the title buffer's V# (and the other buffer's), and the negative controls. + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 8, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + Ref heap; + EXPECT(SUCCEEDED(c.device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p)))); + const std::uint64_t cpu = reinterpret_cast(slot(heap.p, 9))(heap.p); + const std::uint64_t gpu = reinterpret_cast(slot(heap.p, 10))(heap.p); + const UINT inc = c.device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + const D3D12_SHADER_RESOURCE_VIEW_DESC srv = raw_srv(kSrvWord, kElements); + c.device->CreateShaderResourceView(title.p, &srv, D3D12_CPU_DESCRIPTOR_HANDLE{cpu}); + c.device->CreateShaderResourceView(other.p, &srv, D3D12_CPU_DESCRIPTOR_HANDLE{cpu + inc}); + EXPECT(vsharp_base(cpu) == ((shader_va + kSrvWord * 4) & 0xFFFFFFFFFFFFull)); + // Negative controls, descriptor level: one byte past the title range is not translated. + const D3D12_CONSTANT_BUFFER_VIEW_DESC past{title_va + kPages, 256}; + c.device->CreateConstantBufferView(&past, D3D12_CPU_DESCRIPTOR_HANDLE{cpu + 2 * inc}); + EXPECT(vsharp_base(cpu + 2 * inc) == ((title_va + kPages) & 0xFFFFFFFFFFFFull)); + ++checks; + + // An arena buffer for the V# read's result, a READBACK buffer for both results. + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}, readback_heap{D3D12_HEAP_TYPE_READBACK}; + Ref out, readback; + const auto uav = buffer_desc(kBytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &uav, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, + IID_PPV_ARGS(&out.p)))); + const auto readback_desc = buffer_desc(3 * kBytes); + EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + // An arena buffer's V# keeps its VA: identity outside title-placed buffers. + const D3D12_CONSTANT_BUFFER_VIEW_DESC arena_cbv{out->GetGPUVirtualAddress(), 256}; + c.device->CreateConstantBufferView(&arena_cbv, D3D12_CPU_DESCRIPTOR_HANDLE{cpu + 3 * inc}); + EXPECT(vsharp_base(cpu + 3 * inc) == out->GetGPUVirtualAddress()); + + Ref allocator; + Ref list; + EXPECT(SUCCEEDED(c.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(c.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, c.pso, + IID_PPV_ARGS(&list.p)))); + ID3D12DescriptorHeap* heaps[] = {heap.p}; + list->SetDescriptorHeaps(1, heaps); + list->SetComputeRootSignature(c.root); + // Through the V# (buffer SRV mode, s5 = 0xFFFFFFFF), into the arena buffer. Skipped when the buffer's copy is + // not within a V#'s 48 bits of heap_base (an import the driver put below the arena), which the layer logs. + if (vsharp_fits) { + list->SetComputeRoot32BitConstant(0, 0, 0); + list->SetComputeRoot32BitConstant(0, 0xFFFFFFFFu, 1); + list->SetComputeRootUnorderedAccessView(1, out->GetGPUVirtualAddress()); + list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{gpu}); + list->Dispatch(1, 1, 1); + } + // Through the root view: the title's own VA, read at +256 bytes and written at +0. + list->SetComputeRoot32BitConstant(0, kRootAdd, 0); + list->SetComputeRoot32BitConstant(0, 0xFFFFFFFEu, 1); + list->SetComputeRootUnorderedAccessView(1, title_va); + list->Dispatch(1, 1, 1); + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + list->ResourceBarrier(1, &barrier); + D3D12_RESOURCE_BARRIER to_copy{}; + to_copy.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + to_copy.Transition.pResource = out.p; + to_copy.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + to_copy.Transition.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + to_copy.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; + list->ResourceBarrier(1, &to_copy); + list->CopyBufferRegion(readback.p, 0, out.p, 0, kBytes); + list->CopyBufferRegion(readback.p, kBytes, title.p, 0, kBytes); + EXPECT(list->Close() == S_OK); + ID3D12CommandList* lists[] = {list.p}; + c.queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(c.queue) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(c.queue->Signal(c.fence, ++c.fence_value))); + EXPECT(SUCCEEDED(c.fence->SetEventOnCompletion(c.fence_value, nullptr))); + + void* mapped = nullptr; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); + const auto* got = static_cast(mapped); + UINT srv_ok = 0, srv_other = 0, root_ok = 0; + for (UINT i = 0; i < kElements; ++i) { + if (got[i] == words[kSrvWord + i]) ++srv_ok; + if (got[i] == other_words[kSrvWord + i]) ++srv_other; + if (got[kElements + i] == words[64 + i] + kRootAdd) ++root_ok; + } + readback->Unmap(0, nullptr); + std::printf("%s pages: GPU copy %s (shader VA %s); V# read %s, %u/%u words matched, %u/%u read the other " + "buffer's (negative control); root view read+write %u/%u matched\n", + kind, arena_copy ? "in the arena" : "with its own device address", + arena_copy ? "an arena offset" : "device address - heap_base", + vsharp_fits ? "run" : "skipped (out of a V#'s 48 bits)", vsharp_fits ? srv_ok : 0, kElements, + vsharp_fits ? srv_other : 0, kElements, root_ok, kElements); + if (vsharp_fits) { + EXPECT(srv_ok == kElements); + EXPECT(srv_other == 0); + } + EXPECT(root_ok == kElements); + + // After release, the title's VA is no longer translated: a new view of it names the title's VA itself. + title.reset(); + const D3D12_CONSTANT_BUFFER_VIEW_DESC released{title_va, 256}; + c.device->CreateConstantBufferView(&released, D3D12_CPU_DESCRIPTOR_HANDLE{cpu + 4 * inc}); + EXPECT(vsharp_base(cpu + 4 * inc) == (title_va & 0xFFFFFFFFFFFFull)); + EXPECT(leonida::title_va_aliases().shader_va(title_va) == title_va); + checks += 2; + other.reset(); + heap.reset(); + VirtualFree(pages, 0, MEM_RELEASE); + VirtualFree(other_pages, 0, MEM_RELEASE); + return 0; +} + +} // namespace + +int main() { + vktest::Device d; + const auto device_status = d.initialize(); + if (device_status == vktest::DeviceStatus::unavailable) { + std::fprintf(stderr, "SKIP: no usable Vulkan 1.3 device\n"); + return 77; + } + EXPECT(device_status == vktest::DeviceStatus::ready); + + std::vector fssm = {'F', 'S', 'S', 'M'}; + put32(fssm, 6000); + for (std::uint32_t i = 0; i < 14; ++i) put32(fssm, 0xbf810000u + i); + const auto container = shader_container(fssm); + const testfiles::ScratchDir scratch("leonida_title_va_test"); + const auto& library = scratch.path(); + EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), library / "cs_user_data.spv")); + { + std::ofstream index(library / "index.json", std::ios::binary); + index << "{\"cs_user_data\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << leonida::sha256_hex(fssm) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"local_size\": [64, 1, 1], " + "\"uses_code_base\": true, \"wave64\": false}}"; + } + + int checks = 0; + { + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = d.instance_proc; + info.instance = d.instance; + info.physical = d.physical; + info.device = d.device; + info.queue = d.queue; + info.queue_family = d.family; + info.buffer_device_address = true; + info.subgroup = d.subgroup; + info.shader_dir = library.string(); + ID3D12Device* inner = nullptr; // owned by the proxy, as in d3d12_compute_test + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); + Ref device; + EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), + reinterpret_cast(&device.p)))); + rt::d3d12::set_device_outer(inner, device.p); + + // [0] two constants (s4, s5), [1] a root UAV (s6:s7), [2] a one-descriptor table (s8): the console compute + // layout cs_user_data.comp reads. + D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, 1, 0, 0}; + D3D12_ROOT_PARAMETER params[3] = {}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[0].Constants = {0, 0, 2}; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + params[1].Descriptor = {0, 0}; + params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[2].DescriptorTable = {1, &range}; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + root_desc.Desc_1_0 = {3, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + const auto root_blob = serialize(root_desc); + EXPECT(!root_blob.empty()); + Ref root; + EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p)))); + D3D12_COMPUTE_PIPELINE_STATE_DESC pso_desc{}; + pso_desc.pRootSignature = root.p; + pso_desc.CS = {container.data(), container.size()}; + const IID pso_iid = __uuidof(ID3D12PipelineState); + Ref pso; + EXPECT(SUCCEEDED(reinterpret_cast(slot(device.p, 62))( + device.p, &pso_desc, 0, 0, &pso_iid, reinterpret_cast(&pso.p)))); + + const D3D12_COMMAND_QUEUE_DESC queue_desc{}; + Ref queue; + Ref fence; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + + Context c; + c.inner = inner; + c.device = device.p; + c.root = root.p; + c.pso = pso.p; + c.queue = queue.p; + c.fence = fence.p; + c.arena = rt::d3d12::device_arena_size(device.p); + EXPECT(c.arena > 0); + if (check_kind(c, "read-write", PAGE_READWRITE, checks)) return 1; + if (check_kind(c, "write-combined", PAGE_READWRITE | PAGE_WRITECOMBINE, checks)) return 1; + } + if (d.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); + return 1; + } + std::printf("title-placed buffers: a translated shader reached both page kinds through a root view and a buffer " + "V#; %d descriptor-level negative controls held\n", + checks); + return 0; +} diff --git a/runtime/test/glsl/cs_user_data.comp b/runtime/test/glsl/cs_user_data.comp index b285c0f3f9..4e1dfc904e 100644 --- a/runtime/test/glsl/cs_user_data.comp +++ b/runtime/test/glsl/cs_user_data.comp @@ -37,8 +37,14 @@ Words at(uvec2 va) { void main() { const uint i = gl_GlobalInvocationID.x; - Words table = at(uvec2(pc.s[8], 0u)); Words result = at(uvec2(pc.s[6], pc.s[7])); + if (pc.s[5] == 0xFFFFFFFEu) { + // Root view read mode (d3d12_title_va_test): read through the root UAV itself, 256 bytes past its base, and + // write at the base, so the root view's address is both read and written. + result.w[i] = result.w[64u + i] + pc.s[4]; + return; + } + Words table = at(uvec2(pc.s[8], 0u)); if (pc.s[5] == 0u) { // CBV V# mode: table holds a 16-byte GFX10 raw buffer descriptor written by CreateConstantBufferView. const uint num_records = table.w[2]; diff --git a/runtime/test/title_va_alias_test.cpp b/runtime/test/title_va_alias_test.cpp new file mode 100644 index 0000000000..7a4a38b9a8 --- /dev/null +++ b/runtime/test/title_va_alias_test.cpp @@ -0,0 +1,47 @@ +// leonida::TitleVaAliases (src/title_va_alias.h): where an address inside a title-placed buffer (Xbox device slot +// 133) is translated to, and that everything else is left alone. No GPU. +#include "../src/title_va_alias.h" + +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +int main() { + leonida::TitleVaAliases a; + constexpr std::uint64_t title = 0x18500000000ull; // the shape of a Windows VA past 1 TiB + constexpr std::uint64_t size = 0x10000; + constexpr std::uint64_t arena = 0x2340000; + // Empty: identity everywhere. + EXPECT(a.size() == 0 && a.shader_va(title) == title && a.shader_va(0) == 0); + EXPECT(!a.add(title, 0, arena)); // empty range + EXPECT(!a.add(UINT64_MAX - 4, 16, arena)); // wraps + EXPECT(a.add(title, size, arena) && a.size() == 1); + // Inside: the same offset in the copy, first and last byte included. + EXPECT(a.shader_va(title) == arena); + EXPECT(a.shader_va(title + 0x123) == arena + 0x123); + EXPECT(a.shader_va(title + size - 1) == arena + size - 1); + // Negative controls: one byte before, the end itself, and an arena VA are untouched. + EXPECT(a.shader_va(title - 1) == title - 1); + EXPECT(a.shader_va(title + size) == title + size); + EXPECT(a.shader_va(arena) == arena); + // A wrapping target (an import below heap_base) is kept as is: modular arithmetic. + constexpr std::uint64_t below = 0xFFFFFFFFFFF00000ull; + EXPECT(a.add(title + 0x100000, size, below) && a.shader_va(title + 0x100010) == below + 0x10); + // A new buffer over part of a live range replaces it; the old range's removal does not touch the new one. + EXPECT(a.add(title + 0x8000, size, 0x5000000)); + EXPECT(a.shader_va(title) == title); // the replaced range is gone entirely + EXPECT(a.shader_va(title + 0x8000) == 0x5000000); + a.remove(title, arena); // stale: nothing starts there any more + EXPECT(a.shader_va(title + 0x8000) == 0x5000000); + a.remove(title + 0x8000, 0x1234); // another target: kept + EXPECT(a.shader_va(title + 0x8000) == 0x5000000); + a.remove(title + 0x8000, 0x5000000); + EXPECT(a.shader_va(title + 0x8000) == title + 0x8000); + a.remove(title + 0x100000, below); + EXPECT(a.size() == 0 && a.shader_va(title + 0x100010) == title + 0x100010); + std::printf("title_va_alias: translation inside a title-placed range, identity outside it and after release\n"); + return 0; +} From 7a8ae20ca09c355852c55766eb9313f90f179e21 Mon Sep 17 00:00:00 2001 From: Etr0p <216035314+Etr0p@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:39:59 +0100 Subject: [PATCH 013/110] docs: section 3.3 says how shaders reach title-placed buffers Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 22 ++++++++++++++++++++++ runtime/shims/d3d12_vulkan_device.cpp | 5 +++-- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index aae8591bf4..272bc68579 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1496,6 +1496,28 @@ Arena VAs (at most 4095 MiB, so 32-bit) pass. A VA biased from outside the arena VAs above are at or above 2^40 as unsigned values. That is one more reason for the rule above that every buffer a console client can address is an arena range, whichever heap it comes from. +**Title-placed buffers (device slot 133).** Here the title, not the layer, chooses the VA: `CreatePlacedResourceX` +puts a buffer at the CPU address of the title's own pages. On Windows that is a user-mode address around 1.5 TiB, +far past the arena (at most 4095 MiB, and descriptor tables must stay below 4 GiB), so `heap_base + title_va` +names nothing the layer made. The layer therefore translates the title's VA where it +writes an address itself: root CBV/SRV/UAV arguments (`SetGraphicsRoot*View`, `SetComputeRoot*View`) and the base +of the V# it writes for a CBV or a buffer SRV/UAV (counter included). An address inside a title-placed buffer +becomes the console VA of that buffer's GPU copy (`runtime/src/title_va_alias.h`); every other address is left +alone, and the range is forgotten when the buffer is released. +- When the pages can't be imported (write-combined or uncommitted pages, a missing extension, an import budget), + the copy is the per-submission shadow, and the shadow is an **arena range** when it fits. Its console VA is the + arena offset: below 4 GiB, so it holds in a root argument, in a V#'s 48 bits and in a 32-bit table pointer alike. + When the arena has no room, the shadow keeps its own memory and is biased like an upload buffer (logged once; + raise `LEONIDA_ARENA_MB`). +- When the pages are imported (`VK_EXT_external_memory_host`), the copy is the import and its console VA is its + device address minus `heap_base` (mod 2^64): exact for 64-bit root arguments, and for a V# only when the driver + put the import above the arena (otherwise logged once, as measured for upload buffers above). +- The title's own VA is still what `GetGPUVirtualAddress` answers and what vertex, index, copy and immediate-write + calls resolve through the buffer VA index, so nothing the title reads back changes. +- **Not covered:** a pointer or V# the title writes into memory itself (inside its constant data, say). The layer + never sees it, so it keeps the title's VA. Covering it needs the title's pages inside the GPU address space + (one of the options in #7218's design note) or the translator rewriting addresses. + Why not give each buffer its own BDA and set `heap_base = 0`? Because 25,865 of the 26,503 shaders (97.6%) truncate descriptor-table pointers to 32 bits, and host BDAs are not guaranteed to be below 4 GB. The arena keeps console VAs low and stable. diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index ff794dc05f..2fb79e587b 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -2010,8 +2010,9 @@ class Resource final // with VK_EXT_external_memory_host and the buffer bound to it at offset 0, so the CPU's writes there are the GPU's // reads with no copy. Its console VA is `address` itself, the VA the title chose, so vertex, index and immediate // writes the title names by that VA find this buffer (VulkanContext::buffer_at). A shader that adds heap_base to - // that VA does not reach it: the title's own V#s into these pages need the single address space of - // docs/d3d12_vulkan.md section 3.3, which this does not decide. The pages stay the caller's: nothing is zeroed. + // that VA would not reach it, so the root views and V#s the layer writes for it name its device address minus + // heap_base instead (alias_title_va, docs/d3d12_vulkan.md section 3.3 "Title-placed buffers"); V#s the title + // writes into memory itself keep its VA. The pages stay the caller's: nothing is zeroed. HRESULT create_host_buffer(void* address) { auto& vk = device_.context->vk; const VkDeviceSize alignment = device_.info.host_pointer_alignment; From d8ba5ff389ba41478bd2733237a359c6ce070a42 Mon Sep 17 00:00:00 2001 From: Mumogg <104529023+Mumogg@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:40:50 -0600 Subject: [PATCH 014/110] local: trace PresentX --- runtime/shims/d3d12_xs_device.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 72b7a0692c..446f94084a 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -1509,7 +1509,12 @@ std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_ } return hr_to_u64(S_OK); } - if (Slot == (newer ? 32u : 30u)) return queue_present_x(self, a1, a2, a3); // PresentX + if (Slot == (newer ? 32u : 30u)) { // PresentX + const std::uint64_t hr = queue_present_x(self, a1, a2, a3); + // LOCAL: one trace line per present, so a run's presents can be counted. + d3d12_trace::record("XboxID3D12CommandQueue::PresentX", static_cast(hr) < 0 ? "failed" : "ok"); + return hr; + } if (Slot >= self->slot_count || (newer && (Slot == 14 || Slot == 15))) { d3d12_trace::record(child_trace_name(Slot), "console-only"); return hr_to_u64(S_OK); // unmodelled console queue methods: frame pacing flows through them From 65668002e972259722f008617068dd8ee90c82ce Mon Sep 17 00:00:00 2001 From: Etr0p <216035314+Etr0p@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:47:45 +0100 Subject: [PATCH 015/110] d3d12: buffer addresses in the title's own memory reach a shader through an arena window A root view or buffer V# may name the title's own memory outside any slot-133 buffer (a per-frame constant ring, #8862 section 3.5). The layer now makes a 64 KiB-aligned window of those pages in the GPU address arena, copies it before every submission like a slot-133 shadow, and names that copy instead: for root views when set, for V#s the layer writes, and for buffer V#s the title writes into a bound CBV/SRV/UAV table itself, rewritten in place before each submission. Counters per kind, LEONIDA_TITLE_WINDOWS_MB caps the windows (64 MiB). Co-Authored-By: Claude Opus 5.5 --- runtime/shims/d3d12_com.cpp | 30 ++++- runtime/shims/d3d12_vulkan_device.cpp | 148 ++++++++++++++++++++-- runtime/src/title_va_alias.h | 124 ++++++++++++++++--- runtime/src/vulkan_backend.h | 6 + runtime/test/d3d12_title_va_test.cpp | 169 ++++++++++++++++++++++++-- runtime/test/glsl/cs_user_data.comp | 7 ++ runtime/test/title_va_alias_test.cpp | 13 ++ 7 files changed, 453 insertions(+), 44 deletions(-) diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 2d7d6de713..6e718cee72 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -199,6 +199,8 @@ class GraphicsCommandList final } const leonida::CommandList& commands() const { return list_; } + // The descriptor tables this recording binds (console VAs), for the scan before a submission. + const std::vector& tables() const { return tables_; } // The pipeline states and root signatures the recording names (it holds a reference to each until Reset). const std::vector& pinned() const { return held_; } UINT front_stencil_ref() const { return front_stencil_ref_; } @@ -235,6 +237,7 @@ class GraphicsCommandList final record_into(command_allocator); invalid_ = false; calls_.clear(); + tables_.clear(); release_held(); // what the old recording used: it was replayed at ExecuteCommandLists reset_state(state); // Reset returns every list state to its default if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) set_initial_pipeline(state); // reset_state holds it @@ -1168,10 +1171,13 @@ class GraphicsCommandList final return; const RootArgumentLayout::Parameter* p = parameter(state, index, type); if (!p) return; - // A root view inside a buffer the title placed at its own VA (device slot 133) gets the console VA of the - // buffer's GPU copy, so the shader's heap_base + VA reaches it (src/title_va_alias.h). Descriptor tables are - // the layer's own heaps: never translated. - if (type == rt::rootsig::ParamType::Descriptor) va = leonida::title_va_aliases().shader_va(va); + // A root view into the title's own memory (a slot-133 buffer, a constant ring) gets the console VA of a GPU + // copy of it, so the shader's heap_base + VA reaches it (src/title_va_alias.h). A descriptor table is in one + // of the layer's heaps: kept, and its buffer V#s are rewritten the same way before each submission. + if (type == rt::rootsig::ParamType::Descriptor) + va = leonida::title_va_aliases().resolve(va, kRootViewBytes, leonida::TitleVaAliases::root_view); + else if (va && (tables_.empty() || tables_.back() != va)) + tables_.push_back(va); const std::uint32_t first = first_dword(state, *p); write(state, first, std::uint32_t(va)); // In the compute layout a descriptor table is one dword, the 32-bit VA of its first descriptor (the heaps @@ -1196,6 +1202,9 @@ class GraphicsCommandList final std::uint32_t topology_ = 0; // D3D_PRIMITIVE_TOPOLOGY_UNDEFINED std::array vertex_buffers_{}; leonida::IndexBufferView index_{}; + std::vector tables_; // SetGraphicsRootDescriptorTable / SetComputeRootDescriptorTable VAs + // The span a root view may read: D3D12's largest constant buffer (4096 x 16 bytes). + static constexpr std::uint64_t kRootViewBytes = 65536; leonida::Viewport viewport_{}; leonida::Rect scissor_{}; std::array render_targets_{}; @@ -1310,13 +1319,16 @@ class GraphicsCommandList final void set_vertex_buffers(UINT start, UINT count, const D3D12_VERTEX_BUFFER_VIEW* views) { if (count) draw_views_stale_ = true; - for (UINT i = 0; i < count; ++i) + for (UINT i = 0; i < count; ++i) { + if (views) leonida::title_va_aliases().note(views[i].BufferLocation, leonida::TitleVaAliases::vertex_view); vertex_buffers_[start + i] = views ? leonida::VertexBufferView{views[i].BufferLocation, views[i].SizeInBytes, views[i].StrideInBytes} : leonida::VertexBufferView{}; + } } void set_index_buffer(const D3D12_INDEX_BUFFER_VIEW* view) { + if (view) leonida::title_va_aliases().note(view->BufferLocation, leonida::TitleVaAliases::index_view); index_ = view ? leonida::IndexBufferView{view->BufferLocation, view->SizeInBytes, u(view->Format)} : leonida::IndexBufferView{}; } @@ -1567,6 +1579,14 @@ class CommandQueue final recorded.push_back(&list->commands()); graphics.push_back(list); } + // Buffer V#s the title wrote into a bound table itself may name its own memory: rewritten to a GPU copy's + // console VA before the copies are refreshed for this submission (src/title_va_alias.h). + { + std::set scanned; + for (const GraphicsCommandList* list : graphics) + for (const std::uint64_t table : list->tables()) + if (scanned.insert(table).second) leonida::title_va_aliases().scan_table(table); + } last_result_ = queue_.execute(recorded, [&graphics] { return pin_lists(graphics); }); d3d12_trace::record(method, last_result_ == leonida::ReplayResult::success ? "ok" : "failed"); if (last_result_ != leonida::ReplayResult::success) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 2fb79e587b..fdf3cc2f0c 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -87,12 +87,13 @@ void log_once(const char* what, int value) { if (seen.insert({what, value}).second) std::fprintf(stderr, "[rt] d3d12: %s %d\n", what, value); } -// The base address a V# gets for a buffer address: inside a buffer the title placed at its own VA (device slot -// 133), the console VA of the buffer's GPU copy (src/title_va_alias.h, docs/d3d12_vulkan.md section 3.3); anything -// else unchanged. A V# keeps 48 address bits. An arena copy always fits; an imported buffer's address is its device +// The base address a V# gets for a buffer address: in the title's own memory (a slot-133 buffer, a constant ring), +// the console VA of a GPU copy of it (src/title_va_alias.h, docs/d3d12_vulkan.md section 3.3); anything else +// unchanged. A V# keeps 48 address bits. An arena copy always fits; an imported buffer's address is its device // address minus heap_base, which wraps when the driver put it below the arena: logged, and written as before. -std::uint64_t vsharp_address(std::uint64_t va) { - const std::uint64_t to = leonida::title_va_aliases().shader_va(va); +std::uint64_t vsharp_address(std::uint64_t va, std::uint64_t bytes, + leonida::TitleVaAliases::Kind kind = leonida::TitleVaAliases::created_view) { + const std::uint64_t to = leonida::title_va_aliases().resolve(va, bytes, kind); if (to != va && (to >> 48)) log_once("a V# names a title-placed buffer whose GPU copy lies below heap_base, out of a V#'s 48 bits; " "address bits 48-63:", @@ -745,6 +746,110 @@ struct DeviceState { } } + // Windows of the title's own memory in the GPU address arena (src/title_va_alias.h, docs/d3d12_vulkan.md + // section 3.3 "Title-chosen addresses"): a root view or buffer V# that names the title's memory outside any + // slot-133 buffer (a per-frame constant ring, #8862 section 3.5) gets a copy of the 64 KiB-aligned pages it + // covers, refreshed before every submission like a slot-133 shadow, and the address of that copy. Windows are + // kept until the device goes (the ring comes round to the same pages), up to LEONIDA_TITLE_WINDOWS_MB (64 MiB + // by default); past that, or with the arena full, the address is left as it was and counted. + struct TitleWindow { + std::uint64_t start; + std::uint64_t shader_va; + }; + static constexpr std::uint64_t kTitleWindowAlign = 65536; + static constexpr std::uint64_t kTitleWindowMax = 16ull << 20; // the most one address pulls in + std::mutex title_window_mutex; // taken before shadow_mutex, never under it + std::vector title_windows; + std::uint64_t title_window_bytes = 0; + std::uint64_t title_window_cap = 64ull << 20; + + // Called through title_va_aliases().resolve for an address with no copy yet. False: not the title's memory. + bool resolve_title_memory(std::uint64_t va, std::uint64_t bytes, std::uint64_t& out) { + out = va; + if (!arena.mapped || va < arena.size || !context) return false; + if (context->knows_buffer_va(va)) return false; // an upload or readback buffer's biased VA, say + MEMORY_BASIC_INFORMATION mbi{}; + if (!VirtualQuery(reinterpret_cast(static_cast(va)), &mbi, sizeof(mbi)) || + mbi.State != MEM_COMMIT || !mbi.Protect || (mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD))) + return false; + auto& aliases = leonida::title_va_aliases(); + std::lock_guard lock(title_window_mutex); + if (const std::uint64_t made = aliases.shader_va(va); made != va) { // another thread made it meanwhile + out = made; + return true; + } + std::uint64_t lo = 0, hi = UINT64_MAX; + aliases.gap(va, lo, hi); // never over a slot-133 buffer's range or another window + const std::uint64_t want = std::clamp(bytes, 1, kTitleWindowMax); + const std::uint64_t start = std::max(va & ~(kTitleWindowAlign - 1), lo); + std::uint64_t end = va > UINT64_MAX - want - kTitleWindowAlign ? UINT64_MAX + : (va + want + kTitleWindowAlign - 1) & + ~(kTitleWindowAlign - 1); + end = std::min(end, hi); + if (end <= va) return true; + const std::uint64_t size = end - start; + if (title_window_bytes + size > title_window_cap) { + log_once("title memory named by a shader address is past LEONIDA_TITLE_WINDOWS_MB, left untranslated; " + "MiB copied so far:", + int(title_window_bytes >> 20)); + return true; + } + VkDeviceSize offset = 0; + if (!arena_allocate(size, kTitleWindowAlign, offset, arena_buffer)) { + log_once("GPU address arena full (raise LEONIDA_ARENA_MB): title memory left untranslated; window KiB:", + int(std::min(size >> 10, INT_MAX))); + return true; + } + auto* mapped = arena.mapped + offset; + const auto* pages = reinterpret_cast(static_cast(start)); + copy_title_pages(mapped, pages, std::size_t(size)); + add_shadow({pages, mapped, std::size_t(size)}); + aliases.add(start, size, offset); + title_windows.push_back({start, offset}); + title_window_bytes += size; + if (title_windows.size() <= 4 || !(title_windows.size() & (title_windows.size() - 1))) + std::fprintf(stderr, "[rt] d3d12: a %llu KiB window of the title's memory, named by a shader address, is " + "copied into the GPU address arena before every submission (%zu windows, %llu KiB)\n", + static_cast(size >> 10), title_windows.size(), + static_cast(title_window_bytes >> 10)); + out = offset + (va - start); + return true; + } + + // The shader-visible CBV/SRV/UAV heaps (arena offset -> end), for the scan of bound tables before a submission. + std::mutex cbv_heap_mutex; + std::map cbv_heaps; + static constexpr VkDeviceSize kTableScanDescriptors = 1024; // per table and submission + + // The buffer V#s of the table at `table_va` whose base is in the title's own memory get the address of a copy, + // written in place: the title wrote them itself (or copied them), so no Create*View saw them. Images (T#s) and + // null slots are skipped; so is a V# already in the arena, so a rewritten one is left alone next time. + void scan_title_table(std::uint64_t table_va) { + VkDeviceSize end = 0; + { + std::lock_guard lock(cbv_heap_mutex); + auto it = cbv_heaps.upper_bound(table_va); + if (it == cbv_heaps.begin()) return; + --it; + if (table_va >= it->second) return; + end = std::min(it->second, table_va + kTableScanDescriptors * kDescriptorSize); + } + auto& aliases = leonida::title_va_aliases(); + for (VkDeviceSize at = table_va; at + 16 <= end; at += kDescriptorSize) { + auto* w = reinterpret_cast(arena.mapped + at); + const std::uint32_t w0 = w[0], w1 = w[1], w2 = w[2], w3 = w[3]; + if (!(w0 | w1 | w2 | w3) || (w3 >> 30)) continue; // null, or not a buffer V# (TYPE, dword 3 bits 30-31) + const std::uint64_t base = std::uint64_t(w0) | (std::uint64_t(w1 & 0xFFFFu) << 32); + if (base < arena.size) continue; + const std::uint32_t stride = (w1 >> 16) & 0x3FFFu; + const std::uint64_t to = + aliases.resolve(base, std::uint64_t(w2) * (stride ? stride : 1), leonida::TitleVaAliases::table_view); + if (to == base || (to >> 48)) continue; + w[0] = std::uint32_t(to); + w[1] = (w1 & 0xFFFF0000u) | std::uint32_t((to >> 32) & 0xFFFFu); + } + } + // WriteToSubresource/ReadFromSubresource without host image copy: one staging copy at a time, submitted to // the device's VkQueue and waited for. Created on first use. std::mutex staging_mutex; @@ -1767,6 +1872,10 @@ class DescriptorHeap final in_arena_ = true; cpu_ = device.arena.mapped + arena_offset_; std::memset(cpu_, 0, std::size_t(bytes)); + if (desc.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) { + std::lock_guard lock(device.cbv_heap_mutex); + device.cbv_heaps[arena_offset_] = arena_offset_ + bytes; + } } else { storage_.reset(new std::byte[std::size_t(bytes)]()); cpu_ = reinterpret_cast(storage_.get()); @@ -1774,6 +1883,10 @@ class DescriptorHeap final } ~DescriptorHeap() override { + if (in_arena_ && desc_.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) { + std::lock_guard lock(device_.cbv_heap_mutex); + device_.cbv_heaps.erase(arena_offset_); + } if (in_arena_) device_.arena_release(arena_offset_, VkDeviceSize(desc_.NumDescriptors) * kDescriptorSize, DeviceState::arena_descriptor_heap); } @@ -5200,6 +5313,14 @@ class Device final info.xdxr_acceleration_structures && info.buffer_device_address); state_.context->set_before_execute([this] { state_.refresh_shadows(); }); + if (const char* mb = std::getenv("LEONIDA_TITLE_WINDOWS_MB"); mb && *mb) + state_.title_window_cap = std::strtoull(mb, nullptr, 10) << 20; + leonida::title_va_aliases().set_hooks( + &state_, + [](void* device, std::uint64_t va, std::uint64_t bytes, std::uint64_t& out) { + return static_cast(device)->resolve_title_memory(va, bytes, out); + }, + [](void* device, std::uint64_t table) { static_cast(device)->scan_title_table(table); }); if (info.physical && state_.format_properties) { state_.context->set_color_attachment_format( [physical = info.physical, get_props = state_.format_properties](VkFormat format) { @@ -5544,6 +5665,13 @@ class Device final } ~Device() override { + leonida::title_va_aliases().clear_hooks(&state_); + { + std::lock_guard lock(state_.title_window_mutex); + for (const auto& window : state_.title_windows) + leonida::title_va_aliases().remove(window.start, window.shader_va); + state_.title_windows.clear(); + } if (state_.context) { { std::lock_guard lock(state_.context->submit_mutex()); @@ -6460,7 +6588,7 @@ class Device final buffer.num_records = desc->SizeInBytes; buffer.format = leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT); buffer.oob_select = leonida::gfx10::OobSelect::raw; - buffer.address = vsharp_address(buffer.address); + buffer.address = vsharp_address(buffer.address, desc->SizeInBytes); const leonida::gfx10::BufferWords words = leonida::gfx10::encode(buffer); std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); } @@ -6552,7 +6680,8 @@ class Device final } buffer.oob_select = leonida::gfx10::OobSelect::structured; } - buffer.address = vsharp_address(buffer.address); + buffer.address = vsharp_address( + buffer.address, std::uint64_t(buffer.num_records) * (buffer.stride ? buffer.stride : 1)); const leonida::gfx10::BufferWords words = leonida::gfx10::encode(buffer); std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); return; @@ -6710,12 +6839,13 @@ class Device final buffer.swizzle = channels; buffer.oob_select = typed ? g::OobSelect::structured : structured ? g::OobSelect::structured_with_offset : g::OobSelect::raw; - buffer.address = vsharp_address(buffer.address); + buffer.address = vsharp_address(buffer.address, + std::uint64_t(buffer.num_records) * (buffer.stride ? buffer.stride : 1)); const g::BufferWords words = g::encode(buffer); std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); if (counter) { g::Buffer counter_buffer{}; - counter_buffer.address = vsharp_address(counter_va + view.CounterOffsetInBytes); + counter_buffer.address = vsharp_address(counter_va + view.CounterOffsetInBytes, 4); counter_buffer.num_records = 4; counter_buffer.oob_select = g::OobSelect::raw; const g::BufferWords counter_words = g::encode(counter_buffer); diff --git a/runtime/src/title_va_alias.h b/runtime/src/title_va_alias.h index 66739f7c13..6f665f0ec2 100644 --- a/runtime/src/title_va_alias.h +++ b/runtime/src/title_va_alias.h @@ -1,19 +1,22 @@ #pragma once -// Title-chosen buffer VAs (Xbox device slot 133) and the console VA a translated shader reaches them by -// (docs/d3d12_vulkan.md section 3.3, "Title-placed buffers"). +// Buffer addresses in the title's own memory and the console VA a translated shader reaches them by +// (docs/d3d12_vulkan.md section 3.3, "Title-chosen addresses"). // // A translated shader computes heap_base + console_va, with heap_base the GPU address arena's device address. The -// layer chooses every console VA it hands out, so they all land in the arena, but slot 133 places a buffer at a VA -// the title chose: the CPU address of its own pages (about 1.5 TiB on Windows), far past the arena. A shader that -// adds heap_base to that VA reads nothing the layer made. So where the layer itself writes an address a shader will -// dereference (a root CBV/SRV/UAV, and the V# of a CBV or a buffer SRV/UAV), an address inside a title-placed -// buffer is replaced by the console VA of the buffer's GPU copy: its arena offset when the copy is an arena range -// (the slot-133 shadow), or its device address minus heap_base (mod 2^64) when it has its own memory (an imported -// buffer). Everything else is passed through unchanged. Addresses the title writes into memory itself (a V# it -// builds in its own constant data) are not seen by the layer and keep the title's VA. +// layer chooses every console VA it hands out, so they all land in the arena. The title does not always use them: +// - device slot 133 places a buffer at the CPU address of the title's own pages (about 1.5 TiB on Windows); +// - the title points V#s and root views at its own memory (a per-frame constant ring, #8862 section 3.5). +// Both are far past the arena, so heap_base + VA reads nothing the layer made. An address inside such a range is +// therefore replaced, wherever the layer can see it, by the console VA of a GPU copy of that range: its arena offset +// when the copy is an arena range (a slot-133 shadow, or a window of the title's pages copied before every +// submission), or its device address minus heap_base (mod 2^64) when it has its own memory (an imported slot-133 +// buffer). Addresses that are not in the title's memory are passed through unchanged. // -// The table is process-wide, like the title's address space: a title VA names one buffer at a time. It depends only -// on the standard library, so it is tested without a GPU (title_va_alias_test). +// The table is process-wide, like the title's address space. The device behind it registers two hooks: a resolver +// that makes a GPU copy for an address in the title's memory that has none yet, and a scanner that rewrites the +// buffer V#s of a bound descriptor table before a submission. Without hooks the table only translates what was +// added to it, so it is tested without a GPU (title_va_alias_test). +#include #include #include #include @@ -26,6 +29,16 @@ namespace leonida { class TitleVaAliases { public: + // Where the layer saw the address, for the counters. + enum Kind : unsigned { root_view, created_view, table_view, vertex_view, index_view, kind_count }; + static constexpr const char* kKindNames[kind_count] = {"root view", "created view", "table V#", "vertex view", + "index view"}; + + // An address in the title's memory: true, with `shader_va` what a shader must be given (the address itself when + // no copy could be made). False: not the title's memory (an arena VA, a buffer of the layer's). + using Resolver = bool (*)(void* context, std::uint64_t va, std::uint64_t bytes, std::uint64_t& shader_va); + using TableScanner = void (*)(void* context, std::uint64_t table_va); + // [title_va, title_va + bytes) is reached as [shader_va, shader_va + bytes). A range that overlaps a live one // replaces it (the title has placed a new buffer over pages it released). False for an empty or wrapping range. bool add(std::uint64_t title_va, std::uint64_t bytes, std::uint64_t shader_va) { @@ -37,7 +50,7 @@ class TitleVaAliases { return true; } - // Forgets the range that starts at title_va, if it still maps to shader_va (a newer buffer at the same VA keeps + // Forgets the range that starts at title_va, if it still maps to shader_va (a newer range at the same VA keeps // its own entry). void remove(std::uint64_t title_va, std::uint64_t shader_va) { std::unique_lock lock(mutex_); @@ -46,9 +59,10 @@ class TitleVaAliases { count_.store(ranges_.size(), std::memory_order_release); } - // The address a shader must be given for `va`: translated inside a title-placed buffer, unchanged elsewhere. + // The address a shader must be given for `va` from the ranges added so far: translated inside one, unchanged + // elsewhere. No copy is made here. std::uint64_t shader_va(std::uint64_t va) const { - if (!count_.load(std::memory_order_acquire)) return va; // the common case: no title-placed buffer + if (!count_.load(std::memory_order_acquire)) return va; // the common case: no title range at all std::shared_lock lock(mutex_); auto it = ranges_.upper_bound(va); if (it == ranges_.begin()) return va; @@ -57,12 +71,81 @@ class TitleVaAliases { return it->second.shader_va + (va - it->first); } + // The free span around `va` (not in any range): [lo, hi). A copy made for `va` must stay inside it, so it never + // replaces a range another buffer still uses. + void gap(std::uint64_t va, std::uint64_t& lo, std::uint64_t& hi) const { + std::shared_lock lock(mutex_); + lo = 0; + hi = UINT64_MAX; + auto it = ranges_.upper_bound(va); + if (it != ranges_.end()) hi = it->first; + if (it != ranges_.begin()) lo = std::prev(it)->second.end; + } + + // shader_va, and when `va` is in the title's memory with no copy yet, a copy made by the device's resolver. + // Counted by kind: translated, or in the title's memory and left as it was. + std::uint64_t resolve(std::uint64_t va, std::uint64_t bytes, Kind kind) { + if (!va) return va; + std::uint64_t to = shader_va(va); + if (to != va) { + translated_[kind].fetch_add(1, std::memory_order_relaxed); + return to; + } + Resolver resolver; + void* context; + { + std::lock_guard lock(hook_mutex_); + resolver = resolver_; + context = hook_context_; + } + if (!resolver || !resolver(context, va, bytes, to)) return va; + (to != va ? translated_ : untranslated_)[kind].fetch_add(1, std::memory_order_relaxed); + return to; + } + + // Counts an address that the layer resolves through its buffer index instead (vertex and index views): only + // whether it is in a title range. + void note(std::uint64_t va, Kind kind) { + if (va && shader_va(va) != va) untranslated_[kind].fetch_add(1, std::memory_order_relaxed); + } + + // Before a submission: the device rewrites the buffer V#s of the table at `table_va` (a console VA in one of its + // shader-visible CBV/SRV/UAV heaps). + void scan_table(std::uint64_t table_va) { + TableScanner scanner; + void* context; + { + std::lock_guard lock(hook_mutex_); + scanner = scanner_; + context = hook_context_; + } + if (scanner) scanner(context, table_va); + } + + // The first device to register keeps the hooks until it clears them. + void set_hooks(void* context, Resolver resolver, TableScanner scanner) { + std::lock_guard lock(hook_mutex_); + if (hook_context_) return; + hook_context_ = context; + resolver_ = resolver; + scanner_ = scanner; + } + void clear_hooks(void* context) { + std::lock_guard lock(hook_mutex_); + if (hook_context_ != context) return; + hook_context_ = nullptr; + resolver_ = nullptr; + scanner_ = nullptr; + } + std::size_t size() const { return count_.load(std::memory_order_acquire); } + std::uint64_t translated(Kind kind) const { return translated_[kind].load(std::memory_order_relaxed); } + std::uint64_t untranslated(Kind kind) const { return untranslated_[kind].load(std::memory_order_relaxed); } private: struct Range { std::uint64_t end; // exclusive - std::uint64_t shader_va; // what title_va becomes + std::uint64_t shader_va; // what the range's first byte becomes }; void erase_overlapping(std::uint64_t begin, std::uint64_t end) { @@ -77,10 +160,15 @@ class TitleVaAliases { mutable std::shared_mutex mutex_; std::map ranges_; // by title VA std::atomic count_{0}; + std::mutex hook_mutex_; + void* hook_context_ = nullptr; + Resolver resolver_ = nullptr; + TableScanner scanner_ = nullptr; + std::array, kind_count> translated_{}; + std::array, kind_count> untranslated_{}; }; -// The process's table: the slot-133 buffers add and remove their ranges, the command lists and descriptor writers -// read it. +// The process's table: the device's title ranges and hooks, read by the command lists and descriptor writers. inline TitleVaAliases& title_va_aliases() { static TitleVaAliases aliases; return aliases; diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 77e43b90cf..23226d558b 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -1124,6 +1124,12 @@ class VulkanContext { std::unique_lock lock(resource_mutex_); set_resource_locked(id, binding); } + // Whether `va` is in a buffer this context knows by VA (the index buffer_at searches). + bool knows_buffer_va(std::uint64_t va) { + std::shared_lock lock(resource_mutex_); + BufferVaIndex::Hit hit{}; + return buffer_vas_.find(va, hit); + } void add_resource(ResourceId id, const ResourceBinding& binding, VkImageLayout current_layout) { std::unique_lock rlock(resource_mutex_); set_resource_locked(id, binding); diff --git a/runtime/test/d3d12_title_va_test.cpp b/runtime/test/d3d12_title_va_test.cpp index 73447964b5..d971c716e3 100644 --- a/runtime/test/d3d12_title_va_test.cpp +++ b/runtime/test/d3d12_title_va_test.cpp @@ -9,15 +9,18 @@ // (imported with VK_EXT_external_memory_host where the driver takes them) and write-combined pages (refused by the // import, so a shadow copy in the arena, the retail case on an RTX 5070 Ti). The data is written after the buffer // exists, so the shadow's copy before the submission is what the GPU reads. -// Negative controls: a second title buffer with other data must not be what the first one's V# reads; an address -// one byte past the title range, an arena buffer's VA, and the title's VA after the buffer is released are written -// to a V# unchanged. The shader is test/glsl/cs_user_data.comp. No game data. LEONIDA_VK_VALIDATION=1 for the +// Then the title's own memory outside any slot-133 buffer (a constant ring, #8862 section 3.5): a V# the CPU writes +// into a bound table itself, a created CBV and a root view. +// Negative controls: a second title buffer with other data must not be what the first one's V# reads; an arena +// buffer's V# keeps its VA; the title's range is forgotten when the buffer is released; a raw arena V# and a +// T#-shaped slot in a scanned table keep their bytes; a reserved, uncommitted address is left alone. The shader is test/glsl/cs_user_data.comp. No game data. LEONIDA_VK_VALIDATION=1 for the // Khronos validation layer. #include "shader_fixture_path.h" #include "test_temp_dir.h" #include "vk_test_device.h" #include "../shims/d3d12_com.h" #include "../shims/d3d12_xs_device.h" +#include "../src/gfx10_descriptors.h" #include "../src/shader_library.h" #include "../src/title_va_alias.h" @@ -201,11 +204,6 @@ int check_kind(Context& c, const char* kind, DWORD protect, int& checks) { c.device->CreateShaderResourceView(title.p, &srv, D3D12_CPU_DESCRIPTOR_HANDLE{cpu}); c.device->CreateShaderResourceView(other.p, &srv, D3D12_CPU_DESCRIPTOR_HANDLE{cpu + inc}); EXPECT(vsharp_base(cpu) == ((shader_va + kSrvWord * 4) & 0xFFFFFFFFFFFFull)); - // Negative controls, descriptor level: one byte past the title range is not translated. - const D3D12_CONSTANT_BUFFER_VIEW_DESC past{title_va + kPages, 256}; - c.device->CreateConstantBufferView(&past, D3D12_CPU_DESCRIPTOR_HANDLE{cpu + 2 * inc}); - EXPECT(vsharp_base(cpu + 2 * inc) == ((title_va + kPages) & 0xFFFFFFFFFFFFull)); - ++checks; // An arena buffer for the V# read's result, a READBACK buffer for both results. const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}, readback_heap{D3D12_HEAP_TYPE_READBACK}; @@ -286,11 +284,8 @@ int check_kind(Context& c, const char* kind, DWORD protect, int& checks) { } EXPECT(root_ok == kElements); - // After release, the title's VA is no longer translated: a new view of it names the title's VA itself. + // After release, the buffer's range is gone from the table: its old copy is not named any more. title.reset(); - const D3D12_CONSTANT_BUFFER_VIEW_DESC released{title_va, 256}; - c.device->CreateConstantBufferView(&released, D3D12_CPU_DESCRIPTOR_HANDLE{cpu + 4 * inc}); - EXPECT(vsharp_base(cpu + 4 * inc) == (title_va & 0xFFFFFFFFFFFFull)); EXPECT(leonida::title_va_aliases().shader_va(title_va) == title_va); checks += 2; other.reset(); @@ -300,6 +295,155 @@ int check_kind(Context& c, const char* kind, DWORD protect, int& checks) { return 0; } +// The title's own memory outside any slot-133 buffer: a VirtualAlloc range standing for its per-frame constant ring +// (#8862 section 3.5). Three ways a shader is given an address in it, each read back through an arena buffer: +// - a buffer V# the CPU writes into a shader-visible heap itself, as the title does (rewritten before the submission); +// - a V# made by CreateConstantBufferView (translated when written); +// - a root view (translated when set). +// Negative controls: a raw V# whose base is an arena buffer and a T#-shaped slot whose base is the ring keep their +// bytes; an address the ring does not hold is left alone. +int check_title_memory(Context& c, int& checks) { + constexpr UINT64 ring_bytes = 256 * 1024; + auto* ring = static_cast(VirtualAlloc(nullptr, ring_bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + EXPECT(ring); + const auto ring_va = reinterpret_cast(ring); + EXPECT(ring_va >= c.arena); + auto& aliases = leonida::title_va_aliases(); + const std::uint64_t table_before = aliases.translated(leonida::TitleVaAliases::table_view); + const std::uint64_t created_before = aliases.translated(leonida::TitleVaAliases::created_view); + const std::uint64_t root_before = aliases.translated(leonida::TitleVaAliases::root_view); + + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}, readback_heap{D3D12_HEAP_TYPE_READBACK}; + const auto uav = buffer_desc(kBytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + Ref out[3], readback; + for (auto& o : out) + EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &uav, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, + IID_PPV_ARGS(&o.p)))); + const auto readback_desc = buffer_desc(3 * kBytes); + EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 8, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + Ref heap; + EXPECT(SUCCEEDED(c.device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p)))); + const std::uint64_t cpu = reinterpret_cast(slot(heap.p, 9))(heap.p); + const std::uint64_t gpu = reinterpret_cast(slot(heap.p, 10))(heap.p); + const UINT inc = c.device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + const auto raw_vsharp = [](std::uint64_t address) { + leonida::gfx10::Buffer b{}; + b.address = address; + b.num_records = kBytes; + b.format = leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT); + b.oob_select = leonida::gfx10::OobSelect::raw; + return leonida::gfx10::encode(b); + }; + // Slot 0: a V# the CPU writes itself, its base in the ring. Slot 1: CreateConstantBufferView of the ring. + // Slot 2: a raw 64-bit VA (out[2]) for the root-view mode. Slots 3 and 4: the negative controls. + const auto v0 = raw_vsharp(ring_va + 0x1000); + std::memcpy(reinterpret_cast(cpu), v0.data(), sizeof(v0)); + const D3D12_CONSTANT_BUFFER_VIEW_DESC cbv{ring_va + 0x2000, 256}; + c.device->CreateConstantBufferView(&cbv, D3D12_CPU_DESCRIPTOR_HANDLE{cpu + inc}); + EXPECT(vsharp_base(cpu + inc) < c.arena); // translated when written + const std::uint64_t out2 = out[2]->GetGPUVirtualAddress(); + std::memcpy(reinterpret_cast(cpu + 2 * inc), &out2, sizeof(out2)); + const auto arena_vsharp = raw_vsharp(out[0]->GetGPUVirtualAddress()); + std::memcpy(reinterpret_cast(cpu + 3 * inc), arena_vsharp.data(), sizeof(arena_vsharp)); + auto image_like = raw_vsharp(ring_va + 0x4000); + image_like[3] |= 0x8u << 28; // TYPE: an image + std::memcpy(reinterpret_cast(cpu + 4 * inc), image_like.data(), sizeof(image_like)); + std::uint8_t before3[32], before4[32]; + std::memcpy(before3, reinterpret_cast(cpu + 3 * inc), 32); + std::memcpy(before4, reinterpret_cast(cpu + 4 * inc), 32); + + // The ring's data, written before the submission (after the descriptors, as a title fills its ring per frame). + for (UINT i = 0; i < ring_bytes / 4; ++i) ring[i] = 0xC0000000u + i * 7u; + + Ref allocator; + Ref list; + EXPECT(SUCCEEDED(c.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(c.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, c.pso, + IID_PPV_ARGS(&list.p)))); + ID3D12DescriptorHeap* heaps[] = {heap.p}; + list->SetDescriptorHeaps(1, heaps); + list->SetComputeRootSignature(c.root); + // The CPU-written V# (buffer SRV mode). + list->SetComputeRoot32BitConstant(0, 0, 0); + list->SetComputeRoot32BitConstant(0, 0xFFFFFFFFu, 1); + list->SetComputeRootUnorderedAccessView(1, out[0]->GetGPUVirtualAddress()); + list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{gpu}); + list->Dispatch(1, 1, 1); + // The created CBV (CBV mode). + list->SetComputeRoot32BitConstant(0, 0, 1); + list->SetComputeRootUnorderedAccessView(1, out[1]->GetGPUVirtualAddress()); + list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{gpu + inc}); + list->Dispatch(1, 1, 1); + // A root view into the ring, read 256 bytes past its base, written through slot 2's raw VA. + list->SetComputeRoot32BitConstant(0, kRootAdd, 0); + list->SetComputeRoot32BitConstant(0, 0xFFFFFFFDu, 1); + list->SetComputeRootUnorderedAccessView(1, ring_va + 0x3000); + list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{gpu + 2 * inc}); + list->Dispatch(1, 1, 1); + // The negative-control slots are bound too, so the scan reads them. + list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{gpu + 3 * inc}); + list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{gpu + 4 * inc}); + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + list->ResourceBarrier(1, &barrier); + for (UINT k = 0; k < 3; ++k) { + D3D12_RESOURCE_BARRIER to_copy{}; + to_copy.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + to_copy.Transition.pResource = out[k].p; + to_copy.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + to_copy.Transition.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + to_copy.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; + list->ResourceBarrier(1, &to_copy); + list->CopyBufferRegion(readback.p, k * kBytes, out[k].p, 0, kBytes); + } + EXPECT(list->Close() == S_OK); + ID3D12CommandList* lists[] = {list.p}; + c.queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(c.queue) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(c.queue->Signal(c.fence, ++c.fence_value))); + EXPECT(SUCCEEDED(c.fence->SetEventOnCompletion(c.fence_value, nullptr))); + + void* mapped = nullptr; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); + const auto* got = static_cast(mapped); + UINT raw_ok = 0, cbv_ok = 0, root_ok = 0; + for (UINT i = 0; i < kElements; ++i) { + if (got[i] == ring[0x1000 / 4 + i]) ++raw_ok; + if (got[kElements + i] == ring[0x2000 / 4 + i]) ++cbv_ok; + if (got[2 * kElements + i] == ring[0x3000 / 4 + 64 + i] + kRootAdd) ++root_ok; + } + readback->Unmap(0, nullptr); + const bool rewritten = vsharp_base(cpu) < c.arena; + const bool arena_kept = !std::memcmp(before3, reinterpret_cast(cpu + 3 * inc), 32); + const bool image_kept = !std::memcmp(before4, reinterpret_cast(cpu + 4 * inc), 32); + std::printf("title memory (a constant ring): CPU-written table V# %u/%u (rewritten before the submission: %s), " + "created CBV %u/%u, root view %u/%u; negative controls: arena V# kept %s, T#-shaped slot kept %s; " + "translated: %llu table V#, %llu created, %llu root\n", + raw_ok, kElements, rewritten ? "yes" : "no", cbv_ok, kElements, root_ok, kElements, + arena_kept ? "yes" : "no", image_kept ? "yes" : "no", + static_cast(aliases.translated(leonida::TitleVaAliases::table_view) - table_before), + static_cast(aliases.translated(leonida::TitleVaAliases::created_view) - + created_before), + static_cast(aliases.translated(leonida::TitleVaAliases::root_view) - root_before)); + EXPECT(raw_ok == kElements && cbv_ok == kElements && root_ok == kElements); + EXPECT(rewritten && arena_kept && image_kept); + // An address in no committed page is not title memory: left alone, nothing made for it. + void* gone = VirtualAlloc(nullptr, 65536, MEM_RESERVE, PAGE_READWRITE); + const auto gone_va = reinterpret_cast(gone); + const D3D12_CONSTANT_BUFFER_VIEW_DESC reserved_only{gone_va, 256}; + c.device->CreateConstantBufferView(&reserved_only, D3D12_CPU_DESCRIPTOR_HANDLE{cpu + 5 * inc}); + EXPECT(vsharp_base(cpu + 5 * inc) == (gone_va & 0xFFFFFFFFFFFFull)); + VirtualFree(gone, 0, MEM_RELEASE); + checks += 3; + return 0; +} + } // namespace int main() { @@ -386,6 +530,7 @@ int main() { EXPECT(c.arena > 0); if (check_kind(c, "read-write", PAGE_READWRITE, checks)) return 1; if (check_kind(c, "write-combined", PAGE_READWRITE | PAGE_WRITECOMBINE, checks)) return 1; + if (check_title_memory(c, checks)) return 1; } if (d.validation_errors()) { std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); diff --git a/runtime/test/glsl/cs_user_data.comp b/runtime/test/glsl/cs_user_data.comp index 4e1dfc904e..b8f2c12b90 100644 --- a/runtime/test/glsl/cs_user_data.comp +++ b/runtime/test/glsl/cs_user_data.comp @@ -45,6 +45,13 @@ void main() { return; } Words table = at(uvec2(pc.s[8], 0u)); + if (pc.s[5] == 0xFFFFFFFDu) { + // Root view read to a table pointer (d3d12_title_va_test): read through the root view, 256 bytes past its + // base, and write where the table entry's raw 64-bit VA points. + Words out = at(uvec2(table.w[0], table.w[1])); + out.w[i] = result.w[64u + i] + pc.s[4]; + return; + } if (pc.s[5] == 0u) { // CBV V# mode: table holds a 16-byte GFX10 raw buffer descriptor written by CreateConstantBufferView. const uint num_records = table.w[2]; diff --git a/runtime/test/title_va_alias_test.cpp b/runtime/test/title_va_alias_test.cpp index 7a4a38b9a8..e27faa8f60 100644 --- a/runtime/test/title_va_alias_test.cpp +++ b/runtime/test/title_va_alias_test.cpp @@ -27,6 +27,19 @@ int main() { EXPECT(a.shader_va(title - 1) == title - 1); EXPECT(a.shader_va(title + size) == title + size); EXPECT(a.shader_va(arena) == arena); + // The free span around an address: between the ranges, so a window made for it never covers one. + std::uint64_t lo = 1, hi = 1; + a.gap(title + size + 5, lo, hi); + EXPECT(lo == title + size && hi == UINT64_MAX); + a.gap(title - 5, lo, hi); + EXPECT(lo == 0 && hi == title); + // Without a device's resolver, resolve only translates what was added, and counts it. + EXPECT(a.resolve(title + 4, 4, leonida::TitleVaAliases::root_view) == arena + 4); + EXPECT(a.resolve(title - 4, 4, leonida::TitleVaAliases::root_view) == title - 4); + EXPECT(a.translated(leonida::TitleVaAliases::root_view) == 1); + a.note(title + 8, leonida::TitleVaAliases::vertex_view); + a.note(title - 8, leonida::TitleVaAliases::vertex_view); + EXPECT(a.untranslated(leonida::TitleVaAliases::vertex_view) == 1); // A wrapping target (an import below heap_base) is kept as is: modular arithmetic. constexpr std::uint64_t below = 0xFFFFFFFFFFF00000ull; EXPECT(a.add(title + 0x100000, size, below) && a.shader_va(title + 0x100010) == below + 0x10); From d2f328e560dcbbdbc0e34f5d26f5855c5ffd8209 Mon Sep 17 00:00:00 2001 From: Etr0p <216035314+Etr0p@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:51:08 +0100 Subject: [PATCH 016/110] d3d12: only the title's memory gets a copy; the table scan covers the declared slots and is timed The xmem shims record what they hand the title (XMemAlloc, XMemAllocDefault, XMemVirtualAlloc, the title's VirtualAlloc); an address outside those ranges is left as it was and counted. The submit-time scan reads only the CBV/SRV/UAV slots the bound table's root signature declares, and its cost is accumulated per ExecuteCommandLists. Section 3.3 describes the three places addresses are replaced and the two kinds of copy. Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 56 ++++++++++++++++---------- runtime/shims/d3d12_com.cpp | 24 +++++++---- runtime/shims/d3d12_com.h | 3 ++ runtime/shims/d3d12_vulkan_device.cpp | 39 +++++++++++++++--- runtime/shims/xmem.cpp | 36 ++++++++++++++--- runtime/src/title_va_alias.h | 58 ++++++++++++++++++++++++--- runtime/test/d3d12_title_va_test.cpp | 25 ++++++++---- runtime/test/title_va_alias_test.cpp | 8 ++++ 8 files changed, 198 insertions(+), 51 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 272bc68579..f108cc37d3 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1496,27 +1496,41 @@ Arena VAs (at most 4095 MiB, so 32-bit) pass. A VA biased from outside the arena VAs above are at or above 2^40 as unsigned values. That is one more reason for the rule above that every buffer a console client can address is an arena range, whichever heap it comes from. -**Title-placed buffers (device slot 133).** Here the title, not the layer, chooses the VA: `CreatePlacedResourceX` -puts a buffer at the CPU address of the title's own pages. On Windows that is a user-mode address around 1.5 TiB, -far past the arena (at most 4095 MiB, and descriptor tables must stay below 4 GiB), so `heap_base + title_va` -names nothing the layer made. The layer therefore translates the title's VA where it -writes an address itself: root CBV/SRV/UAV arguments (`SetGraphicsRoot*View`, `SetComputeRoot*View`) and the base -of the V# it writes for a CBV or a buffer SRV/UAV (counter included). An address inside a title-placed buffer -becomes the console VA of that buffer's GPU copy (`runtime/src/title_va_alias.h`); every other address is left -alone, and the range is forgotten when the buffer is released. -- When the pages can't be imported (write-combined or uncommitted pages, a missing extension, an import budget), - the copy is the per-submission shadow, and the shadow is an **arena range** when it fits. Its console VA is the - arena offset: below 4 GiB, so it holds in a root argument, in a V#'s 48 bits and in a 32-bit table pointer alike. - When the arena has no room, the shadow keeps its own memory and is biased like an upload buffer (logged once; - raise `LEONIDA_ARENA_MB`). -- When the pages are imported (`VK_EXT_external_memory_host`), the copy is the import and its console VA is its - device address minus `heap_base` (mod 2^64): exact for 64-bit root arguments, and for a V# only when the driver - put the import above the arena (otherwise logged once, as measured for upload buffers above). -- The title's own VA is still what `GetGPUVirtualAddress` answers and what vertex, index, copy and immediate-write - calls resolve through the buffer VA index, so nothing the title reads back changes. -- **Not covered:** a pointer or V# the title writes into memory itself (inside its constant data, say). The layer - never sees it, so it keeps the title's VA. Covering it needs the title's pages inside the GPU address space - (one of the options in #7218's design note) or the translator rewriting addresses. +**Title-chosen addresses.** Two kinds of buffer address are the title's choice, not the layer's: +- device slot 133 (`CreatePlacedResourceX`) puts a buffer at the CPU address of the title's own pages; +- the title points root views and V#s at its own memory, for instance a per-frame constant ring (#8862, section + 3.5 of `docs/retail_boot_chain.md`). + +On Windows these are user-mode addresses around 1.5 TiB, far past the arena (at most 4095 MiB, and descriptor +tables must stay below 4 GiB), so `heap_base + VA` names nothing the layer made (the D3D-53 failure above). The layer +therefore replaces such an address, wherever it sees one, by the console VA of a GPU copy of that memory +(`runtime/src/title_va_alias.h`): + +| Where the address is | When it is replaced | +|---|---| +| Root CBV/SRV/UAV (`Set*Root*View`) | when the argument is set | +| CBV and buffer SRV/UAV V#s the layer writes (`Create*View`, slot 70, counter V#s included) | when the descriptor is written | +| Buffer V#s the title writes into a shader-visible CBV/SRV/UAV heap itself | before each `ExecuteCommandLists`, in place, for the tables the submitted lists bind and only the slots their root signatures declare | + +The copies: +- A **slot-133 buffer** whose pages cannot be imported is the per-submission shadow, and the shadow is an **arena + range** when it fits. Its console VA is its arena offset, which holds in a root argument, in a V#'s 48 bits and in + a 32-bit table pointer alike. Without room in the arena it keeps its own memory and is biased like an upload buffer + (logged once; raise `LEONIDA_ARENA_MB`). An **imported** slot-133 buffer is reached at its device address minus + `heap_base` (mod 2^64): exact for root arguments, and for a V# only when the driver put the import above the arena + (logged once otherwise). +- Any **other address in the title's memory** gets a window: the 64 KiB-aligned pages it covers, clipped to the + title's range, copied into the arena now and before every submission, through the same shadow refresh as slot 133 + (so dirty-page tracking for that refresh applies to both). Windows stay until the device goes, up to + `LEONIDA_TITLE_WINDOWS_MB` (64 MiB by default). +- **Only the title's memory** gets a copy: the blocks and ranges the xmem shims hand the title (`XMemAlloc`, + `XMemAllocDefault`, `XMemVirtualAlloc`, the title's `VirtualAlloc`). An address anywhere else, the runtime's or a + host DLL's memory included, is left as it was and counted, as is an arena VA or a buffer the layer made. + +The title's own VA is still what `GetGPUVirtualAddress` answers, and vertex, index, copy and immediate-write calls +still resolve it through the buffer VA index, which knows slot-133 buffers by that VA. The copies are one way: what +the GPU writes into a copy does not reach the title's pages. A pointer the title hides elsewhere (a raw VA inside its +constant data that a shader dereferences) is not seen by the layer and keeps the title's VA. Why not give each buffer its own BDA and set `heap_base = 0`? Because 25,865 of the 26,503 shaders (97.6%) truncate descriptor-table pointers to 32 bits, and host BDAs are not guaranteed to be below 4 GB. The arena keeps console VAs low and stable. diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 6e718cee72..1ad12e432f 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -12,8 +12,10 @@ #include #include #include +#include #include #include +#include #include #include #include @@ -200,7 +202,7 @@ class GraphicsCommandList final const leonida::CommandList& commands() const { return list_; } // The descriptor tables this recording binds (console VAs), for the scan before a submission. - const std::vector& tables() const { return tables_; } + const std::vector>& tables() const { return tables_; } // The pipeline states and root signatures the recording names (it holds a reference to each until Reset). const std::vector& pinned() const { return held_; } UINT front_stencil_ref() const { return front_stencil_ref_; } @@ -1176,8 +1178,8 @@ class GraphicsCommandList final // of the layer's heaps: kept, and its buffer V#s are rewritten the same way before each submission. if (type == rt::rootsig::ParamType::Descriptor) va = leonida::title_va_aliases().resolve(va, kRootViewBytes, leonida::TitleVaAliases::root_view); - else if (va && (tables_.empty() || tables_.back() != va)) - tables_.push_back(va); + else if (va && p->table_descriptors && (tables_.empty() || tables_.back().first != va)) + tables_.push_back({va, p->table_descriptors}); const std::uint32_t first = first_dword(state, *p); write(state, first, std::uint32_t(va)); // In the compute layout a descriptor table is one dword, the 32-bit VA of its first descriptor (the heaps @@ -1202,7 +1204,8 @@ class GraphicsCommandList final std::uint32_t topology_ = 0; // D3D_PRIMITIVE_TOPOLOGY_UNDEFINED std::array vertex_buffers_{}; leonida::IndexBufferView index_{}; - std::vector tables_; // SetGraphicsRootDescriptorTable / SetComputeRootDescriptorTable VAs + // SetGraphicsRootDescriptorTable / SetComputeRootDescriptorTable: VA, CBV/SRV/UAV slots the signature declares + std::vector> tables_; // The span a root view may read: D3D12's largest constant buffer (4096 x 16 bytes). static constexpr std::uint64_t kRootViewBytes = 65536; leonida::Viewport viewport_{}; @@ -1582,10 +1585,17 @@ class CommandQueue final // Buffer V#s the title wrote into a bound table itself may name its own memory: rewritten to a GPU copy's // console VA before the copies are refreshed for this submission (src/title_va_alias.h). { - std::set scanned; + std::map tables; // each table once, with the most slots it was bound with for (const GraphicsCommandList* list : graphics) - for (const std::uint64_t table : list->tables()) - if (scanned.insert(table).second) leonida::title_va_aliases().scan_table(table); + for (const auto& [table, descriptors] : list->tables()) + tables[table] = std::max(tables[table], descriptors); + if (!tables.empty()) { + const auto start = std::chrono::steady_clock::now(); + for (const auto& [table, descriptors] : tables) leonida::title_va_aliases().scan_table(table, descriptors); + leonida::title_va_aliases().note_scan(std::uint64_t( + std::chrono::duration_cast(std::chrono::steady_clock::now() - start) + .count())); + } } last_result_ = queue_.execute(recorded, [&graphics] { return pin_lists(graphics); }); d3d12_trace::record(method, last_result_ == leonida::ReplayResult::success ? "ok" : "failed"); diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 14ead7b24f..d975b800a0 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -374,6 +374,9 @@ struct RootArgumentLayout { std::uint32_t user_offset; // graphics: first dword; unused for a parameter with no dwords std::uint32_t constant_count; // constants only std::uint32_t compute_offset = rt::rootsig::kNoSgpr; // compute: first user SGPR + // A table: the CBV/SRV/UAV slots its ranges declare (an unbounded range counts as 1024), for the scan of + // title-written V#s before a submission (src/title_va_alias.h). 0: a sampler table, or not a table. + std::uint32_t table_descriptors = 0; }; std::vector parameters; std::uint32_t flags = 0; // D3D12_ROOT_SIGNATURE_FLAGS from the serialized blob diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index fdf3cc2f0c..e431cf8cf2 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -101,6 +101,22 @@ std::uint64_t vsharp_address(std::uint64_t va, std::uint64_t bytes, return to; } +// The CBV/SRV/UAV slots a descriptor table declares: the end of its furthest range (D3D12 appends a range at +// D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND), an unbounded range counted as 1024. 0 for a sampler table or no table. +std::uint32_t table_view_descriptors(const rt::rootsig::RootParameter& param) { + if (param.type != rt::rootsig::ParamType::Table) return 0; + constexpr std::uint32_t kUnbounded = 1024; + std::uint64_t next = 0, end = 0; + for (const auto& range : param.ranges) { + const std::uint64_t start = range.offset_in_table == D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND ? next + : range.offset_in_table; + const std::uint64_t count = range.num_descriptors == UINT_MAX ? kUnbounded : range.num_descriptors; + next = start + count; + if (range.range_type != D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER) end = std::max(end, next); + } + return std::uint32_t(std::min(end, kUnbounded)); +} + // memcpy that a page fault ends instead of killing the process: the title may decommit a page between the // VirtualQuery that saw it committed and the read. No C++ objects here: it is a __try frame. // `streaming` reads with MOVNTDQA, for write-combined pages: ordinary loads from them are not cached, and memcpy @@ -768,11 +784,15 @@ struct DeviceState { out = va; if (!arena.mapped || va < arena.size || !context) return false; if (context->knows_buffer_va(va)) return false; // an upload or readback buffer's biased VA, say + auto& aliases = leonida::title_va_aliases(); + // Only the title's own memory gets a copy (xmem's ranges): an address anywhere else, the runtime's or a host + // DLL's memory included, is left as it was and counted. + std::uint64_t title_lo = 0, title_hi = 0; + if (!aliases.title_memory(va, title_lo, title_hi)) return true; MEMORY_BASIC_INFORMATION mbi{}; if (!VirtualQuery(reinterpret_cast(static_cast(va)), &mbi, sizeof(mbi)) || mbi.State != MEM_COMMIT || !mbi.Protect || (mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD))) - return false; - auto& aliases = leonida::title_va_aliases(); + return true; std::lock_guard lock(title_window_mutex); if (const std::uint64_t made = aliases.shader_va(va); made != va) { // another thread made it meanwhile out = made; @@ -780,6 +800,8 @@ struct DeviceState { } std::uint64_t lo = 0, hi = UINT64_MAX; aliases.gap(va, lo, hi); // never over a slot-133 buffer's range or another window + lo = std::max(lo, title_lo); // nor past the title's range + hi = std::min(hi, title_hi); const std::uint64_t want = std::clamp(bytes, 1, kTitleWindowMax); const std::uint64_t start = std::max(va & ~(kTitleWindowAlign - 1), lo); std::uint64_t end = va > UINT64_MAX - want - kTitleWindowAlign ? UINT64_MAX @@ -824,7 +846,7 @@ struct DeviceState { // The buffer V#s of the table at `table_va` whose base is in the title's own memory get the address of a copy, // written in place: the title wrote them itself (or copied them), so no Create*View saw them. Images (T#s) and // null slots are skipped; so is a V# already in the arena, so a rewritten one is left alone next time. - void scan_title_table(std::uint64_t table_va) { + void scan_title_table(std::uint64_t table_va, std::uint32_t descriptors) { VkDeviceSize end = 0; { std::lock_guard lock(cbv_heap_mutex); @@ -832,7 +854,9 @@ struct DeviceState { if (it == cbv_heaps.begin()) return; --it; if (table_va >= it->second) return; - end = std::min(it->second, table_va + kTableScanDescriptors * kDescriptorSize); + end = std::min( + it->second, table_va + VkDeviceSize(std::min(descriptors, kTableScanDescriptors)) * + kDescriptorSize); } auto& aliases = leonida::title_va_aliases(); for (VkDeviceSize at = table_va; at + 16 <= end; at += kDescriptorSize) { @@ -5320,7 +5344,9 @@ class Device final [](void* device, std::uint64_t va, std::uint64_t bytes, std::uint64_t& out) { return static_cast(device)->resolve_title_memory(va, bytes, out); }, - [](void* device, std::uint64_t table) { static_cast(device)->scan_title_table(table); }); + [](void* device, std::uint64_t table, std::uint32_t descriptors) { + static_cast(device)->scan_title_table(table, descriptors); + }); if (info.physical && state_.format_properties) { state_.context->set_color_attachment_format( [physical = info.physical, get_props = state_.format_properties](VkFormat format) { @@ -6241,7 +6267,8 @@ class Device final break; } layout.parameters.push_back({parsed.sig.params[i].type, first, parsed.sig.params[i].num_values, - compute.ok ? compute.first_sgpr[i] : rt::rootsig::kNoSgpr}); + compute.ok ? compute.first_sgpr[i] : rt::rootsig::kNoSgpr, + table_view_descriptors(parsed.sig.params[i])}); } register_static_samplers(parsed.sig); auto* signature = new RootSignature( diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp index 37f29459f1..cccb4002fc 100644 --- a/runtime/shims/xmem.cpp +++ b/runtime/shims/xmem.cpp @@ -35,6 +35,7 @@ #include "shims.h" #include "startup_trace.h" +#include "../src/title_va_alias.h" namespace { @@ -66,14 +67,27 @@ void note_attributes(const char* api, uint64_t attributes, size_t size, const vo void* allocate_block(size_t size) { return _aligned_malloc(size ? size : 1, kAlign); } +// Every block and range the title gets here is recorded as the title's memory (src/title_va_alias.h): a shader +// address into it can be given a GPU copy, and an address anywhere else cannot. +void* title_block(size_t size) { + void* p = allocate_block(size); + leonida::title_va_aliases().add_title_memory(reinterpret_cast(p), size ? size : 1); + return p; +} + +void free_title_block(void* p) { + if (p) leonida::title_va_aliases().remove_title_memory(reinterpret_cast(p)); + _aligned_free(p); +} + void* __stdcall XMemAlloc(size_t size, uint64_t attributes) { note_attributes("XMemAlloc", attributes, size, _ReturnAddress()); - return allocate_block(size); + return title_block(size); } void __stdcall XMemFree(void* p, uint64_t attributes) { note_attributes("XMemFree", attributes, kNoSize, _ReturnAddress()); - _aligned_free(p); + free_title_block(p); } // XMemAllocDefault / XMemFreeDefault: the GDK's own allocator behind XMemAlloc and XMemFree, which a title that hooks @@ -82,12 +96,12 @@ void __stdcall XMemFree(void* p, uint64_t attributes) { // released by either free. void* __stdcall XMemAllocDefault(size_t size, uint64_t attributes) { note_attributes("XMemAllocDefault", attributes, size, _ReturnAddress()); - return allocate_block(size); + return title_block(size); } void __stdcall XMemFreeDefault(void* p, uint64_t attributes) { note_attributes("XMemFreeDefault", attributes, kNoSize, _ReturnAddress()); - _aligned_free(p); + free_title_block(p); } // BOOL XMemIsToolsMemAvailable(void). The measured title calls it from one helper, which six out-of-memory paths reach @@ -320,8 +334,18 @@ PVOID reserve_placeholder(void* address, SIZE_T size, SIZE_T alignment) { // XMemMapPhysicalPages. The guest page size sets the alignment and rounding of the region; the host's own pages stay // 4 KiB (host large pages need SeLockMemoryPrivilege). A 2 MiB region the host places is reserved 2 MiB-aligned through // VirtualAlloc2. +void* xmem_virtual_alloc(void* address, SIZE_T size, DWORD allocation_type, ULONGLONG attributes, DWORD protect); + void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type, ULONGLONG attributes, DWORD protect) { note_attributes("XMemVirtualAlloc", attributes, size, _ReturnAddress()); + void* result = xmem_virtual_alloc(address, size, allocation_type, attributes, protect); + // The title's memory (src/title_va_alias.h). Never forgotten: a released range is no longer committed, which + // the copy also checks. + if (result) leonida::title_va_aliases().add_title_memory(reinterpret_cast(result), size); + return result; +} + +void* xmem_virtual_alloc(void* address, SIZE_T size, DWORD allocation_type, ULONGLONG attributes, DWORD protect) { if (size == 0) { SetLastError(ERROR_INVALID_PARAMETER); return nullptr; @@ -689,7 +713,9 @@ constexpr DWORD kMemGraphics = 0x10000000; constexpr DWORD kMemTitle = 0x40000000; LPVOID WINAPI TitleVirtualAlloc(LPVOID address, SIZE_T size, DWORD allocation_type, DWORD protect) { - return VirtualAlloc(address, size, allocation_type & ~(kMemGraphics | kMemTitle), host_protect(protect)); + LPVOID result = VirtualAlloc(address, size, allocation_type & ~(kMemGraphics | kMemTitle), host_protect(protect)); + if (result) leonida::title_va_aliases().add_title_memory(reinterpret_cast(result), size); + return result; } } // namespace diff --git a/runtime/src/title_va_alias.h b/runtime/src/title_va_alias.h index 6f665f0ec2..1e907ea437 100644 --- a/runtime/src/title_va_alias.h +++ b/runtime/src/title_va_alias.h @@ -37,7 +37,7 @@ class TitleVaAliases { // An address in the title's memory: true, with `shader_va` what a shader must be given (the address itself when // no copy could be made). False: not the title's memory (an arena VA, a buffer of the layer's). using Resolver = bool (*)(void* context, std::uint64_t va, std::uint64_t bytes, std::uint64_t& shader_va); - using TableScanner = void (*)(void* context, std::uint64_t table_va); + using TableScanner = void (*)(void* context, std::uint64_t table_va, std::uint32_t descriptors); // [title_va, title_va + bytes) is reached as [shader_va, shader_va + bytes). A range that overlaps a live one // replaces it (the title has placed a new buffer over pages it released). False for an empty or wrapping range. @@ -109,9 +109,9 @@ class TitleVaAliases { if (va && shader_va(va) != va) untranslated_[kind].fetch_add(1, std::memory_order_relaxed); } - // Before a submission: the device rewrites the buffer V#s of the table at `table_va` (a console VA in one of its - // shader-visible CBV/SRV/UAV heaps). - void scan_table(std::uint64_t table_va) { + // Before a submission: the device rewrites the buffer V#s of the `descriptors` slots the root signature declares + // for the table at `table_va` (a console VA in one of its shader-visible CBV/SRV/UAV heaps). + void scan_table(std::uint64_t table_va, std::uint32_t descriptors) { TableScanner scanner; void* context; { @@ -119,7 +119,52 @@ class TitleVaAliases { scanner = scanner_; context = hook_context_; } - if (scanner) scanner(context, table_va); + if (scanner) scanner(context, table_va, descriptors); + } + + // The scan's cost, per ExecuteCommandLists that had tables to scan. + void note_scan(std::uint64_t nanoseconds) { + scans_.fetch_add(1, std::memory_order_relaxed); + scan_ns_.fetch_add(nanoseconds, std::memory_order_relaxed); + std::uint64_t seen = scan_max_ns_.load(std::memory_order_relaxed); + while (nanoseconds > seen && !scan_max_ns_.compare_exchange_weak(seen, nanoseconds)) { + } + } + std::uint64_t scans() const { return scans_.load(std::memory_order_relaxed); } + std::uint64_t scan_ns() const { return scan_ns_.load(std::memory_order_relaxed); } + std::uint64_t scan_max_ns() const { return scan_max_ns_.load(std::memory_order_relaxed); } + + // The title's own memory, as the xmem shims hand it out (XMemAlloc, XMemVirtualAlloc, the title's VirtualAlloc): + // only an address in one of these ranges gets a copy. A base anywhere else (the runtime's own heap, a host DLL) + // is left as it was and counted. + void add_title_memory(std::uint64_t base, std::uint64_t bytes) { + if (!base || !bytes || base > UINT64_MAX - bytes) return; + std::uint64_t begin = base, end = base + bytes; + std::unique_lock lock(memory_mutex_); + // A commit inside a reserved range, or two that overlap, are one range. + auto it = memory_.upper_bound(begin); + if (it != memory_.begin() && std::prev(it)->second > begin) --it; + while (it != memory_.end() && it->first < end) { + begin = std::min(begin, it->first); + end = std::max(end, it->second); + it = memory_.erase(it); + } + memory_[begin] = end; + } + void remove_title_memory(std::uint64_t base) { + std::unique_lock lock(memory_mutex_); + memory_.erase(base); + } + // The title range that holds `va`: [lo, hi). False when none does. + bool title_memory(std::uint64_t va, std::uint64_t& lo, std::uint64_t& hi) const { + std::shared_lock lock(memory_mutex_); + auto it = memory_.upper_bound(va); + if (it == memory_.begin()) return false; + --it; + if (va >= it->second) return false; + lo = it->first; + hi = it->second; + return true; } // The first device to register keeps the hooks until it clears them. @@ -166,6 +211,9 @@ class TitleVaAliases { TableScanner scanner_ = nullptr; std::array, kind_count> translated_{}; std::array, kind_count> untranslated_{}; + std::atomic scans_{0}, scan_ns_{0}, scan_max_ns_{0}; + mutable std::shared_mutex memory_mutex_; + std::map memory_; // the title's memory: base -> end }; // The process's table: the device's title ranges and hooks, read by the command lists and descriptor writers. diff --git a/runtime/test/d3d12_title_va_test.cpp b/runtime/test/d3d12_title_va_test.cpp index d971c716e3..7be1e880b4 100644 --- a/runtime/test/d3d12_title_va_test.cpp +++ b/runtime/test/d3d12_title_va_test.cpp @@ -301,7 +301,7 @@ int check_kind(Context& c, const char* kind, DWORD protect, int& checks) { // - a V# made by CreateConstantBufferView (translated when written); // - a root view (translated when set). // Negative controls: a raw V# whose base is an arena buffer and a T#-shaped slot whose base is the ring keep their -// bytes; an address the ring does not hold is left alone. +// bytes; committed memory that is not the title's, and a title range with no committed page, are left alone. int check_title_memory(Context& c, int& checks) { constexpr UINT64 ring_bytes = 256 * 1024; auto* ring = static_cast(VirtualAlloc(nullptr, ring_bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); @@ -309,6 +309,7 @@ int check_title_memory(Context& c, int& checks) { const auto ring_va = reinterpret_cast(ring); EXPECT(ring_va >= c.arena); auto& aliases = leonida::title_va_aliases(); + aliases.add_title_memory(ring_va, ring_bytes); // as the xmem shims record what they hand the title const std::uint64_t table_before = aliases.translated(leonida::TitleVaAliases::table_view); const std::uint64_t created_before = aliases.translated(leonida::TitleVaAliases::created_view); const std::uint64_t root_before = aliases.translated(leonida::TitleVaAliases::root_view); @@ -433,14 +434,24 @@ int check_title_memory(Context& c, int& checks) { static_cast(aliases.translated(leonida::TitleVaAliases::root_view) - root_before)); EXPECT(raw_ok == kElements && cbv_ok == kElements && root_ok == kElements); EXPECT(rewritten && arena_kept && image_kept); - // An address in no committed page is not title memory: left alone, nothing made for it. + // Left alone and counted: committed memory that is not the title's (the runtime's own, say), and a title range + // with no committed page. + const std::uint64_t untranslated_before = aliases.untranslated(leonida::TitleVaAliases::created_view); + void* host = VirtualAlloc(nullptr, 65536, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); void* gone = VirtualAlloc(nullptr, 65536, MEM_RESERVE, PAGE_READWRITE); - const auto gone_va = reinterpret_cast(gone); - const D3D12_CONSTANT_BUFFER_VIEW_DESC reserved_only{gone_va, 256}; - c.device->CreateConstantBufferView(&reserved_only, D3D12_CPU_DESCRIPTOR_HANDLE{cpu + 5 * inc}); - EXPECT(vsharp_base(cpu + 5 * inc) == (gone_va & 0xFFFFFFFFFFFFull)); + const auto host_va = reinterpret_cast(host), gone_va = reinterpret_cast(gone); + aliases.add_title_memory(gone_va, 65536); + const D3D12_CONSTANT_BUFFER_VIEW_DESC not_title{host_va, 256}, reserved_only{gone_va, 256}; + c.device->CreateConstantBufferView(¬_title, D3D12_CPU_DESCRIPTOR_HANDLE{cpu + 5 * inc}); + c.device->CreateConstantBufferView(&reserved_only, D3D12_CPU_DESCRIPTOR_HANDLE{cpu + 6 * inc}); + EXPECT(vsharp_base(cpu + 5 * inc) == (host_va & 0xFFFFFFFFFFFFull)); + EXPECT(vsharp_base(cpu + 6 * inc) == (gone_va & 0xFFFFFFFFFFFFull)); + EXPECT(aliases.untranslated(leonida::TitleVaAliases::created_view) - untranslated_before == 2); + aliases.remove_title_memory(gone_va); + aliases.remove_title_memory(ring_va); + VirtualFree(host, 0, MEM_RELEASE); VirtualFree(gone, 0, MEM_RELEASE); - checks += 3; + checks += 4; return 0; } diff --git a/runtime/test/title_va_alias_test.cpp b/runtime/test/title_va_alias_test.cpp index e27faa8f60..84758dbc97 100644 --- a/runtime/test/title_va_alias_test.cpp +++ b/runtime/test/title_va_alias_test.cpp @@ -40,6 +40,14 @@ int main() { a.note(title + 8, leonida::TitleVaAliases::vertex_view); a.note(title - 8, leonida::TitleVaAliases::vertex_view); EXPECT(a.untranslated(leonida::TitleVaAliases::vertex_view) == 1); + // The title's memory: a commit inside a reservation is one range; outside every range is not the title's. + std::uint64_t mlo = 0, mhi = 0; + a.add_title_memory(0x40000000, 0x100000); + a.add_title_memory(0x40010000, 0x1000); + EXPECT(a.title_memory(0x40080000, mlo, mhi) && mlo == 0x40000000 && mhi == 0x40100000); + EXPECT(!a.title_memory(0x40100000, mlo, mhi) && !a.title_memory(0x3FFFFFFF, mlo, mhi)); + a.remove_title_memory(0x40000000); + EXPECT(!a.title_memory(0x40080000, mlo, mhi)); // A wrapping target (an import below heap_base) is kept as is: modular arithmetic. constexpr std::uint64_t below = 0xFFFFFFFFFFF00000ull; EXPECT(a.add(title + 0x100000, size, below) && a.shader_va(title + 0x100010) == below + 0x10); From e997a1f28ff1e61d33d23b3946f53daae9e9e0ca Mon Sep 17 00:00:00 2001 From: Etr0p <216035314+Etr0p@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:59:03 +0100 Subject: [PATCH 017/110] test: cs_user_data's root-view-to-table mode names its pointer target, not the GLSL keyword out Co-Authored-By: Claude Opus 5.5 --- runtime/test/glsl/cs_user_data.comp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/runtime/test/glsl/cs_user_data.comp b/runtime/test/glsl/cs_user_data.comp index b8f2c12b90..07b4b7e4d4 100644 --- a/runtime/test/glsl/cs_user_data.comp +++ b/runtime/test/glsl/cs_user_data.comp @@ -48,8 +48,8 @@ void main() { if (pc.s[5] == 0xFFFFFFFDu) { // Root view read to a table pointer (d3d12_title_va_test): read through the root view, 256 bytes past its // base, and write where the table entry's raw 64-bit VA points. - Words out = at(uvec2(table.w[0], table.w[1])); - out.w[i] = result.w[64u + i] + pc.s[4]; + Words target = at(uvec2(table.w[0], table.w[1])); + target.w[i] = result.w[64u + i] + pc.s[4]; return; } if (pc.s[5] == 0u) { From 6d7842a55e34eef02150567e05a955b7c2c6a7fd Mon Sep 17 00:00:00 2001 From: Etr0p <216035314+Etr0p@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:59:21 +0100 Subject: [PATCH 018/110] d3d12: read LEONIDA_TITLE_WINDOWS_MB with getenv_s, as the file's other variables Co-Authored-By: Claude Opus 5.5 --- runtime/shims/d3d12_vulkan_device.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index e431cf8cf2..4596535527 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -5337,8 +5337,12 @@ class Device final info.xdxr_acceleration_structures && info.buffer_device_address); state_.context->set_before_execute([this] { state_.refresh_shadows(); }); - if (const char* mb = std::getenv("LEONIDA_TITLE_WINDOWS_MB"); mb && *mb) - state_.title_window_cap = std::strtoull(mb, nullptr, 10) << 20; + { + char text[16] = {}; + size_t length = 0; + if (getenv_s(&length, text, "LEONIDA_TITLE_WINDOWS_MB") == 0 && length > 1) + state_.title_window_cap = std::strtoull(text, nullptr, 10) << 20; + } leonida::title_va_aliases().set_hooks( &state_, [](void* device, std::uint64_t va, std::uint64_t bytes, std::uint64_t& out) { From f9db5e6bb3231c18c6b12d27b25f0ae18297966d Mon Sep 17 00:00:00 2001 From: Etr0p <216035314+Etr0p@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:05:45 +0100 Subject: [PATCH 019/110] d3d12: a bound table's slots the title wrote in its own heap backing are pulled in before the scan Co-Authored-By: Claude Opus 5.5 --- runtime/shims/d3d12_vulkan_device.cpp | 2 ++ runtime/src/title_va_alias.h | 25 +++++++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 4596535527..79d7d63fd1 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -859,6 +859,8 @@ struct DeviceState { kDescriptorSize); } auto& aliases = leonida::title_va_aliases(); + // Slots the title wrote in its own backing of this heap, if it gave the heap one. + aliases.pull_descriptors(arena.mapped + table_va, std::size_t(end - table_va)); for (VkDeviceSize at = table_va; at + 16 <= end; at += kDescriptorSize) { auto* w = reinterpret_cast(arena.mapped + at); const std::uint32_t w0 = w[0], w1 = w[1], w2 = w[2], w3 = w[3]; diff --git a/runtime/src/title_va_alias.h b/runtime/src/title_va_alias.h index 1e907ea437..987cf021be 100644 --- a/runtime/src/title_va_alias.h +++ b/runtime/src/title_va_alias.h @@ -167,6 +167,28 @@ class TitleVaAliases { return true; } + // A title that gives a descriptor heap its own backing memory (__XMemAllocationHooks__) writes descriptors there + // itself, while shaders read the layer's heap. The layer that keeps that mapping registers a source: before a + // bound table is scanned, it copies the slots the title wrote in its own memory over the layer's copy + // ([real, real + bytes) is the layer heap's CPU memory). Returns how many slots it copied. + using DescriptorSource = std::uint64_t (*)(void* context, std::uint8_t* real, std::size_t bytes); + void set_descriptor_source(void* context, DescriptorSource source) { + std::lock_guard lock(hook_mutex_); + source_context_ = context; + source_ = source; + } + void pull_descriptors(std::uint8_t* real, std::size_t bytes) { + DescriptorSource source; + void* context; + { + std::lock_guard lock(hook_mutex_); + source = source_; + context = source_context_; + } + if (source) pulled_.fetch_add(source(context, real, bytes), std::memory_order_relaxed); + } + std::uint64_t pulled() const { return pulled_.load(std::memory_order_relaxed); } + // The first device to register keeps the hooks until it clears them. void set_hooks(void* context, Resolver resolver, TableScanner scanner) { std::lock_guard lock(hook_mutex_); @@ -209,6 +231,9 @@ class TitleVaAliases { void* hook_context_ = nullptr; Resolver resolver_ = nullptr; TableScanner scanner_ = nullptr; + void* source_context_ = nullptr; + DescriptorSource source_ = nullptr; + std::atomic pulled_{0}; std::array, kind_count> translated_{}; std::array, kind_count> untranslated_{}; std::atomic scans_{0}, scan_ns_{0}, scan_max_ns_{0}; From dbab003b0e1ed5f6ab62b990971d60353857d138 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Mon, 23 Nov 2026 21:11:37 +0100 Subject: [PATCH 020/110] d3d12: quad lists draw as triangle-list indices (0 1 2) (0 2 3) so flat inputs use the first quad vertex, and the PSO topology type is read as raw bits Taken from the follow-up patch of @matheuskshn (930e78a2, tested by them on an RTX 4070 Ti: replay_quad_list_test fails the two non-indexed cases on a6b31d51 and passes with it). Re-run here: replay_quad_list_test and d3d12_rect_list_test exit 0 on the pod (Wine, RTX 4090). --- docs/d3d12_vulkan.md | 7 +- runtime/CMakeLists.txt | 6 ++ runtime/shims/d3d12_vulkan_device.cpp | 28 ++++--- runtime/src/rect_list_geometry.h | 2 + runtime/src/vulkan_backend.h | 2 +- runtime/src/vulkan_replay.h | 54 ++++++------ runtime/test/replay_quad_list_test.cpp | 110 +++++++++++++++++++++++++ 7 files changed, 168 insertions(+), 41 deletions(-) create mode 100644 runtime/test/replay_quad_list_test.cpp diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 3233715169..4f7e90553a 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2084,7 +2084,12 @@ The trace will enumerate them. The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiveTopology(17)`, with a PSO whose topology type is 19) and quad list (`IASetPrimitiveTopology(19)`). The facts are from xvalkyrie (GPL-3.0, commit `53af7df77c10`; no code taken): a rectangle is three corners and the fourth is v2 + v3 - v1 for the position and every interpolant, after the vertex stage; a quad is four vertices. The layer draws both as triangles (`d3d12_rect_list_test`, RTX 4090: 4096 of 4096 pixels, the colour plane exact, quad list bit-exact). - **Rectangle list**: PSO type 19 builds a triangle-list pipeline plus a generated geometry stage (`src/rect_list_geometry.h`, written from the vertex shader's own outputs) that takes the three corners and emits the strip v1 v2 v3 v4 (same winding). It has to be post-vertex-stage: the translated vertex shaders fetch by V# themselves, and the fourth corner is a function of what they write. A corner value with the same bits at all three corners (a flat attribute) is copied. Needs `geometryShader` (else `E_NOTIMPL`), no application GS, and a vertex shader with no ClipDistance, CullDistance, Layer or ViewportIndex output. -- **Quad list**: one four-vertex triangle fan per quad (the pattern 0 1 2, 0 2 3). The translated vertex id is `VertexIndex - BaseVertex`, so each fan reads the index values 4q..4q+3: from the application's index buffer when the draw is indexed, else from a shared 0, 1, 2, ... buffer in the arena's reserved pages (16384 quads per draw at most, more are cut off with a log line), with the draw's first vertex as the vertex offset. A quad's instances are drawn together, so several overlapping blended instances rasterize quad by quad rather than instance by instance. The PSO type is the ordinary triangle type. +- **Quad list**: a non-indexed draw uses a shared index buffer containing the triangle-list pattern + `0 1 2, 0 2 3` for each quad. Both triangles start at the first vertex for flat inputs. One draw preserves instance + order and supports up to 16384 quads. The draw's first vertex becomes the vertex offset. Indexed draws still + read the application's index buffer as one four-vertex fan per quad. Vulkan fans use a different provoking + vertex for flat inputs, and overlapping blended instances rasterize quad by quad in this path. The PSO type + is the ordinary triangle type. ## 4. Object model mapping diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 3be2911a9e..6b2db91ac7 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2864,6 +2864,12 @@ if(TARGET Vulkan::Headers) target_compile_definitions(replay_readback_stages_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) endif() add_test(NAME replay_readback_stages COMMAND replay_readback_stages_test) + add_executable(replay_quad_list_test test/replay_quad_list_test.cpp) + target_link_libraries(replay_quad_list_test PRIVATE Vulkan::Headers) + if(WIN32) + target_compile_definitions(replay_quad_list_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + add_test(NAME replay_quad_list COMMAND replay_quad_list_test) # emit of an enhanced texture barrier: no heap allocation for one layout piece, one barrier for each piece (no GPU). add_executable(replay_texture_barrier_test test/replay_texture_barrier_test.cpp) target_link_libraries(replay_texture_barrier_test PRIVATE Vulkan::Headers) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index fbeccc3d34..7bd9cef959 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -66,7 +66,8 @@ constexpr UINT kDescriptorSize = descriptor_size; // The first 64 KiB of the GPU address arena are never handed out: VA 0 stays invalid, and the page is kept zero // for unbound vertex and index buffers to read (D3D12 reads zeros there). constexpr VkDeviceSize kZeroPage = 64 * 1024; // zeroed: what unbound vertex and index buffers read -constexpr std::uint32_t kQuadIndexCount = 64 * 1024; // 0, 1, 2, ... that non-indexed quad lists draw with (16384 quads) +constexpr std::uint32_t kQuadIndicesPerQuad = leonida::quad_triangle_indices.size(); +constexpr std::uint32_t kQuadIndexCount = 16 * 1024 * kQuadIndicesPerQuad; constexpr VkDeviceSize kArenaReserved = kZeroPage + VkDeviceSize(kQuadIndexCount) * sizeof(std::uint32_t); static_assert(sizeof(leonida::TargetView) <= kDescriptorSize); @@ -2828,7 +2829,8 @@ leonida::cached_pso::Key pipeline_key(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& key.text(e.SemanticName).u32(e.SemanticIndex).u32(e.Format).u32(e.InputSlot).u32(e.AlignedByteOffset); key.u32(e.InputSlotClass).u32(e.InstanceDataStepRate); } - key.u32(desc.IBStripCutValue).u32(desc.PrimitiveTopologyType).u32(desc.NumRenderTargets); + key.u32(desc.IBStripCutValue).u32(std::bit_cast(desc.PrimitiveTopologyType)) + .u32(desc.NumRenderTargets); for (const DXGI_FORMAT format : desc.RTVFormats) key.u32(format); key.u32(desc.DSVFormat).u32(desc.SampleDesc.Count).u32(desc.SampleDesc.Quality).u32(desc.NodeMask); return leonida::sha256_hex(key.data()); @@ -3195,13 +3197,15 @@ class PipelineState final // The console's rectangle topology type (19) draws as triangles through a generated geometry stage that adds // each rectangle's fourth corner (src/rect_list_geometry.h); it needs the same device feature, and no GS of // the application's own. - const bool rect_list = !mesh && desc.PrimitiveTopologyType == leonida::topology_type_rect_list; + // Decode the ABI field as bits. The console's value is outside the PC enum's range. + const auto topology_type = std::bit_cast(desc.PrimitiveTopologyType); + const bool rect_list = !mesh && topology_type == leonida::topology_type_rect_list; if (rect_list && (geometry || !device_.info.features.geometryShader)) { log_once("a rectangle-list pipeline needs the geometryShader feature and no geometry shader; stage", 0); return geometry ? E_INVALIDARG : E_NOTIMPL; } - if (geometry && desc.PrimitiveTopologyType != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) { - log_once("a translated geometry shader takes triangles; topology type", desc.PrimitiveTopologyType); + if (geometry && topology_type != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) { + log_once("a translated geometry shader takes triangles; topology type", topology_type); return E_INVALIDARG; } const UINT samples = desc.SampleDesc.Count; @@ -3484,12 +3488,12 @@ class PipelineState final } VkPipelineInputAssemblyStateCreateInfo assembly{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; // Type 19 is the console's rectangles, drawn as triangle lists through the geometry stage added above. - switch (mesh || rect_list ? D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE : desc.PrimitiveTopologyType) { // mesh: not used + switch (mesh || rect_list ? D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE : topology_type) { // mesh: not used case D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT: assembly.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST; break; case D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_LINE_LIST; break; case D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; break; default: - log_once("primitive topology type not supported:", desc.PrimitiveTopologyType); + log_once("primitive topology type not supported:", topology_type); return E_INVALIDARG; } if (!mesh) { // a mesh PSO has no index buffer: its strip cut is ignored @@ -3511,7 +3515,7 @@ class PipelineState final return E_INVALIDARG; } if (r.FillMode != D3D12_FILL_MODE_SOLID || - desc.PrimitiveTopologyType != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) return E_INVALIDARG; + topology_type != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) return E_INVALIDARG; // Target-independent rasterization is a separate pipeline path; do not silently ignore its count. if (r.ForcedSampleCount) return E_NOTIMPL; } @@ -5201,9 +5205,11 @@ class Device final } arena.mapped = static_cast(mapped); std::memset(arena.mapped, 0, kZeroPage); // the zero page unbound vertex and index buffers read - { - auto* iota = reinterpret_cast(arena.mapped + kZeroPage); - for (std::uint32_t i = 0; i < kQuadIndexCount; ++i) iota[i] = i; + auto* indices = reinterpret_cast(arena.mapped + kZeroPage); + for (std::uint32_t i = 0; i < kQuadIndexCount; i += kQuadIndicesPerQuad) { + const std::uint32_t base = i / kQuadIndicesPerQuad * 4; + std::transform(leonida::quad_triangle_indices.begin(), leonida::quad_triangle_indices.end(), indices + i, + [base](std::uint32_t index) { return base + index; }); } VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; address.buffer = arena.buffer; diff --git a/runtime/src/rect_list_geometry.h b/runtime/src/rect_list_geometry.h index 335e4db00e..86826317c6 100644 --- a/runtime/src/rect_list_geometry.h +++ b/runtime/src/rect_list_geometry.h @@ -22,6 +22,7 @@ // Plain word editing, standard library only. #include +#include #include #include #include @@ -35,6 +36,7 @@ namespace leonida { constexpr std::uint32_t topology_rect_list = 17; constexpr std::uint32_t topology_quad_list = 19; constexpr std::uint32_t topology_type_rect_list = 19; +constexpr std::array quad_triangle_indices{0, 1, 2, 0, 2, 3}; // The geometry stage for `vertex_words`' outputs; empty, with `why` set, when the vertex stage cannot be expanded. inline std::vector rect_list_geometry(const std::vector& vertex_words, std::string& why) { diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index b05f5fc1ad..9dd83f20d8 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -1247,7 +1247,7 @@ class VulkanContext { replay_.zero_size = size; } - // 0, 1, 2, ... as 32-bit indices, for non-indexed quad lists (ReplayFunctions::quad_indices). + // Pre-expanded 32-bit triangle indices for non-indexed quad lists (ReplayFunctions::quad_indices). void set_quad_indices(VkBuffer buffer, VkDeviceSize offset, std::uint32_t count) { std::unique_lock lock(resource_mutex_); replay_.quad_indices = buffer; diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 5093fbd027..35ad689b23 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -868,7 +868,7 @@ struct ReplayFunctions { VkBuffer zero_buffer = VK_NULL_HANDLE; VkDeviceSize zero_offset = 0; VkDeviceSize zero_size = 0; - // 0, 1, 2, ... as 32-bit indices: what a non-indexed quad list is drawn with (quad_index_count of them). + // 32-bit triangle indices for non-indexed quad lists: 0, 1, 2, 0, 2, 3, then the same pattern for each quad. VkBuffer quad_indices = VK_NULL_HANDLE; VkDeviceSize quad_indices_offset = 0; std::uint32_t quad_index_count = 0; @@ -2182,7 +2182,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct p.vertex_sizes[slot] = size; p.vertex_strides[slot] = (pipeline->zero_step_slots & (1u << slot)) ? 0 : view.stride; } - // A non-indexed quad list is drawn from the shared 0, 1, 2, ... index buffer (emit). + // A non-indexed quad list is drawn from the shared triangle index buffer (emit). if (!draw.indexed && !draw.mesh && draw.topology == topology_quad_list && !vk.quad_indices) return ReplayResult::unresolved_resource; if (draw.indexed) { @@ -2219,9 +2219,8 @@ inline VkPrimitiveTopology vulkan_topology(std::uint32_t topology) { case 11: return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY; case 12: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY; case 13: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY; - // The console's lists (rect_list_geometry.h). A rectangle list is drawn as the triangle list of its three - // corners, the pipeline's geometry stage adds the fourth. A quad (v0 v1 v2 v3) is the fan (v0 v1 v2) (v0 v2 v3), - // which is the index pattern 0 1 2, 0 2 3; the draw below issues one fan per quad. + // Rectangles draw as triangle lists through a geometry stage. Indexed quads draw as separate fans; + // emit() overrides non-indexed quads to a triangle list backed by the shared indices. case topology_rect_list: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; case topology_quad_list: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN; default: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; @@ -4103,7 +4102,8 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c // A mesh pipeline has no input assembly: its topology comes from the shader, and neither the topology // nor primitive restart is dynamic state there (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065). if (!draw->mesh) { - const VkPrimitiveTopology topology = detail::vulkan_topology(draw->topology); + const VkPrimitiveTopology topology = draw->topology == topology_quad_list && !draw->indexed + ? VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST : detail::vulkan_topology(draw->topology); vk.set_primitive_topology(command_buffer, topology); const bool restart = draw->indexed && detail::strip_topology(topology) && ((graphics.strip_cut == 1 && d.index_type == VK_INDEX_TYPE_UINT16) || @@ -4121,29 +4121,27 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c if (draw->mesh) { vk.draw_mesh_tasks(command_buffer, draw->count, draw->instances, draw->first); } else if (draw->topology == topology_quad_list) { - // One four-vertex fan per quad. The translated vertex shaders take their vertex id from the index - // value (VertexIndex - BaseVertex), so a fan must be drawn with the index values 4q..4q+3: an - // indexed draw reads them from the application's index buffer, a non-indexed one from the - // shared 0, 1, 2, ... buffer (quad_indices), with the draw's first vertex as the vertex offset, as - // VertexIndex is first + i for a plain draw. - const bool generated = !draw->indexed; // prepare() has checked that quad_indices is there - if (generated) - vk.bind_index_buffer(command_buffer, vk.quad_indices, vk.quad_indices_offset, VK_INDEX_TYPE_UINT32); - else + if (draw->indexed) { + // Indexed quads still read their vertices from the application's index buffer, one fan per quad. vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); - // The shared buffer holds quad_index_count / 4 quads: more are cut off here and said so. - const std::uint32_t wanted = draw->count / 4, room = generated ? vk.quad_index_count / 4 : UINT32_MAX; - const std::uint32_t quads = std::min(wanted, room); - if (quads < wanted) - std::fprintf(stderr, "[rt] d3d12: a non-indexed quad list of %u quads draws only the first %u\n", - wanted, quads); - const std::int32_t vertex_offset = generated ? std::int32_t(draw->first) : draw->base_vertex; - // All the instances of a quad are drawn together (a split by instance would zero the translated - // instance id, InstanceIndex - BaseInstance), so with several instances the primitive order is quad - // by quad, not instance by instance: only overlapping blended instances can tell. - for (std::uint32_t quad = 0; quad < quads; ++quad) - vk.draw_indexed(command_buffer, 4, draw->instances, (generated ? 0 : draw->first) + 4 * quad, - vertex_offset, draw->first_instance); + for (std::uint32_t quad = 0; quad < draw->count / 4; ++quad) + vk.draw_indexed(command_buffer, 4, draw->instances, draw->first + 4 * quad, + draw->base_vertex, draw->first_instance); + } else { + // Both triangles start at the quad's first vertex for flat inputs. One draw also preserves + // the original instance order, and VertexIndex - BaseVertex still gives 4q + k. + constexpr std::uint32_t indices_per_quad = quad_triangle_indices.size(); + const std::uint32_t wanted = draw->count / 4; + const std::uint32_t quads = std::min(wanted, vk.quad_index_count / indices_per_quad); + if (quads < wanted) + std::fprintf(stderr, "[rt] d3d12: a non-indexed quad list of %u quads draws only the first %u\n", + wanted, quads); + if (quads) { + vk.bind_index_buffer(command_buffer, vk.quad_indices, vk.quad_indices_offset, VK_INDEX_TYPE_UINT32); + vk.draw_indexed(command_buffer, quads * indices_per_quad, draw->instances, 0, + std::int32_t(draw->first), draw->first_instance); + } + } } else if (draw->indexed) { vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); vk.draw_indexed(command_buffer, draw->count, draw->instances, draw->first, draw->base_vertex, diff --git a/runtime/test/replay_quad_list_test.cpp b/runtime/test/replay_quad_list_test.cpp new file mode 100644 index 0000000000..15b0c7e781 --- /dev/null +++ b/runtime/test/replay_quad_list_test.cpp @@ -0,0 +1,110 @@ +// Quad lists without an index buffer are one triangle-list draw. A switch back to Vulkan triangle fans +// changes the provoking vertex for flat attributes and the order of overlapping blended instances. +#include "../src/vulkan_replay.h" + +#include +#include +#include + +namespace { +using namespace leonida; + +struct DrawCall { + VkPrimitiveTopology topology; + VkBuffer buffer; + VkDeviceSize offset; + VkIndexType index_type; + std::uint32_t count, instances, first_index; + std::int32_t base_vertex; + std::uint32_t first_instance; + bool operator==(const DrawCall&) const = default; +}; + +DrawCall recorded{}; +std::vector calls; + +bool check(bool condition, const char* description) { + if (!condition) std::fprintf(stderr, "FAIL: %s\n", description); + return condition; +} +} + +int main() { + using namespace leonida; + ReplayFunctions vk{}; + vk.begin_rendering = +[](VkCommandBuffer, const VkRenderingInfo*) {}; + vk.end_rendering = +[](VkCommandBuffer) {}; + vk.bind_pipeline = +[](VkCommandBuffer, VkPipelineBindPoint, VkPipeline) {}; + vk.push_constants = +[](VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags, std::uint32_t, + std::uint32_t, const void*) {}; + vk.set_viewport = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, const VkViewport*) {}; + vk.set_scissor = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, const VkRect2D*) {}; + vk.set_primitive_topology = +[](VkCommandBuffer, VkPrimitiveTopology topology) { recorded.topology = topology; }; + vk.set_primitive_restart_enable = +[](VkCommandBuffer, VkBool32) {}; + vk.set_stencil_reference = +[](VkCommandBuffer, VkStencilFaceFlags, std::uint32_t) {}; + vk.set_blend_constants = +[](VkCommandBuffer, const float*) {}; + vk.bind_index_buffer = +[](VkCommandBuffer, VkBuffer buffer, VkDeviceSize offset, VkIndexType type) { + recorded.buffer = buffer; + recorded.offset = offset; + recorded.index_type = type; + }; + vk.draw_indexed = +[](VkCommandBuffer, std::uint32_t count, std::uint32_t instances, std::uint32_t first, + std::int32_t base, std::uint32_t first_instance) { + recorded.count = count; + recorded.instances = instances; + recorded.first_index = first; + recorded.base_vertex = base; + recorded.first_instance = first_instance; + calls.push_back(recorded); + }; + + vk.quad_indices = reinterpret_cast(std::uintptr_t{1}); + vk.quad_indices_offset = 64; + vk.quad_index_count = 12; + const auto app_buffer = reinterpret_cast(std::uintptr_t{2}); + + GraphicsPipeline graphics{}; + const auto collect = [&](const Draw& draw) { + calls.clear(); + CommandList list; + if (!list.draw(draw) || !list.close()) return false; + PreparedList prepared; + prepared.list = &list; + prepared.commands.resize(1); + prepared.commands[0].draw = 0; + auto& entry = prepared.draws.emplace_back(); + entry.graphics = &graphics; + entry.index_buffer = app_buffer; + entry.index_offset = 32; + emit(prepared, VK_NULL_HANDLE, vk); + return true; + }; + + Draw draw{}; + draw.pipeline = 1; + draw.topology = topology_quad_list; + draw.count = 8; + draw.instances = 2; + draw.first = 13; + draw.first_instance = 7; + + const DrawCall triangles{VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, vk.quad_indices, 64, VK_INDEX_TYPE_UINT32, + 12, 2, 0, 13, 7}; + bool ok = check(collect(draw) && calls == std::vector{triangles}, + "non-indexed quads use one triangle-list draw and preserve draw bases"); + draw.count = 13; + ok &= check(collect(draw) && calls == std::vector{triangles}, + "a draw is limited to whole quads in the generated index buffer"); + draw.count = 3; + ok &= check(collect(draw) && calls.empty(), "an incomplete quad emits no draw"); + + draw.indexed = true; + draw.count = 8; + draw.first = 5; + draw.base_vertex = -2; + const DrawCall first_fan{VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN, app_buffer, 32, VK_INDEX_TYPE_UINT16, 4, 2, 5, -2, 7}; + const DrawCall second_fan{VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN, app_buffer, 32, VK_INDEX_TYPE_UINT16, 4, 2, 9, -2, 7}; + ok &= check(collect(draw) && calls == std::vector{first_fan, second_fan}, + "indexed quads use the application's index buffer and base vertex"); + return ok ? 0 : 1; +} From 6d1f046da6083c623bf78f2438f37c988df6b3f8 Mon Sep 17 00:00:00 2001 From: Etr0p <216035314+Etr0p@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:13:38 +0100 Subject: [PATCH 021/110] docs, comments: describe the title's VA by its range, not by a measured value Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 2 +- runtime/shims/d3d12_vulkan_device.cpp | 2 +- runtime/src/title_va_alias.h | 2 +- runtime/test/title_va_alias_test.cpp | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index f108cc37d3..9096e475cb 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1501,7 +1501,7 @@ a console client can address is an arena range, whichever heap it comes from. - the title points root views and V#s at its own memory, for instance a per-frame constant ring (#8862, section 3.5 of `docs/retail_boot_chain.md`). -On Windows these are user-mode addresses around 1.5 TiB, far past the arena (at most 4095 MiB, and descriptor +On Windows these are user-mode addresses far above 4 GiB, past the arena (at most 4095 MiB, and descriptor tables must stay below 4 GiB), so `heap_base + VA` names nothing the layer made (the D3D-53 failure above). The layer therefore replaces such an address, wherever it sees one, by the console VA of a GPU copy of that memory (`runtime/src/title_va_alias.h`): diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 79d7d63fd1..6d94072525 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -2275,7 +2275,7 @@ class Resource final return E_INVALIDARG; const auto* pages = static_cast(address); // The shadow is a range of the GPU address arena when it fits there (docs/d3d12_vulkan.md section 3.3). - // The title's VA is about 1.5 TiB on Windows, far past the arena, so a shader's heap_base + VA would miss + // The title's VA is a user-mode Windows address far above 4 GiB, past the arena, so a shader's heap_base + VA would miss // any buffer of the layer's; the root views and V#s the layer writes for that VA name the arena offset // instead (src/title_va_alias.h), a VA below 4 GiB that a root view and a V#'s 48 bits both hold. The arena // is host-visible, so the per-submission copy writes it in place. diff --git a/runtime/src/title_va_alias.h b/runtime/src/title_va_alias.h index 987cf021be..829c1d8740 100644 --- a/runtime/src/title_va_alias.h +++ b/runtime/src/title_va_alias.h @@ -4,7 +4,7 @@ // // A translated shader computes heap_base + console_va, with heap_base the GPU address arena's device address. The // layer chooses every console VA it hands out, so they all land in the arena. The title does not always use them: -// - device slot 133 places a buffer at the CPU address of the title's own pages (about 1.5 TiB on Windows); +// - device slot 133 places a buffer at the CPU address of the title's own pages (a user-mode Windows address, far above 4 GiB); // - the title points V#s and root views at its own memory (a per-frame constant ring, #8862 section 3.5). // Both are far past the arena, so heap_base + VA reads nothing the layer made. An address inside such a range is // therefore replaced, wherever the layer can see it, by the console VA of a GPU copy of that range: its arena offset diff --git a/runtime/test/title_va_alias_test.cpp b/runtime/test/title_va_alias_test.cpp index 84758dbc97..133f7f2e54 100644 --- a/runtime/test/title_va_alias_test.cpp +++ b/runtime/test/title_va_alias_test.cpp @@ -11,7 +11,7 @@ int main() { leonida::TitleVaAliases a; - constexpr std::uint64_t title = 0x18500000000ull; // the shape of a Windows VA past 1 TiB + constexpr std::uint64_t title = 0x20000000000ull; // a synthetic user-mode VA far above 4 GiB constexpr std::uint64_t size = 0x10000; constexpr std::uint64_t arena = 0x2340000; // Empty: identity everywhere. From 81caaa165312c32d5cb9fe7afd4b36ed4f8b6c9a Mon Sep 17 00:00:00 2001 From: tedin7 Date: Mon, 23 Nov 2026 21:19:02 +0100 Subject: [PATCH 022/110] d3d12: rect_list_geometry records that packed f16 attributes cannot be told apart from float outputs on the vertex side (comment only) --- runtime/src/rect_list_geometry.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/runtime/src/rect_list_geometry.h b/runtime/src/rect_list_geometry.h index 86826317c6..15d7368d34 100644 --- a/runtime/src/rect_list_geometry.h +++ b/runtime/src/rect_list_geometry.h @@ -92,6 +92,10 @@ inline std::vector rect_list_geometry(const std::vector Date: Tue, 24 Nov 2026 05:06:50 +0800 Subject: [PATCH 023/110] d3d12: support Xbox R32G8X24 depth and stencil UAVs (D3D-991, part 1) --- docs/d3d12_vulkan.md | 7 + runtime/CMakeLists.txt | 14 + runtime/shims/d3d12_com.cpp | 2 + runtime/shims/d3d12_com.h | 2 + runtime/shims/d3d12_vulkan_device.cpp | 97 +++++- runtime/shims/d3d12_xs_device.cpp | 25 ++ runtime/shims/d3d12_xs_device.h | 3 + runtime/src/vulkan_backend.h | 4 + runtime/src/vulkan_replay.h | 149 +++++++++- runtime/test/d3d12_depth_stencil_uav_test.cpp | 281 ++++++++++++++++++ runtime/test/device_proxy_test.cpp | 16 + runtime/test/glsl/cs_depth_stencil_uav.comp | 30 ++ runtime/test/replay_texture_barrier_test.cpp | 105 +++++++ runtime/test/vk_test_device.h | 3 + 14 files changed, 728 insertions(+), 10 deletions(-) create mode 100644 runtime/test/d3d12_depth_stencil_uav_test.cpp create mode 100644 runtime/test/glsl/cs_depth_stencil_uav.comp diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 019f66fa28..33d4f979ab 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2468,6 +2468,13 @@ The trace will enumerate them. `DEPTH_STENCIL_ATTACHMENT`, `ALLOW_UNORDERED_ACCESS` → `STORAGE`, `ALLOW_SIMULTANEOUS_ACCESS` → concurrent sharing, `DENY_*` → omit the corresponding usage. Buffers get the union of usages their states and flags imply; images copy dimension, format, mip levels, array layers and sample count. +- Xbox slot 76 supports UAVs on committed 2D `R32G8X24_TYPELESS` depth/stencil textures with one mip, layer and + sample. Use a `TEXTURE2D` UAV with `R32_FLOAT` on plane 0 or `R8_UINT` on plane 1. Each plane has its own + storage image and descriptor address. On explicit transitions into or out of UAV access, the graphics queue + family transfers the affected planes through a scratch buffer. Depth attachment and shader-resource views + keep their original image. For these textures, replay rejects the queue-specific enhanced `DIRECT_QUEUE_COMMON` + and `COMPUTE_QUEUE_COMMON` layouts, which allow switching between the images without a texture barrier. + `d3d12_depth_stencil_uav_test` exercises both planes with a synthetic compute shader. - Copies: `CopyBufferRegion` → `vkCmdCopyBuffer` with arena offsets; `CopyTextureRegion` → `vkCmdCopyBufferToImage`/`vkCmdCopyImageToBuffer`/`vkCmdCopyImage`, using the `D3D12_PLACED_SUBRESOURCE_FOOTPRINT` row pitch and height; `CopyResource` → a whole-subresource copy; colour resolves → `vkCmdResolveImage`; diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 7080d87bf0..776542b667 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2638,6 +2638,20 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_set0_compute_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_set0_compute COMMAND d3d12_set0_compute_test) set_tests_properties(d3d12_set0_compute PROPERTIES SKIP_RETURN_CODE 77) + set(depth_uav_spv ${CMAKE_CURRENT_BINARY_DIR}/generated/cs_depth_stencil_uav.spv) + add_custom_command(OUTPUT ${depth_uav_spv} + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_CURRENT_BINARY_DIR}/generated + COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${depth_uav_spv} + ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_depth_stencil_uav.comp + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_depth_stencil_uav.comp VERBATIM) + add_executable(d3d12_depth_stencil_uav_test test/d3d12_depth_stencil_uav_test.cpp + shims/d3d12_xs_device.cpp ${depth_uav_spv}) + target_link_libraries(d3d12_depth_stencil_uav_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_depth_stencil_uav_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_DEPTH_UAV_SPV="${depth_uav_spv}") + target_compile_options(d3d12_depth_stencil_uav_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_depth_stencil_uav COMMAND d3d12_depth_stencil_uav_test) + set_tests_properties(d3d12_depth_stencil_uav PROPERTIES SKIP_RETURN_CODE 77) # Bindless table churn on a direct and a compute queue: the table grows and live keys move without a # device-idle wait (D3D-314); the same shader, run twice (deferred retirement, and the old wait for timing). add_executable(d3d12_bindless_churn_test test/d3d12_bindless_churn_test.cpp shims/d3d12_xs_device.cpp diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index f25168a2af..41d00b1a4b 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -1119,6 +1119,8 @@ class GraphicsCommandList final if (g::is_image(words)) { g::Image image{}; if (!g::decode(words, image)) return false; + out.resource = uav_image_resource(resource, image.address); + if (!out.resource) return false; const bool volume = image.type == g::ImageType::image_3d; out.buffer = false; out.format = std::uint32_t(descriptor_format(image.format, image.swizzle)); diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 8f37b1ff24..af767ccf2b 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -212,6 +212,8 @@ void set_device_outer(ID3D12Device* device, IUnknown* outer); // The VkImage behind a texture created by such a device, or VK_NULL_HANDLE. For tests and the swapchain. VkImage vulkan_image(ID3D12Resource* resource); +// Resolves the resource that a UAV clear writes. Xbox depth/stencil UAVs name one of two color images by T#. +leonida::ResourceId uav_image_resource(ID3D12Resource* resource, std::uint64_t address); // The VkBuffer behind a buffer created by such a device, or VK_NULL_HANDLE. For tests. VkBuffer vulkan_buffer(ID3D12Resource* resource); // What a device from create_vulkan_device* was created with (enabled features included), or null. For tests. diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 3b9958b35c..3616d69bdd 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -38,6 +38,7 @@ #endif #include +#include #include #include #include @@ -50,6 +51,7 @@ #include #include #include +#include #include #include #include @@ -1762,6 +1764,9 @@ class Resource final VkImageAspectFlags aspects() const { return aspects_; } bool rgb96() const { return rgb96_; } // a 96-bit texture in an RGBA32 image std::uint64_t image_address() const { return image_address_; } // what a T# names the texture by + const Resource* depth_stencil_uav(UINT plane) const { + return plane < storage_planes_.size() ? storage_planes_[plane].get() : nullptr; + } VkMemoryPropertyFlags memory_flags() const { return memory_flags_; } // of the memory type behind it const DeviceState& device_state() const { return device_; } @@ -2091,10 +2096,44 @@ class Resource final return S_OK; } + // The Xbox proxy calls this before publishing an allocated depth texture. Each storage plane owns a + // regular color image with its own GFX10 address, so a UAV cannot replace the original SRV in set 0. + HRESULT enable_depth_stencil_uav() { + if (!image_ || desc_.Format != DXGI_FORMAT_R32G8X24_TYPELESS || + !(desc_.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) || + desc_.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc_.MipLevels != 1 || + desc_.DepthOrArraySize != 1 || desc_.SampleDesc.Count != 1) + return E_INVALIDARG; + if (storage_planes_[0]) return S_OK; + try { + decltype(storage_planes_) planes; + D3D12_RESOURCE_DESC plane_desc = desc_; + plane_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + constexpr DXGI_FORMAT formats[] = {DXGI_FORMAT_R32_FLOAT, DXGI_FORMAT_R8_UINT}; + for (UINT plane = 0; plane < planes.size(); ++plane) { + plane_desc.Format = formats[plane]; + planes[plane] = std::make_unique(device_, plane_desc, heap_, D3D12_HEAP_FLAG_NONE); + const HRESULT hr = planes[plane]->create_texture(device_.texture_format(plane_desc)); + if (FAILED(hr)) return hr; + } + // Replacing the binding preserves the tracked layout of the original depth/stencil image. + auto binding = binding_; + binding.depth_uav = planes[0]->id(); + binding.stencil_uav = planes[1]->id(); + device_.context->add_resource(id(), binding); + binding_ = binding; + storage_planes_ = std::move(planes); + } catch (const std::bad_alloc&) { + return E_OUTOFMEMORY; + } + return S_OK; + } + // D3D12 reports the placement alignment of a description that left it 0: 64 KiB, or 4 MiB for a multisampled // texture. One the description asked for is kept. Measured on the PC runtime and WARP (d3d12_resource_desc_test). D3D12_RESOURCE_DESC STDMETHODCALLTYPE GetDesc() override { D3D12_RESOURCE_DESC desc = desc_; + if (storage_planes_[0]) desc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; if (!desc.Alignment) { desc.Alignment = (desc.SampleDesc.Count > 1 && !is_tiled_layout(desc.Layout)) ? D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT @@ -2426,6 +2465,7 @@ class Resource final bool sparse_image_ = false; bool placed_ = false; leonida::ResourceBinding binding_{}; // a texture's, as registered with the context + std::array, 2> storage_planes_; // Xbox depth/stencil UAV, by plane bool host_transfer_ = false; // created with VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT D3D12_GPU_VIRTUAL_ADDRESS va_ = 0; VkDeviceSize arena_offset_ = 0; @@ -4896,6 +4936,7 @@ class Device final info.conditional_rendering, info.ray_tracing, info.xdxr_acceleration_structures && info.buffer_device_address); + state_.context->set_graphics_family(info.queue_family); if (info.physical && state_.format_properties) { state_.context->set_color_attachment_format( [physical = info.physical, get_props = state_.format_properties](VkFormat format) { @@ -6326,7 +6367,7 @@ class Device final return; } } - write_image_descriptor(*r, view, destination, false); + write_image_descriptor(*r, view, destination, ImageViewUse::sampled); } // An unordered-access view of a buffer is a V# in the slot (docs section 3.4): the shader loads those four dwords @@ -6435,6 +6476,28 @@ class Device final log_once("unordered-access view of a texture with a counter resource; dimension", int(r->desc().Dimension)); return; } + if (r->depth_stencil_uav(0)) { + if (!desc || desc->ViewDimension != D3D12_UAV_DIMENSION_TEXTURE2D || desc->Texture2D.MipSlice) { + log_once("Xbox depth-stencil UAV requires an explicit 2D mip-zero view; dimension", + desc ? int(desc->ViewDimension) : 0); + return; + } + const Resource* plane = r->depth_stencil_uav(desc->Texture2D.PlaneSlice); + if (!plane) { + log_once("unsupported Xbox depth-stencil UAV plane", int(desc->Texture2D.PlaneSlice)); + return; + } + if (desc->Format != plane->desc().Format) { + log_once(desc->Texture2D.PlaneSlice ? "unsupported Xbox stencil UAV format" + : "unsupported Xbox depth UAV format", int(desc->Format)); + return; + } + TextureView view{}; + view.format = desc->Format; + view.mip_count = view.layer_count = 1; + write_image_descriptor(*plane, view, destination, ImageViewUse::depth_stencil_uav); + return; + } if (!(r->desc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { log_once("unordered-access view of a texture created without ALLOW_UNORDERED_ACCESS; flags", int(r->desc().Flags)); @@ -6479,7 +6542,7 @@ class Device final log_once("unordered-access view of a B8G8R8X8 format; format", int(view.format)); return; } - write_image_descriptor(*r, view, destination, true); + write_image_descriptor(*r, view, destination, ImageViewUse::storage); state_.context->note_shader_image(r->id()); } @@ -7986,18 +8049,21 @@ class Device final return std::min(fallback, align_up(total, alignment)); } + enum class ImageViewUse { sampled, storage, depth_stencil_uav }; + // Writes the view's T# into the slot and makes sure set 0 and the hash table know it. A view that cannot be // shown leaves the slot a null descriptor. void write_image_descriptor(const Resource& resource, const TextureView& view, - D3D12_CPU_DESCRIPTOR_HANDLE destination, bool storage) { + D3D12_CPU_DESCRIPTOR_HANDLE destination, ImageViewUse use) { leonida::gfx10::Image image{}; if (!image_descriptor(resource, view, image)) return; const leonida::gfx10::ImageWords words = leonida::gfx10::encode(image); - const bool registered = state_.bind_image(words, image, resource.image(), resource.format(), - resource.aspects(), storage, resource.has_view_format_list(), + const bool registered = state_.bind_image(words, image, resource.image(), resource.format(), resource.aspects(), + use != ImageViewUse::sampled, resource.has_view_format_list(), resource.r9g9b9e5_as_r32_uint()); - if (registered && resource.sparse_image()) state_.context->note_shader_image(resource.id()); - if (leonida::gfx10::multisampled(image.type) && !registered) return; + const bool storage_plane = use == ImageViewUse::depth_stencil_uav; + if (registered && (resource.sparse_image() || storage_plane)) state_.context->note_shader_image(resource.id()); + if (!registered && (leonida::gfx10::multisampled(image.type) || storage_plane)) return; std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); } @@ -8349,6 +8415,21 @@ bool is_sparse_image(ID3D12Resource* resource) { return object && object->sparse_image(); } +static HRESULT enable_depth_stencil_uav(ID3D12Resource* resource) { + Resource* r = Resource::from(resource); + return r ? r->enable_depth_stencil_uav() : E_INVALIDARG; +} + +leonida::ResourceId uav_image_resource(ID3D12Resource* resource, std::uint64_t address) { + const Resource* r = Resource::from(resource); + if (!r || !r->depth_stencil_uav(0)) return resource_id(resource); + for (UINT plane = 0; plane < 2; ++plane) { + const Resource* storage = r->depth_stencil_uav(plane); + if (storage->image_address() == address) return storage->id(); + } + return 0; +} + void set_device_outer(ID3D12Device* device, IUnknown* outer) { Device* d = Device::from(device); if (!d) return; @@ -8360,6 +8441,7 @@ void set_device_outer(ID3D12Device* device, IUnknown* outer) { // out this layer's adapter, the one create_dxgi_factory enumerates, so a title on the Vulkan device never gets // a host DXGI object from it. if (!rt::d3d12_xs::is_device_proxy(outer)) return; + rt::d3d12_xs::set_depth_stencil_uav_provider(outer, &enable_depth_stencil_uav); rt::d3d12_xs::set_device_adapter_provider(outer, [](ID3D12Device* real, REFIID riid, void** out) { IDXGIFactory1* factory = nullptr; HRESULT hr = create_dxgi_factory(real, __uuidof(IDXGIFactory1), reinterpret_cast(&factory)); @@ -9325,6 +9407,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin enable.shaderClipDistance = chosen_features.shaderClipDistance; enable.shaderCullDistance = chosen_features.shaderCullDistance; enable.shaderStorageImageWriteWithoutFormat = chosen_features.shaderStorageImageWriteWithoutFormat; + enable.shaderStorageImageExtendedFormats = chosen_features.shaderStorageImageExtendedFormats; enable.shaderStorageImageReadWithoutFormat = chosen_features.shaderStorageImageReadWithoutFormat; enable.shaderImageGatherExtended = chosen_features.shaderImageGatherExtended; enable.shaderResourceMinLod = chosen_features.shaderResourceMinLod; diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index e17a80353b..2e018d95ef 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -60,6 +60,7 @@ struct DeviceProxy { // The device's IDXGIDevice1 (see "IDXGIDevice1 on the device" below): a title's IDXGIDevice1* points here. void** dxgi_vtable; DxgiAdapterProvider adapter_provider; + DepthStencilUavProvider depth_stencil_uav_provider = nullptr; std::atomic gpu_thread_priority; std::atomic max_frame_latency; // The first-frame subset of SetFrameIntervalX/ScheduleFrameEventX/WaitFrameEventX. Tokens were never measured; @@ -1476,6 +1477,23 @@ HRESULT proxy_create_resource(DeviceProxy* self, const D3D12_HEAP_PROPERTIES* he "[rt] d3d12_xs: slot 76 resource: dimension=%d xbox layout=0x%x -> PC layout=0x%x\n", static_cast(pc_desc.Dimension), xbox_layout, static_cast(pc_desc.Layout)); } + constexpr auto depth_uav_flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + if (self->depth_stencil_uav_provider && (xbox_desc->Flags & depth_uav_flags) == depth_uav_flags && + pc_desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && pc_desc.Format == DXGI_FORMAT_R32G8X24_TYPELESS && + pc_desc.DepthOrArraySize == 1 && pc_desc.MipLevels == 1 && pc_desc.SampleDesc.Count == 1) { + pc_desc.Flags &= ~D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + // Only the color storage images need UAV access. The native depth image must be created in a legal PC state. + const auto depth_state = initial_state == D3D12_RESOURCE_STATE_UNORDERED_ACCESS + ? D3D12_RESOURCE_STATE_COMMON : initial_state; + ID3D12Resource* resource = nullptr; + HRESULT hr = self->real->CreateCommittedResource(heap_properties, heap_flags, &pc_desc, depth_state, + clear_value, IID_PPV_ARGS(&resource)); + if (FAILED(hr)) return hr; + hr = self->depth_stencil_uav_provider(resource); + if (SUCCEEDED(hr)) hr = resource->QueryInterface(*riid, out); + resource->Release(); + return hr; + } return self->real->CreateCommittedResource(heap_properties, heap_flags, &pc_desc, initial_state, clear_value, *riid, out); } @@ -1684,6 +1702,13 @@ bool set_device_adapter_provider(void* device, DxgiAdapterProvider provider) { return true; } +bool set_depth_stencil_uav_provider(void* device, DepthStencilUavProvider provider) { + auto* proxy = static_cast(device_proxy_primary(device)); + if (!proxy) return false; + proxy->depth_stencil_uav_provider = provider; + return true; +} + bool is_heap_proxy(const void* heap) { return heap && *reinterpret_cast(heap) == reinterpret_cast(get_heap_vtable()); } diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index 0019ec5069..fa4378cb53 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -74,6 +74,9 @@ bool is_device_proxy(const void* device); using DxgiAdapterProvider = HRESULT (*)(ID3D12Device* real, REFIID riid, void** out); // `device` is the proxy or its DXGI pointer. False, with a line on stderr, when it is neither: nothing is set then. bool set_device_adapter_provider(void* device, DxgiAdapterProvider provider); +// Called before publishing a slot-76 resource when the backend can implement the Xbox depth/stencil UAV views. +using DepthStencilUavProvider = HRESULT (*)(ID3D12Resource* resource); +bool set_depth_stencil_uav_provider(void* device, DepthStencilUavProvider provider); // The device proxy an IDXGIDevice pointer handed out by one belongs to, or null. void* device_proxy_from_dxgi_device(void* dxgi_device); // The device proxy itself, given the proxy or its DXGI pointer; null for anything else. diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index e659a762dc..91001de96e 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -1175,6 +1175,7 @@ class VulkanContext { } { std::lock_guard lock(storage_mutex_); // a buffer destroyed before any submission is not filled + storage_pending_.erase(id); std::erase_if(zero_pending_, [id](const PendingZero& zero) { return zero.id == id; }); } if (img) { @@ -1361,6 +1362,7 @@ class VulkanContext { // written: the device brings the bindless set 0 of the translated shaders up to date there (vulkan_bindless.h) // and records what the set needs first. When it fails, nothing of that call is executed. void set_transfer_only_family(std::uint32_t family) { transfer_only_family_ = family; } + void set_graphics_family(std::uint32_t family) { graphics_family_ = family; } void set_bindless_prepare(std::function prepare) { std::unique_lock lock(resource_mutex_); @@ -1687,6 +1689,7 @@ class VulkanContext { std::unique_ptr counted_dispatch_; std::uint32_t predicate_family_ = UINT32_MAX; std::uint32_t transfer_only_family_ = UINT32_MAX; + std::uint32_t graphics_family_ = UINT32_MAX; DebugLabelFunctions labels_; }; #ifdef _MSC_VER @@ -2201,6 +2204,7 @@ class VulkanQueue : private QueueHolds::Holder { // use only the first lists.size() entries, so stale entries are never prepared, queried or emitted. if (prepared.size() < lists.size()) prepared.resize(lists.size()); ReplayFunctions replay = context_.replay_; + replay.graphics_family = family_ == context_.graphics_family_; replay.queue_stages = kind_ == QueueKind::copy ? detail::queue_stages_copy : kind_ == QueueKind::compute ? detail::queue_stages_compute : 0; diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 7ed8d251a5..e334a945a1 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -94,6 +94,8 @@ struct ResourceBinding { bool sampled = false; // has SAMPLED usage (no DENY_SHADER_RESOURCE): the present compose pass reads it bool host_readable = false; // D3D12_HEAP_TYPE_READBACK (or CUSTOM write-back): needs host-read flush bool sparse_buffer = false; + // The two independently addressable storage images of an Xbox depth/stencil UAV. + ResourceId depth_uav = 0, stencil_uav = 0; }; struct VulkanAccess { @@ -810,6 +812,7 @@ struct ReplayFunctions { // Optional; a list that needs a missing one is rejected with ReplayResult::unsupported. PFN_vkCmdPipelineBarrier2 pipeline_barrier2 = nullptr; // enhanced barriers VkPipelineStageFlags2 queue_stages = 0; + bool graphics_family = true; // depth/stencil image-buffer transfers require a graphics-capable queue PFN_vkCmdBeginRendering begin_rendering = nullptr; // rectangle clears PFN_vkCmdEndRendering end_rendering = nullptr; PFN_vkCmdClearAttachments clear_attachments = nullptr; @@ -1021,12 +1024,30 @@ struct Prepared { QueryPool* queries = nullptr; // query commands: the heap ComputePipeline pipeline; // dispatches std::uint32_t draw = 0; // draws: its PreparedDraw in PreparedList::draws + std::uint32_t depth_uav_copy = UINT32_MAX; + bool order_depth_uav = false; VkAccelerationStructureKHR accel_dst = VK_NULL_HANDLE; VkDeviceAddress khr_instances = 0; // staged ARRAY_OF_POINTERS instance list for a KHR TLAS; 0: use the VA directly std::uint64_t xdxr_bytes = 0; // CopyAccelerationStructure: the most bytes the copy may write VkAccelerationStructureKHR accel_src = VK_NULL_HANDLE; }; +struct DepthUavCopy { + std::array storage; + VkBuffer scratch; + VkDeviceSize offset; + bool to_storage; +}; + +inline bool texture_uav_layout(std::uint32_t layout) { + return layout == d3d12_layout::unordered_access || layout == d3d12_layout::direct_queue_unordered_access || + layout == d3d12_layout::compute_queue_unordered_access; +} + +inline bool queue_common_layout(std::uint32_t layout) { + return layout == d3d12_layout::direct_queue_common || layout == d3d12_layout::compute_queue_common; +} + inline constexpr std::size_t max_render_targets = 8; // D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT // What a draw needs beyond Prepared, kept apart in PreparedList::draws: every command's entry is refilled on every @@ -1490,7 +1511,8 @@ inline void initialize(const ReplayFunctions& vk, VkCommandBuffer command_buffer if (piece.layout != VK_IMAGE_LAYOUT_UNDEFINED) continue; const BlockFormat fmt = block_format(resource.format, VK_IMAGE_ASPECT_COLOR_BIT); const bool color = piece.range.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT; - const bool can_clear = !vk.queue_stages || ((vk.queue_stages & VK_PIPELINE_STAGE_2_CLEAR_BIT) && color); + const bool can_clear = !vk.queue_stages || ((vk.queue_stages & VK_PIPELINE_STAGE_2_CLEAR_BIT) && color) || + (resource.depth_uav && vk.graphics_family); const bool compressed = fmt.block > 1 || (!can_clear && color); if (resource.not_zeroed || (!can_clear && !color)) { image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, layout, 0, @@ -2068,6 +2090,51 @@ void round_trip(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const } } +// Vulkan cannot copy a depth or stencil image aspect directly to or from a color image. The transfer +// buffer preserves the native D32 or S8 bits. Only the requested planes are copied, even when the device +// requires both parent aspects to transition layouts together. A storage descriptor always names GENERAL. +inline void copy_depth_uav(const ReplayFunctions& vk, VkCommandBuffer cb, const Prepared& p, const DepthUavCopy& copy, + VkImageLayout parent_layout, LayoutTracker* tracker) { + constexpr auto all = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; + constexpr auto transfer = VK_PIPELINE_STAGE_TRANSFER_BIT; + constexpr VkAccessFlags any = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; + const auto parent_access = copy.to_storage ? VK_ACCESS_TRANSFER_READ_BIT : VK_ACCESS_TRANSFER_WRITE_BIT; + const auto child_access = copy.to_storage ? VK_ACCESS_TRANSFER_WRITE_BIT : VK_ACCESS_TRANSFER_READ_BIT; + const auto parent_range = planes_for_layout(p.binding, p.range, vk.separate_depth_stencil_layouts); + image_barrier(vk, cb, p.binding, parent_range, parent_layout, VK_IMAGE_LAYOUT_GENERAL, + any, all, parent_access, transfer); + constexpr VkImageSubresourceRange color{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + for (unsigned plane = 0; plane < copy.storage.size(); ++plane) { + const ResourceBinding& child = copy.storage[plane]; + if (!child.image) continue; + const ResourceId child_id = plane ? p.binding.stencil_uav : p.binding.depth_uav; + auto pieces = current(tracker, child_id, color, VK_IMAGE_LAYOUT_GENERAL); + if (!copy.to_storage) initialize(vk, cb, child, child_id, pieces, VK_IMAGE_LAYOUT_GENERAL, tracker); + for (const auto& piece : pieces) + image_barrier(vk, cb, child, color, piece.layout, VK_IMAGE_LAYOUT_GENERAL, + piece.layout == VK_IMAGE_LAYOUT_UNDEFINED ? 0 : any, all, child_access, transfer); + if (tracker) tracker->set(child_id, color, VK_IMAGE_LAYOUT_GENERAL); + VkBufferImageCopy parent_region{}; + parent_region.bufferOffset = copy.offset; + const VkImageAspectFlags aspect = plane ? VK_IMAGE_ASPECT_STENCIL_BIT : VK_IMAGE_ASPECT_DEPTH_BIT; + parent_region.imageSubresource = {aspect, 0, 0, 1}; + parent_region.imageExtent = {p.binding.width, p.binding.height, 1}; + VkBufferImageCopy child_region = parent_region; + child_region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + // Last use of this staging range was a read by CopyBufferToImage, possibly on the previous barrier. + memory_barrier(vk, cb, VK_ACCESS_TRANSFER_READ_BIT, transfer, VK_ACCESS_TRANSFER_WRITE_BIT, transfer); + vk.copy_image_to_buffer(cb, copy.to_storage ? p.binding.image : child.image, VK_IMAGE_LAYOUT_GENERAL, + copy.scratch, 1, copy.to_storage ? &parent_region : &child_region); + memory_barrier(vk, cb, VK_ACCESS_TRANSFER_WRITE_BIT, transfer, VK_ACCESS_TRANSFER_READ_BIT, transfer); + vk.copy_buffer_to_image(cb, copy.scratch, copy.to_storage ? child.image : p.binding.image, VK_IMAGE_LAYOUT_GENERAL, + 1, copy.to_storage ? &child_region : &parent_region); + image_barrier(vk, cb, child, color, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL, + child_access, transfer, any, all); + } + image_barrier(vk, cb, p.binding, parent_range, VK_IMAGE_LAYOUT_GENERAL, parent_layout, + parent_access, transfer, any, all); +} + } // namespace detail namespace detail { @@ -2267,6 +2334,7 @@ class PreparedList { // The draws' own data, by Prepared::draw. Kept from one execution to the next like the PreparedList itself: the // first draw_count entries are this list's, and the rest keep their vectors' storage for later draws. std::vector draws; + std::vector depth_uav_copies; std::size_t draw_count = 0; std::vector queries; VkQueryPool segment_pool = VK_NULL_HANDLE; @@ -2526,6 +2594,12 @@ inline bool zero_clear_unavailable(const PreparedList& prepared, const ReplayFun }, command); if (missing(id, p.binding, p.range)) return true; + if (p.depth_uav_copy != UINT32_MAX) { + const auto& copy = prepared.depth_uav_copies[p.depth_uav_copy]; + constexpr VkImageSubresourceRange color{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + if (!copy.to_storage && (missing(p.binding.depth_uav, copy.storage[0], color) || + missing(p.binding.stencil_uav, copy.storage[1], color))) return true; + } } return false; } @@ -2543,6 +2617,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun out.list = &list; out.commands.assign(commands.size(), {}); out.draw_count = 0; + out.depth_uav_copies.clear(); out.queries.clear(); out.segment_pool = VK_NULL_HANDLE; out.segment_base = out.segment_count = 0; @@ -2572,6 +2647,43 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun out.wrote_readback = false; out.readback_src_stages = 0; + // Successive plane transfers use the same transient range and order their buffer accesses in emit(). + VkBuffer plane_scratch = VK_NULL_HANDLE; + VkDeviceSize plane_capacity = 0, plane_offset = 0; + const auto prepare_depth_uav = [&](detail::Prepared& p, bool before, bool after) { + if (!p.binding.depth_uav && !p.binding.stencil_uav) return ReplayResult::success; + if (before == after) { + p.order_depth_uav = after; + return ReplayResult::success; + } + if (!vk.graphics_family || !vk.copy_image_to_buffer || !vk.copy_buffer_to_image || !vk.copy_scratch) + return ReplayResult::unsupported; + detail::DepthUavCopy copy{}; + const ResourceId ids[] = {p.binding.depth_uav, p.binding.stencil_uav}; + for (unsigned plane = 0; plane < 2; ++plane) { + const auto aspect = plane ? VK_IMAGE_ASPECT_STENCIL_BIT : VK_IMAGE_ASPECT_DEPTH_BIT; + if (!(p.range.aspectMask & aspect)) continue; + const auto* child = resolve(ids[plane]); + if (!child || !child->image) return ReplayResult::unresolved_resource; + copy.storage[plane] = *child; + } + const VkDeviceSize texels = VkDeviceSize(p.binding.width) * p.binding.height; + const VkDeviceSize bytes_per_texel = p.range.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT ? 4 : 1; + if (!texels || texels > UINT64_MAX / bytes_per_texel) return ReplayResult::unsupported; + const VkDeviceSize bytes = texels * bytes_per_texel; + if (bytes > plane_capacity) { + if (!vk.copy_scratch(bytes, plane_scratch, plane_offset) || !plane_scratch || plane_offset % 4) + return ReplayResult::unsupported; + plane_capacity = bytes; + } + copy.scratch = plane_scratch; + copy.offset = plane_offset; + copy.to_storage = after; + p.depth_uav_copy = static_cast(out.depth_uav_copies.size()); + out.depth_uav_copies.push_back(copy); + return ReplayResult::success; + }; + for (std::size_t i = 0; i < commands.size(); ++i) { const auto& command = commands[i]; auto& p = out.commands[i]; @@ -2609,6 +2721,9 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun } else if (!image_range(p.binding, transition->subresource, p.range)) { return ReplayResult::invalid_subresource; } + const auto result = prepare_depth_uav(p, transition->before & d3d12_state::unordered_access, + transition->after & d3d12_state::unordered_access); + if (result != ReplayResult::success) return result; } else if (std::holds_alternative(command) || std::holds_alternative(command)) { if (!vk.pipeline_barrier2) return ReplayResult::unsupported; if (const auto* buffer_barrier = std::get_if(&command)) @@ -2618,6 +2733,17 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!bind(texture->resource)) return ReplayResult::unresolved_resource; if (!p.binding.image || !barrier_range(p.binding, texture->range, p.range)) return ReplayResult::invalid_subresource; + // In a queue-specific COMMON layout shaders can write a UAV then read the SRV or copy the + // parent after only a global barrier. Bindless shaders need no per-resource bind command, so + // there is no observable ownership transition at which to synchronize the two images. + if (p.binding.depth_uav && (detail::queue_common_layout(texture->layout_before) || + detail::queue_common_layout(texture->layout_after))) + return ReplayResult::unsupported; + if (!(texture->flags & texture_barrier_discard) && texture->layout_before != d3d12_layout::undefined) { + const auto result = prepare_depth_uav(p, detail::texture_uav_layout(texture->layout_before), + detail::texture_uav_layout(texture->layout_after)); + if (result != ReplayResult::success) return result; + } } else if (const auto* color_clear = std::get_if(&command)) { if (!bind(color_clear->target.resource)) return ReplayResult::unresolved_resource; if (!p.binding.image || p.binding.aspects != VK_IMAGE_ASPECT_COLOR_BIT) return ReplayResult::invalid_clear; @@ -3363,6 +3489,15 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c vk.depth24_run(command_buffer, job); if (predicate.buffer) vk.begin_conditional_rendering(command_buffer, &predicate); }; + const auto finish_depth_uav_barrier = [&](const detail::Prepared& p, VkImageLayout layout) { + if (p.depth_uav_copy != UINT32_MAX) { + detail::copy_depth_uav(vk, command_buffer, p, prepared.depth_uav_copies[p.depth_uav_copy], layout, tracker); + } else if (p.order_depth_uav) { + // A UAV-to-UAV texture barrier names the parent, but the actual shader accesses target its children. + detail::memory_barrier(vk, command_buffer, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); + } + }; for (std::size_t i = 0; i < commands.size(); ++i) { const auto& command = commands[i]; @@ -3430,6 +3565,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c detail::image_barrier(vk, command_buffer, p.binding, piece.range, piece.layout, new_layout, from.access, from.stages, to.access, to.stages); if (tracker) tracker->set(id, range, new_layout); + finish_depth_uav_barrier(p, new_layout); } else if (std::holds_alternative(command)) { const VulkanAccess uav = vulkan_access(d3d12_state::unordered_access, false); VkAccessFlags src_access = VK_ACCESS_SHADER_WRITE_BIT; @@ -3446,7 +3582,10 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c detail::memory_barrier(vk, command_buffer, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); - } else if (std::holds_alternative(command) || std::holds_alternative(command)) { + } else if (const auto* texture_memory = std::get_if(&command); + std::holds_alternative(command) || std::holds_alternative(command) || + (texture_memory && p.binding.depth_uav && texture_memory->layout_before == d3d12_layout::undefined && + texture_memory->layout_after == d3d12_layout::undefined)) { const auto [sync_before, sync_after, access_before, access_after] = std::visit( [](const auto& c) -> std::array { if constexpr (requires { c.sync_before; }) @@ -3475,10 +3614,13 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c const VkImageLayout new_layout = image_layout(p.binding, vulkan_layout(texture->layout_after, p.binding.presentable)); LayoutPieces pieces; - if (discard) + // With coupled layouts, discarding a single plane must preserve the other plane's data. + const bool keep_sibling = p.binding.depth_uav && range.aspectMask != p.range.aspectMask; + if (discard && !keep_sibling) pieces.push_back({range, VK_IMAGE_LAYOUT_UNDEFINED}); else { const VkImageLayout before = + 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); detail::initialize(vk, command_buffer, p.binding, id, pieces, before, tracker); @@ -3512,6 +3654,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c dependency.pImageMemoryBarriers = barriers; vk.pipeline_barrier2(command_buffer, &dependency); if (tracker) tracker->set(id, range, new_layout); + finish_depth_uav_barrier(p, new_layout); } else if (const auto* color_clear = std::get_if(&command)) { if (p.skip) continue; const VulkanAccess state = vulkan_access(d3d12_state::render_target, false); diff --git a/runtime/test/d3d12_depth_stencil_uav_test.cpp b/runtime/test/d3d12_depth_stencil_uav_test.cpp new file mode 100644 index 0000000000..cc47031a3c --- /dev/null +++ b/runtime/test/d3d12_depth_stencil_uav_test.cpp @@ -0,0 +1,281 @@ +// Xbox slot 76, a compute dispatch through the Vulkan backend, and separate depth/stencil readbacks. +// A synthetic compute shader looks up the T#s that the device writes. No game data. +#include "d3d12_copy_compare.h" +#include "d3d12_test_shaders.h" +#include "shader_fixture_path.h" +#include "test_temp_dir.h" +#include "vk_test_device.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/shader_library.h" + +#include +#include +#include + +#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #x); return 1; } } while (0) + +namespace { +using d3d12test::Ref; + +void enhanced_transition(ID3D12GraphicsCommandList7* list, ID3D12Resource* texture, + D3D12_BARRIER_SYNC before_sync, D3D12_BARRIER_ACCESS before_access, + D3D12_BARRIER_LAYOUT before_layout, D3D12_BARRIER_SYNC after_sync, + D3D12_BARRIER_ACCESS after_access, D3D12_BARRIER_LAYOUT after_layout) { + D3D12_TEXTURE_BARRIER barrier{}; + barrier.SyncBefore = before_sync; + barrier.AccessBefore = before_access; + barrier.LayoutBefore = before_layout; + barrier.SyncAfter = after_sync; + barrier.AccessAfter = after_access; + barrier.LayoutAfter = after_layout; + barrier.Subresources = {D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, 0, 0, 0, 0, 0}; + barrier.pResource = texture; + D3D12_BARRIER_GROUP group{}; + group.Type = D3D12_BARRIER_TYPE_TEXTURE; + group.NumBarriers = 1; + group.pTextureBarriers = &barrier; + list->Barrier(1, &group); +} + +int run(vktest::Device& vk, UINT width, UINT height, bool enhanced) { + const auto program = d3d12test::fssm_program({0x44535541, 0xbf810000}); + const auto shader = d3d12test::shader_container(program); + const testfiles::ScratchDir library("leonida_depth_stencil_uav"); + CHECK(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_DEPTH_UAV_SPV), library.path() / "write.spv")); + { + std::ofstream index(library.path() / "index.json", std::ios::binary); + index << "{\"write\":{\"stage\":\"cs\",\"fssm_sha256\":\"" << leonida::sha256_hex(program) + << "\",\"bindings\":[2,8,9],\"push_constant_bytes\":80,\"local_size\":[1,1,1],\"wave64\":false}}"; + CHECK(index.good()); + } + + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = vk.instance_proc; + info.instance = vk.instance; + info.physical = vk.physical; + info.device = vk.device; + info.queue = vk.queue; + info.queue_family = vk.family; + info.bindless = vk.bindless; + info.bindless_partially_bound = vk.partially_bound; + info.buffer_device_address = vk.buffer_device_address; + info.shader_dir = library.path().string(); + ID3D12Device* device = nullptr; + CHECK(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device)))); + Ref xbox; + CHECK(SUCCEEDED(rt::d3d12_xs::create_device_proxy(device, IID_PPV_ARGS(&xbox.p)))); // takes ownership + rt::d3d12::set_device_outer(device, xbox.p); + + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = width; + desc.Height = height; + desc.MipLevels = desc.DepthOrArraySize = 1; + desc.SampleDesc.Count = 1; + desc.Format = DXGI_FORMAT_R32G8X24_TYPELESS; + desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + desc.Layout = static_cast(0x101); + using CreateFn = HRESULT(WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS, + const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_STATES, const D3D12_CLEAR_VALUE*, + REFIID, void**); + // The Xbox slot-25 sizing path from #7110/#7679 is covered on the Forge integration branch. + // Use the inner PC device's native depth description for allocation size and readback footprints. + auto native_depth = desc; + native_depth.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + native_depth.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + const auto size = device->GetResourceAllocationInfo(0, 1, &native_depth); + CHECK(size.SizeInBytes > 0 && size.SizeInBytes != UINT64_MAX); + D3D12_HEAP_PROPERTIES props{}; + props.Type = D3D12_HEAP_TYPE_DEFAULT; + Ref texture; + const auto create_texture = reinterpret_cast(d3d12test::slot(xbox.p, 76)); + CHECK(SUCCEEDED(create_texture(xbox.p, &props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_DEPTH_WRITE, + nullptr, IID_PPV_ARGS(&texture.p)))); + CHECK(texture->GetDesc().Flags == desc.Flags); + + const D3D12_DESCRIPTOR_HEAP_DESC dsv_desc{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + const D3D12_DESCRIPTOR_HEAP_DESC views_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4, + D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + Ref dsv, views; + CHECK(SUCCEEDED(device->CreateDescriptorHeap(&dsv_desc, IID_PPV_ARGS(&dsv.p)))); + CHECK(SUCCEEDED(device->CreateDescriptorHeap(&views_desc, IID_PPV_ARGS(&views.p)))); + D3D12_DEPTH_STENCIL_VIEW_DESC depth_view{}; + depth_view.Format = DXGI_FORMAT_D32_FLOAT_S8X24_UINT; + depth_view.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D; + const auto depth_handle = dsv->GetCPUDescriptorHandleForHeapStart(); + device->CreateDepthStencilView(texture.p, &depth_view, depth_handle); + const SIZE_T base = views->GetCPUDescriptorHandleForHeapStart().ptr; + const SIZE_T step = device->GetDescriptorHandleIncrementSize(views_desc.Type); + CHECK(base && step >= 32); + std::uint32_t keys[2][8]{}; + for (UINT plane = 0; plane < 2; ++plane) { + D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; + view.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; + view.Format = plane == 0 ? DXGI_FORMAT_R32_FLOAT : DXGI_FORMAT_R8_UINT; + view.Texture2D.PlaneSlice = plane; + const D3D12_CPU_DESCRIPTOR_HANDLE handle{base + plane * step}; + device->CreateUnorderedAccessView(texture.p, nullptr, &view, handle); + std::memcpy(keys[plane], reinterpret_cast(handle.ptr), sizeof(keys[plane])); + CHECK(rt::d3d12::bindless_hash_lookup(device, keys[plane]) != 0); + } + CHECK(std::memcmp(keys[0], keys[1], sizeof(keys[0])) != 0); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Texture2D.MipLevels = 1; + const D3D12_CPU_DESCRIPTOR_HANDLE sampled{base + 2 * step}; + device->CreateShaderResourceView(texture.p, &srv, sampled); + std::uint32_t sampled_key[8]{}; + std::memcpy(sampled_key, reinterpret_cast(sampled.ptr), sizeof(sampled_key)); + CHECK(rt::d3d12::bindless_hash_lookup(device, sampled_key) != 0); + CHECK(std::memcmp(sampled_key, keys[0], sizeof(sampled_key)) != 0); + const D3D12_CPU_DESCRIPTOR_HANDLE invalid{base + 3 * step}; + std::uint32_t zero[8]{}; + for (UINT plane = 0; plane < 2; ++plane) { + std::memset(reinterpret_cast(invalid.ptr), 0x55, sizeof(zero)); + D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; + view.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; + view.Texture2D.PlaneSlice = plane; + view.Format = plane == 0 ? DXGI_FORMAT_R8_UINT : DXGI_FORMAT_R32_FLOAT; + device->CreateUnorderedAccessView(texture.p, nullptr, &view, invalid); + CHECK(std::memcmp(reinterpret_cast(invalid.ptr), zero, sizeof(zero)) == 0); + } + + // ClearUAV takes matching handles to two copies of the descriptor and the original Xbox resource. + const D3D12_DESCRIPTOR_HEAP_DESC visible_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + Ref visible; + CHECK(SUCCEEDED(device->CreateDescriptorHeap(&visible_desc, IID_PPV_ARGS(&visible.p)))); + device->CopyDescriptorsSimple(2, visible->GetCPUDescriptorHandleForHeapStart(), {base}, visible_desc.Type); + const auto gpu = visible->GetGPUDescriptorHandleForHeapStart(); + const FLOAT depth_clear[] = {0.75f, 0, 0, 0}; + const UINT stencil_clear[] = {0x31, 0, 0, 0}; + { + // Both parents have a real R32_FLOAT storage plane, but this T# belongs to the first parent only. + auto other_desc = desc; + other_desc.Width = other_desc.Height = 2; + Ref other; + CHECK(SUCCEEDED(create_texture(xbox.p, &props, D3D12_HEAP_FLAG_NONE, &other_desc, + D3D12_RESOURCE_STATE_DEPTH_WRITE, nullptr, IID_PPV_ARGS(&other.p)))); + copycmp::Run rejected; + CHECK(rejected.init(device, true)); + rejected.begin(); + rejected.barrier(other.p, D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + ID3D12DescriptorHeap* heaps[] = {visible.p}; + rejected.list->SetDescriptorHeaps(1, heaps); + rejected.list->ClearUnorderedAccessViewFloat(gpu, {base}, other.p, depth_clear, 0, nullptr); + CHECK(rejected.list->Close() == E_INVALIDARG); + } + + D3D12_ROOT_PARAMETER param{}; + param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + param.Constants.Num32BitValues = 16; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC rs{}; + rs.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + rs.Desc_1_0 = {1, ¶m, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + const auto root_blob = d3d12test::serialize_root_signature(rs); + Ref root; + CHECK(!root_blob.empty()); + CHECK(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p)))); + D3D12_COMPUTE_PIPELINE_STATE_DESC pipeline_desc{}; + pipeline_desc.pRootSignature = root.p; + pipeline_desc.CS = {shader.data(), shader.size()}; + Ref pipeline; + CHECK(SUCCEEDED(device->CreateComputePipelineState(&pipeline_desc, IID_PPV_ARGS(&pipeline.p)))); + + copycmp::Run commands; + CHECK(commands.init(device, true)); + D3D12_PLACED_SUBRESOURCE_FOOTPRINT layouts[2]{}; + UINT64 row_bytes[2]{}, total = 0; + device->GetCopyableFootprints(&native_depth, 0, 2, 0, layouts, nullptr, row_bytes, &total); + CHECK(row_bytes[0] == width * sizeof(float) && row_bytes[1] == width); + copycmp::Ptr readback; + CHECK(commands.buffer(D3D12_HEAP_TYPE_READBACK, total, D3D12_RESOURCE_STATE_COPY_DEST, readback)); + + commands.begin(); + commands.list->ClearDepthStencilView(depth_handle, D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, + 0.5f, 0x5a, 0, nullptr); + Ref enhanced_list; + if (enhanced) { + CHECK(SUCCEEDED(commands.list->QueryInterface(IID_PPV_ARGS(&enhanced_list.p)))); + enhanced_transition(enhanced_list.p, texture.p, D3D12_BARRIER_SYNC_DEPTH_STENCIL, + D3D12_BARRIER_ACCESS_DEPTH_STENCIL_WRITE, D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE, + D3D12_BARRIER_SYNC_COMPUTE_SHADING, D3D12_BARRIER_ACCESS_UNORDERED_ACCESS, + D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS); + } else { + commands.barrier(texture.p, D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + } + const D3D12_RECT depth_rect{1, 3, 2, 4}, stencil_rect{3, 2, 4, 3}; + ID3D12DescriptorHeap* clear_heaps[] = {visible.p}; + commands.list->SetDescriptorHeaps(1, clear_heaps); + commands.list->ClearUnorderedAccessViewFloat(gpu, {base}, texture.p, depth_clear, 1, &depth_rect); + commands.list->ClearUnorderedAccessViewUint({gpu.ptr + step}, {base + step}, texture.p, stencil_clear, 1, + &stencil_rect); + D3D12_RESOURCE_BARRIER uav_order{}; + uav_order.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + uav_order.UAV.pResource = texture.p; + commands.list->ResourceBarrier(1, &uav_order); + commands.list->SetComputeRootSignature(root.p); + commands.list->SetPipelineState(pipeline.p); + commands.list->SetComputeRoot32BitConstants(0, 16, keys, 0); + commands.list->Dispatch(1, 1, 1); + if (enhanced) { + enhanced_transition(enhanced_list.p, texture.p, D3D12_BARRIER_SYNC_COMPUTE_SHADING, + D3D12_BARRIER_ACCESS_UNORDERED_ACCESS, D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS, + D3D12_BARRIER_SYNC_COPY, D3D12_BARRIER_ACCESS_COPY_SOURCE, D3D12_BARRIER_LAYOUT_COPY_SOURCE); + } else { + commands.barrier(texture.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + } + for (UINT plane = 0; plane < 2; ++plane) { + D3D12_TEXTURE_COPY_LOCATION src{}, dst{}; + src.pResource = texture.p; + src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + src.SubresourceIndex = plane; + dst.pResource = readback.p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = layouts[plane]; + commands.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + } + const auto error = commands.submit(); + if (!error.empty()) { std::fprintf(stderr, "%s\n", error.c_str()); return 1; } + + unsigned char* mapped = nullptr; + CHECK(SUCCEEDED(readback.p->Map(0, nullptr, reinterpret_cast(&mapped))) && mapped); + for (UINT y = 0; y < height; ++y) { + for (UINT x = 0; x < width; ++x) { + float depth = 0.0f; + std::memcpy(&depth, mapped + layouts[0].Offset + y * layouts[0].Footprint.RowPitch + x * sizeof(float), + sizeof(depth)); + const auto stencil = mapped[layouts[1].Offset + y * layouts[1].Footprint.RowPitch + x]; + float expected_depth = x == 2 && y == 1 ? 0.125f : 0.5f; + unsigned expected_stencil = x == 5 && y == 3 ? 0xa5 : 0x5a; + if (x == UINT(depth_rect.left) && y == UINT(depth_rect.top)) expected_depth = depth_clear[0]; + if (x == UINT(stencil_rect.left) && y == UINT(stencil_rect.top)) expected_stencil = stencil_clear[0]; + if (depth != expected_depth || stencil != expected_stencil) { + std::fprintf(stderr, "(%u,%u): depth %g, stencil %#x\n", x, y, depth, unsigned(stencil)); + readback.p->Unmap(0, nullptr); + return 1; + } + } + } + readback.p->Unmap(0, nullptr); + std::printf("depth/stencil UAV: %s barriers, %ux%u, read back all %u pixels on each plane\n", + enhanced ? "enhanced" : "legacy", width, height, width * height); + return 0; +} +} // namespace + +int main() { + vktest::Device vk; + vk.request_buffer_device_address = true; + const auto status = vk.initialize(); + if (status == vktest::DeviceStatus::unavailable) return 77; + if (status != vktest::DeviceStatus::ready) return 1; + if (!vk.bindless || !vk.storage_image_extended_formats) { + std::fprintf(stderr, "SKIP: shader requires bindless images and typed r8ui storage\n"); + return 77; + } + if (run(vk, 9, 7, false) || run(vk, 2560, 1440, true)) return 1; + return vk.validation_errors() ? 1 : 0; +} diff --git a/runtime/test/device_proxy_test.cpp b/runtime/test/device_proxy_test.cpp index 46a853e7c3..00c5462dff 100644 --- a/runtime/test/device_proxy_test.cpp +++ b/runtime/test/device_proxy_test.cpp @@ -324,6 +324,22 @@ int main(int argc, char** argv) { check(rt::d3d12_xs::device_slot_hits(76) == 2, "slot 76 hit counter is 2"); check(rt::d3d12_xs::device_slot_first_call_seen(76), "slot 76 first-call flag is set"); + // A backend can run out of memory after allocating the native depth image. Slot 76 must propagate that + // failure without handing a depth-only resource to a caller that requested a working UAV. + { + auto ds_uav = xbox_texture; + ds_uav.Format = DXGI_FORMAT_R32G8X24_TYPELESS; + ds_uav.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + check(rt::d3d12_xs::set_depth_stencil_uav_provider(device.Get(), [](ID3D12Resource*) -> HRESULT { + return E_OUTOFMEMORY; + }), "install a failing Xbox storage-image provider"); + void* result = reinterpret_cast(1); + hr = create_resource(device.Get(), &heap_properties, D3D12_HEAP_FLAG_NONE, &ds_uav, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, iid_resource, &result); + check(hr == E_OUTOFMEMORY && !result, "slot 76 propagates storage-image allocation failure atomically"); + rt::d3d12_xs::set_depth_stencil_uav_provider(device.Get(), nullptr); + } + // Xbox device slots from the public HLE. On the Vulkan device the PC entries at 78/79 are // CreateReservedResource2/CreateSampler2 and 80 is past the 80-slot table, so success here can only come from // the routes: frame events return S_OK and a fresh token, CreateCommandQueueX returns a queue proxy and diff --git a/runtime/test/glsl/cs_depth_stencil_uav.comp b/runtime/test/glsl/cs_depth_stencil_uav.comp new file mode 100644 index 0000000000..bd5e9ca2b6 --- /dev/null +++ b/runtime/test/glsl/cs_depth_stencil_uav.comp @@ -0,0 +1,30 @@ +#version 460 +#extension GL_EXT_nonuniform_qualifier : require + +// The two T#s are passed as root constants in s4..s19, exactly as written by CreateUnorderedAccessView. +layout(local_size_x = 1) in; +layout(push_constant) uniform UserData { uint s[20]; } pc; +layout(set = 0, binding = 2, std430) readonly buffer DescriptorMap { uint words[]; }; +layout(set = 0, binding = 8, r32f) uniform image2D depths[]; +layout(set = 0, binding = 9, r8ui) uniform uimage2D stencils[]; + +uint lookup(uint first) { + uint hash = 2166136261u; + for (uint i = 0; i < 8; ++i) hash = (hash ^ pc.s[first + i]) * 16777619u; + for (uint probe = 0; probe < 8; ++probe) { + uint slot = 1 + ((hash + probe) & words[0]) * 10; + bool equal = true; + for (uint i = 0; i < 8; ++i) equal = equal && words[slot + i] == pc.s[first + i]; + if (equal) return words[slot + 8]; + } + return 0; +} + +void main() { + // Read before writing. A stale copy (or writing back the wrong plane) changes the expected bytes. + uint depth = lookup(4), stencil = lookup(12); + float before = imageLoad(depths[depth], ivec2(2, 1)).r; + uint mask = imageLoad(stencils[stencil], ivec2(5, 3)).r; + imageStore(depths[depth], ivec2(2, 1), vec4(before * 0.25)); + imageStore(stencils[stencil], ivec2(5, 3), uvec4(mask ^ 0xffu)); +} diff --git a/runtime/test/replay_texture_barrier_test.cpp b/runtime/test/replay_texture_barrier_test.cpp index 66c594779e..83c5111bf1 100644 --- a/runtime/test/replay_texture_barrier_test.cpp +++ b/runtime/test/replay_texture_barrier_test.cpp @@ -61,9 +61,11 @@ using namespace leonida; // measured emit, so that the record itself does not allocate there. std::vector g_barriers; std::uint32_t g_calls = 0; +std::uint32_t g_memory = 0; void VKAPI_CALL record_barrier2(VkCommandBuffer, const VkDependencyInfo* info) { ++g_calls; + g_memory += info->memoryBarrierCount; for (std::uint32_t i = 0; i < info->imageMemoryBarrierCount; ++i) g_barriers.push_back(info->pImageMemoryBarriers[i]); } @@ -76,6 +78,108 @@ void expect(bool ok, const char* what) { } } +// Run a stencil-only round trip with coupled depth/stencil layouts. Vulkan transitions both aspects +// together on this device, but the data transfer must never read or write the sibling depth plane. +void depth_uav_barriers(VkCommandBuffer cb) { + namespace y = d3d12_sync; + namespace a = d3d12_access; + namespace l = d3d12_layout; + std::array resources{}; + auto& parent = resources[1]; + parent.aspects = depth_stencil_aspects; + parent.format = VK_FORMAT_D32_SFLOAT_S8_UINT; + parent.depth_uav = 2; + parent.stencil_uav = 3; + resources[2].format = VK_FORMAT_R32_SFLOAT; + resources[3].format = VK_FORMAT_R8_UINT; + LayoutTracker tracker; + for (ResourceId i = 1; i <= 3; ++i) { + auto& r = resources[i]; + r.image = reinterpret_cast(std::uintptr_t(i)); + r.width = 5; + r.height = 7; + tracker.track(i, r, VK_IMAGE_LAYOUT_GENERAL); + } + const auto resolve = [&](ResourceId id) -> const ResourceBinding* { + return id && id < resources.size() ? &resources[id] : nullptr; + }; + struct Access { VkImage image; VkImageAspectFlags aspect; bool read; }; + static std::vector accesses; + accesses.clear(); + ReplayFunctions vk{}; + vk.pipeline_barrier2 = record_barrier2; + vk.pipeline_barrier = [](VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags, VkDependencyFlags, + std::uint32_t, const VkMemoryBarrier*, std::uint32_t, const VkBufferMemoryBarrier*, + std::uint32_t, const VkImageMemoryBarrier*) {}; + vk.copy_image_to_buffer = [](VkCommandBuffer, VkImage image, VkImageLayout, VkBuffer, std::uint32_t, + const VkBufferImageCopy* region) { + accesses.push_back({image, region->imageSubresource.aspectMask, true}); + }; + vk.copy_buffer_to_image = [](VkCommandBuffer, VkBuffer, VkImage image, VkImageLayout, std::uint32_t, + const VkBufferImageCopy* region) { + accesses.push_back({image, region->imageSubresource.aspectMask, false}); + }; + const BarrierSubresourceRange stencil{1, 0, 0, 0, 0, 0}; + const BarrierSubresourceRange all_planes{all_subresources, 0, 0, 0, 0, 0}; + g_barriers.clear(); + g_memory = 0; + CommandList list; + expect(list.barrier(TextureBarrier{y::depth_stencil, y::all, a::depth_stencil_write, a::common, + l::undefined, l::undefined, 1, all_planes, 0}) && + list.barrier(TextureBarrier{y::depth_stencil, y::compute_shading, a::depth_stencil_write, a::unordered_access, + l::depth_stencil_write, l::unordered_access, 1, stencil, 0}) && + list.barrier(TextureBarrier{y::compute_shading, y::all, a::unordered_access, a::shader_resource, + l::unordered_access, l::generic_read, 1, stencil, 0}) && + list.barrier(TextureBarrier{y::all, y::copy, a::shader_resource, a::copy_source, + l::generic_read, l::common, 1, stencil, 0}) && list.close(), + "record DSV to stencil UAV then copy source"); + std::uint32_t allocations = 0; + vk.copy_scratch = [&](VkDeviceSize size, VkBuffer& out, VkDeviceSize& offset) { + expect(size == parent.width * parent.height, "stencil scratch holds one byte per texel"); + ++allocations; + out = reinterpret_cast(std::uintptr_t(0x10)); + offset = 0; + return true; + }; + PreparedList prepared; + vk.graphics_family = false; + expect(prepare(list, resolve, vk, prepared) == ReplayResult::unsupported && !allocations, + "reject depth/stencil transfers on a non-graphics family before scratch allocation"); + vk.graphics_family = true; + // A global memory barrier in a queue-specific COMMON layout can switch accesses from a shader write + // on the child to a copy or sample on the parent without a texture layout transition. + for (const auto layout : {l::direct_queue_common, l::compute_queue_common}) { + CommandList implicit; + expect(implicit.barrier(TextureBarrier{y::copy, y::compute_shading, a::copy_dest, a::unordered_access, + l::copy_dest, layout, 1, all_planes, 0}) && + implicit.barrier(GlobalBarrier{y::compute_shading, y::copy, a::unordered_access, a::copy_source}) && + implicit.close(), "record queue-specific COMMON and a global dependency"); + expect(prepare(implicit, resolve, vk, prepared) == ReplayResult::unsupported && !allocations, + "reject ambiguous queue-specific COMMON at prepare"); + } + if (prepare(list, resolve, vk, prepared) != ReplayResult::success) { + expect(false, "prepare stencil transfers"); + return; + } + emit(prepared, cb, vk, &tracker); + expect(g_memory == 1 && !g_barriers.empty() && g_barriers.front().oldLayout == VK_IMAGE_LAYOUT_GENERAL && + std::none_of(g_barriers.begin(), g_barriers.end(), [](const auto& b) { return b.newLayout == VK_IMAGE_LAYOUT_UNDEFINED; }), + "UNDEFINED to UNDEFINED only orders memory and preserves both data and tracked layouts"); + expect(allocations == 1 && accesses.size() == 4, "reuse one staging range across both stencil transitions"); + if (accesses.size() == 4) { + expect(accesses[0].read && accesses[0].image == parent.image && accesses[0].aspect == VK_IMAGE_ASPECT_STENCIL_BIT && + !accesses[1].read && accesses[1].image == resources[3].image && accesses[1].aspect == VK_IMAGE_ASPECT_COLOR_BIT && + accesses[2].read && accesses[2].image == resources[3].image && accesses[2].aspect == VK_IMAGE_ASPECT_COLOR_BIT && + !accesses[3].read && accesses[3].image == parent.image && accesses[3].aspect == VK_IMAGE_ASPECT_STENCIL_BIT, + "stencil only moves through the R8 storage image in both directions"); + } + expect(tracker.layout(1, 0) == VK_IMAGE_LAYOUT_GENERAL && + tracker.layout(1, 1) == VK_IMAGE_LAYOUT_GENERAL && + tracker.layout(3, 0) == VK_IMAGE_LAYOUT_GENERAL, "coupled parent and independently tracked storage layouts"); + vk.copy_scratch = [](VkDeviceSize, VkBuffer&, VkDeviceSize&) { return false; }; + expect(prepare(list, resolve, vk, prepared) == ReplayResult::unsupported, "scratch failure refuses the list"); +} + } // namespace int main() { @@ -170,6 +274,7 @@ int main() { } } + depth_uav_barriers(cb); 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 949e5abfba..db042bac56 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h @@ -104,6 +104,7 @@ class Device { bool sampler_filter_minmax = false; bool vertex_attribute_divisor = false; bool storage_buffer_8bit = false; // storageBuffer8BitAccess enabled + bool storage_image_extended_formats = false; // typed r8ui storage images bool conditional_rendering = false; // VK_EXT_conditional_rendering enabled, where available bool host_image_copy = false; // VK_EXT_host_image_copy and hostImageCopy enabled // create(true) only: VK_KHR (else EXT) swapchain_maintenance1 and its feature enabled, with the surface half on the @@ -425,6 +426,8 @@ class Device { sharing_.push_back(f); } VkPhysicalDeviceFeatures enable{}; + storage_image_extended_formats = features.features.shaderStorageImageExtendedFormats == VK_TRUE; + enable.shaderStorageImageExtendedFormats = storage_image_extended_formats; enable.textureCompressionBC = features.features.textureCompressionBC; // BC uploads, where available enable.shaderInt64 = features.features.shaderInt64; // translated shaders declare Int64 (index features) bc = features.features.textureCompressionBC == VK_TRUE; From 237f9e0ba83c8b8e740dd7bcc0e10d311fddb897 Mon Sep 17 00:00:00 2001 From: Mumogg <104529023+Mumogg@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:20:43 -0600 Subject: [PATCH 024/110] local: diagnostics (draw/present/clear/rect state), rect experiments --- runtime/shims/d3d12_com.cpp | 12 +++ runtime/shims/d3d12_vulkan_device.cpp | 77 +++++++++++++++++ runtime/shims/d3d12_xs_device.cpp | 7 ++ runtime/shims/xbox_present.cpp | 10 +++ runtime/src/vulkan_backend.h | 6 ++ runtime/src/vulkan_replay.h | 120 ++++++++++++++++++-------- 6 files changed, 198 insertions(+), 34 deletions(-) diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index e1408d281c..ca28ac6da8 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -1,3 +1,4 @@ +#include #include "d3d12_com.h" #include "d3d12_stubs.h" // generated @@ -698,6 +699,17 @@ class GraphicsCommandList final d3d12_trace::record("ID3D12GraphicsCommandList::ClearRenderTargetView"); if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); if (!view.ptr || !color) return check(false); + // LOCAL DIAGNOSTIC: LEONIDA_DEBUG_CLEAR=1 clears to magenta; the first clears are logged. + static const bool magenta = [] { const char* v = std::getenv("LEONIDA_DEBUG_CLEAR"); return v && *v == '1'; }(); + const auto* target = reinterpret_cast(view.ptr); + static std::atomic shown{0}; + if (shown.fetch_add(1, std::memory_order_relaxed) < 6) + std::fprintf(stderr, "[rt] localdbg: clear resource=0x%llx colour=%g %g %g %g rects=%u\n", + static_cast(target->resource), color[0], color[1], color[2], color[3], count); + if (magenta) { + check(list_.clear_render_target(*target, {1.0f, 0.0f, 1.0f, 1.0f}, to_rects(count, rects))); + return; + } check(list_.clear_render_target(*reinterpret_cast(view.ptr), {color[0], color[1], color[2], color[3]}, to_rects(count, rects))); } diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 6c2e9d7bd8..95fb1187df 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -3745,6 +3745,16 @@ class PipelineState final : VK_CULL_MODE_NONE; // With the negative-height viewport, framebuffer winding matches D3D12's screen-space winding. raster.frontFace = r.FrontCounterClockwise ? VK_FRONT_FACE_COUNTER_CLOCKWISE : VK_FRONT_FACE_CLOCKWISE; + // LOCAL EXPERIMENT: LEONIDA_RECT_NOCULL=1 draws rectangle lists without face culling (hypothesis: the + // console's rectangle primitive has no facing, so the PSO's cull mode does not apply to it). + if (rect_list) { + static const bool no_cull = [] { const char* v = std::getenv("LEONIDA_RECT_NOCULL"); return v && *v == '1'; }(); + static std::atomic said{0}; + if (said.fetch_add(1) < 4) + std::fprintf(stderr, "[rt] localdbg: rect-list pipeline cull=%u frontCCW=%d depthClip=%d no_cull=%d\n", + unsigned(r.CullMode), int(r.FrontCounterClockwise), int(r.DepthClipEnable), int(no_cull)); + if (no_cull) raster.cullMode = VK_CULL_MODE_NONE; + } // The D24-as-D32 pixel stage applies the bias itself, in D24 units (depth24_fragment above): the // rasterizer's bias stays off and zero, so its clamp needs no depthBiasClamp feature either. raster.depthBiasEnable = !depth24_fragment && (r.DepthBias || r.SlopeScaledDepthBias != 0.0f); @@ -3785,6 +3795,25 @@ class PipelineState final blends[i].dstAlphaBlendFactor = blend_factor(b.DestBlendAlpha); blends[i].alphaBlendOp = blend_op(b.BlendOpAlpha); blends[i].colorWriteMask = b.RenderTargetWriteMask & 0xf; // R, G, B, A in both APIs + if (rect_list) { // LOCAL DIAGNOSTIC / EXPERIMENT (LEONIDA_RECT_FORCE=1: opaque, no depth or stencil test) + static const bool force = [] { const char* v = std::getenv("LEONIDA_RECT_FORCE"); return v && *v == '1'; }(); + static std::atomic said{0}; + if (said.fetch_add(1) < 6) + std::fprintf(stderr, "[rt] localdbg: rect pipeline rt%u/%u blend=%d src=%d dst=%d op=%d srcA=%d dstA=%d " + "mask=0x%x depth=%d write=%d func=%d stencil=%d samplemask=0x%x fmt=%d a2c=%d force=%d\n", + i, desc.NumRenderTargets, int(b.BlendEnable), int(b.SrcBlend), int(b.DestBlend), + int(b.BlendOp), int(b.SrcBlendAlpha), int(b.DestBlendAlpha), + unsigned(b.RenderTargetWriteMask), int(ds.DepthEnable), int(ds.DepthWriteMask), + int(ds.DepthFunc), int(ds.StencilEnable), unsigned(desc.SampleMask), + int(desc.RTVFormats[i]), int(desc.BlendState.AlphaToCoverageEnable), int(force)); + if (force) { + blends[i].blendEnable = VK_FALSE; + blends[i].colorWriteMask = 0xf; + depth.depthTestEnable = VK_FALSE; + depth.depthWriteEnable = VK_FALSE; + depth.stencilTestEnable = VK_FALSE; + } + } // B8G8R8X8 has no alpha, so blending reads destination alpha as 1 there (WARP and AMD's D3D12 driver), // where its BGRA8 Vulkan image would read the X byte. For colour SRC_ALPHA_SAT is min(As, 1 - Ad), so 0; // for alpha it is 1 in both APIs already. @@ -5461,6 +5490,54 @@ class Device final state_.context->set_heap_base(arena.address); state_.context->set_zero_page(arena.buffer, 0, kZeroPage); state_.context->set_quad_indices(arena.buffer, kZeroPage, kQuadIndexCount); + // LOCAL: vertex and index views that name the title's own CPU memory are copied into a ring carved from the + // arena at replay (not fence-tracked: the ring is large against a frame's few KiB of immediate geometry). + state_.context->set_title_memory( + [st = &state_](std::uint64_t va, std::uint64_t size, VkBuffer& buffer, VkDeviceSize& offset) { + static constexpr VkDeviceSize kRing = 16ull << 20; + static std::mutex mutex; + static VkDeviceSize ring_base = 0, ring_next = 0; + static bool tried = false, logged = false; + static std::atomic dbg{0}; + if (dbg.fetch_add(1) < 6) { + MEMORY_BASIC_INFORMATION q{}; + const SIZE_T got = VirtualQuery(reinterpret_cast(va), &q, sizeof(q)); + std::fprintf(stderr, "[rt] localdbg: title_memory va=0x%llx size=0x%llx query=%zu state=0x%lx " + "protect=0x%lx type=0x%lx region=0x%llx mapped=%d\n", + static_cast(va), static_cast(size), + static_cast(got), q.State, q.Protect, q.Type, + static_cast(q.RegionSize), st->arena.mapped != nullptr); + } + if (!va || !size || size > kRing / 4 || !st->arena.mapped) return false; + // The whole range must be committed, readable host memory. + for (std::uint64_t at = va; at < va + size;) { + MEMORY_BASIC_INFORMATION info{}; + if (!VirtualQuery(reinterpret_cast(at), &info, sizeof(info))) return false; + if (info.State != MEM_COMMIT || (info.Protect & (PAGE_NOACCESS | PAGE_GUARD)) || !info.Protect) + return false; + at = reinterpret_cast(info.BaseAddress) + info.RegionSize; + } + std::lock_guard lock(mutex); + if (!tried) { + tried = true; + if (!st->arena_allocate(kRing, 256, ring_base, DeviceState::arena_shader)) ring_base = 0; + } + if (!ring_base) return false; + const VkDeviceSize aligned = (size + 255) & ~VkDeviceSize(255); + if (ring_next + aligned > kRing) ring_next = 0; + std::memcpy(st->arena.mapped + ring_base + ring_next, reinterpret_cast(va), + std::size_t(size)); + buffer = st->arena.buffer; + offset = ring_base + ring_next; + ring_next += aligned; + if (!logged) { + logged = true; + std::fprintf(stderr, "[rt] d3d12: local: vertex/index views in title memory are copied into a " + "%llu MiB ring (first: %llu bytes)\n", + static_cast(kRing >> 20), static_cast(size)); + } + return true; + }); return true; } diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 446f94084a..a19157136a 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -1342,6 +1342,13 @@ PresentState* present_state_for(DeviceProxy* device) { HWND target = rt::d3d12::find_title_window(GetCurrentProcessId(), state->window); if (target) { std::fprintf(stderr, "[rt] d3d12_xs: PresentX uses the title's own window %p\n", static_cast(target)); + // LOCAL: LEONIDA_WINDOW=WxH resizes the title's window without waiting on its thread (SWP_ASYNCWINDOWPOS). + if (const char* size = std::getenv("LEONIDA_WINDOW")) { + int w = 0, h = 0; + if (std::sscanf(size, "%dx%d", &w, &h) == 2 && w > 0 && h > 0) + SetWindowPos(target, nullptr, 0, 0, w, h, + SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOMOVE | SWP_ASYNCWINDOWPOS); + } } else { target = state->window; ShowWindow(target, SW_SHOWNOACTIVATE); diff --git a/runtime/shims/xbox_present.cpp b/runtime/shims/xbox_present.cpp index 003b0d3fee..0b05ad4b9d 100644 --- a/runtime/shims/xbox_present.cpp +++ b/runtime/shims/xbox_present.cpp @@ -1,3 +1,4 @@ +#include #include "xbox_present.h" #include "../src/vulkan_present.h" @@ -128,6 +129,15 @@ HRESULT XboxPresentation::PresentX(UINT plane_count, const XboxPresentPlaneParam return result; } + { // LOCAL DIAGNOSTIC: what the first presents show + static std::atomic shown{0}; + if (shown.fetch_add(1, std::memory_order_relaxed) < 8) + for (UINT i = 0; i < plane_count; ++i) + std::fprintf(stderr, "[rt] localdbg: PresentX plane %u/%u resource=%p count=%u src=%p dest=%p cs=%d flags=0x%x\n", + i, plane_count, planes[i].ppResources ? static_cast(planes[i].ppResources[0]) : nullptr, + planes[i].ResourceCount, static_cast(planes[i].pSrcViewRects), + static_cast(planes[i].pDestPlacementBase), planes[i].ColorSpace, planes[i].Flags); + } // All planes carry the token of one frame. const std::uint64_t token = planes[0].Token; for (UINT i = 0; i < plane_count; ++i) { diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 77c8827b08..0d4d84d6b3 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -1247,6 +1247,12 @@ class VulkanContext { replay_.zero_size = size; } + // LOCAL: the copy-in fallback for vertex and index views in title memory (ReplayFunctions::title_memory). + void set_title_memory(std::function copy) { + std::unique_lock lock(resource_mutex_); + replay_.title_memory = std::move(copy); + } + // Pre-expanded 32-bit triangle indices for non-indexed quad lists (ReplayFunctions::quad_indices). void set_quad_indices(VkBuffer buffer, VkDeviceSize offset, std::uint32_t count) { std::unique_lock lock(resource_mutex_); diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index af58efbbd3..0daaae4bad 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -1,3 +1,4 @@ +#include #pragma once #include "resource_tiling.h" @@ -808,6 +809,14 @@ enum class ReplayResult { invalid_draw, // DispatchMesh with a pipeline that has no mesh shader, or a vertex draw with one that has unsupported }; +// LOCAL DIAGNOSTIC: which check returned unresolved_resource (first 3 times per source line). +inline ReplayResult local_unresolved_at(int line) { + static std::atomic seen[8192]; + if (line >= 0 && line < 8192 && seen[line].fetch_add(1, std::memory_order_relaxed) < 3) + std::fprintf(stderr, "[rt] localdbg: unresolved_resource at vulkan_replay.h:%d\n", line); + return ReplayResult::unresolved_resource; +} + struct ReplayFunctions { // Set 0 for the pipelines that declare one (their own `bindless_set` is only the marker): the device's current @@ -868,6 +877,10 @@ struct ReplayFunctions { // cut to what the buffer holds from there: vertex and index views use what fits, WriteBufferImmediate needs all // of it. std::function buffer_at; + // LOCAL: a vertex or index view whose VA is the title's own CPU memory, not a registered buffer (on the console + // the GPU reads title memory directly). Copies [va, va + size) into a GPU-visible ring and names the copy; false + // when the range is not readable host memory. + std::function title_memory; // Host bytes for a whole console VA range; `not_cpu_written` when it names GPU-writable memory. For small // CPU-written inputs, such as the pointer list of an ARRAY_OF_POINTERS TLAS build. std::function host_at; @@ -2100,7 +2113,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct !vk.draw_indexed || !vk.bind_pipeline || !vk.push_constants) return ReplayResult::unsupported; const GraphicsPipeline* pipeline = vk.graphics_pipeline(draw.pipeline); - if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; + if (!pipeline || !pipeline->pipeline) return local_unresolved_at(__LINE__); if (pipeline->mesh != draw.mesh) return ReplayResult::invalid_draw; if (draw.mesh && !vk.draw_mesh_tasks) return ReplayResult::unsupported; if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; @@ -2121,7 +2134,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct const TargetView& target = draw.views->render_targets[slot]; if (!target.resource) continue; const ResourceBinding* binding = resolve(target.resource); - if (!binding) return ReplayResult::unresolved_resource; + if (!binding) return local_unresolved_at(__LINE__); auto& a = p.colors[slot]; a.binding = *binding; a.id = target.resource; @@ -2138,7 +2151,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct } if (draw.depth.resource && pipeline->depth_format != VK_FORMAT_UNDEFINED) { const ResourceBinding* binding = resolve(draw.depth.resource); - if (!binding) return ReplayResult::unresolved_resource; + if (!binding) return local_unresolved_at(__LINE__); auto& a = p.depth; a.binding = *binding; a.id = draw.depth.resource; @@ -2179,7 +2192,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct const bool bound = draw.views && slot < draw.views->vertex_buffers.size() && draw.views->vertex_buffers[slot].va; if (!bound) { - if (!vk.zero_buffer) return ReplayResult::unresolved_resource; + if (!vk.zero_buffer) return local_unresolved_at(__LINE__); p.vertex_buffers[slot] = vk.zero_buffer; p.vertex_offsets[slot] = vk.zero_offset; p.vertex_sizes[slot] = vk.zero_size; @@ -2188,26 +2201,65 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct } const VertexBufferView& view = draw.views->vertex_buffers[slot]; std::uint64_t size = view.size; - if (!vk.buffer_at(view.va, size, p.vertex_buffers[slot], p.vertex_offsets[slot])) - return ReplayResult::unresolved_resource; + if (!vk.buffer_at(view.va, size, p.vertex_buffers[slot], p.vertex_offsets[slot])) { + size = view.size; + if (!vk.title_memory || !vk.title_memory(view.va, size, p.vertex_buffers[slot], p.vertex_offsets[slot])) + return local_unresolved_at(__LINE__); + { // LOCAL DIAGNOSTIC: the first draws that read title memory + static std::atomic shown{0}; + if (shown.fetch_add(1, std::memory_order_relaxed) < 12) { + const float* f = reinterpret_cast(view.va); + std::fprintf(stderr, "[rt] localdbg: draw slot=%u topology=%u count=%u instances=%u first=%u stride=%u " + "bytes=%llu viewport=%.0f,%.0f %.0fx%.0f depth %.2f..%.2f\n", slot, draw.topology, + draw.count, draw.instances, draw.first, view.stride, + static_cast(view.size), draw.viewport.x, draw.viewport.y, + draw.viewport.width, draw.viewport.height, draw.viewport.min_depth, draw.viewport.max_depth); + for (std::uint32_t t = 0; draw.views && t < draw.views->render_target_count; ++t) + std::fprintf(stderr, "[rt] localdbg: target %u resource=0x%llx mip=%u pipeline=0x%llx depth=0x%llx " + "scissor=%d,%d..%d,%d\n", t, + static_cast(draw.views->render_targets[t].resource), + draw.views->render_targets[t].mip, static_cast(draw.pipeline), + static_cast(draw.depth.resource), draw.scissor.left, + draw.scissor.top, draw.scissor.right, draw.scissor.bottom); + std::fprintf(stderr, "[rt] localdbg: heap_base=0x%llx user_data:", static_cast(vk.heap_base)); + for (int w = 0; w < 16; ++w) std::fprintf(stderr, " %08x", draw.user_data[w]); + std::fprintf(stderr, "\n"); + for (int w = 0; w < 16; ++w) { // which root words name a registered buffer + std::uint64_t room = 1; VkBuffer bb = VK_NULL_HANDLE; VkDeviceSize bo = 0; + if (draw.user_data[w] && vk.buffer_at(draw.user_data[w], room, bb, bo)) + std::fprintf(stderr, "[rt] localdbg: user_data[%d] is a registered buffer VA\n", w); + } + const std::uint32_t words = view.stride / 4 ? view.stride / 4 : 1; + for (std::uint32_t v = 0; v < 4 && (draw.first + v + 1) * view.stride <= view.size; ++v) { + const float* q = f + (draw.first + v) * words; + std::fprintf(stderr, "[rt] localdbg: v%u = %g %g %g %g %g %g\n", v, q[0], q[1], + words > 2 ? q[2] : 0.f, words > 3 ? q[3] : 0.f, words > 4 ? q[4] : 0.f, + words > 5 ? q[5] : 0.f); + } + } + } + } p.vertex_sizes[slot] = size; p.vertex_strides[slot] = (pipeline->zero_step_slots & (1u << slot)) ? 0 : view.stride; } // A non-indexed quad list is drawn from the shared triangle index buffer (emit). if (!draw.indexed && !draw.mesh && draw.topology == topology_quad_list && !vk.quad_indices) - return ReplayResult::unresolved_resource; + return local_unresolved_at(__LINE__); if (draw.indexed) { if (draw.index.format == 57) p.index_type = VK_INDEX_TYPE_UINT16; else if (draw.index.format == 42) p.index_type = VK_INDEX_TYPE_UINT32; else if (draw.index.va) return ReplayResult::unsupported; if (!draw.index.va) { // no index buffer: every index reads 0 - if (!vk.zero_buffer) return ReplayResult::unresolved_resource; + if (!vk.zero_buffer) return local_unresolved_at(__LINE__); p.index_buffer = vk.zero_buffer; p.index_offset = vk.zero_offset; } else { std::uint64_t size = draw.index.size; - if (!vk.buffer_at(draw.index.va, size, p.index_buffer, p.index_offset)) - return ReplayResult::unresolved_resource; + if (!vk.buffer_at(draw.index.va, size, p.index_buffer, p.index_offset)) { + size = draw.index.size; + if (!vk.title_memory || !vk.title_memory(draw.index.va, size, p.index_buffer, p.index_offset)) + return local_unresolved_at(__LINE__); + } } } return ReplayResult::success; @@ -2626,7 +2678,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun }; if (const auto* transition = std::get_if(&command)) { - if (!bind(transition->resource)) return ReplayResult::unresolved_resource; + if (!bind(transition->resource)) return local_unresolved_at(__LINE__); if (p.binding.image == VK_NULL_HANDLE) { if (transition->subresource != 0 && transition->subresource != all_subresources) return ReplayResult::invalid_subresource; @@ -2636,14 +2688,14 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun } else if (std::holds_alternative(command) || std::holds_alternative(command)) { if (!vk.pipeline_barrier2) return ReplayResult::unsupported; if (const auto* buffer_barrier = std::get_if(&command)) - if (!bind(buffer_barrier->resource)) return ReplayResult::unresolved_resource; + if (!bind(buffer_barrier->resource)) return local_unresolved_at(__LINE__); } else if (const auto* texture = std::get_if(&command)) { if (!vk.pipeline_barrier2) return ReplayResult::unsupported; - if (!bind(texture->resource)) return ReplayResult::unresolved_resource; + if (!bind(texture->resource)) return local_unresolved_at(__LINE__); if (!p.binding.image || !barrier_range(p.binding, texture->range, p.range)) return ReplayResult::invalid_subresource; } else if (const auto* color_clear = std::get_if(&command)) { - if (!bind(color_clear->target.resource)) return ReplayResult::unresolved_resource; + if (!bind(color_clear->target.resource)) return local_unresolved_at(__LINE__); if (!p.binding.image || p.binding.aspects != VK_IMAGE_ASPECT_COLOR_BIT) return ReplayResult::invalid_clear; if (!detail::view_range(p.binding, color_clear->target, VK_IMAGE_ASPECT_COLOR_BIT, p.range)) return ReplayResult::invalid_subresource; @@ -2665,7 +2717,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun r != ReplayResult::success) return r; if (!p.skip && p.rects.empty() && !vk.clear_color_image) return ReplayResult::unsupported; } else if (const auto* depth_clear = std::get_if(&command)) { - if (!bind(depth_clear->target.resource)) return ReplayResult::unresolved_resource; + if (!bind(depth_clear->target.resource)) return local_unresolved_at(__LINE__); VkImageAspectFlags aspects = 0; if (depth_clear->flags & clear_depth) aspects |= VK_IMAGE_ASPECT_DEPTH_BIT; if (depth_clear->flags & clear_stencil) aspects |= VK_IMAGE_ASPECT_STENCIL_BIT; @@ -2685,7 +2737,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!p.skip && p.rects.empty() && !vk.clear_depth_stencil_image) return ReplayResult::unsupported; } else if (const auto* uav = std::get_if(&command)) { const UavView& view = uav->view; - if (!bind(view.resource)) return ReplayResult::unresolved_resource; + if (!bind(view.resource)) return local_unresolved_at(__LINE__); if (view.buffer) { if (!vk.fill_buffer || !vk.update_buffer || !vk.copy_buffer) return ReplayResult::unsupported; if (predicated) ++out.unpredicated_copies; // fills and copies are transfer commands @@ -2745,7 +2797,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (predicated && !std::holds_alternative(command)) ++out.unpredicated_copies; const auto [dst_id, src_id] = copy_ids(command); const ResourceBinding* source = resolve(src_id); - if (!bind(dst_id) || !source) return ReplayResult::unresolved_resource; + if (!bind(dst_id) || !source) return local_unresolved_at(__LINE__); p.source = *source; ReplayResult result = ReplayResult::success; if (const auto* buffer_copy = std::get_if(&command)) { @@ -2878,7 +2930,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!vk.resolve_image) return ReplayResult::unsupported; if (predicated) ++out.unpredicated_copies; // a transfer command, like the copies const ResourceBinding* source = resolve(resolve_command->src); - if (!bind(resolve_command->dst) || !source) return ReplayResult::unresolved_resource; + if (!bind(resolve_command->dst) || !source) return local_unresolved_at(__LINE__); p.source = *source; if (const auto result = detail::prepare_resolve(*resolve_command, p); result != ReplayResult::success) return result; @@ -2909,7 +2961,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun } } else if (const auto* discard = std::get_if(&command)) { // Buffers and partial (rectangle) discards keep their contents, which "undefined" allows. - if (!bind(discard->resource)) return ReplayResult::unresolved_resource; + if (!bind(discard->resource)) return local_unresolved_at(__LINE__); const std::uint64_t end = std::uint64_t(discard->first_subresource) + discard->count; if (!p.binding.image) { if (!discard->whole && end > 1) return ReplayResult::invalid_subresource; @@ -2929,7 +2981,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!vk.update_buffer || !vk.buffer_at) return ReplayResult::unsupported; std::uint64_t bytes = 4; if (!vk.buffer_at(write->address, bytes, p.write_buffer, p.write_offset) || bytes < 4) - return ReplayResult::unresolved_resource; + return local_unresolved_at(__LINE__); if (p.write_offset % 4) return ReplayResult::invalid_copy; // WriteBufferImmediate resolves by VA and may target a readback buffer in COPY_DEST. out.wrote_readback = true; @@ -2938,14 +2990,14 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!vk.copy_buffer) return ReplayResult::unsupported; if (predicated) ++out.unpredicated_copies; // a transfer command, like the copies const ResourceBinding* source = resolve(atomic->src); - if (!bind(atomic->dst) || !source) return ReplayResult::unresolved_resource; + if (!bind(atomic->dst) || !source) return local_unresolved_at(__LINE__); p.source = *source; if (!p.binding.buffer || !p.source.buffer || !detail::within(atomic->dst_offset, atomic->bytes, p.binding.size) || !detail::within(atomic->src_offset, atomic->bytes, p.source.size)) return ReplayResult::invalid_copy; for (const auto& d : atomic->dependencies) { const ResourceBinding* dependent = resolve(d.resource); - if (!dependent) return ReplayResult::unresolved_resource; + if (!dependent) return local_unresolved_at(__LINE__); if (!dependent->image) { const std::uint64_t end = d.end == UINT64_MAX ? dependent->size : d.end; if (d.subresource != 0 || d.begin >= end || end > dependent->size) @@ -2964,7 +3016,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!conditional) return ReplayResult::unsupported; // Without physical segments the capture dispatch would pollute CSInvocations. if (statistics_active && !statistics_helpers) return ReplayResult::unsupported; - if (!bind(predication->buffer)) return ReplayResult::unresolved_resource; + if (!bind(predication->buffer)) return local_unresolved_at(__LINE__); if (!p.binding.buffer || !detail::within(predication->offset, 8, p.binding.size) || predication->offset > UINT64_MAX - p.binding.buffer_offset) return ReplayResult::invalid_predication; @@ -2976,7 +3028,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun // not suppress them (emit_query suspends conditional rendering around ResolveQueryData). if (!queries) return ReplayResult::unsupported; QueryPool* heap = vk.query_pool(range.heap); - if (!heap) return ReplayResult::unresolved_resource; + if (!heap) return local_unresolved_at(__LINE__); if (!query_fits_heap(heap->heap_type, range.type)) return ReplayResult::invalid_query; if (range.first >= heap->count || range.count > heap->count - range.first) return ReplayResult::invalid_query; @@ -2999,7 +3051,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun } if (const auto* resolve_queries = std::get_if(&command)) { // The destination is a buffer, as D3D12 requires, large enough for every result. - if (!bind(resolve_queries->dst)) return ReplayResult::unresolved_resource; + if (!bind(resolve_queries->dst)) return local_unresolved_at(__LINE__); const std::uint64_t bytes = std::uint64_t(range.count) * query_result_size(range.type); if (!p.binding.buffer || p.binding.buffer_offset % 8 || !detail::within(resolve_queries->offset, bytes, p.binding.size) || @@ -3017,7 +3069,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun } out.queries.push_back({i, heap, statistics_active}); } else if (const auto* ind = std::get_if(&command)) { - if (!bind(ind->argument_buffer) || !p.binding.buffer) return ReplayResult::unresolved_resource; + if (!bind(ind->argument_buffer) || !p.binding.buffer) return local_unresolved_at(__LINE__); const VkDeviceSize record_size = detail::indirect_record_size(ind->kind); if (!record_size || ind->stride < record_size || ind->stride % sizeof(std::uint32_t)) return ReplayResult::invalid_indirect_arguments; @@ -3026,7 +3078,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun return ReplayResult::invalid_indirect_arguments; if (ind->count_buffer) { const ResourceBinding* cnt = resolve(ind->count_buffer); - if (!cnt || !cnt->buffer) return ReplayResult::unresolved_resource; + if (!cnt || !cnt->buffer) return local_unresolved_at(__LINE__); if (!detail::indirect_range(*cnt, ind->count_offset, sizeof(std::uint32_t))) return ReplayResult::invalid_indirect_arguments; p.source = *cnt; @@ -3052,7 +3104,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (ind->kind == IndirectKind::dispatch && ind->pipeline) { // the pipeline and root arguments it was recorded if (!vk.bind_pipeline || !vk.push_constants || !vk.compute_pipeline) return ReplayResult::unsupported; const ComputePipeline* pipeline = vk.compute_pipeline(ind->pipeline); - if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; + if (!pipeline || !pipeline->pipeline) return local_unresolved_at(__LINE__); if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; p.pipeline = *pipeline; } @@ -3064,10 +3116,10 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!vk.build_acceleration_structures || !vk.resolve_acceleration_structure) return ReplayResult::unsupported; p.accel_dst = vk.resolve_acceleration_structure(build->dst_va); - if (!p.accel_dst) return ReplayResult::unresolved_resource; + if (!p.accel_dst) return local_unresolved_at(__LINE__); if (build->update && build->src_va) { p.accel_src = vk.resolve_acceleration_structure(build->src_va); - if (!p.accel_src) return ReplayResult::unresolved_resource; + if (!p.accel_src) return local_unresolved_at(__LINE__); } if (build->is_tlas && build->instance_pointers && build->instance_count) { if (!vk.prepare_khr_instances || !vk.host_at || !vk.buffer_at) return ReplayResult::unsupported; @@ -3081,9 +3133,9 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun std::uint64_t room = ~std::uint64_t(0); VkBuffer buffer = VK_NULL_HANDLE; VkDeviceSize offset = 0; - if (!vk.buffer_at(copy->dst_va, room, buffer, offset)) return ReplayResult::unresolved_resource; + if (!vk.buffer_at(copy->dst_va, room, buffer, offset)) return local_unresolved_at(__LINE__); std::uint64_t source = ~std::uint64_t(0); - if (!vk.buffer_at(copy->src_va, source, buffer, offset)) return ReplayResult::unresolved_resource; + if (!vk.buffer_at(copy->src_va, source, buffer, offset)) return local_unresolved_at(__LINE__); p.xdxr_bytes = std::min(room, source); } else if (const auto* info = std::get_if(&command)) { // The KHR path never wrote postbuild values; it keeps skipping them rather than failing the list. @@ -3094,14 +3146,14 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun std::uint64_t room = 8 * info->sources.size(); VkBuffer buffer = VK_NULL_HANDLE; VkDeviceSize offset = 0; - if (!vk.buffer_at(info->dest_va, room, buffer, offset)) return ReplayResult::unresolved_resource; + if (!vk.buffer_at(info->dest_va, room, buffer, offset)) return local_unresolved_at(__LINE__); if (room < 8 * info->sources.size()) return ReplayResult::invalid_copy; } } else if (const auto* dispatch = std::get_if(&command)) { if (!vk.bind_pipeline || !vk.push_constants || !vk.dispatch || !vk.compute_pipeline) return ReplayResult::unsupported; const ComputePipeline* pipeline = vk.compute_pipeline(dispatch->pipeline); - if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; + if (!pipeline || !pipeline->pipeline) return local_unresolved_at(__LINE__); if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; p.pipeline = *pipeline; } else if (const auto* draw = std::get_if(&command)) { From 73b52fbfe4c97e1976c5f781e5c46643f9156311 Mon Sep 17 00:00:00 2001 From: channa317 <183341518+channa317@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:50:41 +0800 Subject: [PATCH 025/110] d3d12: complete placed depth UAV arrays and fenced queue transfers (D3D-991) --- docs/d3d12_vulkan.md | 21 +- runtime/CMakeLists.txt | 21 +- runtime/shims/d3d12_com.h | 6 +- runtime/shims/d3d12_vulkan_device.cpp | 129 ++++-- runtime/shims/d3d12_xs_device.cpp | 89 ++++- runtime/shims/d3d12_xs_device.h | 25 +- runtime/shims/d3d12_xs_placed_depth.h | 125 ++++++ runtime/src/queue_families.h | 10 + runtime/src/vulkan_backend.h | 11 +- runtime/src/vulkan_bindless.h | 9 +- runtime/src/vulkan_replay.h | 133 +++++-- runtime/src/vulkan_scratch.h | 9 +- runtime/test/d3d12_depth_stencil_uav_test.cpp | 376 +++++++++++++----- runtime/test/d3d12_depth_stencil_uav_views.h | 79 ++++ runtime/test/d3d12_placed_depth_test.h | 115 ++++++ runtime/test/device_proxy_test.cpp | 2 +- runtime/test/glsl/cs_depth_stencil_uav.comp | 35 +- runtime/test/replay_texture_barrier_test.cpp | 76 +++- runtime/test/replay_uav_clear_offset_test.cpp | 38 ++ runtime/test/vk_test_device.h | 16 + runtime/test/vulkan_scratch_test.cpp | 8 +- 21 files changed, 1112 insertions(+), 221 deletions(-) create mode 100644 runtime/shims/d3d12_xs_placed_depth.h create mode 100644 runtime/test/d3d12_depth_stencil_uav_views.h create mode 100644 runtime/test/d3d12_placed_depth_test.h diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 33d4f979ab..f5d7cfe2cc 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2468,13 +2468,20 @@ The trace will enumerate them. `DEPTH_STENCIL_ATTACHMENT`, `ALLOW_UNORDERED_ACCESS` → `STORAGE`, `ALLOW_SIMULTANEOUS_ACCESS` → concurrent sharing, `DENY_*` → omit the corresponding usage. Buffers get the union of usages their states and flags imply; images copy dimension, format, mip levels, array layers and sample count. -- Xbox slot 76 supports UAVs on committed 2D `R32G8X24_TYPELESS` depth/stencil textures with one mip, layer and - sample. Use a `TEXTURE2D` UAV with `R32_FLOAT` on plane 0 or `R8_UINT` on plane 1. Each plane has its own - storage image and descriptor address. On explicit transitions into or out of UAV access, the graphics queue - family transfers the affected planes through a scratch buffer. Depth attachment and shader-resource views - keep their original image. For these textures, replay rejects the queue-specific enhanced `DIRECT_QUEUE_COMMON` - and `COMPUTE_QUEUE_COMMON` layouts, which allow switching between the images without a texture barrier. - `d3d12_depth_stencil_uav_test` exercises both planes with a synthetic compute shader. +- Xbox depth textures with `ALLOW_DEPTH_STENCIL | ALLOW_UNORDERED_ACCESS` can use either committed creation + (slot 76) or placement at a guest address (slot 133). The supported shapes are single-sample, single-mip 2D + textures and 2D arrays. For `R32G8X24_TYPELESS`, use `R32_FLOAT` on depth plane 0 and `R8_UINT` on stencil + plane 1. For `R16_TYPELESS`, use `R16_UINT` on plane 0 to access the raw D16 bits. An array UAV selects a + contiguous range of layers. The depth/stencil and shader-resource views continue to use the attachment image. + Slot 133 keeps the guest address. Identical, live placements share their image and writable planes across + distinct COM objects. A partial overlap or incompatible reinterpretation is refused. +- Legacy and enhanced texture transitions copy the selected planes and layers to or from their storage images. + Fence-ordered graphics and compute queues can share UAV access. A dedicated compute family can perform + the plane transfer itself when `VK_KHR_maintenance10` and the format's depth/stencil copy flags allow it. + Otherwise the graphics queue issues the explicit transitions on either side of the compute work. The two + queue-specific COMMON layouts allow implicit UAV access, so replay refuses them for these textures. + Generic COMMON remains available for copies, shader reads and queue handoffs. + `d3d12_depth_stencil_uav_test` verifies these paths with a synthetic shader and per-pixel readback. - Copies: `CopyBufferRegion` → `vkCmdCopyBuffer` with arena offsets; `CopyTextureRegion` → `vkCmdCopyBufferToImage`/`vkCmdCopyImageToBuffer`/`vkCmdCopyImage`, using the `D3D12_PLACED_SUBRESOURCE_FOOTPRINT` row pitch and height; `CopyResource` → a whole-subresource copy; colour resolves → `vkCmdResolveImage`; diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 776542b667..6be827f847 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2638,17 +2638,22 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_set0_compute_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_set0_compute COMMAND d3d12_set0_compute_test) set_tests_properties(d3d12_set0_compute PROPERTIES SKIP_RETURN_CODE 77) - set(depth_uav_spv ${CMAKE_CURRENT_BINARY_DIR}/generated/cs_depth_stencil_uav.spv) - add_custom_command(OUTPUT ${depth_uav_spv} - COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_CURRENT_BINARY_DIR}/generated - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${depth_uav_spv} - ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_depth_stencil_uav.comp - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_depth_stencil_uav.comp VERBATIM) + set(depth_uav_shader ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_depth_stencil_uav.comp) + foreach(variant IN ITEMS DEPTH_STENCIL_2D DEPTH_STENCIL_ARRAY DEPTH16_2D DEPTH16_ARRAY) + set(spv ${CMAKE_CURRENT_BINARY_DIR}/generated/cs_depth_uav_${variant}.spv) + add_custom_command(OUTPUT ${spv} + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_CURRENT_BINARY_DIR}/generated + COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -D${variant}=1 + -o ${spv} ${depth_uav_shader} + DEPENDS ${depth_uav_shader} VERBATIM) + list(APPEND depth_uav_shaders ${spv}) + list(APPEND depth_uav_definitions LEONIDA_${variant}_SPV="${spv}") + endforeach() add_executable(d3d12_depth_stencil_uav_test test/d3d12_depth_stencil_uav_test.cpp - shims/d3d12_xs_device.cpp ${depth_uav_spv}) + shims/d3d12_xs_device.cpp ${depth_uav_shaders}) target_link_libraries(d3d12_depth_stencil_uav_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) target_compile_definitions(d3d12_depth_stencil_uav_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_DEPTH_UAV_SPV="${depth_uav_spv}") + ${depth_uav_definitions}) target_compile_options(d3d12_depth_stencil_uav_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_depth_stencil_uav COMMAND d3d12_depth_stencil_uav_test) set_tests_properties(d3d12_depth_stencil_uav PROPERTIES SKIP_RETURN_CODE 77) diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index af767ccf2b..24e92a9d47 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -5,7 +5,7 @@ // interfaces as far as is known; docs/d3d12_vulkan.md section 3.1 lists what is still unverified. // // Contracts with the rest of the layer (the device proxy that will hand these objects out): -// - an ID3D12Resource's leonida::ResourceId is its pointer value; the device registers it with the VulkanContext; +// - a resource's ID is its backing pointer value (identical Xbox depth placements share storage and layouts); // - so is an ID3D12QueryHeap's leonida::QueryHeapId, registered with its VkQueryPool; // - the CPU handle of an RTV or DSV points at a leonida::TargetView in the device's descriptor heap. #pragma once @@ -15,6 +15,7 @@ #include #include +#include "d3d12_xs_device.h" #include "../src/gfx10_descriptors.h" #include "../src/vulkan_backend.h" @@ -154,6 +155,7 @@ struct VulkanDeviceInfo { bool fragment_shader_barycentric = false; bool fragment_shader_interlock = false; bool maintenance8 = false; + bool maintenance10 = false; // VK_KHR_maintenance10 enabled: query depth/stencil copy support per format // The instance enabled VK_EXT_debug_utils: SetMarker/BeginEvent/EndEvent become debug labels. Otherwise they // do nothing. bool debug_utils = false; @@ -412,7 +414,7 @@ bool front_back_stencil_ref(ID3D12GraphicsCommandList8* list, UINT& front, UINT& bool recorded_commands(ID3D12GraphicsCommandList* list, std::vector& commands); inline leonida::ResourceId resource_id(const ID3D12Resource* resource) { - return reinterpret_cast(resource); + return reinterpret_cast(rt::d3d12_xs::texture_backing(resource)); } // A query heap's ID in the command-list IR and the VulkanContext: its pointer value, as for resources. diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 3616d69bdd..bbda465aaf 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -572,10 +572,7 @@ struct DeviceState { template void share(CreateInfo& create) const { - if (families.size() < 2) return; - create.sharingMode = VK_SHARING_MODE_CONCURRENT; - create.queueFamilyIndexCount = std::uint32_t(families.size()); - create.pQueueFamilyIndices = families.data(); + leonida::share_across_queue_families(create, families); } std::unique_ptr context; VkPhysicalDeviceMemoryProperties memory{}; @@ -1712,8 +1709,7 @@ class DescriptorHeap final class Resource final : public Child { public: - // {9b3e5f12-7c48-4d0e-a6b1-2f8d4c7e9a35} - static constexpr GUID kTag{0x9b3e5f12, 0x7c48, 0x4d0e, {0xa6, 0xb1, 0x2f, 0x8d, 0x4c, 0x7e, 0x9a, 0x35}}; + static constexpr GUID kTag = rt::d3d12_xs::kVulkanResourceTag; Resource(DeviceState& device, const D3D12_RESOURCE_DESC& desc, const D3D12_HEAP_PROPERTIES& heap, D3D12_HEAP_FLAGS heap_flags) @@ -2098,31 +2094,35 @@ class Resource final // The Xbox proxy calls this before publishing an allocated depth texture. Each storage plane owns a // regular color image with its own GFX10 address, so a UAV cannot replace the original SRV in set 0. - HRESULT enable_depth_stencil_uav() { - if (!image_ || desc_.Format != DXGI_FORMAT_R32G8X24_TYPELESS || + HRESULT enable_depth_stencil_uav(D3D12_HEAP_FLAGS storage_heap_flags) { + const bool depth16 = desc_.Format == DXGI_FORMAT_R16_TYPELESS; + if (!image_ || (!depth16 && desc_.Format != DXGI_FORMAT_R32G8X24_TYPELESS) || !(desc_.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) || desc_.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc_.MipLevels != 1 || - desc_.DepthOrArraySize != 1 || desc_.SampleDesc.Count != 1) + !desc_.DepthOrArraySize || desc_.SampleDesc.Count != 1) return E_INVALIDARG; if (storage_planes_[0]) return S_OK; try { decltype(storage_planes_) planes; D3D12_RESOURCE_DESC plane_desc = desc_; plane_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; - constexpr DXGI_FORMAT formats[] = {DXGI_FORMAT_R32_FLOAT, DXGI_FORMAT_R8_UINT}; - for (UINT plane = 0; plane < planes.size(); ++plane) { + // D16 copies through a buffer as raw UNORM bits. R16_UINT lets an Xbox UAV read/write those bits. + const DXGI_FORMAT formats[] = {depth16 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_FLOAT, DXGI_FORMAT_R8_UINT}; + const UINT plane_count = depth16 ? 1 : 2; + for (UINT plane = 0; plane < plane_count; ++plane) { plane_desc.Format = formats[plane]; - planes[plane] = std::make_unique(device_, plane_desc, heap_, D3D12_HEAP_FLAG_NONE); + planes[plane] = std::make_unique(device_, plane_desc, heap_, storage_heap_flags); const HRESULT hr = planes[plane]->create_texture(device_.texture_format(plane_desc)); if (FAILED(hr)) return hr; } // Replacing the binding preserves the tracked layout of the original depth/stencil image. auto binding = binding_; binding.depth_uav = planes[0]->id(); - binding.stencil_uav = planes[1]->id(); + binding.stencil_uav = planes[1] ? planes[1]->id() : 0; device_.context->add_resource(id(), binding); binding_ = binding; storage_planes_ = std::move(planes); + heap_flags_ |= storage_heap_flags; // GetHeapProperties describes the caller's entire logical texture. } catch (const std::bad_alloc&) { return E_OUTOFMEMORY; } @@ -4937,6 +4937,31 @@ class Device final info.xdxr_acceleration_structures && info.buffer_device_address); state_.context->set_graphics_family(info.queue_family); +#ifdef VK_KHR_MAINTENANCE_10_EXTENSION_NAME + if (info.maintenance10 && info.physical) { + const auto get_props = reinterpret_cast( + info.get_instance_proc(info.instance, "vkGetPhysicalDeviceFormatProperties2")); + if (get_props) { + const auto aspects = [&](VkFormat format) { + VkFormatProperties3 props{VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_3}; + VkFormatProperties2 query{VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2, &props}; + get_props(info.physical, format, &query); + VkImageAspectFlags mask = 0; + if (props.optimalTilingFeatures & VK_FORMAT_FEATURE_2_DEPTH_COPY_ON_COMPUTE_QUEUE_BIT_KHR) + mask |= VK_IMAGE_ASPECT_DEPTH_BIT; + if (props.optimalTilingFeatures & VK_FORMAT_FEATURE_2_STENCIL_COPY_ON_COMPUTE_QUEUE_BIT_KHR) + mask |= VK_IMAGE_ASPECT_STENCIL_BIT; + return mask; + }; + state_.context->set_compute_copy_aspects( + [d16 = aspects(VK_FORMAT_D16_UNORM), ds = aspects(VK_FORMAT_D32_SFLOAT_S8_UINT)](VkFormat format) { + if (format == VK_FORMAT_D16_UNORM) return d16; + if (format == VK_FORMAT_D32_SFLOAT_S8_UINT) return ds; + return VkImageAspectFlags{}; + }); + } + } +#endif if (info.physical && state_.format_properties) { state_.context->set_color_attachment_format( [physical = info.physical, get_props = state_.format_properties](VkFormat format) { @@ -4971,7 +4996,7 @@ class Device final // Depth <-> colour copies are staged through scratch buffers (vulkan_scratch.h), on every GPU. state_.context->enable_copy_scratch(get_device, [this](const VkMemoryRequirements& requirements) { return state_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); - }); + }, state_.families); if (info.buffer_device_address && info.physical && info.get_instance_proc) { if (const auto get_props = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties"))) { @@ -5123,7 +5148,8 @@ class Device final "sampler heap (%u of %u besides the fallback): its limits or " "vkGetDescriptorSetLayoutSupport allow no more\n", features.counts[b::sampler_binding] - 1, unsigned(D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE)); - state_.bindless = std::make_unique(get_device, state_.info.device, state_.memory, features); + state_.bindless = std::make_unique(get_device, state_.info.device, state_.memory, features, + state_.families); if (!state_.bindless->ok() || !state_.context->vk.vkCreateSampler) { state_.bindless.reset(); return false; @@ -6476,29 +6502,8 @@ class Device final log_once("unordered-access view of a texture with a counter resource; dimension", int(r->desc().Dimension)); return; } - if (r->depth_stencil_uav(0)) { - if (!desc || desc->ViewDimension != D3D12_UAV_DIMENSION_TEXTURE2D || desc->Texture2D.MipSlice) { - log_once("Xbox depth-stencil UAV requires an explicit 2D mip-zero view; dimension", - desc ? int(desc->ViewDimension) : 0); - return; - } - const Resource* plane = r->depth_stencil_uav(desc->Texture2D.PlaneSlice); - if (!plane) { - log_once("unsupported Xbox depth-stencil UAV plane", int(desc->Texture2D.PlaneSlice)); - return; - } - if (desc->Format != plane->desc().Format) { - log_once(desc->Texture2D.PlaneSlice ? "unsupported Xbox stencil UAV format" - : "unsupported Xbox depth UAV format", int(desc->Format)); - return; - } - TextureView view{}; - view.format = desc->Format; - view.mip_count = view.layer_count = 1; - write_image_descriptor(*plane, view, destination, ImageViewUse::depth_stencil_uav); - return; - } - if (!(r->desc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { + const bool depth_uav = r->depth_stencil_uav(0) != nullptr; + if (!depth_uav && !(r->desc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { log_once("unordered-access view of a texture created without ALLOW_UNORDERED_ACCESS; flags", int(r->desc().Flags)); return; @@ -6537,6 +6542,25 @@ class Device final return; } } + if (depth_uav) { + const UINT layers = r->desc().DepthOrArraySize; + if (!desc || !(desc->ViewDimension == D3D12_UAV_DIMENSION_TEXTURE2DARRAY || + (desc->ViewDimension == D3D12_UAV_DIMENSION_TEXTURE2D && layers == 1)) || + view.first_mip || !view.layer_count || view.first_layer >= layers || + (view.layer_count != UINT_MAX && view.layer_count > layers - view.first_layer)) { + log_once("Xbox depth-stencil UAV requires a valid mip-zero 2D or array view; dimension", + desc ? int(desc->ViewDimension) : 0); + return; + } + const Resource* storage = r->depth_stencil_uav(view.plane); + if (!storage || view.format != storage->desc().Format) { + log_once("unsupported Xbox depth-stencil UAV plane or format; format", int(view.format)); + return; + } + view.plane = 0; // The chosen shadow is a single-plane colour image with the same array layers. + write_image_descriptor(*storage, view, destination, ImageViewUse::depth_stencil_uav); + return; + } // B8G8R8X8 has no typed UAV, so no format of its family gives an unordered-access view. if (alpha_unused(r->desc().Format) || alpha_unused(view.format)) { log_once("unordered-access view of a B8G8R8X8 format; format", int(view.format)); @@ -8415,9 +8439,9 @@ bool is_sparse_image(ID3D12Resource* resource) { return object && object->sparse_image(); } -static HRESULT enable_depth_stencil_uav(ID3D12Resource* resource) { +static HRESULT enable_depth_stencil_uav(ID3D12Resource* resource, D3D12_HEAP_FLAGS storage_heap_flags) { Resource* r = Resource::from(resource); - return r ? r->enable_depth_stencil_uav() : E_INVALIDARG; + return r ? r->enable_depth_stencil_uav(storage_heap_flags) : E_INVALIDARG; } leonida::ResourceId uav_image_resource(ID3D12Resource* resource, std::uint64_t address) { @@ -8425,7 +8449,7 @@ leonida::ResourceId uav_image_resource(ID3D12Resource* resource, std::uint64_t a if (!r || !r->depth_stencil_uav(0)) return resource_id(resource); for (UINT plane = 0; plane < 2; ++plane) { const Resource* storage = r->depth_stencil_uav(plane); - if (storage->image_address() == address) return storage->id(); + if (storage && storage->image_address() == address) return storage->id(); } return 0; } @@ -8441,7 +8465,12 @@ void set_device_outer(ID3D12Device* device, IUnknown* outer) { // out this layer's adapter, the one create_dxgi_factory enumerates, so a title on the Vulkan device never gets // a host DXGI object from it. if (!rt::d3d12_xs::is_device_proxy(outer)) return; - rt::d3d12_xs::set_depth_stencil_uav_provider(outer, &enable_depth_stencil_uav); + rt::d3d12_xs::set_depth_stencil_uav_provider(outer, &enable_depth_stencil_uav, + [](const D3D12_RESOURCE_DESC& desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear) { + D3D12_HEAP_PROPERTIES heap{}; + heap.Type = D3D12_HEAP_TYPE_DEFAULT; + return !committed_resource_refusal(heap, D3D12_HEAP_FLAG_NONE, desc, state, clear, false, false); + }); rt::d3d12_xs::set_device_adapter_provider(outer, [](ID3D12Device* real, REFIID riid, void** out) { IDXGIFactory1* factory = nullptr; HRESULT hr = create_dxgi_factory(real, __uuidof(IDXGIFactory1), reinterpret_cast(&factory)); @@ -9359,6 +9388,19 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin } #endif +#ifdef VK_KHR_MAINTENANCE_10_EXTENSION_NAME + VkPhysicalDeviceMaintenance10FeaturesKHR maintenance10{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_10_FEATURES_KHR}; + // Vulkan 1.3 makes the 64-bit optimal tiling format features used by this path core. + if (v13.core && has_device_extension(VK_KHR_MAINTENANCE_10_EXTENSION_NAME)) { + VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &maintenance10}; + vkGetPhysicalDeviceFeatures2(info.physical, &query); + info.maintenance10 = maintenance10.maintenance10 == VK_TRUE; + if (info.maintenance10) { + maintenance10.pNext = *v13.next(); + *v13.next() = &maintenance10; + } + } +#endif #ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME // VK_KHR_shader_fma: OpFmaKHR is a single-rounding multiply-add in SPIR-V (GLSL.std.450 Fma may round twice). // Translated shaders built with `rdna2spirv.py --fma khr` need it (index capability FMAKHR, feature @@ -9498,6 +9540,9 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin #ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME if (info.maintenance8) device_extensions.push_back(VK_KHR_MAINTENANCE_8_EXTENSION_NAME); #endif +#ifdef VK_KHR_MAINTENANCE_10_EXTENSION_NAME + if (info.maintenance10) device_extensions.push_back(VK_KHR_MAINTENANCE_10_EXTENSION_NAME); +#endif #ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME if (info.shader_fma) device_extensions.push_back(VK_KHR_SHADER_FMA_EXTENSION_NAME); #endif diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 2e018d95ef..2219dfe33f 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -23,6 +23,7 @@ // for a trace that disagrees. The frame-event calls answer from a per-device token counter: there is no vblank source // behind the device before a presenter exists, so WaitFrameEventX returns at once with a fresh non-zero token. #include "d3d12_xs_device.h" +#include "d3d12_xs_placed_depth.h" #include "d3d12_trace.h" #include "../src/shader_library.h" // leonida::fspx_payload_from_parts for slot 67 @@ -44,7 +45,7 @@ namespace rt::d3d12_xs { namespace { -constexpr unsigned kMaxSlots = 128; +constexpr unsigned kMaxSlots = 134; // includes the measured CreatePlacedResourceX slot static_assert(kMaxSlots > 83, "the proxy table must cover ID3D12Device14 (83 slots)"); static_assert(sizeof(void*) == 8, "the Xbox-ABI proxy is x64-only"); static_assert(sizeof(D3D12_CPU_DESCRIPTOR_HANDLE) == 8, @@ -61,6 +62,8 @@ struct DeviceProxy { void** dxgi_vtable; DxgiAdapterProvider adapter_provider; DepthStencilUavProvider depth_stencil_uav_provider = nullptr; + ValidateDepthPlacement validate_depth_placement = nullptr; + PlacedDepthTextures placed_depth_textures; std::atomic gpu_thread_priority; std::atomic max_frame_latency; // The first-frame subset of SetFrameIntervalX/ScheduleFrameEventX/WaitFrameEventX. Tokens were never measured; @@ -148,6 +151,7 @@ const char* slot_name(unsigned slot) { case 78: return "Xbox SetFrameIntervalX"; case 79: return "Xbox ScheduleFrameEventX"; case 80: return "Xbox WaitFrameEventX"; + case 133: return "Xbox CreatePlacedResourceX"; default: return "forwarded"; } } @@ -1453,6 +1457,64 @@ HRESULT proxy_create_compute_pipeline_from_native_code(DeviceProxy* self, const return hr; } +bool supports_depth_uav(const DeviceProxy* self, const D3D12_RESOURCE_DESC& desc) { + constexpr auto flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + return self->depth_stencil_uav_provider && (desc.Flags & flags) == flags && + desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && + (desc.Format == DXGI_FORMAT_R32G8X24_TYPELESS || desc.Format == DXGI_FORMAT_R16_TYPELESS) && + desc.DepthOrArraySize && desc.MipLevels == 1 && desc.SampleDesc.Count == 1; +} + +D3D12_RESOURCE_DESC depth_image_desc(D3D12_RESOURCE_DESC desc) { + // Keep desktop resource flags up to RTAS and USE_TIGHT_ALIGNMENT. Xbox stores additional flags above them. + desc.Flags = static_cast((UINT(desc.Flags) & 0x5ffu) & + ~UINT(D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)); + desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + return desc; +} + +D3D12_RESOURCE_STATES depth_image_state(D3D12_RESOURCE_STATES requested) { + return requested == D3D12_RESOURCE_STATE_UNORDERED_ACCESS ? D3D12_RESOURCE_STATE_COMMON : requested; +} + +HRESULT create_depth_uav_backing(DeviceProxy* self, const D3D12_HEAP_PROPERTIES* props, D3D12_HEAP_FLAGS flags, + const D3D12_RESOURCE_DESC& native, D3D12_RESOURCE_STATES initial, + const D3D12_CLEAR_VALUE* clear, ID3D12Resource** out) { + // The logical Xbox texture has a UAV. Its writable planes take ALLOW_SHADER_ATOMICS, which the PC + // rejects on the depth-only attachment. Upload/readback heaps cannot hold a UAV on either API. + if (props && (props->Type == D3D12_HEAP_TYPE_UPLOAD || props->Type == D3D12_HEAP_TYPE_READBACK)) + return E_INVALIDARG; + const auto storage_flags = flags & D3D12_HEAP_FLAG_ALLOW_SHADER_ATOMICS; + HRESULT hr = self->real->CreateCommittedResource(props, flags & ~storage_flags, &native, initial, clear, + IID_PPV_ARGS(out)); + if (FAILED(hr)) return hr; + hr = self->depth_stencil_uav_provider(*out, storage_flags); + if (FAILED(hr)) { + (*out)->Release(); + *out = nullptr; + } + return hr; +} + +HRESULT proxy_create_placed_depth(DeviceProxy* self, UINT64 address, const D3D12_RESOURCE_DESC* desc, + UINT state, const D3D12_CLEAR_VALUE* clear, const IID* riid, void** out) { + note_slot(133); + if (!out) return E_POINTER; + *out = nullptr; + if (!self->validate_depth_placement) return E_NOTIMPL; + if (!desc || !riid) return E_POINTER; + if (!supports_depth_uav(self, *desc)) return E_NOTIMPL; + const auto native = depth_image_desc(*desc); + const auto initial = state == UINT_MAX ? D3D12_RESOURCE_STATE_COMMON + : depth_image_state(static_cast(state)); + if (!self->validate_depth_placement(native, initial, clear)) return E_INVALIDARG; + const auto alloc = self->real->GetResourceAllocationInfo(0, 1, &native); + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + return self->placed_depth_textures.create(address, native, alloc, clear, *riid, out, [&](ID3D12Resource** backing) { + return create_depth_uav_backing(self, &heap, D3D12_HEAP_FLAG_NONE, native, initial, clear, backing); + }); +} + HRESULT proxy_create_resource(DeviceProxy* self, const D3D12_HEAP_PROPERTIES* heap_properties, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC* xbox_desc, D3D12_RESOURCE_STATES initial_state, const D3D12_CLEAR_VALUE* clear_value, @@ -1477,20 +1539,12 @@ HRESULT proxy_create_resource(DeviceProxy* self, const D3D12_HEAP_PROPERTIES* he "[rt] d3d12_xs: slot 76 resource: dimension=%d xbox layout=0x%x -> PC layout=0x%x\n", static_cast(pc_desc.Dimension), xbox_layout, static_cast(pc_desc.Layout)); } - constexpr auto depth_uav_flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; - if (self->depth_stencil_uav_provider && (xbox_desc->Flags & depth_uav_flags) == depth_uav_flags && - pc_desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && pc_desc.Format == DXGI_FORMAT_R32G8X24_TYPELESS && - pc_desc.DepthOrArraySize == 1 && pc_desc.MipLevels == 1 && pc_desc.SampleDesc.Count == 1) { - pc_desc.Flags &= ~D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; - // Only the color storage images need UAV access. The native depth image must be created in a legal PC state. - const auto depth_state = initial_state == D3D12_RESOURCE_STATE_UNORDERED_ACCESS - ? D3D12_RESOURCE_STATE_COMMON : initial_state; + if (supports_depth_uav(self, *xbox_desc)) { ID3D12Resource* resource = nullptr; - HRESULT hr = self->real->CreateCommittedResource(heap_properties, heap_flags, &pc_desc, depth_state, - clear_value, IID_PPV_ARGS(&resource)); + HRESULT hr = create_depth_uav_backing(self, heap_properties, heap_flags, depth_image_desc(pc_desc), + depth_image_state(initial_state), clear_value, &resource); if (FAILED(hr)) return hr; - hr = self->depth_stencil_uav_provider(resource); - if (SUCCEEDED(hr)) hr = resource->QueryInterface(*riid, out); + hr = resource->QueryInterface(*riid, out); resource->Release(); return hr; } @@ -1539,6 +1593,10 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64 return hr_to_u64(proxy_create_compute_pipeline_from_native_code( self, reinterpret_cast(a1), reinterpret_cast(a2), reinterpret_cast(a3))); + } else if constexpr (Slot == 133) { + return hr_to_u64(proxy_create_placed_depth(self, a1, reinterpret_cast(a2), + static_cast(a3), reinterpret_cast(a4), + reinterpret_cast(a5), reinterpret_cast(a6))); } else if constexpr (Slot == 76) { return hr_to_u64(proxy_create_resource( self, reinterpret_cast(a1), @@ -1702,10 +1760,11 @@ bool set_device_adapter_provider(void* device, DxgiAdapterProvider provider) { return true; } -bool set_depth_stencil_uav_provider(void* device, DepthStencilUavProvider provider) { +bool set_depth_stencil_uav_provider(void* device, DepthStencilUavProvider provider, ValidateDepthPlacement validate) { auto* proxy = static_cast(device_proxy_primary(device)); if (!proxy) return false; proxy->depth_stencil_uav_provider = provider; + proxy->validate_depth_placement = validate; return true; } @@ -1731,7 +1790,7 @@ ID3D12Device* device_proxy_real_device(const void* device) { bool device_slot_overridden(unsigned slot) { if (slot <= 2 || slot == 8 || slot == 9 || slot == 14 || slot == 31 || slot == 32 || slot == 34 || slot == 35 || slot == 36 || slot == 45 || slot == 46 || slot == 50 || slot == 62 || slot == 67 || - slot == 75 || slot == 76) + slot == 75 || slot == 76 || slot == 133) return true; const XboxDeviceSlotRoutes& routes = xbox_device_slot_routes(); return slot == routes.frame_interval || slot == routes.schedule_event || slot == routes.wait_event || diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index fa4378cb53..bd04b323d7 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -49,6 +49,7 @@ #include +#include #include namespace rt::d3d12_xs { @@ -74,9 +75,27 @@ bool is_device_proxy(const void* device); using DxgiAdapterProvider = HRESULT (*)(ID3D12Device* real, REFIID riid, void** out); // `device` is the proxy or its DXGI pointer. False, with a line on stderr, when it is neither: nothing is set then. bool set_device_adapter_provider(void* device, DxgiAdapterProvider provider); -// Called before publishing a slot-76 resource when the backend can implement the Xbox depth/stencil UAV views. -using DepthStencilUavProvider = HRESULT (*)(ID3D12Resource* resource); -bool set_depth_stencil_uav_provider(void* device, DepthStencilUavProvider provider); +// Called before publishing an Xbox resource when the backend can implement its depth/stencil UAV views. +using DepthStencilUavProvider = HRESULT (*)(ID3D12Resource* resource, D3D12_HEAP_FLAGS storage_heap_flags); +using ValidateDepthPlacement = bool (*)(const D3D12_RESOURCE_DESC&, D3D12_RESOURCE_STATES, const D3D12_CLEAR_VALUE*); +bool set_depth_stencil_uav_provider(void* device, DepthStencilUavProvider provider, + ValidateDepthPlacement validate_placement = nullptr); + +// The Vulkan implementation uses this private interface to look up an image for view creation. +inline constexpr GUID kVulkanResourceTag{0x9b3e5f12, 0x7c48, 0x4d0e, {0xa6, 0xb1, 0x2f, 0x8d, 0x4c, 0x7e, 0x9a, 0x35}}; + +// Identically placed Xbox depth textures have distinct COM identities but refer to one GPU image and layout. +// Only these wrappers carry a backing pointer. Every other resource retains its ordinary pointer-valued IR ID. +struct PlacedDepthInterface : ID3D12Resource { + ID3D12Resource* backing = nullptr; +}; +inline std::atomic placed_depth_vtable{nullptr}; +inline const ID3D12Resource* texture_backing(const ID3D12Resource* resource) { + const void* vtable = placed_depth_vtable.load(std::memory_order_acquire); + if (resource && vtable && *reinterpret_cast(resource) == vtable) + return static_cast(resource)->backing; + return resource; +} // The device proxy an IDXGIDevice pointer handed out by one belongs to, or null. void* device_proxy_from_dxgi_device(void* dxgi_device); // The device proxy itself, given the proxy or its DXGI pointer; null for anything else. diff --git a/runtime/shims/d3d12_xs_placed_depth.h b/runtime/shims/d3d12_xs_placed_depth.h new file mode 100644 index 0000000000..a4796e6af9 --- /dev/null +++ b/runtime/shims/d3d12_xs_placed_depth.h @@ -0,0 +1,125 @@ +// GPU backing for slot-133 depth/UAV textures, keyed by the Xbox placement range on one device. +#pragma once + +#include "d3d12_com_object.h" +#include "d3d12_xs_device.h" + +#include +#include +#include +#include +#include +#include + +namespace rt::d3d12_xs { + +class PlacedDepthTexture final + : public d3d12::Object { +public: + static constexpr GUID kTag{0x64472a85, 0x967d, 0x46bc, {0x96, 0xaf, 0x68, 0x1f, 0x50, 0x35, 0x64, 0x71}}; + + PlacedDepthTexture(std::shared_ptr owner, UINT64 address) + : owner_(std::move(owner)), address_(address) { + backing = owner_.get(); + placed_depth_vtable.store(*reinterpret_cast(this), std::memory_order_release); + } + + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void** out) override { + if (iid == kVulkanResourceTag) return backing->QueryInterface(iid, out); + return Object::QueryInterface(iid, out); + } + HRESULT STDMETHODCALLTYPE GetDevice(REFIID iid, void** out) override { return backing->GetDevice(iid, out); } + D3D12_RESOURCE_DESC STDMETHODCALLTYPE GetDesc() override { return backing->GetDesc(); } + D3D12_GPU_VIRTUAL_ADDRESS STDMETHODCALLTYPE GetGPUVirtualAddress() override { return address_; } + HRESULT STDMETHODCALLTYPE GetHeapProperties(D3D12_HEAP_PROPERTIES* props, D3D12_HEAP_FLAGS* flags) override { + return backing->GetHeapProperties(props, flags); + } + HRESULT STDMETHODCALLTYPE Map(UINT index, const D3D12_RANGE* read, void** data) override { + return backing->Map(index, read, data); + } + void STDMETHODCALLTYPE Unmap(UINT index, const D3D12_RANGE* written) override { backing->Unmap(index, written); } + HRESULT STDMETHODCALLTYPE WriteToSubresource(UINT index, const D3D12_BOX* box, const void* data, + UINT row_pitch, UINT depth_pitch) override { + return backing->WriteToSubresource(index, box, data, row_pitch, depth_pitch); + } + HRESULT STDMETHODCALLTYPE ReadFromSubresource(void* data, UINT row_pitch, UINT depth_pitch, + UINT index, const D3D12_BOX* box) override { + return backing->ReadFromSubresource(data, row_pitch, depth_pitch, index, box); + } + +private: + std::shared_ptr owner_; + UINT64 address_; +}; + +class PlacedDepthTextures { +public: + // The valid legacy state and optimized clear are checked for each caller before looking up an alias. + // Reusing a live compatible placement retains both the attachment image and its writable plane images. + template + HRESULT create(UINT64 address, const D3D12_RESOURCE_DESC& desc, D3D12_RESOURCE_ALLOCATION_INFO allocation, + const D3D12_CLEAR_VALUE* clear, REFIID iid, void** out, Create create_backing) { + if (!address || !allocation.Alignment || address % allocation.Alignment || !allocation.SizeInBytes || + allocation.SizeInBytes > UINT64_MAX - address) + return E_INVALIDARG; + const UINT64 end = address + allocation.SizeInBytes; + // Placed RT/DS textures can inherit contents only when their optimized clear values also match. + // Compare the defined fields. D3D12_CLEAR_VALUE has union padding, and D16 has no stencil plane. + std::optional optimized; + if (clear) optimized = OptimizedClear{clear->Format, std::bit_cast(clear->DepthStencil.Depth), + desc.Format == DXGI_FORMAT_R16_TYPELESS ? UINT8(0) : clear->DepthStencil.Stencil}; + std::shared_ptr owner; + try { + { + std::lock_guard lock(mutex_); + // Weak ownership avoids keeping GPU images or the device alive just because an address was used. + std::erase_if(ranges_, [](const auto& entry) { return entry.second.backing.expired(); }); + auto next = ranges_.lower_bound(address); + if (next != ranges_.begin() && std::prev(next)->second.end > address) return E_NOTIMPL; + if (next != ranges_.end() && next->first < end) { + const auto& range = next->second; + if (next->first != address || range.end != end || !compatible(desc, range.desc) || + range.optimized != optimized) return E_NOTIMPL; + owner = range.backing.lock(); + } + if (!owner) { + ID3D12Resource* resource = nullptr; + const HRESULT hr = create_backing(&resource); + if (FAILED(hr)) return hr; + owner = {resource, [](ID3D12Resource* r) { r->Release(); }}; + ranges_.insert_or_assign(address, Range{end, desc, optimized, owner}); + } + } + auto* alias = new PlacedDepthTexture(std::move(owner), address); + return d3d12::hand_out(alias, iid, out); + } catch (const std::bad_alloc&) { + return E_OUTOFMEMORY; + } + } + +private: + // Dimension, mip/sample counts and layout are fixed by the slot handler. The effective alignment and byte + // interval have already been validated. All remaining usage and image geometry must match for data inheritance. + static bool compatible(const D3D12_RESOURCE_DESC& a, const D3D12_RESOURCE_DESC& b) { + return a.Format == b.Format && a.Width == b.Width && a.Height == b.Height && + a.DepthOrArraySize == b.DepthOrArraySize && a.SampleDesc.Quality == b.SampleDesc.Quality && + a.Flags == b.Flags; + } + struct OptimizedClear { + DXGI_FORMAT format; + UINT depth_bits; + UINT8 stencil; + bool operator==(const OptimizedClear&) const = default; + }; + struct Range { + UINT64 end; + D3D12_RESOURCE_DESC desc; + std::optional optimized; + std::weak_ptr backing; + }; + std::mutex mutex_; + std::map ranges_; +}; + +} // namespace rt::d3d12_xs diff --git a/runtime/src/queue_families.h b/runtime/src/queue_families.h index 3148d0ad11..51a8c40c18 100644 --- a/runtime/src/queue_families.h +++ b/runtime/src/queue_families.h @@ -12,6 +12,16 @@ namespace leonida { +// The device's distinct family indices. An object used on more than one family keeps its contents +// across fenced D3D12 queue handoffs without explicit Vulkan ownership transfers. +template +void share_across_queue_families(CreateInfo& create, std::span families) { + if (families.size() < 2) return; + create.sharingMode = VK_SHARING_MODE_CONCURRENT; + create.queueFamilyIndexCount = static_cast(families.size()); + create.pQueueFamilyIndices = families.data(); +} + // Queue families for D3D12's three queue types. Direct needs graphics. Compute prefers a family with compute and no // graphics (async compute), copy one with transfer and neither (a DMA engine); each falls back to a more capable // family, ending at the graphics one. A dedicated copy family is only used when its image transfer granularity is diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 91001de96e..9a1aa36b06 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -1363,6 +1363,9 @@ class VulkanContext { // and records what the set needs first. When it fails, nothing of that call is executed. void set_transfer_only_family(std::uint32_t family) { transfer_only_family_ = family; } void set_graphics_family(std::uint32_t family) { graphics_family_ = family; } + void set_compute_copy_aspects(std::function check) { + replay_.compute_copy_aspects = std::move(check); + } void set_bindless_prepare(std::function prepare) { std::unique_lock lock(resource_mutex_); @@ -1387,9 +1390,10 @@ class VulkanContext { // Copies the replay stages through a buffer (depth <-> colour, vulkan_replay.h) take device-local scratch from // `allocate`. Without this such a copy is refused as unsupported. - void enable_copy_scratch(PFN_vkGetDeviceProcAddr get, ScratchBuffers::Allocate allocate) { + void enable_copy_scratch(PFN_vkGetDeviceProcAddr get, ScratchBuffers::Allocate allocate, + std::vector families = {}) { std::unique_lock lock(resource_mutex_); - scratch_ = std::make_unique(get, device_, std::move(allocate)); + scratch_ = std::make_unique(get, device_, std::move(allocate), std::move(families)); if (!scratch_->loaded()) scratch_.reset(); } @@ -2450,8 +2454,7 @@ class VulkanQueue : private QueueHolds::Holder { storage_init_seen_ = context_.storage_init_version_; } // The set this submission binds may be a new generation whose table another queue's submission uploads: - // wait for that one, as for the storage images (the table's buffers are used by one queue family only: - // every D3D12 queue of the device is made in info.queue_family). + // wait for that one, as for the storage images. The table and fallback images share the device's families. if (context_.bindless_upload_semaphore_ && context_.bindless_upload_semaphore_ != progress_ && context_.bindless_upload_version_ != bindless_upload_seen_) { waits_.push_back(context_.bindless_upload_semaphore_); diff --git a/runtime/src/vulkan_bindless.h b/runtime/src/vulkan_bindless.h index cb5b61f655..826c3d6bb6 100644 --- a/runtime/src/vulkan_bindless.h +++ b/runtime/src/vulkan_bindless.h @@ -43,6 +43,7 @@ #define VK_NO_PROTOTYPES #endif #include "descriptor_table.h" +#include "queue_families.h" #include @@ -52,6 +53,7 @@ #include #include #include +#include #include namespace leonida { @@ -314,8 +316,8 @@ inline bool size_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimi class BindlessSet { public: BindlessSet(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceMemoryProperties& memory, - BindlessFeatures features = {}) - : device_(device), memory_(memory), features_(features) { + BindlessFeatures features = {}, std::vector families = {}) + : device_(device), memory_(memory), features_(features), families_(std::move(families)) { ok_ = vk_.load(get, device) && create_layout() && create_fallbacks() && create_table_buffers() && fill(); } @@ -713,6 +715,7 @@ class BindlessSet { if (t != ms_type) info.usage |= VK_IMAGE_USAGE_STORAGE_BIT; if (t == ms_type || c == 0) info.usage |= VK_IMAGE_USAGE_SAMPLED_BIT; FallbackImage& image = fallback_images_[t * classes + c]; + share_across_queue_families(info, families_); if (vk_.vkCreateImage(device_, &info, nullptr, &image.image) != VK_SUCCESS) return false; VkMemoryRequirements requirements{}; vk_.vkGetImageMemoryRequirements(device_, image.image, &requirements); @@ -760,6 +763,7 @@ class BindlessSet { (device_local ? VK_BUFFER_USAGE_TRANSFER_DST_BIT : VK_BUFFER_USAGE_TRANSFER_SRC_BIT); TableBuffer made; made.size = bytes; + share_across_queue_families(info, families_); if (vk_.vkCreateBuffer(device_, &info, nullptr, &made.buffer) != VK_SUCCESS) return false; VkMemoryRequirements requirements{}; vk_.vkGetBufferMemoryRequirements(device_, made.buffer, &requirements); @@ -1014,6 +1018,7 @@ class BindlessSet { VkDevice device_; VkPhysicalDeviceMemoryProperties memory_; BindlessFeatures features_; + std::vector families_; Functions vk_; bool ok_ = false; VkDescriptorSetLayout layout_ = VK_NULL_HANDLE; diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index e334a945a1..5c0bf246d2 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -812,7 +812,9 @@ struct ReplayFunctions { // Optional; a list that needs a missing one is rejected with ReplayResult::unsupported. PFN_vkCmdPipelineBarrier2 pipeline_barrier2 = nullptr; // enhanced barriers VkPipelineStageFlags2 queue_stages = 0; - bool graphics_family = true; // depth/stencil image-buffer transfers require a graphics-capable queue + bool graphics_family = true; + // Aspects with maintenance10 depth/stencil transfer support on a dedicated compute family. + std::function compute_copy_aspects; PFN_vkCmdBeginRendering begin_rendering = nullptr; // rectangle clears PFN_vkCmdEndRendering end_rendering = nullptr; PFN_vkCmdClearAttachments clear_attachments = nullptr; @@ -1013,6 +1015,7 @@ struct Prepared { // A depth <-> colour copy: the source into `staged` (image to buffer), then `staged` into the destination. VkBuffer staged = VK_NULL_HANDLE; std::vector staged_reads, staged_writes; + VkDeviceSize clear_pattern_bytes = 0; // rectangular UAV clear on a compute-only queue std::vector discards; // DiscardResource: the subresources to discard VkBuffer write_buffer = VK_NULL_HANDLE; // WriteBufferImmediate: where the address lands VkDeviceSize write_offset = 0; @@ -1044,8 +1047,11 @@ inline bool texture_uav_layout(std::uint32_t layout) { layout == d3d12_layout::compute_queue_unordered_access; } -inline bool queue_common_layout(std::uint32_t layout) { - return layout == d3d12_layout::direct_queue_common || layout == d3d12_layout::compute_queue_common; +inline bool unsupported_depth_uav_access(std::uint32_t layout, std::uint32_t access) { + // A queue-specific COMMON layout permits implicit storage writes. Generic COMMON permits only + // sampling and copies, even when the access scope is COMMON (zero). + return layout == d3d12_layout::direct_queue_common || layout == d3d12_layout::compute_queue_common || + (layout == d3d12_layout::common && (access & d3d12_access::unordered_access)); } inline constexpr std::size_t max_render_targets = 8; // D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT @@ -1358,14 +1364,12 @@ inline LayoutPieces current(const LayoutTracker* tracker, ResourceId id, const V return out; } -// Zero-fills a block-compressed image range via vkCmdCopyBufferToImage from either the device's zero page -// (`vk.zero_buffer`) or a zeroed transfer-scratch chunk (`vk.copy_scratch` + `vk.fill_buffer`). Vulkan forbids -// vkCmdClearColorImage on BC formats, yet D3D12 committed resources start zeroed unless CREATE_NOT_ZEROED is set -// (D3D-220). -inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer command_buffer, - const ResourceBinding& resource, const VkImageSubresourceRange& range, - VkImageLayout dst_layout) { - const BlockFormat fmt = block_format(resource.format, VK_IMAGE_ASPECT_COLOR_BIT); +// Copies zeroes from the device's zero page or transfer scratch. A buffer can initialize block-compressed +// images and, with maintenance10, a depth or stencil aspect on a compute-only queue where a clear is illegal. +inline bool zero_image_aspect(const ReplayFunctions& vk, VkCommandBuffer command_buffer, + const ResourceBinding& resource, const VkImageSubresourceRange& range, + VkImageAspectFlags aspect, VkImageLayout dst_layout) { + const BlockFormat fmt = block_format(resource.format, aspect); if (fmt.block < 1 || !fmt.bytes || !vk.copy_buffer_to_image) return false; const std::uint32_t mip_begin = range.baseMipLevel; const std::uint32_t mip_end = @@ -1399,7 +1403,7 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com VkDeviceSize zero_off = 0; VkDeviceSize zero_cap = 0; if (vk.zero_buffer && vk.zero_size >= fmt.bytes) { - const VkDeviceSize align = fmt.bytes; + const VkDeviceSize align = std::max(4, fmt.bytes); const VkDeviceSize pad = (align - (vk.zero_offset % align)) % align; if (vk.zero_size >= pad + fmt.bytes) { zero_buf = vk.zero_buffer; @@ -1408,12 +1412,11 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com } } if (!zero_buf && vk.copy_scratch && vk.fill_buffer) { - // Round up to a multiple of fmt.bytes (8 or 16, always a multiple of 4 for vkCmdFillBuffer). - const VkDeviceSize fill_bytes = ((needed + fmt.bytes - 1) / fmt.bytes) * fmt.bytes; + const VkDeviceSize align = std::max(4, fmt.bytes); + const VkDeviceSize fill_bytes = ((needed + align - 1) / align) * align; VkBuffer scratch = VK_NULL_HANDLE; VkDeviceSize offset = 0; if (vk.copy_scratch(fill_bytes, scratch, offset)) { - const VkDeviceSize align = fmt.bytes; const VkDeviceSize pad = (align - (offset % align)) % align; if (fill_bytes >= pad + fmt.bytes) { vk.fill_buffer(command_buffer, scratch, offset + pad, fill_bytes - pad, 0); @@ -1438,7 +1441,7 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com layer_count <= zero_cap / (slice_bytes * mip_d)) { VkBufferImageCopy r{}; r.bufferOffset = zero_off; - r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, mip, layer_begin, layer_count}; + r.imageSubresource = {aspect, mip, layer_begin, layer_count}; r.imageExtent = {ext.width, ext.height, mip_d}; regions.push_back(r); continue; @@ -1451,7 +1454,7 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com for (std::uint32_t z = 0; z < mip_d; z += slices_per_copy) { VkBufferImageCopy r{}; r.bufferOffset = zero_off; - r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, mip, layer, 1}; + r.imageSubresource = {aspect, mip, layer, 1}; r.imageOffset = {0, 0, std::int32_t(z)}; r.imageExtent = {ext.width, ext.height, std::min(slices_per_copy, mip_d - z)}; regions.push_back(r); @@ -1465,7 +1468,7 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com const std::uint32_t eh = std::min(rows_per_copy * fmt.block, ext.height - oy); VkBufferImageCopy r{}; r.bufferOffset = zero_off; - r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, mip, layer, 1}; + r.imageSubresource = {aspect, mip, layer, 1}; r.imageOffset = {0, std::int32_t(oy), std::int32_t(z)}; r.imageExtent = {ext.width, eh, 1}; regions.push_back(r); @@ -1484,7 +1487,7 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com std::min(cols_per_copy * fmt.block, ext.width - ox); VkBufferImageCopy r{}; r.bufferOffset = zero_off; - r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, mip, layer, 1}; + r.imageSubresource = {aspect, mip, layer, 1}; r.imageOffset = {std::int32_t(ox), std::int32_t(oy), std::int32_t(z)}; r.imageExtent = {ew, eh, 1}; regions.push_back(r); @@ -1513,11 +1516,13 @@ inline void initialize(const ReplayFunctions& vk, VkCommandBuffer command_buffer const bool color = piece.range.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT; const bool can_clear = !vk.queue_stages || ((vk.queue_stages & VK_PIPELINE_STAGE_2_CLEAR_BIT) && color) || (resource.depth_uav && vk.graphics_family); - const bool compressed = fmt.block > 1 || (!can_clear && color); - if (resource.not_zeroed || (!can_clear && !color)) { + const bool compute_depth = !color && resource.depth_uav && !vk.graphics_family && + (vk.queue_stages & VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT) && vk.compute_copy_aspects && + (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); - } else if (compressed) { + } else if (fmt.block > 1 || !can_clear) { const bool can_zero = vk.copy_buffer_to_image && ((vk.zero_buffer && vk.zero_size >= fmt.bytes) || (vk.copy_scratch && vk.fill_buffer)); @@ -1526,7 +1531,10 @@ inline void initialize(const ReplayFunctions& vk, VkCommandBuffer command_buffer 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); - const bool zeroed = zero_compressed_image(vk, command_buffer, resource, piece.range, dst); + 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) + zeroed &= zero_image_aspect(vk, command_buffer, resource, piece.range, aspect, dst); 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, @@ -2091,7 +2099,7 @@ void round_trip(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const } // Vulkan cannot copy a depth or stencil image aspect directly to or from a color image. The transfer -// buffer preserves the native D32 or S8 bits. Only the requested planes are copied, even when the device +// buffer preserves the native D16, D32 or S8 bits. Only the requested layers and planes are copied, even when the device // requires both parent aspects to transition layouts together. A storage descriptor always names GENERAL. inline void copy_depth_uav(const ReplayFunctions& vk, VkCommandBuffer cb, const Prepared& p, const DepthUavCopy& copy, VkImageLayout parent_layout, LayoutTracker* tracker) { @@ -2103,7 +2111,8 @@ inline void copy_depth_uav(const ReplayFunctions& vk, VkCommandBuffer cb, const const auto parent_range = planes_for_layout(p.binding, p.range, vk.separate_depth_stencil_layouts); image_barrier(vk, cb, p.binding, parent_range, parent_layout, VK_IMAGE_LAYOUT_GENERAL, any, all, parent_access, transfer); - constexpr VkImageSubresourceRange color{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + auto color = p.range; + color.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; for (unsigned plane = 0; plane < copy.storage.size(); ++plane) { const ResourceBinding& child = copy.storage[plane]; if (!child.image) continue; @@ -2111,13 +2120,13 @@ inline void copy_depth_uav(const ReplayFunctions& vk, VkCommandBuffer cb, const auto pieces = current(tracker, child_id, color, VK_IMAGE_LAYOUT_GENERAL); if (!copy.to_storage) initialize(vk, cb, child, child_id, pieces, VK_IMAGE_LAYOUT_GENERAL, tracker); for (const auto& piece : pieces) - image_barrier(vk, cb, child, color, piece.layout, VK_IMAGE_LAYOUT_GENERAL, + image_barrier(vk, cb, child, piece.range, piece.layout, VK_IMAGE_LAYOUT_GENERAL, piece.layout == VK_IMAGE_LAYOUT_UNDEFINED ? 0 : any, all, child_access, transfer); if (tracker) tracker->set(child_id, color, VK_IMAGE_LAYOUT_GENERAL); VkBufferImageCopy parent_region{}; parent_region.bufferOffset = copy.offset; const VkImageAspectFlags aspect = plane ? VK_IMAGE_ASPECT_STENCIL_BIT : VK_IMAGE_ASPECT_DEPTH_BIT; - parent_region.imageSubresource = {aspect, 0, 0, 1}; + parent_region.imageSubresource = {aspect, p.range.baseMipLevel, p.range.baseArrayLayer, p.range.layerCount}; parent_region.imageExtent = {p.binding.width, p.binding.height, 1}; VkBufferImageCopy child_region = parent_region; child_region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; @@ -2596,7 +2605,8 @@ inline bool zero_clear_unavailable(const PreparedList& prepared, const ReplayFun if (missing(id, p.binding, p.range)) return true; if (p.depth_uav_copy != UINT32_MAX) { const auto& copy = prepared.depth_uav_copies[p.depth_uav_copy]; - constexpr VkImageSubresourceRange color{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + auto color = p.range; + color.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; if (!copy.to_storage && (missing(p.binding.depth_uav, copy.storage[0], color) || missing(p.binding.stencil_uav, copy.storage[1], color))) return true; } @@ -2656,8 +2666,16 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun p.order_depth_uav = after; return ReplayResult::success; } - if (!vk.graphics_family || !vk.copy_image_to_buffer || !vk.copy_buffer_to_image || !vk.copy_scratch) + if (!vk.copy_image_to_buffer || !vk.copy_buffer_to_image || !vk.copy_scratch) return ReplayResult::unsupported; + if (!vk.graphics_family) { + // Coupled layouts can also need to zero-initialize the sibling plane on first use. + const auto aspects = detail::planes_for_layout(p.binding, p.range, vk.separate_depth_stencil_layouts).aspectMask; + if (!(vk.queue_stages & VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT) || !vk.compute_copy_aspects || + (vk.compute_copy_aspects(p.binding.format) & aspects) != aspects) + return ReplayResult::unsupported; + } + if (p.range.baseMipLevel || p.range.levelCount != 1) return ReplayResult::unsupported; detail::DepthUavCopy copy{}; const ResourceId ids[] = {p.binding.depth_uav, p.binding.stencil_uav}; for (unsigned plane = 0; plane < 2; ++plane) { @@ -2668,9 +2686,12 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun copy.storage[plane] = *child; } const VkDeviceSize texels = VkDeviceSize(p.binding.width) * p.binding.height; - const VkDeviceSize bytes_per_texel = p.range.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT ? 4 : 1; - if (!texels || texels > UINT64_MAX / bytes_per_texel) return ReplayResult::unsupported; - const VkDeviceSize bytes = texels * bytes_per_texel; + const auto largest_aspect = p.range.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT ? VK_IMAGE_ASPECT_DEPTH_BIT : + VK_IMAGE_ASPECT_STENCIL_BIT; + const VkDeviceSize bytes_per_texel = block_format(p.binding.format, largest_aspect).bytes; + if (!texels || !bytes_per_texel || texels > UINT64_MAX / bytes_per_texel / p.range.layerCount) + return ReplayResult::unsupported; + const VkDeviceSize bytes = texels * bytes_per_texel * p.range.layerCount; if (bytes > plane_capacity) { if (!vk.copy_scratch(bytes, plane_scratch, plane_offset) || !plane_scratch || plane_offset % 4) return ReplayResult::unsupported; @@ -2736,8 +2757,9 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun // In a queue-specific COMMON layout shaders can write a UAV then read the SRV or copy the // parent after only a global barrier. Bindless shaders need no per-resource bind command, so // there is no observable ownership transition at which to synchronize the two images. - if (p.binding.depth_uav && (detail::queue_common_layout(texture->layout_before) || - detail::queue_common_layout(texture->layout_after))) + if (p.binding.depth_uav && + (detail::unsupported_depth_uav_access(texture->layout_before, texture->access_before) || + detail::unsupported_depth_uav_access(texture->layout_after, texture->access_after))) return ReplayResult::unsupported; if (!(texture->flags & texture_barrier_discard) && texture->layout_before != d3d12_layout::undefined) { const auto result = prepare_depth_uav(p, detail::texture_uav_layout(texture->layout_before), @@ -2830,6 +2852,34 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!uav_clear::decode(clear_format, p.element, p.clear_color)) return ReplayResult::unsupported; if (reinterpret) p.clear_format = view_format; + // Compute list barriers have no attachment stages, and a dedicated compute queue cannot render. + // Copy the encoded texel bits from a filled buffer. Transfers cannot implement a predicated clear. + if ((vk.queue_stages & VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT) && + (!uav->rects.empty() || reinterpret || predicated)) { + if (predicated || p.binding.volume || !vk.copy_scratch || !vk.fill_buffer || !vk.copy_buffer_to_image || + (p.element.size != 1 && p.element.size != 2 && p.element.size != 4)) + return ReplayResult::unsupported; + const auto rects = uav->rects.empty() ? std::span(&whole_view, 1) : + std::span(uav->rects); + detail::clip(rects, detail::mip_extent(p.binding, view.mip), view.layer_count, p.rects); + if (p.rects.empty()) { p.skip = true; continue; } + for (const auto& rect : p.rects) { + VkBufferImageCopy region{}; + region.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, view.mip, view.first_layer, view.layer_count}; + region.imageOffset = {rect.rect.offset.x, rect.rect.offset.y, 0}; + region.imageExtent = {rect.rect.extent.width, rect.rect.extent.height, 1}; + const VkDeviceSize pixels = VkDeviceSize(region.imageExtent.width) * region.imageExtent.height; + const VkDeviceSize stride = VkDeviceSize(view.layer_count) * p.element.size; + if (pixels > (UINT64_MAX - 3) / stride) return ReplayResult::unsupported; + p.clear_pattern_bytes = std::max(p.clear_pattern_bytes, (pixels * stride + 3) & ~VkDeviceSize(3)); + p.staged_writes.push_back(region); + } + VkDeviceSize offset = 0; + if (!vk.copy_scratch(p.clear_pattern_bytes, p.staged, offset) || !p.staged || offset % 4) + return ReplayResult::unsupported; + for (auto& region : p.staged_writes) region.bufferOffset = offset; + continue; + } if (!uav->rects.empty() && !attachment) return ReplayResult::unsupported; // Under a predicate a whole view is cleared as one rectangle where the image can be an attachment, as @@ -3753,6 +3803,21 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c 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); + 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, [&] { + detail::emit_buffer_fill(vk, command_buffer, p.staged, p.element, p.staged_writes.front().bufferOffset, + p.clear_pattern_bytes); + for (const auto& region : p.staged_writes) { + // The fill must be visible, and two clear rectangles may overlap. + detail::memory_barrier(vk, command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT); + vk.copy_buffer_to_image(command_buffer, p.staged, p.binding.image, layout, 1, ®ion); + } + }); + 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, [&] { diff --git a/runtime/src/vulkan_scratch.h b/runtime/src/vulkan_scratch.h index 4a8a59ddd7..48bfa50487 100644 --- a/runtime/src/vulkan_scratch.h +++ b/runtime/src/vulkan_scratch.h @@ -9,6 +9,7 @@ #define VK_NO_PROTOTYPES #endif #include +#include "queue_families.h" #include #include @@ -23,8 +24,9 @@ class ScratchBuffers { // A device-local allocation for a chunk; null on failure. using Allocate = std::function; - ScratchBuffers(PFN_vkGetDeviceProcAddr get, VkDevice device, Allocate allocate) - : device_(device), allocate_(std::move(allocate)) { + ScratchBuffers(PFN_vkGetDeviceProcAddr get, VkDevice device, Allocate allocate, + std::vector families = {}) + : device_(device), allocate_(std::move(allocate)), families_(std::move(families)) { loaded_ = vk_.load(get, device); } @@ -149,6 +151,8 @@ class ScratchBuffers { VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; info.size = size; info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; + // A retired chunk can be reused by a submission on a different queue family. + share_across_queue_families(info, families_); if (vk_.vkCreateBuffer(device_, &info, nullptr, &out.buffer) != VK_SUCCESS) return false; VkMemoryRequirements requirements{}; vk_.vkGetBufferMemoryRequirements(device_, out.buffer, &requirements); @@ -172,6 +176,7 @@ class ScratchBuffers { VkDevice device_; Allocate allocate_; + std::vector families_; Functions vk_; bool loaded_ = false; Batch current_; // handed out, not yet submitted diff --git a/runtime/test/d3d12_depth_stencil_uav_test.cpp b/runtime/test/d3d12_depth_stencil_uav_test.cpp index cc47031a3c..ff34f90107 100644 --- a/runtime/test/d3d12_depth_stencil_uav_test.cpp +++ b/runtime/test/d3d12_depth_stencil_uav_test.cpp @@ -1,6 +1,8 @@ -// Xbox slot 76, a compute dispatch through the Vulkan backend, and separate depth/stencil readbacks. +// Xbox depth/stencil creation, shader read-modify-write and exhaustive readback across queue submissions. // A synthetic compute shader looks up the T#s that the device writes. No game data. #include "d3d12_copy_compare.h" +#include "d3d12_depth_stencil_uav_views.h" +#include "d3d12_placed_depth_test.h" #include "d3d12_test_shaders.h" #include "shader_fixture_path.h" #include "test_temp_dir.h" @@ -37,15 +39,68 @@ void enhanced_transition(ID3D12GraphicsCommandList7* list, ID3D12Resource* textu list->Barrier(1, &group); } -int run(vktest::Device& vk, UINT width, UINT height, bool enhanced) { +enum class Handoff { direct, graphics_transitions, compute_transitions }; + +struct Batch { + Ref allocator; + Ref list; + bool open(ID3D12Device* device, D3D12_COMMAND_LIST_TYPE type) { + return SUCCEEDED(device->CreateCommandAllocator(type, IID_PPV_ARGS(&allocator.p))) && + SUCCEEDED(device->CreateCommandList(0, type, allocator.p, nullptr, IID_PPV_ARGS(&list.p))); + } + bool submit(ID3D12CommandQueue* queue, ID3D12Fence* done, UINT64 value) { + if (FAILED(list->Close())) return false; + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + return rt::d3d12::last_execute_result(queue) == leonida::ReplayResult::success && + SUCCEEDED(queue->Signal(done, value)); + } +}; + +bool compute_transfers(const vktest::Device& vk, VkFormat format, bool stencil) { + if (vk.compute_family == vk.family) return true; +#ifdef VK_KHR_maintenance10 + if (!vk.maintenance10) return false; + VkFormatProperties3 flags{VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_3}; + VkFormatProperties2 properties{VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2, &flags}; + vk.instance_fn("vkGetPhysicalDeviceFormatProperties2")( + vk.physical, format, &properties); + const VkFormatFeatureFlags2 required = VK_FORMAT_FEATURE_2_DEPTH_COPY_ON_COMPUTE_QUEUE_BIT_KHR | + (stencil ? VK_FORMAT_FEATURE_2_STENCIL_COPY_ON_COMPUTE_QUEUE_BIT_KHR : 0); + return (flags.optimalTilingFeatures & required) == required; +#else + return false; +#endif +} + +struct GuestAllocation { + void* address = nullptr; + ~GuestAllocation() { if (address) VirtualFree(address, 0, MEM_RELEASE); } +}; + +enum class Texture { committed, committed_array, placed, placed_array }; + +int run(vktest::Device& vk, UINT width, UINT height, bool enhanced, Texture kind, DXGI_FORMAT format, Handoff handoff) { + const bool array = kind == Texture::committed_array || kind == Texture::placed_array; + const bool placed = kind == Texture::placed || kind == Texture::placed_array; + const bool depth16 = format == DXGI_FORMAT_R16_TYPELESS; + const UINT layers = array ? 3 : 1; + const UINT planes = depth16 ? 1 : 2; + const UINT subresources = planes * layers; + const char* fixture = array ? LEONIDA_DEPTH_STENCIL_ARRAY_SPV : LEONIDA_DEPTH_STENCIL_2D_SPV; + const char* bindings = array ? "2,11,12" : "2,8,9"; + if (depth16) { + fixture = array ? LEONIDA_DEPTH16_ARRAY_SPV : LEONIDA_DEPTH16_2D_SPV; + bindings = array ? "2,12" : "2,9"; + } const auto program = d3d12test::fssm_program({0x44535541, 0xbf810000}); const auto shader = d3d12test::shader_container(program); const testfiles::ScratchDir library("leonida_depth_stencil_uav"); - CHECK(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_DEPTH_UAV_SPV), library.path() / "write.spv")); + CHECK(testfiles::copy_file(vktest::shader_fixture_path(fixture), library.path() / "write.spv")); { std::ofstream index(library.path() / "index.json", std::ios::binary); index << "{\"write\":{\"stage\":\"cs\",\"fssm_sha256\":\"" << leonida::sha256_hex(program) - << "\",\"bindings\":[2,8,9],\"push_constant_bytes\":80,\"local_size\":[1,1,1],\"wave64\":false}}"; + << "\",\"bindings\":[" << bindings << "],\"push_constant_bytes\":80,\"local_size\":[1,1,1],\"wave64\":false}}"; CHECK(index.good()); } @@ -56,6 +111,9 @@ int run(vktest::Device& vk, UINT width, UINT height, bool enhanced) { info.device = vk.device; info.queue = vk.queue; info.queue_family = vk.family; + info.compute_family = vk.compute_family; + info.compute_queues = {vk.compute_queue}; + info.maintenance10 = vk.maintenance10; info.bindless = vk.bindless; info.bindless_partially_bound = vk.partially_bound; info.buffer_device_address = vk.buffer_device_address; @@ -65,65 +123,116 @@ int run(vktest::Device& vk, UINT width, UINT height, bool enhanced) { Ref xbox; CHECK(SUCCEEDED(rt::d3d12_xs::create_device_proxy(device, IID_PPV_ARGS(&xbox.p)))); // takes ownership rt::d3d12::set_device_outer(device, xbox.p); + if (!enhanced && !array && !depth16) CHECK(placeddepthtest::check_alias_lifetime(device, xbox.p)); D3D12_RESOURCE_DESC desc{}; desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; desc.Width = width; desc.Height = height; - desc.MipLevels = desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.DepthOrArraySize = static_cast(layers); desc.SampleDesc.Count = 1; - desc.Format = DXGI_FORMAT_R32G8X24_TYPELESS; + desc.Format = format; desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; desc.Layout = static_cast(0x101); using CreateFn = HRESULT(WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS, const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_STATES, const D3D12_CLEAR_VALUE*, REFIID, void**); - // The Xbox slot-25 sizing path from #7110/#7679 is covered on the Forge integration branch. - // Use the inner PC device's native depth description for allocation size and readback footprints. + // The baseline uses PC sizing. In builds with the Xbox slot-25 dependency, size the placement through + // the console's return-buffer-first ABI; keep native footprints for the host pixel readback. auto native_depth = desc; native_depth.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; native_depth.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; - const auto size = device->GetResourceAllocationInfo(0, 1, &native_depth); + auto size = device->GetResourceAllocationInfo(0, 1, &native_depth); CHECK(size.SizeInBytes > 0 && size.SizeInBytes != UINT64_MAX); + if (rt::d3d12_xs::device_slot_overridden(25)) { + using SizeFn = D3D12_RESOURCE_ALLOCATION_INFO*(WINAPI*)(D3D12_RESOURCE_ALLOCATION_INFO*, void*, + UINT, UINT, const D3D12_RESOURCE_DESC*); + D3D12_RESOURCE_ALLOCATION_INFO xbox_size{}; + const auto get_size = reinterpret_cast(d3d12test::slot(xbox.p, 25)); + CHECK(get_size(&xbox_size, xbox.p, 0, 1, &desc) == &xbox_size); + CHECK(xbox_size.SizeInBytes >= size.SizeInBytes && xbox_size.SizeInBytes != UINT64_MAX && + xbox_size.Alignment >= size.Alignment); + size = xbox_size; + } D3D12_HEAP_PROPERTIES props{}; props.Type = D3D12_HEAP_TYPE_DEFAULT; - Ref texture; + GuestAllocation guest; + Ref texture, alias; const auto create_texture = reinterpret_cast(d3d12test::slot(xbox.p, 76)); - CHECK(SUCCEEDED(create_texture(xbox.p, &props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_DEPTH_WRITE, - nullptr, IID_PPV_ARGS(&texture.p)))); + if (placed) { + using PlaceFn = HRESULT(WINAPI*)(void*, UINT64, const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_STATES, + const D3D12_CLEAR_VALUE*, REFIID, void**); + const auto place = reinterpret_cast(d3d12test::slot(xbox.p, 133)); + guest.address = VirtualAlloc(nullptr, SIZE_T(size.SizeInBytes), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + CHECK(guest.address); + const auto va = reinterpret_cast(guest.address); + CHECK(SUCCEEDED(place(xbox.p, va, &desc, D3D12_RESOURCE_STATE_DEPTH_WRITE, nullptr, + IID_PPV_ARGS(&texture.p)))); + CHECK(SUCCEEDED(place(xbox.p, va, &desc, D3D12_RESOURCE_STATE_DEPTH_WRITE, nullptr, + IID_PPV_ARGS(&alias.p)))); + CHECK(texture.p != alias.p && texture->GetGPUVirtualAddress() == va && alias->GetGPUVirtualAddress() == va); + } else { + const auto heap_flags = !enhanced && !array && !depth16 + ? D3D12_HEAP_FLAG_ALLOW_SHADER_ATOMICS : D3D12_HEAP_FLAG_NONE; + CHECK(SUCCEEDED(create_texture(xbox.p, &props, heap_flags, &desc, D3D12_RESOURCE_STATE_DEPTH_WRITE, + nullptr, IID_PPV_ARGS(&texture.p)))); + D3D12_HEAP_FLAGS reported{}; + CHECK(SUCCEEDED(texture->GetHeapProperties(nullptr, &reported))); + CHECK((reported & D3D12_HEAP_FLAG_ALLOW_SHADER_ATOMICS) == heap_flags); + if (heap_flags) { + Ref depth_only; + CHECK(device->CreateCommittedResource(&props, heap_flags, &native_depth, D3D12_RESOURCE_STATE_DEPTH_WRITE, + nullptr, IID_PPV_ARGS(&depth_only.p)) == E_INVALIDARG && !depth_only.p); + for (auto type : {D3D12_HEAP_TYPE_UPLOAD, D3D12_HEAP_TYPE_READBACK}) { + auto cpu_heap = props; + cpu_heap.Type = type; + Ref invalid; + CHECK(create_texture(xbox.p, &cpu_heap, heap_flags, &desc, D3D12_RESOURCE_STATE_COMMON, + nullptr, IID_PPV_ARGS(&invalid.p)) == E_INVALIDARG && !invalid.p); + } + } + } CHECK(texture->GetDesc().Flags == desc.Flags); + if (array) CHECK(check_depth_uav_array_views(device, texture.p, depth16)); - const D3D12_DESCRIPTOR_HEAP_DESC dsv_desc{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + const D3D12_DESCRIPTOR_HEAP_DESC dsv_desc{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, layers, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; const D3D12_DESCRIPTOR_HEAP_DESC views_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; Ref dsv, views; CHECK(SUCCEEDED(device->CreateDescriptorHeap(&dsv_desc, IID_PPV_ARGS(&dsv.p)))); CHECK(SUCCEEDED(device->CreateDescriptorHeap(&views_desc, IID_PPV_ARGS(&views.p)))); D3D12_DEPTH_STENCIL_VIEW_DESC depth_view{}; - depth_view.Format = DXGI_FORMAT_D32_FLOAT_S8X24_UINT; - depth_view.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D; + depth_view.Format = depth16 ? DXGI_FORMAT_D16_UNORM : DXGI_FORMAT_D32_FLOAT_S8X24_UINT; + depth_view.ViewDimension = array ? D3D12_DSV_DIMENSION_TEXTURE2DARRAY : D3D12_DSV_DIMENSION_TEXTURE2D; + const SIZE_T dsv_step = device->GetDescriptorHandleIncrementSize(dsv_desc.Type); const auto depth_handle = dsv->GetCPUDescriptorHandleForHeapStart(); - device->CreateDepthStencilView(texture.p, &depth_view, depth_handle); + for (UINT layer = 0; layer < layers; ++layer) { + if (array) depth_view.Texture2DArray = {0, layer, 1}; + device->CreateDepthStencilView(texture.p, &depth_view, {depth_handle.ptr + dsv_step * layer}); + } const SIZE_T base = views->GetCPUDescriptorHandleForHeapStart().ptr; const SIZE_T step = device->GetDescriptorHandleIncrementSize(views_desc.Type); CHECK(base && step >= 32); std::uint32_t keys[2][8]{}; - for (UINT plane = 0; plane < 2; ++plane) { + for (UINT plane = 0; plane < planes; ++plane) { D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; - view.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; - view.Format = plane == 0 ? DXGI_FORMAT_R32_FLOAT : DXGI_FORMAT_R8_UINT; - view.Texture2D.PlaneSlice = plane; + view.ViewDimension = array ? D3D12_UAV_DIMENSION_TEXTURE2DARRAY : D3D12_UAV_DIMENSION_TEXTURE2D; + view.Format = depth16 ? DXGI_FORMAT_R16_UINT : plane == 0 ? DXGI_FORMAT_R32_FLOAT : DXGI_FORMAT_R8_UINT; + if (array) view.Texture2DArray = {0, 1, 2, plane}; + else view.Texture2D.PlaneSlice = plane; const D3D12_CPU_DESCRIPTOR_HANDLE handle{base + plane * step}; device->CreateUnorderedAccessView(texture.p, nullptr, &view, handle); std::memcpy(keys[plane], reinterpret_cast(handle.ptr), sizeof(keys[plane])); CHECK(rt::d3d12::bindless_hash_lookup(device, keys[plane]) != 0); } - CHECK(std::memcmp(keys[0], keys[1], sizeof(keys[0])) != 0); + if (planes == 2) CHECK(std::memcmp(keys[0], keys[1], sizeof(keys[0])) != 0); D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; - srv.Format = DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS; + srv.Format = depth16 ? DXGI_FORMAT_R16_UNORM : DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS; srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; - srv.Texture2D.MipLevels = 1; + srv.ViewDimension = array ? D3D12_SRV_DIMENSION_TEXTURE2DARRAY : D3D12_SRV_DIMENSION_TEXTURE2D; + if (array) srv.Texture2DArray = {0, 1, 1, 2, 0, 0.0f}; + else srv.Texture2D.MipLevels = 1; const D3D12_CPU_DESCRIPTOR_HANDLE sampled{base + 2 * step}; device->CreateShaderResourceView(texture.p, &srv, sampled); std::uint32_t sampled_key[8]{}; @@ -135,8 +244,9 @@ int run(vktest::Device& vk, UINT width, UINT height, bool enhanced) { for (UINT plane = 0; plane < 2; ++plane) { std::memset(reinterpret_cast(invalid.ptr), 0x55, sizeof(zero)); D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; - view.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; - view.Texture2D.PlaneSlice = plane; + view.ViewDimension = array ? D3D12_UAV_DIMENSION_TEXTURE2DARRAY : D3D12_UAV_DIMENSION_TEXTURE2D; + if (array) view.Texture2DArray = {0, 1, 2, plane}; + else view.Texture2D.PlaneSlice = plane; view.Format = plane == 0 ? DXGI_FORMAT_R8_UINT : DXGI_FORMAT_R32_FLOAT; device->CreateUnorderedAccessView(texture.p, nullptr, &view, invalid); CHECK(std::memcmp(reinterpret_cast(invalid.ptr), zero, sizeof(zero)) == 0); @@ -147,11 +257,11 @@ int run(vktest::Device& vk, UINT width, UINT height, bool enhanced) { D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; Ref visible; CHECK(SUCCEEDED(device->CreateDescriptorHeap(&visible_desc, IID_PPV_ARGS(&visible.p)))); - device->CopyDescriptorsSimple(2, visible->GetCPUDescriptorHandleForHeapStart(), {base}, visible_desc.Type); + device->CopyDescriptorsSimple(planes, visible->GetCPUDescriptorHandleForHeapStart(), {base}, visible_desc.Type); const auto gpu = visible->GetGPUDescriptorHandleForHeapStart(); const FLOAT depth_clear[] = {0.75f, 0, 0, 0}; const UINT stencil_clear[] = {0x31, 0, 0, 0}; - { + if (!array) { // Both parents have a real R32_FLOAT storage plane, but this T# belongs to the first parent only. auto other_desc = desc; other_desc.Width = other_desc.Height = 2; @@ -184,84 +294,151 @@ int run(vktest::Device& vk, UINT width, UINT height, bool enhanced) { Ref pipeline; CHECK(SUCCEEDED(device->CreateComputePipelineState(&pipeline_desc, IID_PPV_ARGS(&pipeline.p)))); - copycmp::Run commands; - CHECK(commands.init(device, true)); - D3D12_PLACED_SUBRESOURCE_FOOTPRINT layouts[2]{}; - UINT64 row_bytes[2]{}, total = 0; - device->GetCopyableFootprints(&native_depth, 0, 2, 0, layouts, nullptr, row_bytes, &total); - CHECK(row_bytes[0] == width * sizeof(float) && row_bytes[1] == width); + // Three submissions. Only the final fence is waited on by the CPU. + copycmp::Run graphics; + CHECK(graphics.init(device, true)); + const auto worker_type = handoff == Handoff::direct ? D3D12_COMMAND_LIST_TYPE_DIRECT : D3D12_COMMAND_LIST_TYPE_COMPUTE; + D3D12_COMMAND_QUEUE_DESC worker_desc{}; + worker_desc.Type = worker_type; + Ref worker; + CHECK(SUCCEEDED(device->CreateCommandQueue(&worker_desc, IID_PPV_ARGS(&worker.p)))); + Batch shader_batch, read_batch; + CHECK(shader_batch.open(device, worker_type) && read_batch.open(device, D3D12_COMMAND_LIST_TYPE_DIRECT)); + std::vector layouts(subresources); + std::vector row_bytes(subresources); + UINT64 total = 0; + device->GetCopyableFootprints(&native_depth, 0, subresources, 0, layouts.data(), nullptr, row_bytes.data(), &total); + CHECK(row_bytes[0] == width * (depth16 ? 2 : 4)); + if (planes == 2) CHECK(row_bytes[layers] == width); copycmp::Ptr readback; - CHECK(commands.buffer(D3D12_HEAP_TYPE_READBACK, total, D3D12_RESOURCE_STATE_COPY_DEST, readback)); + CHECK(graphics.buffer(D3D12_HEAP_TYPE_READBACK, total, D3D12_RESOURCE_STATE_COPY_DEST, readback)); - commands.begin(); - commands.list->ClearDepthStencilView(depth_handle, D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, - 0.5f, 0x5a, 0, nullptr); - Ref enhanced_list; + const float depth_seed[] = {0.5f, 0.25f, 1.0f}; + const UINT8 stencil_seed[] = {0x5a, 0x37, 0xcb}; + const UINT16 d16_seed[] = {0, 0xffff, 257}; + const auto flags = depth16 ? D3D12_CLEAR_FLAG_DEPTH : D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL; + for (UINT layer = 0; layer < layers; ++layer) + graphics.list->ClearDepthStencilView({depth_handle.ptr + dsv_step * layer}, flags, + depth16 ? float(d16_seed[layer]) / 65535.0f : depth_seed[layer], stencil_seed[layer], 0, nullptr); + + const bool compute_copy = handoff == Handoff::compute_transitions; + // Graphics-side transfers use ordinary cross-queue UAV layout. With maintenance10 the compute family can + // also perform the transfers, with COMMON as the shared handoff layout at both fences. if (enhanced) { - CHECK(SUCCEEDED(commands.list->QueryInterface(IID_PPV_ARGS(&enhanced_list.p)))); - enhanced_transition(enhanced_list.p, texture.p, D3D12_BARRIER_SYNC_DEPTH_STENCIL, - D3D12_BARRIER_ACCESS_DEPTH_STENCIL_WRITE, D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE, - D3D12_BARRIER_SYNC_COMPUTE_SHADING, D3D12_BARRIER_ACCESS_UNORDERED_ACCESS, - D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS); + Ref list; + CHECK(SUCCEEDED(graphics.list->QueryInterface(IID_PPV_ARGS(&list.p)))); + enhanced_transition(list.p, texture.p, D3D12_BARRIER_SYNC_DEPTH_STENCIL, + D3D12_BARRIER_ACCESS_DEPTH_STENCIL_WRITE, D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE, + D3D12_BARRIER_SYNC_ALL, compute_copy ? D3D12_BARRIER_ACCESS_COMMON : D3D12_BARRIER_ACCESS_UNORDERED_ACCESS, + compute_copy ? D3D12_BARRIER_LAYOUT_COMMON : D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS); } else { - commands.barrier(texture.p, D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + graphics.barrier(texture.p, D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + } + CHECK(SUCCEEDED(graphics.list->Close())); + ID3D12CommandList* write_lists[] = {graphics.list.p}; + graphics.queue->ExecuteCommandLists(1, write_lists); + CHECK(rt::d3d12::last_execute_result(graphics.queue.p) == leonida::ReplayResult::success); + CHECK(SUCCEEDED(graphics.queue->Signal(graphics.fence.p, 1))); + CHECK(SUCCEEDED(worker->Wait(graphics.fence.p, 1))); + Ref compute_list; + if (compute_copy) { + CHECK(SUCCEEDED(shader_batch.list->QueryInterface(IID_PPV_ARGS(&compute_list.p)))); + enhanced_transition(compute_list.p, texture.p, D3D12_BARRIER_SYNC_ALL, D3D12_BARRIER_ACCESS_COMMON, + D3D12_BARRIER_LAYOUT_COMMON, D3D12_BARRIER_SYNC_COMPUTE_SHADING, D3D12_BARRIER_ACCESS_UNORDERED_ACCESS, + D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS); } const D3D12_RECT depth_rect{1, 3, 2, 4}, stencil_rect{3, 2, 4, 3}; ID3D12DescriptorHeap* clear_heaps[] = {visible.p}; - commands.list->SetDescriptorHeaps(1, clear_heaps); - commands.list->ClearUnorderedAccessViewFloat(gpu, {base}, texture.p, depth_clear, 1, &depth_rect); - commands.list->ClearUnorderedAccessViewUint({gpu.ptr + step}, {base + step}, texture.p, stencil_clear, 1, - &stencil_rect); - D3D12_RESOURCE_BARRIER uav_order{}; - uav_order.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; - uav_order.UAV.pResource = texture.p; - commands.list->ResourceBarrier(1, &uav_order); - commands.list->SetComputeRootSignature(root.p); - commands.list->SetPipelineState(pipeline.p); - commands.list->SetComputeRoot32BitConstants(0, 16, keys, 0); - commands.list->Dispatch(1, 1, 1); + auto* list = shader_batch.list.p; + list->SetDescriptorHeaps(1, clear_heaps); + const UINT d16_clear[] = {0x4512, 0, 0, 0}; + if (depth16) list->ClearUnorderedAccessViewUint(gpu, {base}, texture.p, d16_clear, 1, &depth_rect); + else { + list->ClearUnorderedAccessViewFloat(gpu, {base}, texture.p, depth_clear, 1, &depth_rect); + list->ClearUnorderedAccessViewUint({gpu.ptr + step}, {base + step}, texture.p, stencil_clear, 1, &stencil_rect); + } + D3D12_RESOURCE_BARRIER order{}; + order.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + order.UAV.pResource = texture.p; + list->ResourceBarrier(1, &order); + list->SetComputeRootSignature(root.p); + list->SetPipelineState(pipeline.p); + list->SetComputeRoot32BitConstants(0, 16, keys, 0); + list->Dispatch(1, 1, 1); + if (compute_copy) + enhanced_transition(compute_list.p, texture.p, D3D12_BARRIER_SYNC_COMPUTE_SHADING, + D3D12_BARRIER_ACCESS_UNORDERED_ACCESS, D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS, + D3D12_BARRIER_SYNC_ALL, D3D12_BARRIER_ACCESS_COMMON, D3D12_BARRIER_LAYOUT_COMMON); + CHECK(shader_batch.submit(worker.p, graphics.fence.p, 2)); + CHECK(SUCCEEDED(graphics.queue->Wait(graphics.fence.p, 2))); + + // The second placement reads the first one's writes at the same guest address. + auto* reader = placed ? alias.p : texture.p; + if (placed) { + D3D12_RESOURCE_BARRIER activate{}; + activate.Type = D3D12_RESOURCE_BARRIER_TYPE_ALIASING; + activate.Aliasing = {texture.p, reader}; + read_batch.list->ResourceBarrier(1, &activate); + } if (enhanced) { - enhanced_transition(enhanced_list.p, texture.p, D3D12_BARRIER_SYNC_COMPUTE_SHADING, - D3D12_BARRIER_ACCESS_UNORDERED_ACCESS, D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS, - D3D12_BARRIER_SYNC_COPY, D3D12_BARRIER_ACCESS_COPY_SOURCE, D3D12_BARRIER_LAYOUT_COPY_SOURCE); + Ref read_list; + CHECK(SUCCEEDED(read_batch.list->QueryInterface(IID_PPV_ARGS(&read_list.p)))); + enhanced_transition(read_list.p, reader, D3D12_BARRIER_SYNC_ALL, + compute_copy ? D3D12_BARRIER_ACCESS_COMMON : D3D12_BARRIER_ACCESS_UNORDERED_ACCESS, + compute_copy ? D3D12_BARRIER_LAYOUT_COMMON : D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS, + D3D12_BARRIER_SYNC_COPY, D3D12_BARRIER_ACCESS_COPY_SOURCE, D3D12_BARRIER_LAYOUT_COPY_SOURCE); } else { - commands.barrier(texture.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + D3D12_RESOURCE_BARRIER copy{}; + copy.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + copy.Transition = {reader, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE}; + read_batch.list->ResourceBarrier(1, ©); } - for (UINT plane = 0; plane < 2; ++plane) { - D3D12_TEXTURE_COPY_LOCATION src{}, dst{}; - src.pResource = texture.p; - src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; - src.SubresourceIndex = plane; - dst.pResource = readback.p; - dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; - dst.PlacedFootprint = layouts[plane]; - commands.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + for (UINT sub = 0; sub < subresources; ++sub) { + const auto src = copycmp::sub_loc(reader, sub); + const auto dst = copycmp::foot_loc(readback.p, layouts[sub]); + read_batch.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); } - const auto error = commands.submit(); - if (!error.empty()) { std::fprintf(stderr, "%s\n", error.c_str()); return 1; } - + CHECK(read_batch.submit(graphics.queue.p, graphics.fence.p, 3)); + CHECK(SUCCEEDED(graphics.fence->SetEventOnCompletion(3, nullptr))); + CHECK(graphics.fence->GetCompletedValue() >= 3 && SUCCEEDED(device->GetDeviceRemovedReason())); unsigned char* mapped = nullptr; - CHECK(SUCCEEDED(readback.p->Map(0, nullptr, reinterpret_cast(&mapped))) && mapped); - for (UINT y = 0; y < height; ++y) { - for (UINT x = 0; x < width; ++x) { - float depth = 0.0f; - std::memcpy(&depth, mapped + layouts[0].Offset + y * layouts[0].Footprint.RowPitch + x * sizeof(float), - sizeof(depth)); - const auto stencil = mapped[layouts[1].Offset + y * layouts[1].Footprint.RowPitch + x]; - float expected_depth = x == 2 && y == 1 ? 0.125f : 0.5f; - unsigned expected_stencil = x == 5 && y == 3 ? 0xa5 : 0x5a; - if (x == UINT(depth_rect.left) && y == UINT(depth_rect.top)) expected_depth = depth_clear[0]; - if (x == UINT(stencil_rect.left) && y == UINT(stencil_rect.top)) expected_stencil = stencil_clear[0]; - if (depth != expected_depth || stencil != expected_stencil) { - std::fprintf(stderr, "(%u,%u): depth %g, stencil %#x\n", x, y, depth, unsigned(stencil)); - readback.p->Unmap(0, nullptr); - return 1; + CHECK(SUCCEEDED(readback->Map(0, nullptr, reinterpret_cast(&mapped))) && mapped); + for (UINT sub = 0; sub < subresources; ++sub) { + const UINT layer = sub % layers; + const UINT plane = sub / layers; + const UINT bytes = plane ? 1 : depth16 ? 2 : 4; + for (UINT y = 0; y < height; ++y) { + for (UINT x = 0; x < width; ++x) { + const bool in_view = !array || layer >= 1; + const bool cleared = in_view && (plane ? x == 3 && y == 2 : x == 1 && y == 3); + UINT32 expected = 0; + if (depth16) { + expected = cleared ? d16_clear[0] : d16_seed[layer]; + if (layer == (array ? 2u : 0u) && x == 2 && y == 1) expected ^= 0x1357u; + } else if (plane == 0) { + float depth = cleared ? depth_clear[0] : depth_seed[layer]; + if (layer == (array ? 1u : 0u) && x == 2 && y == 1) depth *= 0.25f; + std::memcpy(&expected, &depth, sizeof(depth)); + } else { + expected = cleared ? stencil_clear[0] : stencil_seed[layer]; + if (layer == (array ? 2u : 0u) && x == 5 && y == 3) expected ^= 0xffu; + } + UINT32 actual = 0; + std::memcpy(&actual, mapped + layouts[sub].Offset + y * layouts[sub].Footprint.RowPitch + x * bytes, bytes); + if (actual != expected) { + std::fprintf(stderr, "subresource %u pixel (%u,%u): got %#x, expected %#x\n", sub, x, y, actual, expected); + readback->Unmap(0, nullptr); + return 1; + } } } } - readback.p->Unmap(0, nullptr); - std::printf("depth/stencil UAV: %s barriers, %ux%u, read back all %u pixels on each plane\n", - enhanced ? "enhanced" : "legacy", width, height, width * height); + readback->Unmap(0, nullptr); + std::printf("slot %u, %ux%u, %u layers, %u planes, %s barriers, graphics family %u, shader family %u, " + "plane transfers on %s: every pixel matched\n", placed ? 133u : 76u, width, height, layers, planes, + enhanced ? "enhanced" : "legacy", vk.family, handoff == Handoff::direct ? vk.family : vk.compute_family, + compute_copy ? "compute" : "graphics"); return 0; } } // namespace @@ -269,6 +446,7 @@ int run(vktest::Device& vk, UINT width, UINT height, bool enhanced) { int main() { vktest::Device vk; vk.request_buffer_device_address = true; + vk.all_queue_types = true; const auto status = vk.initialize(); if (status == vktest::DeviceStatus::unavailable) return 77; if (status != vktest::DeviceStatus::ready) return 1; @@ -276,6 +454,20 @@ int main() { std::fprintf(stderr, "SKIP: shader requires bindless images and typed r8ui storage\n"); return 77; } - if (run(vk, 9, 7, false) || run(vk, 2560, 1440, true)) return 1; + const auto d32s8 = DXGI_FORMAT_R32G8X24_TYPELESS, d16 = DXGI_FORMAT_R16_TYPELESS; + if (run(vk, 9, 7, false, Texture::committed, d32s8, Handoff::direct) || + run(vk, 2560, 1440, true, Texture::committed, d32s8, Handoff::direct) || + run(vk, 9, 7, true, Texture::placed, d16, Handoff::graphics_transitions)) return 1; + for (const auto format : {d32s8, d16}) { + if (run(vk, 9, 7, false, Texture::committed_array, format, Handoff::graphics_transitions) || + run(vk, 13, 9, true, Texture::placed_array, format, Handoff::graphics_transitions)) return 1; + const auto vk_format = format == d16 ? VK_FORMAT_D16_UNORM : VK_FORMAT_D32_SFLOAT_S8_UINT; + if (compute_transfers(vk, vk_format, format != d16)) { + if (run(vk, 9, 7, true, Texture::placed_array, format, Handoff::compute_transitions)) return 1; + } else { + std::printf("compute-side depth transfers unavailable for VkFormat %u; graphics-side handoff tested\n", + unsigned(vk_format)); + } + } return vk.validation_errors() ? 1 : 0; } diff --git a/runtime/test/d3d12_depth_stencil_uav_views.h b/runtime/test/d3d12_depth_stencil_uav_views.h new file mode 100644 index 0000000000..8800132adf --- /dev/null +++ b/runtime/test/d3d12_depth_stencil_uav_views.h @@ -0,0 +1,79 @@ +#pragma once + +#include "d3d12_test_shaders.h" +#include "../src/gfx10_descriptors.h" + +#include +#include + +// Exercise the descriptors as seen by a console shader, including the array size sentinel and invalid ranges. +inline bool check_depth_uav_array_views(ID3D12Device* device, ID3D12Resource* resource, bool depth16) { + namespace g = leonida::gfx10; + const UINT layers = resource->GetDesc().DepthOrArraySize; + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, + D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + d3d12test::Ref heap; + if (layers < 2 || FAILED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p)))) return false; + const auto slot = heap->GetCPUDescriptorHandleForHeapStart(); + const auto read = [&] { + g::ImageWords words{}; + std::memcpy(words.data(), reinterpret_cast(slot.ptr), sizeof(words)); + return words; + }; + const auto uav = [&](const D3D12_UNORDERED_ACCESS_VIEW_DESC* view) { + std::memset(reinterpret_cast(slot.ptr), 0x55, sizeof(g::ImageWords)); + device->CreateUnorderedAccessView(resource, nullptr, view, slot); + return read(); + }; + const g::ImageWords empty{}; + D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; + view.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + view.Format = depth16 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_FLOAT; + view.Texture2DArray = {0, 0, 1, 0}; + g::Image first{}, tail{}; + if (!g::decode(uav(&view), first) || first.type != g::ImageType::image_2d_array || + first.first_layer != 0 || first.layer_count != 1) return false; + view.Texture2DArray = {0, 1, UINT_MAX, 0}; + const auto remaining = uav(&view); + view.Texture2DArray.ArraySize = layers - 1; + if (remaining != uav(&view) || !g::decode(remaining, tail) || tail.address != first.address || + tail.first_layer != 1 || tail.layer_count != layers - 1) return false; + + // A depth SRV still names the original image, with the same base layer and count. + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = depth16 ? DXGI_FORMAT_R16_UNORM : DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; + srv.Texture2DArray = {0, 1, 1, layers - 1, 0, 0}; + device->CreateShaderResourceView(resource, &srv, slot); + g::Image attachment{}; + if (!g::decode(read(), attachment) || attachment.type != g::ImageType::image_2d_array || + attachment.address == tail.address || attachment.first_layer != 1 || attachment.layer_count != layers - 1) + return false; + if (!depth16) { + srv.Format = DXGI_FORMAT_X32_TYPELESS_G8X24_UINT; + srv.Texture2DArray.PlaneSlice = 1; + device->CreateShaderResourceView(resource, &srv, slot); + g::Image stencil{}; + if (!g::decode(read(), stencil) || stencil.address != attachment.address || + stencil.format != g::stencil_format || stencil.first_layer != 1 || stencil.layer_count != layers - 1) + return false; + } + for (const D3D12_TEX2D_ARRAY_UAV invalid : { + D3D12_TEX2D_ARRAY_UAV{1, 0, 1, 0}, {0, 0, 0, 0}, {0, layers, UINT_MAX, 0}, + {0, 1, layers, 0}, {0, 0, 1, depth16 ? 1u : 2u}}) { + view.Texture2DArray = invalid; + if (uav(&view) != empty) { + std::fprintf(stderr, "accepted invalid UAV mip %u layers %u+%u plane %u\n", + invalid.MipSlice, invalid.FirstArraySlice, invalid.ArraySize, invalid.PlaneSlice); + return false; + } + } + view.Texture2DArray = {0, 0, 1, 0}; + view.Format = DXGI_FORMAT_R8_UINT; + if (uav(&view) != empty) return false; + view.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; + view.Format = depth16 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_FLOAT; + view.Texture2D = {}; + return uav(&view) == empty && uav(nullptr) == empty; +} diff --git a/runtime/test/d3d12_placed_depth_test.h b/runtime/test/d3d12_placed_depth_test.h new file mode 100644 index 0000000000..ab0e0fb79e --- /dev/null +++ b/runtime/test/d3d12_placed_depth_test.h @@ -0,0 +1,115 @@ +// Slot-133 aliases share GPU contents and retain individual COM identities. +#pragma once +#include "d3d12_copy_compare.h" + +namespace placeddepthtest { + +inline bool check_alias_lifetime(ID3D12Device* device, ID3D12Device* xbox) { + using copycmp::Ptr; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = 256; + desc.Height = 128; + desc.DepthOrArraySize = desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Format = DXGI_FORMAT_R32G8X24_TYPELESS; + desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + const auto allocation = device->GetResourceAllocationInfo(0, 1, &desc); + if (!allocation.Alignment || allocation.SizeInBytes == UINT64_MAX || allocation.SizeInBytes <= allocation.Alignment) + return false; + struct Pages { + void* ptr; + ~Pages() { if (ptr) VirtualFree(ptr, 0, MEM_RELEASE); } + } pages{VirtualAlloc(nullptr, SIZE_T(allocation.SizeInBytes * 2), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)}; + if (!pages.ptr) return false; + const UINT64 address = reinterpret_cast(pages.ptr); + auto xbox_desc = desc; + xbox_desc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + xbox_desc.Layout = static_cast(0x101); + using Create = HRESULT(WINAPI*)(void*, UINT64, const D3D12_RESOURCE_DESC*, UINT, + const D3D12_CLEAR_VALUE*, REFIID, void**); + const auto create = reinterpret_cast((*reinterpret_cast(xbox))[133]); + const auto place = [&](UINT64 va, const D3D12_RESOURCE_DESC& shape, Ptr& result, + const D3D12_CLEAR_VALUE* clear = nullptr) { + return create(xbox, va, &shape, UINT_MAX, clear, IID_PPV_ARGS(&result.p)); + }; + Ptr first, alias, next, invalid; + if (FAILED(place(address, xbox_desc, first)) || FAILED(place(address, xbox_desc, alias)) || + FAILED(place(address + allocation.SizeInBytes, xbox_desc, next))) return false; + if (first.p == alias.p || alias->GetGPUVirtualAddress() != address || + next->GetGPUVirtualAddress() != address + allocation.SizeInBytes) return false; + // Independent COM private data helps catch accidental reuse of the object itself as the alias. + constexpr GUID cookie_key{0x650cf350, 0xa07e, 0x428d, {0xb4, 0x14, 0xdc, 0xaf, 0xc6, 0x97, 0xe8, 0x4b}}; + const UINT cookie = 12; + UINT bytes = 0; + if (FAILED(first->SetPrivateData(cookie_key, sizeof(cookie), &cookie)) || + alias->GetPrivateData(cookie_key, &bytes, nullptr) != DXGI_ERROR_NOT_FOUND) return false; + auto smaller = xbox_desc; + smaller.Width /= 2; + D3D12_CLEAR_VALUE optimized{}; + optimized.Format = DXGI_FORMAT_D32_FLOAT_S8X24_UINT; + optimized.DepthStencil = {1.0f, 0}; + if (place(address, xbox_desc, invalid, &optimized) != E_NOTIMPL || invalid.p) return false; + if (place(address, smaller, invalid) != E_NOTIMPL || invalid.p || + place(address + allocation.Alignment, xbox_desc, invalid) != E_NOTIMPL || invalid.p || + place(address + 1, xbox_desc, invalid) != E_INVALIDARG || invalid.p) return false; + + Ptr heap; + D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1}; + if (FAILED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p)))) return false; + D3D12_DEPTH_STENCIL_VIEW_DESC dsv{}; + dsv.Format = DXGI_FORMAT_D32_FLOAT_S8X24_UINT; + dsv.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D; + const auto handle = heap->GetCPUDescriptorHandleForHeapStart(); + device->CreateDepthStencilView(first.p, &dsv, handle); + copycmp::Run commands; + if (!commands.init(device, true)) return false; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT layouts[2]{}; + UINT64 total = 0; + device->GetCopyableFootprints(&desc, 0, 2, 0, layouts, nullptr, nullptr, &total); + Ptr readback; + if (!commands.buffer(D3D12_HEAP_TYPE_READBACK, total, D3D12_RESOURCE_STATE_COPY_DEST, readback)) return false; + commands.begin(); + commands.list->ClearDepthStencilView(handle, D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, + 0.375f, 0xb7, 0, nullptr); + D3D12_RESOURCE_BARRIER activate{}; + activate.Type = D3D12_RESOURCE_BARRIER_TYPE_ALIASING; + activate.Aliasing = {first.p, alias.p}; + commands.list->ResourceBarrier(1, &activate); + if (!commands.submit().empty()) return false; + first.reset(); + if (place(address, smaller, invalid) != E_NOTIMPL || invalid.p) return false; + commands.begin(); + commands.barrier(alias.p, D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_COPY_SOURCE); + for (UINT plane = 0; plane < 2; ++plane) { + D3D12_TEXTURE_COPY_LOCATION src{}, dst{}; + src.pResource = alias.p; + src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + src.SubresourceIndex = plane; + dst.pResource = readback.p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = layouts[plane]; + commands.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + } + if (!commands.submit().empty()) return false; + unsigned char* mapped = nullptr; + if (FAILED(readback->Map(0, nullptr, reinterpret_cast(&mapped)))) return false; + bool valid = true; + for (UINT y = 0; y < desc.Height && valid; ++y) { + for (UINT x = 0; x < desc.Width; ++x) { + float depth; + std::memcpy(&depth, mapped + layouts[0].Offset + y * layouts[0].Footprint.RowPitch + x * sizeof(depth), + sizeof(depth)); + if (depth != 0.375f || mapped[layouts[1].Offset + y * layouts[1].Footprint.RowPitch + x] != 0xb7) { + std::fprintf(stderr, "slot-133 alias: wrong readback at (%u, %u)\n", x, y); + valid = false; + break; + } + } + } + readback->Unmap(0, nullptr); + alias.reset(); + return valid && SUCCEEDED(place(address, smaller, invalid)) && invalid->GetGPUVirtualAddress() == address; +} + +} // namespace placeddepthtest diff --git a/runtime/test/device_proxy_test.cpp b/runtime/test/device_proxy_test.cpp index 00c5462dff..e951bb0ece 100644 --- a/runtime/test/device_proxy_test.cpp +++ b/runtime/test/device_proxy_test.cpp @@ -330,7 +330,7 @@ int main(int argc, char** argv) { auto ds_uav = xbox_texture; ds_uav.Format = DXGI_FORMAT_R32G8X24_TYPELESS; ds_uav.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; - check(rt::d3d12_xs::set_depth_stencil_uav_provider(device.Get(), [](ID3D12Resource*) -> HRESULT { + check(rt::d3d12_xs::set_depth_stencil_uav_provider(device.Get(), [](ID3D12Resource*, D3D12_HEAP_FLAGS) -> HRESULT { return E_OUTOFMEMORY; }), "install a failing Xbox storage-image provider"); void* result = reinterpret_cast(1); diff --git a/runtime/test/glsl/cs_depth_stencil_uav.comp b/runtime/test/glsl/cs_depth_stencil_uav.comp index bd5e9ca2b6..277a86df46 100644 --- a/runtime/test/glsl/cs_depth_stencil_uav.comp +++ b/runtime/test/glsl/cs_depth_stencil_uav.comp @@ -5,8 +5,17 @@ layout(local_size_x = 1) in; layout(push_constant) uniform UserData { uint s[20]; } pc; layout(set = 0, binding = 2, std430) readonly buffer DescriptorMap { uint words[]; }; +#if defined(DEPTH16_ARRAY) +layout(set = 0, binding = 12, r16ui) uniform uimage2DArray depths[]; +#elif defined(DEPTH16_2D) +layout(set = 0, binding = 9, r16ui) uniform uimage2D depths[]; +#elif defined(DEPTH_STENCIL_ARRAY) +layout(set = 0, binding = 11, r32f) uniform image2DArray depths[]; +layout(set = 0, binding = 12, r8ui) uniform uimage2DArray stencils[]; +#else layout(set = 0, binding = 8, r32f) uniform image2D depths[]; layout(set = 0, binding = 9, r8ui) uniform uimage2D stencils[]; +#endif uint lookup(uint first) { uint hash = 2166136261u; @@ -22,9 +31,25 @@ uint lookup(uint first) { void main() { // Read before writing. A stale copy (or writing back the wrong plane) changes the expected bytes. - uint depth = lookup(4), stencil = lookup(12); - float before = imageLoad(depths[depth], ivec2(2, 1)).r; - uint mask = imageLoad(stencils[stencil], ivec2(5, 3)).r; - imageStore(depths[depth], ivec2(2, 1), vec4(before * 0.25)); - imageStore(stencils[stencil], ivec2(5, 3), uvec4(mask ^ 0xffu)); + uint depth = lookup(4); +#if defined(DEPTH16_2D) || defined(DEPTH16_ARRAY) +#if defined(DEPTH16_2D) + ivec2 pixel = ivec2(2, 1); +#else + ivec3 pixel = ivec3(2, 1, 1); +#endif + uint before = imageLoad(depths[depth], pixel).r; + imageStore(depths[depth], pixel, uvec4(before ^ 0x1357u)); +#else + uint stencil = lookup(12); +#if defined(DEPTH_STENCIL_ARRAY) + ivec3 depth_pixel = ivec3(2, 1, 0), stencil_pixel = ivec3(5, 3, 1); +#else + ivec2 depth_pixel = ivec2(2, 1), stencil_pixel = ivec2(5, 3); +#endif + float before = imageLoad(depths[depth], depth_pixel).r; + uint mask = imageLoad(stencils[stencil], stencil_pixel).r; + imageStore(depths[depth], depth_pixel, vec4(before * 0.25)); + imageStore(stencils[stencil], stencil_pixel, uvec4(mask ^ 0xffu)); +#endif } diff --git a/runtime/test/replay_texture_barrier_test.cpp b/runtime/test/replay_texture_barrier_test.cpp index 83c5111bf1..527c8adec1 100644 --- a/runtime/test/replay_texture_barrier_test.cpp +++ b/runtime/test/replay_texture_barrier_test.cpp @@ -103,7 +103,7 @@ void depth_uav_barriers(VkCommandBuffer cb) { const auto resolve = [&](ResourceId id) -> const ResourceBinding* { return id && id < resources.size() ? &resources[id] : nullptr; }; - struct Access { VkImage image; VkImageAspectFlags aspect; bool read; }; + struct Access { VkImage image; VkImageAspectFlags aspect; bool read; std::uint32_t layer, layers; }; static std::vector accesses; accesses.clear(); ReplayFunctions vk{}; @@ -113,11 +113,13 @@ void depth_uav_barriers(VkCommandBuffer cb) { std::uint32_t, const VkImageMemoryBarrier*) {}; vk.copy_image_to_buffer = [](VkCommandBuffer, VkImage image, VkImageLayout, VkBuffer, std::uint32_t, const VkBufferImageCopy* region) { - accesses.push_back({image, region->imageSubresource.aspectMask, true}); + const auto& sub = region->imageSubresource; + accesses.push_back({image, sub.aspectMask, true, sub.baseArrayLayer, sub.layerCount}); }; vk.copy_buffer_to_image = [](VkCommandBuffer, VkBuffer, VkImage image, VkImageLayout, std::uint32_t, const VkBufferImageCopy* region) { - accesses.push_back({image, region->imageSubresource.aspectMask, false}); + const auto& sub = region->imageSubresource; + accesses.push_back({image, sub.aspectMask, false, sub.baseArrayLayer, sub.layerCount}); }; const BarrierSubresourceRange stencil{1, 0, 0, 0, 0, 0}; const BarrierSubresourceRange all_planes{all_subresources, 0, 0, 0, 0, 0}; @@ -157,6 +159,15 @@ void depth_uav_barriers(VkCommandBuffer cb) { expect(prepare(implicit, resolve, vk, prepared) == ReplayResult::unsupported && !allocations, "reject ambiguous queue-specific COMMON at prepare"); } + for (bool before : {false, true}) { + CommandList invalid; + expect(invalid.barrier(TextureBarrier{y::all, y::all, + before ? a::unordered_access : a::copy_source, before ? a::copy_source : a::unordered_access, + before ? l::common : l::copy_source, before ? l::copy_source : l::common, + 1, all_planes, 0}) && invalid.close(), "record explicit UAV access in generic COMMON"); + expect(prepare(invalid, resolve, vk, prepared) == ReplayResult::unsupported && !allocations, + "generic COMMON disallows explicit UAV access on either side of a barrier"); + } if (prepare(list, resolve, vk, prepared) != ReplayResult::success) { expect(false, "prepare stencil transfers"); return; @@ -178,6 +189,65 @@ void depth_uav_barriers(VkCommandBuffer cb) { tracker.layout(3, 0) == VK_IMAGE_LAYOUT_GENERAL, "coupled parent and independently tracked storage layouts"); vk.copy_scratch = [](VkDeviceSize, VkBuffer&, VkDeviceSize&) { return false; }; expect(prepare(list, resolve, vk, prepared) == ReplayResult::unsupported, "scratch failure refuses the list"); + + // Select layers 1 and 2 (out of 4). The depth-only array has no stencil child. Check the staging size, + // image copy ranges, and the independent initial layouts of the two selected storage layers. + parent.aspects = VK_IMAGE_ASPECT_DEPTH_BIT; + parent.format = VK_FORMAT_D16_UNORM; + parent.stencil_uav = 0; + resources[2].format = VK_FORMAT_R16_UINT; + LayoutTracker arrays; + for (ResourceId id : {1u, 2u}) { + resources[id].array_layers = 4; + arrays.track(id, resources[id], VK_IMAGE_LAYOUT_GENERAL); + } + arrays.set(2, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); + arrays.set(2, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 2, 1}, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); + const BarrierSubresourceRange two_layers{0, 1, 1, 2, 0, 1}; + CommandList compute; + expect(compute.barrier(TextureBarrier{y::all, y::compute_shading, a::common, a::unordered_access, + l::common, l::unordered_access, 1, two_layers, 0}) && + compute.barrier(TextureBarrier{y::compute_shading, y::all, a::unordered_access, a::common, + l::unordered_access, l::common, 1, two_layers, 0}) && compute.close(), + "record D16 array compute handoff"); + vk.graphics_family = false; + vk.queue_stages = detail::queue_stages_compute; + vk.copy_scratch = [&](VkDeviceSize size, VkBuffer& buffer, VkDeviceSize& offset) { + expect(size == 2 * 2 * parent.width * parent.height, "D16 scratch holds two bytes per texel and two layers"); + buffer = reinterpret_cast(std::uintptr_t(0x10)); + offset = 0; + return true; + }; + vk.compute_copy_aspects = [](VkFormat) -> VkImageAspectFlags { return VK_IMAGE_ASPECT_STENCIL_BIT; }; + expect(prepare(compute, resolve, vk, prepared) == ReplayResult::unsupported, + "stencil-only compute copy capability does not authorize a depth transfer"); + vk.compute_copy_aspects = [](VkFormat fmt) -> VkImageAspectFlags { + return fmt == VK_FORMAT_D16_UNORM ? VK_IMAGE_ASPECT_DEPTH_BIT : 0; + }; + if (prepare(compute, resolve, vk, prepared) != ReplayResult::success) { + expect(false, "prepare supported D16 compute transfers"); + return; + } + accesses.clear(); + emit(prepared, cb, vk, &arrays); + expect(accesses.size() == 4 && std::all_of(accesses.begin(), accesses.end(), [](const Access& access) { + return access.layer == 1 && access.layers == 2; + }), "both images are read and written only at the requested layers"); + expect(arrays.layout(2, 0) == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && + arrays.layout(2, 1) == VK_IMAGE_LAYOUT_GENERAL && arrays.layout(2, 2) == VK_IMAGE_LAYOUT_GENERAL, + "selected storage layers end in their descriptor layout and the untouched layer keeps its layout"); + // vkCmdClearDepthStencilImage requires graphics even with maintenance10. A committed depth array first + // seen on compute is initialized from the zero page through a buffer-to-image transfer. + vk.zero_buffer = reinterpret_cast(std::uintptr_t(0x11)); + vk.zero_size = 1024; + const VkImageSubresourceRange fresh{VK_IMAGE_ASPECT_DEPTH_BIT, 0, 1, 1, 2}; + arrays.set(1, fresh, VK_IMAGE_LAYOUT_UNDEFINED); + auto pieces = detail::current(&arrays, 1, fresh, VK_IMAGE_LAYOUT_GENERAL); + accesses.clear(); + detail::initialize(vk, cb, parent, 1, pieces, VK_IMAGE_LAYOUT_GENERAL, &arrays); + expect(accesses.size() == 1 && !accesses[0].read && accesses[0].image == parent.image && + accesses[0].aspect == VK_IMAGE_ASPECT_DEPTH_BIT && accesses[0].layer == 1 && accesses[0].layers == 2, + "first use on compute copies zeros into the selected native depth layers"); } } // namespace diff --git a/runtime/test/replay_uav_clear_offset_test.cpp b/runtime/test/replay_uav_clear_offset_test.cpp index 35818fe8e1..4f70fc6714 100644 --- a/runtime/test/replay_uav_clear_offset_test.cpp +++ b/runtime/test/replay_uav_clear_offset_test.cpp @@ -210,6 +210,44 @@ int main() { tex.array_layers = 4; tex.color_attachment = true; + // A dedicated compute family has no rendering commands. A rectangular clear fills transfer scratch and + // copies the clipped rectangle to the requested array slices without disturbing adjacent pixels. + { + auto image = tex; + image.format = VK_FORMAT_R8_UINT; + auto compute = tex_vk; + compute.graphics_family = false; + compute.queue_stages = detail::queue_stages_compute; + compute.begin_rendering = nullptr; + compute.image_view = {}; + VkDeviceSize requested_bytes = 0; + compute.copy_scratch = [&](VkDeviceSize size, VkBuffer& buffer, VkDeviceSize& offset) { + requested_bytes = size; + buffer = scratch; + offset = 256; + return true; + }; + static std::vector copies; + compute.copy_buffer_to_image = [](VkCommandBuffer, VkBuffer, VkImage, VkImageLayout layout, + std::uint32_t count, const VkBufferImageCopy* regions) { + expect(layout == VK_IMAGE_LAYOUT_GENERAL && count == 1, "one compute clear transfer in UAV layout"); + copies.push_back(regions[0]); + }; + const std::array rects{{{-1, 2, 3, 4}, {1, 3, 2, 4}}}; + writes.clear(); + expect(run_tex(image, {2, false, VK_FORMAT_R8_UINT, 0, 0, 0, 0, 1, 2}, false, {0x39,0,0,0}, + rects, &compute) == ReplayResult::success, "rectangle UAV clear on compute-only family"); + expect(requested_bytes == 12 && writes.size() == 1 && writes[0].kind == 'f' && writes[0].offset == 256 && + writes[0].size == 12 && copies.size() == 2 && attachment_clears == 0, "one fill and two rectangle copies"); + if (copies.size() == 2) { + const auto& r = copies[0]; + expect(r.bufferOffset == 256 && r.imageOffset.x == 0 && r.imageOffset.y == 2 && + r.imageExtent.width == 3 && r.imageExtent.height == 2 && + r.imageSubresource.baseArrayLayer == 1 && r.imageSubresource.layerCount == 2 && + copies[1].imageOffset.x == 1 && copies[1].imageOffset.y == 3, "clipped pixels and exactly two layers"); + } + } + const auto fbits = [](float f) { return std::bit_cast(f); }; // R16G16_TYPELESS (SFLOAT) cleared as R16G16_UNORM Float(1.0, 1.0): uses R16G16_UNORM view and float32 {1, 1}. expect(run_tex(tex, {2, false, VK_FORMAT_R16G16_UNORM, 0, 0, 0, 0, 1, 2}, true, {fbits(1.0f), fbits(1.0f), 0, 0}) == diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h index db042bac56..0517486895 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h @@ -105,6 +105,7 @@ class Device { bool vertex_attribute_divisor = false; bool storage_buffer_8bit = false; // storageBuffer8BitAccess enabled bool storage_image_extended_formats = false; // typed r8ui storage images + bool maintenance10 = false; // depth/stencil transfers on non-graphics families, per format bool conditional_rendering = false; // VK_EXT_conditional_rendering enabled, where available bool host_image_copy = false; // VK_EXT_host_image_copy and hostImageCopy enabled // create(true) only: VK_KHR (else EXT) swapchain_maintenance1 and its feature enabled, with the surface half on the @@ -566,6 +567,21 @@ class Device { if (vertex_attribute_divisor) device_extensions.push_back(divisor_extension); if (conditional_rendering) device_extensions.push_back(conditional_extension); if (host_image_copy) device_extensions.push_back(host_image_copy_name); +#ifdef VK_KHR_maintenance10 + VkPhysicalDeviceMaintenance10FeaturesKHR maint10{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_10_FEATURES_KHR}; + if (v13_.core && all_queue_types && std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { + return std::strcmp(e.extensionName, VK_KHR_MAINTENANCE_10_EXTENSION_NAME) == 0; + })) { + VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &maint10}; + instance_fn("vkGetPhysicalDeviceFeatures2")(physical, &query); + maintenance10 = maint10.maintenance10 == VK_TRUE; + if (maintenance10) { + maint10.pNext = *v13_.next(); + *v13_.next() = &maint10; + device_extensions.push_back(VK_KHR_MAINTENANCE_10_EXTENSION_NAME); + } + } +#endif const char* swapchain = "VK_KHR_swapchain"; if (presentation) device_extensions.push_back(swapchain); #if defined(VK_KHR_swapchain_maintenance1) diff --git a/runtime/test/vulkan_scratch_test.cpp b/runtime/test/vulkan_scratch_test.cpp index 8ca6a819a3..90a3fa0c6a 100644 --- a/runtime/test/vulkan_scratch_test.cpp +++ b/runtime/test/vulkan_scratch_test.cpp @@ -37,6 +37,8 @@ struct FakeVulkan { int free_memory_calls = 0; int wait_idle_calls = 0; int get_counter_calls = 0; + VkSharingMode sharing_mode = VK_SHARING_MODE_EXCLUSIVE; + std::vector families; VkResult create_buffer_result = VK_SUCCESS; VkResult bind_result = VK_SUCCESS; @@ -52,6 +54,9 @@ const VkDevice k_device = make_handle(0x100); VKAPI_ATTR VkResult VKAPI_CALL fake_create_buffer( VkDevice, const VkBufferCreateInfo* info, const VkAllocationCallbacks*, VkBuffer* out) { ++g_vk->create_buffer_calls; + g_vk->sharing_mode = info->sharingMode; + if (info->queueFamilyIndexCount) + g_vk->families.assign(info->pQueueFamilyIndices, info->pQueueFamilyIndices + info->queueFamilyIndexCount); if (g_vk->create_buffer_result != VK_SUCCESS) return g_vk->create_buffer_result; const std::uintptr_t id = g_vk->next_buffer++; g_vk->live_buffers[id] = info->size; @@ -148,7 +153,7 @@ int main() { g_vk = &vk; constexpr VkDeviceSize k_4mib = 4u << 20; { - ScratchBuffers scratch(fake_get_device_proc, k_device, fake_allocate); + ScratchBuffers scratch(fake_get_device_proc, k_device, fake_allocate, {2, 5}); EXPECT(scratch.loaded()); VkBuffer buf = VK_NULL_HANDLE; @@ -157,6 +162,7 @@ int main() { EXPECT(vk.create_buffer_calls == 0); EXPECT(scratch.get(100, buf, off)); + EXPECT(vk.sharing_mode == VK_SHARING_MODE_CONCURRENT && vk.families == std::vector({2, 5})); const VkBuffer chunk1 = buf; EXPECT(chunk1 != VK_NULL_HANDLE && off == 0); EXPECT(vk.live_buffers[reinterpret_cast(chunk1)] == k_4mib); From c9ea50842077678228204a2be52314c4065f87d7 Mon Sep 17 00:00:00 2001 From: Mumogg <104529023+Mumogg@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:10:47 -0600 Subject: [PATCH 026/110] local: descriptor write-through and table mirror for title-backed heaps; diagnostics --- runtime/shims/d3d12_vulkan_device.cpp | 65 +++++++++++++++++- runtime/shims/d3d12_xs_device.cpp | 94 +++++++++++++++++++++++++++ runtime/src/vulkan_replay.h | 47 +++++++++++++- 3 files changed, 204 insertions(+), 2 deletions(-) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 4c4c5f60e1..0a75413d6c 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -4087,6 +4087,18 @@ class PipelineState final stage.words = std::move(patched); } } + { // LOCAL EXPERIMENT: LEONIDA_RECT_GREEN=1 gives rectangle-list pipelines a solid green pixel stage, to + // tell "no fragments" from "the pixel shader writes nothing". + static const bool green = [] { const char* v = std::getenv("LEONIDA_RECT_GREEN"); return v && *v == '1'; }(); + static const bool trivial_vs = [] { const char* v = std::getenv("LEONIDA_RECT_VS"); return v && *v == '1'; }(); + if (trivial_vs && rect_list && stage.bit == VK_SHADER_STAGE_VERTEX_BIT) + stage.words = {0x7230203,0x10500,0x70000,0x1d,0x0,0x20011,0x1,0x3000e,0x0,0x1,0x7000f,0x0,0x1,0x6e69616d,0x0,0x2,0x3,0x40047,0x2,0xb,0x2a,0x40047,0x3,0xb,0x0,0x20013,0x4,0x30021,0x5,0x4,0x30016,0x6,0x20,0x40015,0x7,0x20,0x1,0x40017,0x8,0x6,0x4,0x40020,0x9,0x1,0x7,0x40020,0xa,0x3,0x8,0x4003b,0x9,0x2,0x1,0x4003b,0xa,0x3,0x3,0x4002b,0x7,0xb,0x1,0x4002b,0x7,0xc,0x2,0x4002b,0x6,0xd,0x0,0x4002b,0x6,0xe,0x3f800000,0x4002b,0x6,0xf,0x40800000,0x4002b,0x6,0x10,0xbf800000,0x50036,0x4,0x1,0x0,0x5,0x200f8,0x11,0x4003d,0x7,0x12,0x2,0x500c7,0x7,0x13,0x12,0xb,0x500c3,0x7,0x14,0x12,0xb,0x500c7,0x7,0x15,0x14,0xb,0x4006f,0x6,0x16,0x13,0x4006f,0x6,0x17,0x15,0x50085,0x6,0x18,0x16,0xf,0x50085,0x6,0x19,0x17,0xf,0x50081,0x6,0x1a,0x18,0x10,0x50081,0x6,0x1b,0x19,0x10,0x70050,0x8,0x1c,0x1a,0x1b,0xd,0xe,0x3003e,0x3,0x1c,0x100fd,0x10038}; + static const bool passthrough_vs = [] { const char* v = std::getenv("LEONIDA_RECT_VS"); return v && *v == '2'; }(); + if (passthrough_vs && rect_list && stage.bit == VK_SHADER_STAGE_VERTEX_BIT) + stage.words = {0x7230203,0x10500,0x70000,0x11,0x0,0x20011,0x1,0x3000e,0x0,0x1,0x7000f,0x0,0x1,0x6e69616d,0x0,0x2,0x3,0x40047,0x2,0x1e,0x0,0x40047,0x3,0xb,0x0,0x20013,0x4,0x30021,0x5,0x4,0x30016,0x6,0x20,0x40017,0x7,0x6,0x4,0x40020,0x8,0x1,0x7,0x40020,0x9,0x3,0x7,0x4003b,0x8,0x2,0x1,0x4003b,0x9,0x3,0x3,0x4002b,0x6,0xa,0x0,0x4002b,0x6,0xb,0x3f800000,0x50036,0x4,0x1,0x0,0x5,0x200f8,0xc,0x4003d,0x7,0xd,0x2,0x50051,0x6,0xe,0xd,0x0,0x50051,0x6,0xf,0xd,0x1,0x70050,0x7,0x10,0xe,0xf,0xa,0xb,0x3003e,0x3,0x10,0x100fd,0x10038}; + if (green && rect_list && stage.bit == VK_SHADER_STAGE_FRAGMENT_BIT) + stage.words = {0x7230203,0x10500,0x70000,0xc,0x0,0x20011,0x1,0x3000e,0x0,0x1,0x6000f,0x4,0x1,0x6e69616d,0x0,0x2,0x30010,0x1,0x7,0x40047,0x2,0x1e,0x0,0x20013,0x3,0x30021,0x4,0x3,0x30016,0x5,0x20,0x40017,0x6,0x5,0x4,0x40020,0x7,0x3,0x6,0x4003b,0x7,0x2,0x3,0x4002b,0x5,0x8,0x0,0x4002b,0x5,0x9,0x3f800000,0x7002c,0x6,0xa,0x8,0x9,0x8,0x9,0x50036,0x3,0x1,0x0,0x4,0x200f8,0xb,0x3003e,0x2,0xa,0x100fd,0x10038}; + } VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; module_info.codeSize = stage.words.size() * 4; module_info.pCode = stage.words.data(); @@ -4100,7 +4112,9 @@ class PipelineState final subgroup_size_for(*stage.entry, required_sizes[stage_infos.size()], info); stage_infos.push_back(info); } - if (rect_list) { // the stage that adds each rectangle's fourth corner, from the vertex shader's outputs + // LOCAL EXPERIMENT: LEONIDA_RECT_NOGS=1 draws the rectangle list's three corners as a plain triangle. + static const bool local_no_gs = [] { const char* v = std::getenv("LEONIDA_RECT_NOGS"); return v && *v == '1'; }(); + if (rect_list && !local_no_gs) { // the stage that adds each rectangle's fourth corner, from the vertex shader's outputs std::string why; const std::vector words = leonida::rect_list_geometry(vs_stage.words, why); if (words.empty()) { @@ -4161,6 +4175,16 @@ class PipelineState final if (e.system_value == 0 && e.semantic_index == element.SemanticIndex && equal_semantic(e.semantic, element.SemanticName)) input = &e; + { // LOCAL DIAGNOSTIC: the input layout of the first graphics pipelines with one + static std::atomic said{0}; + const std::string& vsn = stages[0].entry->name; + if ((vsn.find("Blit") != std::string::npos || vsn.find("sga_dr") != std::string::npos) && said.fetch_add(1) < 24) + std::fprintf(stderr, "[rt] localdbg: input element %u/%u %s%u dxgi=%d slot=%u offset=%u -> %s (vs %s)\n", i, + desc.InputLayout.NumElements, element.SemanticName ? element.SemanticName : "?", + element.SemanticIndex, int(element.Format), element.InputSlot, offset, + input ? ("location " + std::to_string(input->register_index)).c_str() : "not read", + stages[0].entry->name.c_str()); + } if (!input) continue; // the shader does not read this element attributes.push_back({input->register_index, element.InputSlot, format, offset}); const bool instance = element.InputSlotClass == D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA; @@ -4183,6 +4207,13 @@ class PipelineState final instance ? VK_VERTEX_INPUT_RATE_INSTANCE : VK_VERTEX_INPUT_RATE_VERTEX}); } } + { // LOCAL DIAGNOSTIC + static std::atomic said2{0}; + const std::string& vsn = stages[0].entry->name; + if (!mesh && (vsn.find("Blit") != std::string::npos || vsn.find("sga_dr") != std::string::npos) && said2.fetch_add(1) < 8) + std::fprintf(stderr, "[rt] localdbg: %s input layout elements=%u attributes=%zu signature=%zu\n", vsn.c_str(), + desc.InputLayout.NumElements, attributes.size(), stages[0].entry->input_signature.size()); + } for (const auto& e : stages[0].entry->input_signature) { if (e.system_value) continue; const bool fed = std::any_of(attributes.begin(), attributes.end(), @@ -4286,6 +4317,12 @@ class PipelineState final if (rect_list) { // LOCAL DIAGNOSTIC / EXPERIMENT (LEONIDA_RECT_FORCE=1: opaque, no depth or stencil test) static const bool force = [] { const char* v = std::getenv("LEONIDA_RECT_FORCE"); return v && *v == '1'; }(); static std::atomic said{0}; + if (said.load() < 6) + for (const auto& st : stages) + if (st.entry) + std::fprintf(stderr, "[rt] localdbg: rect pipeline stage %s = %s wave64=%d emulated=%d push=%u\n", + st.entry->stage.c_str(), st.entry->name.c_str(), int(st.entry->wave64), + int(st.entry->emulated()), st.entry->push_constant_bytes); if (said.fetch_add(1) < 6) std::fprintf(stderr, "[rt] localdbg: rect pipeline rt%u/%u blend=%d src=%d dst=%d op=%d srcA=%d dstA=%d " "mask=0x%x depth=%d write=%d func=%d stencil=%d samplemask=0x%x fmt=%d a2c=%d force=%d\n", @@ -6000,6 +6037,9 @@ class Device final state_.context->set_heap_base(arena.address); state_.context->set_zero_page(arena.buffer, 0, kZeroPage); state_.context->set_quad_indices(arena.buffer, kZeroPage, kQuadIndexCount); + leonida::g_local_arena_mapped = arena.mapped; // LOCAL DIAGNOSTIC + std::fprintf(stderr, "[rt] localdbg: arena mapped at %p\n", static_cast(arena.mapped)); + leonida::g_local_arena_size = arena.size; // LOCAL: vertex and index views that name the title's own CPU memory are copied into a ring carved from the // arena at replay (not fence-tracked: the ring is large against a frame's few KiB of immediate geometry). state_.context->set_title_memory( @@ -6037,6 +6077,29 @@ class Device final if (ring_next + aligned > kRing) ring_next = 0; std::memcpy(st->arena.mapped + ring_base + ring_next, reinterpret_cast(va), std::size_t(size)); + { // LOCAL EXPERIMENT: LEONIDA_VTX_TEST=1 overwrites the copy with a screen-covering triangle (stride 24) + static const char mode = [] { const char* v = std::getenv("LEONIDA_VTX_TEST"); return v ? *v : '0'; }(); + const float second_y = reinterpret_cast(st->arena.mapped + ring_base + ring_next)[7]; + const bool test = mode == '1' || (mode == 'A' && second_y < 100.f) || (mode == 'B' && second_y >= 100.f); + if (test && size >= 72) { + const float tri[3][2] = {{-1.f, -1.f}, {3.f, -1.f}, {-1.f, 3.f}}; + for (int v = 0; v < 3; ++v) { + float* q = reinterpret_cast(st->arena.mapped + ring_base + ring_next + v * 24); + q[0] = tri[v][0]; q[1] = tri[v][1]; q[2] = 0.f; + } + } + static std::atomic said{0}; + if (said.load() < 6) { + const float* q = reinterpret_cast(st->arena.mapped + ring_base + ring_next); + std::fprintf(stderr, "[rt] localdbg: ring copy holds %g,%g | %g,%g | %g,%g (size %llu)\n", q[0], q[1], + q[6], q[7], q[12], q[13], static_cast(size)); + } + if (said.fetch_add(1) < 3) + std::fprintf(stderr, "[rt] localdbg: ring copy at arena offset 0x%llx (ring_base 0x%llx) arena size 0x%llx\n", + static_cast(ring_base + ring_next), + static_cast(ring_base), + static_cast(st->arena.size)); + } buffer = st->arena.buffer; offset = ring_base + ring_next; ring_next += aligned; diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 937390efae..2d00e00c9b 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -166,6 +166,9 @@ bool register_descriptor_range(const DeviceProxy* device, const HeapProxy* heap, return false; try { std::lock_guard lock(descriptor_range_mutex()); + std::fprintf(stderr, "[rt] localdbg: descriptor range custom=0x%llx..0x%llx real_cpu=0x%llx heap=%p\n", + static_cast(custom_start), static_cast(custom_start + byte_size), + static_cast(real_start), static_cast(heap)); descriptor_ranges().push_back({custom_start, custom_start + byte_size, real_start, device, heap}); g_custom_range_count.store(descriptor_ranges().size(), std::memory_order_release); return true; @@ -201,6 +204,59 @@ D3D12_CPU_DESCRIPTOR_HANDLE translate_cpu_handle(const DeviceProxy* device, D3D1 return handle; } +// LOCAL (title-backed descriptor heaps): the title copies descriptors between its heaps' backing memory itself, with +// no API call, so (1) every descriptor the layer writes for a title-backed slot is also stored at the title's address, +// and (2) when a table is bound, what the title wrote at that table's address is carried into the real heap. +// LEONIDA_DESC_MIRROR=0 turns both off. +constexpr SIZE_T kLocalDescriptorBytes = 32; +constexpr SIZE_T kLocalMirrorSlots = 64; + +bool local_desc_mirror() { + static const bool on = [] { const char* v = std::getenv("LEONIDA_DESC_MIRROR"); return !(v && *v == '0'); }(); + return on; +} + +void local_write_through(const DeviceProxy* device, D3D12_CPU_DESCRIPTOR_HANDLE custom, SIZE_T count) { + if (!local_desc_mirror() || !custom.ptr || !count) return; + const D3D12_CPU_DESCRIPTOR_HANDLE real = translate_cpu_handle(device, custom); + if (real.ptr == custom.ptr) return; + std::memcpy(reinterpret_cast(custom.ptr), reinterpret_cast(real.ptr), + count * kLocalDescriptorBytes); + static std::atomic said{false}; + if (!said.exchange(true)) + std::fprintf(stderr, "[rt] d3d12_xs: local: descriptors written for a title-backed heap are also stored at the " + "title's address\n"); +} + +D3D12_GPU_DESCRIPTOR_HANDLE local_real_gpu_start(const HeapProxy* heap); + +void local_mirror_table(const DeviceProxy* device, std::uint64_t gpu_handle) { + if (!local_desc_mirror() || !gpu_handle || g_custom_range_count.load(std::memory_order_acquire) == 0) return; + std::lock_guard lock(descriptor_range_mutex()); + for (const DescriptorRange& range : descriptor_ranges()) { + if ((device && range.device != device) || !range.heap) continue; + const std::uint64_t gpu_start = local_real_gpu_start(range.heap).ptr; + const std::uint64_t bytes = range.custom_end - range.custom_start; + if (!gpu_start || gpu_handle < gpu_start || gpu_handle >= gpu_start + bytes) continue; + const std::uint64_t offset = (gpu_handle - gpu_start) / kLocalDescriptorBytes * kLocalDescriptorBytes; + const std::uint64_t slots = (std::min)(kLocalMirrorSlots, (bytes - offset) / kLocalDescriptorBytes); + std::uint64_t copied = 0; + for (std::uint64_t i = 0; i < slots; ++i) { + const auto* from = reinterpret_cast(range.custom_start + offset + i * kLocalDescriptorBytes); + if (!(from[0] | from[1] | from[2] | from[3])) continue; // nothing the title wrote: keep the real slot + std::memcpy(reinterpret_cast(range.real_start + offset + i * kLocalDescriptorBytes), from, + kLocalDescriptorBytes); + ++copied; + } + static std::atomic said{0}; + if (said.fetch_add(1) < 4) + std::fprintf(stderr, "[rt] d3d12_xs: local: table at heap offset 0x%llx: %llu of %llu slots taken from the " + "title's backing memory\n", static_cast(offset), + static_cast(copied), static_cast(slots)); + return; + } +} + std::atomic g_hits[kMaxSlots]; std::atomic g_first[kMaxSlots]; std::atomic g_beyond_warned[kMaxSlots]; @@ -684,12 +740,31 @@ D3D12_CPU_DESCRIPTOR_HANDLE heap_get_cpu_handle(HeapProxy* self) { D3D12_GPU_DESCRIPTOR_HANDLE heap_get_gpu_handle(HeapProxy* self) { note_heap_slot(10); + { + static std::atomic said{0}; + if (said.fetch_add(1) < 8) std::fprintf(stderr, "[rt] localdbg: heap slot 10 (GPU handle) asked on heap %p\n", static_cast(self)); + } constexpr UINT64 kUnset = ~static_cast(0); D3D12_GPU_DESCRIPTOR_HANDLE handle{}; handle.ptr = kUnset; using Fn = D3D12_GPU_DESCRIPTOR_HANDLE(WINAPI*)(ID3D12DescriptorHeap*, D3D12_GPU_DESCRIPTOR_HANDLE*); const D3D12_GPU_DESCRIPTOR_HANDLE returned = reinterpret_cast(self->real_vtable[10])(self->real, &handle); + { + static std::atomic said{0}; + if (said.fetch_add(1) < 4) + std::fprintf(stderr, "[rt] localdbg: heap %p slot 10 answers GPU handle 0x%llx\n", static_cast(self), + static_cast(handle.ptr != kUnset ? handle.ptr : returned.ptr)); + } + return handle.ptr != kUnset ? handle : returned; +} + +D3D12_GPU_DESCRIPTOR_HANDLE local_real_gpu_start(const HeapProxy* heap) { + constexpr UINT64 kUnset = ~static_cast(0); + D3D12_GPU_DESCRIPTOR_HANDLE handle{}; + handle.ptr = kUnset; + using Fn = D3D12_GPU_DESCRIPTOR_HANDLE(WINAPI*)(ID3D12DescriptorHeap*, D3D12_GPU_DESCRIPTOR_HANDLE*); + const D3D12_GPU_DESCRIPTOR_HANDLE returned = reinterpret_cast(heap->real_vtable[10])(heap->real, &handle); return handle.ptr != kUnset ? handle : returned; } @@ -2050,6 +2125,8 @@ std::uint64_t WINAPI list_slot(ListProxy* self, std::uint64_t a1, std::uint64_t std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t); auto** const real_vtable = *reinterpret_cast(self->real); + // LOCAL: console SetComputeRootDescriptorTable (35) and SetGraphicsRootDescriptorTable (36) + if constexpr (Slot == 35 || Slot == 36) local_mirror_table(self->device, a2); if constexpr (pc == 10) { // Reset(allocator, pso) — console 10, and 139 as the retail title calls it: the title hands its // allocator proxy; the real list takes the real one (and a wrapped pipeline state, if that ever @@ -2673,19 +2750,32 @@ HRESULT proxy_create_descriptor_heap(DeviceProxy* self, const D3D12_DESCRIPTOR_H void proxy_create_cbv(DeviceProxy* self, const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE dest) { note_slot(17); + { // LOCAL DIAGNOSTIC + static std::atomic said{0}; + const int n = said.fetch_add(1); + if (n < 6 || (n > 3000 && n < 3008)) { + const D3D12_CPU_DESCRIPTOR_HANDLE t = translate_cpu_handle(self, dest); + std::fprintf(stderr, "[rt] localdbg: CreateCBV #%d dest=0x%llx -> 0x%llx location=0x%llx size=%u\n", n, + static_cast(dest.ptr), static_cast(t.ptr), + desc ? static_cast(desc->BufferLocation) : 0ull, desc ? desc->SizeInBytes : 0u); + } + } self->real->CreateConstantBufferView(desc, translate_cpu_handle(self, dest)); + local_write_through(self, dest, 1); } void proxy_create_srv(DeviceProxy* self, ID3D12Resource* resource, const D3D12_SHADER_RESOURCE_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE dest) { note_slot(18); self->real->CreateShaderResourceView(resource, desc, translate_cpu_handle(self, dest)); + local_write_through(self, dest, 1); } void proxy_create_uav(DeviceProxy* self, ID3D12Resource* resource, ID3D12Resource* counter, const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE dest) { note_slot(19); self->real->CreateUnorderedAccessView(resource, counter, desc, translate_cpu_handle(self, dest)); + local_write_through(self, dest, 1); } void proxy_create_rtv(DeviceProxy* self, ID3D12Resource* resource, const D3D12_RENDER_TARGET_VIEW_DESC* desc, @@ -2703,6 +2793,7 @@ void proxy_create_dsv(DeviceProxy* self, ID3D12Resource* resource, const D3D12_D void proxy_create_sampler(DeviceProxy* self, const D3D12_SAMPLER_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE dest) { note_slot(22); self->real->CreateSampler(desc, translate_cpu_handle(self, dest)); + local_write_through(self, dest, 1); } void proxy_copy_descriptors(DeviceProxy* self, UINT num_dest, const D3D12_CPU_DESCRIPTOR_HANDLE* dest_starts, @@ -2743,6 +2834,8 @@ void proxy_copy_descriptors(DeviceProxy* self, UINT num_dest, const D3D12_CPU_DE return; } self->real->CopyDescriptors(num_dest, dest_out, dest_sizes, num_src, src_out, src_sizes, type); + for (UINT i = 0; dest_starts && i < num_dest; ++i) + local_write_through(self, dest_starts[i], dest_sizes ? dest_sizes[i] : 1); } void proxy_copy_descriptors_simple(DeviceProxy* self, UINT num_descriptors, D3D12_CPU_DESCRIPTOR_HANDLE dest_start, @@ -2750,6 +2843,7 @@ void proxy_copy_descriptors_simple(DeviceProxy* self, UINT num_descriptors, D3D1 note_slot(24); self->real->CopyDescriptorsSimple(num_descriptors, translate_cpu_handle(self, dest_start), translate_cpu_handle(self, src_start), type); + local_write_through(self, dest_start, num_descriptors); } // The Xbox slot 62 takes two more words between the description and the IID: (desc, w2, w3, riid, out). Measured diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 0daaae4bad..c4dac14349 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -809,6 +809,10 @@ enum class ReplayResult { invalid_draw, // DispatchMesh with a pipeline that has no mesh shader, or a vertex draw with one that has unsupported }; +// LOCAL DIAGNOSTIC: the arena's host mapping and size, for dumps of what a shader would read. +inline std::uint8_t* g_local_arena_mapped = nullptr; +inline std::uint64_t g_local_arena_size = 0; + // LOCAL DIAGNOSTIC: which check returned unresolved_resource (first 3 times per source line). inline ReplayResult local_unresolved_at(int line) { static std::atomic seen[8192]; @@ -2207,7 +2211,8 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct return local_unresolved_at(__LINE__); { // LOCAL DIAGNOSTIC: the first draws that read title memory static std::atomic shown{0}; - if (shown.fetch_add(1, std::memory_order_relaxed) < 12) { + const int nth = shown.fetch_add(1, std::memory_order_relaxed); + if (nth < 12 || (nth % 20000) < 3) { const float* f = reinterpret_cast(view.va); std::fprintf(stderr, "[rt] localdbg: draw slot=%u topology=%u count=%u instances=%u first=%u stride=%u " "bytes=%llu viewport=%.0f,%.0f %.0fx%.0f depth %.2f..%.2f\n", slot, draw.topology, @@ -2229,6 +2234,46 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct if (draw.user_data[w] && vk.buffer_at(draw.user_data[w], room, bb, bo)) std::fprintf(stderr, "[rt] localdbg: user_data[%d] is a registered buffer VA\n", w); } + if (g_local_arena_mapped && draw.user_data[0] && draw.user_data[0] + 256ull <= g_local_arena_size) { + const std::uint32_t* t = reinterpret_cast(g_local_arena_mapped + draw.user_data[0]); + for (int e = 0; e < 4; ++e) { + std::fprintf(stderr, "[rt] localdbg: table[%d]:", e); + for (int w = 0; w < 8; ++w) std::fprintf(stderr, " %08x", t[e * 8 + w]); + std::fprintf(stderr, "\n"); + const std::uint64_t va = (std::uint64_t(t[e * 8 + 1] & 0xffff) << 32) | t[e * 8]; + if (va && va + 64 <= g_local_arena_size) { + const float* f2 = reinterpret_cast(g_local_arena_mapped + va); + std::fprintf(stderr, "[rt] localdbg: at va 0x%llx:", static_cast(va)); + for (int w = 0; w < 16; ++w) std::fprintf(stderr, " %g", f2[w]); + std::fprintf(stderr, "\n"); + } + } + } + { // the same table read from the title's memory, taking the high dword from the vertex view's VA + const std::uint64_t guess = (view.va & 0xffffffff00000000ull) | draw.user_data[0]; + std::fprintf(stderr, "[rt] localdbg: vertex va=0x%llx table guess=0x%llx delta=%lld\n", + static_cast(view.va), static_cast(guess), + static_cast(view.va - guess)); + std::uint64_t probe = 256; VkBuffer pb = VK_NULL_HANDLE; VkDeviceSize po = 0; + if (draw.user_data[0] && vk.title_memory && vk.title_memory(guess, probe, pb, po)) { + const std::uint32_t* t = reinterpret_cast(guess); + for (int e = 0; e < 3; ++e) { + std::fprintf(stderr, "[rt] localdbg: title table[%d]:", e); + for (int w = 0; w < 8; ++w) std::fprintf(stderr, " %08x", t[e * 8 + w]); + std::fprintf(stderr, "\n"); + } + } else { + std::fprintf(stderr, "[rt] localdbg: title table guess is not readable title memory\n"); + } + } + { // what sits just before the vertices in the title's ring + const std::uint32_t* t = reinterpret_cast(view.va - 0x60); + for (int e = 0; e < 3; ++e) { + std::fprintf(stderr, "[rt] localdbg: before vertices[-0x%x]:", 0x60 - e * 0x20); + for (int w = 0; w < 8; ++w) std::fprintf(stderr, " %08x", t[e * 8 + w]); + std::fprintf(stderr, "\n"); + } + } const std::uint32_t words = view.stride / 4 ? view.stride / 4 : 1; for (std::uint32_t v = 0; v < 4 && (draw.first + v + 1) * view.stride <= view.size; ++v) { const float* q = f + (draw.first + v) * words; From 0c7ec65c0e0d1890139eda86cc92fc4f0ed830e6 Mon Sep 17 00:00:00 2001 From: Mumogg <104529023+Mumogg@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:11:49 -0600 Subject: [PATCH 027/110] local: apply #9419 (present dump) as a patch --- runtime/CMakeLists.txt | 9 + runtime/src/present_dump.h | 256 ++++++++++++++++++++++++++ runtime/src/vulkan_present.h | 40 ++-- runtime/test/vk_present_dump_test.cpp | 113 ++++++++++++ 4 files changed, 407 insertions(+), 11 deletions(-) create mode 100644 runtime/src/present_dump.h create mode 100644 runtime/test/vk_present_dump_test.cpp diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index e24a5786c8..16aef2c294 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -1575,6 +1575,15 @@ if(TARGET Vulkan::Headers) endif() add_test(NAME vk_presenter_sync COMMAND vk_presenter_sync_test) set_tests_properties(vk_presenter_sync PROPERTIES SKIP_RETURN_CODE 77) + set(conformance_src ${CMAKE_CURRENT_SOURCE_DIR}/../tools/conformance/native/src) + add_executable(vk_present_dump_test test/vk_present_dump_test.cpp + ${conformance_src}/png_io.cpp ${conformance_src}/diagnostics.cpp) + target_link_libraries(vk_present_dump_test PRIVATE Vulkan::Headers user32 windowscodecs ole32) + target_compile_definitions(vk_present_dump_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + add_test(NAME vk_present_dump COMMAND vk_present_dump_test) + add_test(NAME vk_present_dump_default COMMAND vk_present_dump_test --default) + add_test(NAME vk_present_dump_invalid COMMAND vk_present_dump_test --invalid) + set_tests_properties(vk_present_dump vk_present_dump_default vk_present_dump_invalid PROPERTIES SKIP_RETURN_CODE 77) endif() if(NOT Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) find_program(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE glslangValidator HINTS "$ENV{VULKAN_SDK}/Bin" "$ENV{VULKAN_SDK}/bin") diff --git a/runtime/src/present_dump.h b/runtime/src/present_dump.h new file mode 100644 index 0000000000..2e594fcb50 --- /dev/null +++ b/runtime/src/present_dump.h @@ -0,0 +1,256 @@ +#pragma once + +// LEONIDA_PRESENT_DUMP: the final swapchain texels, encoded on a worker after their frame fence signals. +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace leonida::present_dump { + +inline unsigned texel_size(VkFormat format) { + switch (format) { + case VK_FORMAT_B8G8R8A8_UNORM: case VK_FORMAT_B8G8R8A8_SRGB: + case VK_FORMAT_R8G8B8A8_UNORM: case VK_FORMAT_R8G8B8A8_SRGB: + case VK_FORMAT_A2B10G10R10_UNORM_PACK32: case VK_FORMAT_A2R10G10B10_UNORM_PACK32: return 4; + case VK_FORMAT_R16G16B16A16_SFLOAT: return 8; + case VK_FORMAT_R32G32B32A32_SFLOAT: return 16; + default: return 0; + } +} + +inline std::uint8_t unorm8(float v) { + return v > 0 ? std::uint8_t(std::min(v, 1.0f) * 255 + 0.5f) : 0; +} + +inline std::uint8_t half_unorm8(std::uint16_t bits) { + const int exponent = bits >> 10; + const int fraction = bits & 1023; + if (bits >= 0x8000 || !exponent || (exponent == 31 && fraction)) return 0; + return unorm8(std::ldexp(float(1024 + fraction), exponent - 25)); +} + +inline void rgba_row(std::uint8_t* dst, const std::uint8_t* src, unsigned width, VkFormat format, bool pq) { + if (format == VK_FORMAT_R8G8B8A8_UNORM || format == VK_FORMAT_R8G8B8A8_SRGB) { + std::memcpy(dst, src, size_t(width) * 4); + return; + } + const unsigned stride = texel_size(format); + for (unsigned x = 0; x < width; ++x, src += stride, dst += 4) { + if (format == VK_FORMAT_B8G8R8A8_UNORM || format == VK_FORMAT_B8G8R8A8_SRGB) { + dst[0] = src[2]; dst[1] = src[1]; dst[2] = src[0]; dst[3] = src[3]; + } else if (format == VK_FORMAT_R16G16B16A16_SFLOAT) { + std::uint16_t v[4]; + std::memcpy(v, src, sizeof(v)); + std::transform(v, v + 4, dst, half_unorm8); + } else if (format == VK_FORMAT_R32G32B32A32_SFLOAT) { + float v[4]; + std::memcpy(v, src, sizeof(v)); + std::transform(v, v + 4, dst, unorm8); + } else { + // A cheap HDR10 preview: decode ST.2084 per component, clip at 203 nits and encode for SDR. + // Keep the source primaries. A 10-bit SDR swapchain just scales its code values to eight bits. + static const auto pq_to_sdr = [] { + std::array table{}; + for (unsigned i = 0; i < table.size(); ++i) { + const double p = std::pow(i / 1023.0, 1.0 / 78.84375); + const double linear = (10000.0 / 203.0) * + std::pow(std::max(0.0, p - 0.8359375) / (18.8515625 - 18.6875 * p), 1.0 / 0.1593017578125); + const double srgb = linear <= 0.0031308 ? 12.92 * linear : 1.055 * std::pow(linear, 1.0 / 2.4) - 0.055; + table[i] = unorm8(float(srgb)); + } + return table; + }(); + std::uint32_t packed; + std::memcpy(&packed, src, sizeof(packed)); + for (unsigned channel = 0; channel < 3; ++channel) { + const unsigned bits = (packed >> (10 * channel)) & 1023; + dst[channel] = pq ? pq_to_sdr[bits] : std::uint8_t((bits * 255 + 511) / 1023); + } + if (format == VK_FORMAT_A2R10G10B10_UNORM_PACK32) std::swap(dst[0], dst[2]); + dst[3] = std::uint8_t((packed >> 30) * 85); + } + } +} + +inline std::array big_endian(std::uint32_t n) { + return {std::uint8_t(n >> 24), std::uint8_t(n >> 16), std::uint8_t(n >> 8), std::uint8_t(n)}; +} + +inline bool chunk(std::FILE* file, const char (&type)[5], std::span data, + std::span prefix = {}) { + static constexpr auto crc_table = [] { + std::array table{}; + for (unsigned i = 0; i < table.size(); ++i) { + unsigned c = i; + for (int bit = 0; bit < 8; ++bit) c = (c >> 1) ^ ((c & 1) ? 0xedb88320u : 0); + table[i] = c; + } + return table; + }(); + std::uint32_t crc = ~0u; + const auto write = [&](std::span bytes) { + for (auto b : bytes) crc = crc_table[(crc ^ b) & 255] ^ (crc >> 8); + return bytes.empty() || std::fwrite(bytes.data(), 1, bytes.size(), file) == bytes.size(); + }; + return std::fwrite(big_endian(std::uint32_t(prefix.size() + data.size())).data(), 1, 4, file) == 4 && + write({reinterpret_cast(type), 4}) && write(prefix) && write(data) && + std::fwrite(big_endian(~crc).data(), 1, 4, file) == 4; +} + +inline bool write_png(std::FILE* file, VkExtent2D extent, VkFormat format, bool pq, const std::uint8_t* src) { + constexpr std::uint8_t signature[]{137, 80, 78, 71, 13, 10, 26, 10}; + std::array ihdr{}; + const auto w = big_endian(extent.width), h = big_endian(extent.height); + std::copy(w.begin(), w.end(), ihdr.begin()); + std::copy(h.begin(), h.end(), ihdr.begin() + 4); + ihdr[8] = 8; + ihdr[9] = 6; // 8-bit RGBA + constexpr std::uint8_t zlib_header[]{0x78, 0x01}; + if (std::fwrite(signature, 1, sizeof(signature), file) != sizeof(signature) || + !chunk(file, "IHDR", ihdr) || !chunk(file, "IDAT", zlib_header)) return false; + + // IDAT chunks concatenate to one zlib stream. Each scanline starts with PNG filter 0 and occupies + // one or more stored DEFLATE blocks (16-bit little-endian length and its ones' complement). + std::vector row(1 + size_t(extent.width) * 4); + std::uint32_t a = 1, b = 0; + for (unsigned y = 0; y < extent.height; ++y, src += size_t(extent.width) * texel_size(format)) { + rgba_row(row.data() + 1, src, extent.width, format, pq); + std::span rest(row); + while (!rest.empty()) { + auto block = rest.first(std::min(rest.size(), 65535)); + rest = rest.subspan(block.size()); + const auto len = std::uint16_t(block.size()); + const std::uint8_t header[]{std::uint8_t(y + 1 == extent.height && rest.empty()), + std::uint8_t(len), std::uint8_t(len >> 8), std::uint8_t(~len), std::uint8_t((len >> 8) ^ 255)}; + for (auto byte : block) { + a = (a + byte) % 65521; + b = (b + a) % 65521; + } + if (!chunk(file, "IDAT", block, header)) return false; + } + } + return chunk(file, "IDAT", big_endian((b << 16) | a)) && chunk(file, "IEND", {}); +} + +class PresentDump { +public: + PresentDump() { +#ifdef _WIN32 + wchar_t* env = nullptr; + size_t length = 0; + if (_wdupenv_s(&env, &length, L"LEONIDA_PRESENT_DUMP") != 0) { + bad_value(); + return; + } + const std::unique_ptr owned(env, &std::free); +#else + const auto* env = std::getenv("LEONIDA_PRESENT_DUMP"); +#endif + if (!env) return; + try { + auto value = std::filesystem::path(env).native(); + std::uint64_t interval = 60; + const auto comma = value.rfind(','); + if (comma != value.npos) { + const auto n = std::filesystem::path(value.substr(comma + 1)).string(); + const auto end = n.data() + n.size(); + const auto parsed = std::from_chars(n.data(), end, interval); + if (parsed.ec != std::errc{} || parsed.ptr != end || !interval) { + bad_value(); + return; + } + value.resize(comma); + } + if (value.empty()) { + bad_value(); + return; + } + dir_ = std::filesystem::absolute(value); + std::filesystem::create_directories(dir_); + interval_ = interval; + } catch (const std::exception&) { bad_value(); } + } + + bool enabled() const { return interval_ != 0; } + bool due(std::uint64_t frames_shown) const { + const auto n = interval_.load(); + return n && frames_shown % n == 0; + } + void disable(const char* why) { + if (interval_.exchange(0)) std::fprintf(stderr, "[rt] present: %s; LEONIDA_PRESENT_DUMP disabled\n", why); + } + void save(std::uint64_t frame, VkExtent2D extent, VkFormat format, bool pq, const std::uint8_t* src, size_t size) { + try { + // Bound memory to one outstanding write even at N=1. Teardown joins the final writer. + if (writer_.joinable()) writer_.join(); + if (!enabled()) return; + char name[48]; + std::snprintf(name, sizeof(name), "present_%06llu.png", static_cast(frame)); + writer_ = std::jthread([this, frame, extent, format, pq, path = dir_ / name, + bytes = std::vector(src, src + size)] { + try { + if (publish(path, extent, format, pq, bytes.data())) { + const auto utf8 = path.u8string(); + std::fprintf(stderr, "[rt] present: dumped frame %llu to %s\n", + static_cast(frame), reinterpret_cast(utf8.c_str())); + return; + } + } catch (const std::exception&) {} + disable("could not write the present dump"); + }); + } catch (const std::exception&) { disable("could not queue the present dump"); } + } + +private: + static void bad_value() { + static std::once_flag once; + std::call_once(once, [] { + std::fprintf(stderr, "[rt] present: invalid LEONIDA_PRESENT_DUMP (expected a writable dir[,N], N > 0); disabled\n"); + }); + } + static bool publish(const std::filesystem::path& path, VkExtent2D extent, VkFormat format, bool pq, + const std::uint8_t* src) { + // Never open an existing output for writing: it could be a link to a file outside the dump directory. + // Build a complete sibling exclusively, then replace the directory entry in a single rename. + auto tmp = path; + tmp += ".tmp"; +#ifdef _WIN32 + std::FILE* file = nullptr; + _wfopen_s(&file, tmp.c_str(), L"wbx"); +#else + auto* file = std::fopen(tmp.c_str(), "wbx"); +#endif + if (!file) return false; + bool ok = false; + try { ok = write_png(file, extent, format, pq, src); } catch (const std::exception&) {} + if (std::fclose(file) != 0) ok = false; + std::error_code ec; + if (ok) { + std::filesystem::rename(tmp, path, ec); + if (!ec) return true; + } + std::filesystem::remove(tmp, ec); + return false; + } + + std::filesystem::path dir_; + std::atomic interval_{0}; + std::jthread writer_; // joined before the state it uses is destroyed +}; + +} // namespace leonida::present_dump diff --git a/runtime/src/vulkan_present.h b/runtime/src/vulkan_present.h index 8644346c53..2ce6f457b2 100644 --- a/runtime/src/vulkan_present.h +++ b/runtime/src/vulkan_present.h @@ -27,6 +27,7 @@ #include "vulkan_backend.h" #include "vulkan_present_compose.h" +#include "present_dump.h" // Use the original EXT spellings. They are aliases of the promoted KHR types and are available in older headers. #if defined(VK_EXT_SWAPCHAIN_MAINTENANCE_1_EXTENSION_NAME) && defined(VK_EXT_SURFACE_MAINTENANCE_1_EXTENSION_NAME) @@ -583,7 +584,15 @@ class VulkanPresenter { // Only a present the engine took counts (SUBOPTIMAL is shown too). OUT_OF_DATE was not shown: the swapchain // is recreated next time, and the caller sees VK_SUCCESS, since its work was submitted. if (result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR) { - ++presented_; + const auto shown = ++presented_; + if (dump_.due(shown - 1)) { + // Presentation is already queued and the queue/tracker locks are released. A sampled frame + // may stall here for its transfer fence and a private CPU copy. PNG and disk I/O run on a worker. + if (vkWaitForFences_(device, 1, &frame.done, VK_TRUE, UINT64_MAX) == VK_SUCCESS) + dump_.save(shown, extent_, format_, dump_pq_, capture_ptr_, size_t(capture_size_)); + else + dump_.disable("present dump fence wait failed"); + } if (planes) ++composed_; if (tearing) { last_tore_ = true; @@ -915,7 +924,7 @@ class VulkanPresenter { const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; VkImageLayout layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; VkAccessFlags access = VK_ACCESS_TRANSFER_WRITE_BIT; - if (capture_ && capture_buffer_) { + if (capture_buffer_ && (capture_ || dump_.due(presented_))) { // Two frames may be in flight and share `capture_buffer_`: serialize the prior frame's capture copy // before overwriting it, while moving this frame's swapchain image to TRANSFER_SRC. VkBufferMemoryBarrier capture_waw{VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER}; @@ -942,6 +951,10 @@ class VulkanPresenter { copy.imageExtent = {extent_.width, extent_.height, 1}; fn.copy_image_to_buffer(commands, images_[image], VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, capture_buffer_, 1, ©); + auto to_host = capture_waw; + to_host.dstAccessMask = VK_ACCESS_HOST_READ_BIT; + fn.pipeline_barrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, + 0, nullptr, 1, &to_host, 0, nullptr); layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; access = VK_ACCESS_TRANSFER_READ_BIT; } @@ -954,7 +967,7 @@ class VulkanPresenter { release_capture(); auto& vk = context_.vk; const VkDevice device = context_.device(); - capture_size_ = VkDeviceSize(extent_.width) * extent_.height * 4; + capture_size_ = VkDeviceSize(extent_.width) * extent_.height * present_dump::texel_size(format_); VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; info.size = capture_size_; info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT; @@ -1039,7 +1052,9 @@ class VulkanPresenter { return true; } VkImageUsageFlags usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT; - if (capture_) usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; + if (dump_.enabled() && !(caps.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_SRC_BIT)) + dump_.disable("surface does not support swapchain readback"); + if (capture_ || dump_.enabled()) usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; if ((caps.supportedUsageFlags & usage) != usage) return false; // Not used by the presenter itself (it blits or copies into the images), but overlays that hook the swapchain // draw their own frame into its images through a framebuffer, which needs COLOR_ATTACHMENT: without it @@ -1183,13 +1198,14 @@ class VulkanPresenter { extent_ = extent; extent_packed_ = (std::uint64_t(extent.width) << 32) | extent.height; hdr_active_ = chose_hdr; - if (capture_) { - // A capture that cannot be made fails the recreation with the swapchain in place and stale_ still set. - const bool four_bytes = format_ == VK_FORMAT_B8G8R8A8_UNORM || format_ == VK_FORMAT_R8G8B8A8_UNORM || - format_ == VK_FORMAT_B8G8R8A8_SRGB || format_ == VK_FORMAT_R8G8B8A8_SRGB || - format_ == VK_FORMAT_A2B10G10R10_UNORM_PACK32 || - format_ == VK_FORMAT_A2R10G10B10_UNORM_PACK32; - if (!four_bytes || !make_capture_buffer()) return false; + dump_pq_ = chosen.colorSpace == VK_COLOR_SPACE_HDR10_ST2084_EXT; + if (capture_ || dump_.enabled()) { + const auto stride = present_dump::texel_size(format_); + if (capture_ && stride != 4) return false; // read_back() promises four bytes per texel + if (!stride || !make_capture_buffer()) { + dump_.disable("cannot read back this swapchain format or allocate its capture buffer"); + if (capture_) return false; + } } vsync_ = vsync; swapchain_srgb_ = srgb; @@ -1300,6 +1316,8 @@ class VulkanPresenter { std::map features_; bool warned_srgb_ = false; bool capture_ = false; + present_dump::PresentDump dump_; + bool dump_pq_ = false; VkBuffer capture_buffer_ = VK_NULL_HANDLE; VkDeviceMemory capture_memory_ = VK_NULL_HANDLE; VkDeviceSize capture_size_ = 0; diff --git a/runtime/test/vk_present_dump_test.cpp b/runtime/test/vk_present_dump_test.cpp new file mode 100644 index 0000000000..a4497166f9 --- /dev/null +++ b/runtime/test/vk_present_dump_test.cpp @@ -0,0 +1,113 @@ +// Present a small solid texture through the window blit and the PresentX plane composer. Only the composed +// image has a black lower half. Decode the PNGs independently with the conformance tool's WIC reader. +#define VK_USE_PLATFORM_WIN32_KHR +#include +#include + +#include "test_temp_dir.h" +#include "vk_test_device.h" +#include "../src/vulkan_present.h" +#include "../../tools/conformance/native/src/png_io.h" + +#include +#include +#include +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +int main(int argc, char** argv) { + using namespace leonida; + namespace fs = std::filesystem; + vktest::Device d; + const auto status = d.initialize(true); + if (status == vktest::DeviceStatus::unavailable) return 77; + EXPECT(status == vktest::DeviceStatus::ready); + EXPECT(SUCCEEDED(CoInitializeEx(nullptr, COINIT_MULTITHREADED))); + testfiles::ScratchDir scratch("leonida_present_dump"); + const fs::path dir = scratch.path() / "frames"; + const std::string_view mode = argc == 2 ? argv[1] : ""; + EXPECT(mode.empty() || mode == "--default" || mode == "--invalid"); + const int interval = mode == "--default" ? 60 : 2; + const auto setting = dir.wstring() + (mode == "--default" ? L"" : mode == "--invalid" ? L",0" : L",2"); + EXPECT(_wputenv_s(L"LEONIDA_PRESENT_DUMP", setting.c_str()) == 0); + // An earlier dump might be a hard link outside the requested directory. Replacing it must leave that file intact. + const auto sentinel = scratch.path() / "outside"; + if (mode == "--default") { + EXPECT(fs::create_directory(dir)); + EXPECT(std::ofstream(sentinel).put('X')); + std::error_code ec; + fs::create_hard_link(sentinel, dir / "present_000001.png", ec); // optional on filesystems without links + } + + constexpr int width = 192, height = 100; + const HINSTANCE instance = GetModuleHandleW(nullptr); + HWND window = CreateWindowExW(0, L"STATIC", L"Leonida present dump test", WS_POPUP, 0, 0, width, height, + nullptr, nullptr, instance, nullptr); + EXPECT(window); + ShowWindow(window, SW_SHOWNOACTIVATE); + VulkanContext context(d.device_proc, d.device, true); + VulkanQueue queue(context, d.queue, d.family); + EXPECT(context.loaded() && queue.ok()); + ResourceBinding back{}; + back.format = VK_FORMAT_R8G8B8A8_UNORM; + back.width = back.height = 2; + back.aspects = VK_IMAGE_ASPECT_COLOR_BIT; + back.sampled = back.color_attachment = true; + back.image = d.image(back.format, 2, 2, 1, VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT); + EXPECT(back.image); + context.add_resource(1, back, VK_IMAGE_LAYOUT_UNDEFINED); + CommandList commands; + EXPECT(commands.transition({1, 0, d3d12_state::common, d3d12_state::render_target})); + EXPECT(commands.clear_render_target({1, 0, 0, 1}, {1.0f, 0.4f, 0.0f, 1.0f})); + EXPECT(commands.transition({1, 0, d3d12_state::render_target, d3d12_state::common})); + EXPECT(commands.close()); + const CommandList* list = &commands; + EXPECT(queue.execute({&list, 1}) == ReplayResult::success); + + VkWin32SurfaceCreateInfoKHR info{VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR}; + info.hinstance = instance; + info.hwnd = window; + VkSurfaceKHR surface{}; + EXPECT(d.instance_fn("vkCreateWin32SurfaceKHR")( + d.instance, &info, nullptr, &surface) == VK_SUCCESS); + { + VulkanPresenter presenter(context, d.instance_proc, d.instance, d.physical, d.queue, d.family, surface, + false, [] { return VkExtent2D{width, height}; }); + EXPECT(presenter.ok()); + EXPECT(presenter.present(1, true) == VK_SUCCESS); + for (int i = 1; i < interval; ++i) EXPECT(presenter.present_blank(true) == VK_SUCCESS); + PresentPlanes planes; + planes.plane[0].source = 1; + planes.plane[0].dest[3] = 0.5f; + EXPECT(presenter.present_planes(planes, true) == VK_SUCCESS); + EXPECT(presenter.presented() == unsigned(interval + 1) && presenter.composed_presents() == 1); + } + DestroyWindow(window); + EXPECT(d.validation_errors() == 0); + if (mode == "--invalid") { + EXPECT(!fs::exists(dir)); + CoUninitialize(); + return 0; + } + if (mode == "--default") EXPECT(fs::file_size(sentinel) == 1 && std::ifstream(sentinel).get() == 'X'); + for (bool composed : {false, true}) { + const auto* name = !composed ? "present_000001.png" : interval == 2 ? "present_000003.png" : "present_000061.png"; + PixelSurface png; + EXPECT(ReadPngFile(dir / name, png)); + EXPECT(png.width == width && png.height == height); + for (int y = 0; y < height; ++y) { + const bool black = composed && y >= height / 2; + const std::array expected = black ? std::array{0, 0, 0, 255} + : std::array{255, 102, 0, 255}; + for (int x = 0; x < width; ++x) + EXPECT(std::equal(expected.begin(), expected.end(), png.At(x, y))); + } + } + EXPECT(std::distance(fs::directory_iterator(dir), fs::directory_iterator{}) == 2); + CoUninitialize(); + return 0; +} From 6ff056074a99eabbc0aee77fa34ade559843c3ec Mon Sep 17 00:00:00 2001 From: channa317 <183341518+channa317@users.noreply.github.com> Date: Tue, 24 Nov 2026 06:14:16 +0800 Subject: [PATCH 028/110] d3d12: support Xbox depth UAVs through CreateCommittedResource3 (D3D-991) --- docs/d3d12_vulkan.md | 7 +- runtime/shims/d3d12_vulkan_device.cpp | 52 ++++++- runtime/shims/d3d12_xs_device.cpp | 6 +- runtime/shims/d3d12_xs_device.h | 6 + runtime/test/d3d12_depth_stencil_uav_test.cpp | 139 ++++++++++++++---- 5 files changed, 165 insertions(+), 45 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index f5d7cfe2cc..547a5df1ad 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2468,8 +2468,11 @@ The trace will enumerate them. `DEPTH_STENCIL_ATTACHMENT`, `ALLOW_UNORDERED_ACCESS` → `STORAGE`, `ALLOW_SIMULTANEOUS_ACCESS` → concurrent sharing, `DENY_*` → omit the corresponding usage. Buffers get the union of usages their states and flags imply; images copy dimension, format, mip levels, array layers and sample count. -- Xbox depth textures with `ALLOW_DEPTH_STENCIL | ALLOW_UNORDERED_ACCESS` can use either committed creation - (slot 76) or placement at a guest address (slot 133). The supported shapes are single-sample, single-mip 2D +- Xbox depth textures with `ALLOW_DEPTH_STENCIL | ALLOW_UNORDERED_ACCESS` can use legacy committed creation + (slot 76), `CreateCommittedResource3` (forwarded by Xbox slot 127 in the boot stack), or placement at a guest + address (slot 133). The Device10 path validates the requested initial layout and clear value against the logical + texture. Xbox allocation queries return the attachment's placement size for XMem accounting; the writable + planes are private backend allocations. The supported shapes are single-sample, single-mip 2D textures and 2D arrays. For `R32G8X24_TYPELESS`, use `R32_FLOAT` on depth plane 0 and `R8_UINT` on stencil plane 1. For `R16_TYPELESS`, use `R16_UINT` on plane 0 to access the raw D16 bits. An array UAV selects a contiguous range of layers. The depth/stencil and shader-resource views continue to use the attachment image. diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index bbda465aaf..0194515fea 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -52,6 +52,7 @@ #include #include #include +#include #include #include #include @@ -1375,11 +1376,24 @@ Format texture_format(const DeviceState& device, const D3D12_RESOURCE_DESC& desc // runtime refuses other sizes, and a size-mismatched VkImageFormatListCreateInfo is a Vulkan validation error // (VUID-VkImageCreateInfo-pNext-06722). A nonzero count with a null list is no list. E_INVALIDARG on a bad format. HRESULT castable_view_formats(const Format& format, UINT32 count, const DXGI_FORMAT* castable, - std::vector& out) { + std::vector& out, bool depth_uav_planes = false) { if (!count || !castable) return S_OK; const bool depth = (format.aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) != 0; const leonida::BlockFormat own = leonida::block_format(format.format, format.aspects); for (UINT32 i = 0; i < count; ++i) { + if (depth_uav_planes) { + // Attachment and sampled views use the original depth image's VkFormat. Each typed UAV + // already has its own image; putting its colour format on the depth image is invalid. + const DXGI_FORMAT view = castable[i]; + const bool valid = format.format == VK_FORMAT_D16_UNORM + ? view == DXGI_FORMAT_R16_TYPELESS || view == DXGI_FORMAT_D16_UNORM || + view == DXGI_FORMAT_R16_UNORM || view == DXGI_FORMAT_R16_UINT + : view == DXGI_FORMAT_R32G8X24_TYPELESS || view == DXGI_FORMAT_D32_FLOAT_S8X24_UINT || + view == DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS || view == DXGI_FORMAT_X32_TYPELESS_G8X24_UINT || + view == DXGI_FORMAT_R32_FLOAT || view == DXGI_FORMAT_R8_UINT; + if (!valid) return E_INVALIDARG; + continue; + } const Format cast = vulkan_format(castable[i], depth); if (cast.format == VK_FORMAT_UNDEFINED) { log_once("castable format not supported yet:", castable[i]); @@ -6811,15 +6825,23 @@ class Device final if (texture_mip_region(*desc)) return d3d12_trace::result(method, E_INVALIDARG); // A count with a null array is no list (as on the PC runtime). The layer reports relaxed format casting, so // a real list is passed through; only buffers are refused. - const D3D12_RESOURCE_DESC base = resource_desc(*desc); + D3D12_RESOURCE_DESC base = resource_desc(*desc); if (const char* why = barrier_layout_refusal(base, layout)) { log_once((std::string(method) + " refused (" + why + "), layout").c_str(), int(layout)); return d3d12_trace::result(method, E_INVALIDARG); } + // The Xbox slot-127 bridge forwards the logical texture to Device10. Validate its layout above, + // then allocate the depth attachment and enable the typed storage planes before returning it. + std::optional storage_heap_flags; + if (xbox_depth_uav(base)) { + storage_heap_flags = heap_flags & D3D12_HEAP_FLAG_ALLOW_SHADER_ATOMICS; + heap_flags &= ~*storage_heap_flags; + base.Flags &= ~D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + } // D3D12_BARRIER_LAYOUT has no acceleration-structure value; an AS buffer's state comes through the // legacy CreateCommittedResource path. Buffers here start COMMON, as before. return create_committed_validated(method, heap, heap_flags, &base, D3D12_RESOURCE_STATE_COMMON, clear, - castable_count, castable, riid, out); + castable_count, castable, riid, out, storage_heap_flags); } // Device9. The creator ID only groups queues for tools; one creator is as good as another here. @@ -7898,6 +7920,10 @@ class Device final return value > UINT64_MAX - (to - 1) ? UINT64_MAX / to * to : (value + to - 1) / to * to; } + bool xbox_depth_uav(const D3D12_RESOURCE_DESC& desc) const { + return rt::d3d12_xs::depth_uav_description(desc) && rt::d3d12_xs::is_device_proxy(outer_); + } + // Lays `count` resources out one after another; `each` (optional) gets every resource's offset, size and // alignment. As on the PC runtime, the total is rounded up to the largest alignment (1 for no resources) and // saturates near 2^64 rather than wrapping. @@ -7907,7 +7933,13 @@ class Device final D3D12_RESOURCE_ALLOCATION_INFO total{0, 1}; bool failed = count && !descs; for (UINT i = 0; i < count; ++i) { - const D3D12_RESOURCE_ALLOCATION_INFO one = failed ? kInvalidAllocation : allocation(get(i)); + D3D12_RESOURCE_ALLOCATION_INFO one = kInvalidAllocation; + if (!failed) { + auto desc = get(i); + // The boot stack charges XMem for the guest placement; storage planes are private to Vulkan. + if (xbox_depth_uav(desc)) desc.Flags &= ~D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + one = allocation(desc); + } failed = failed || one.SizeInBytes == UINT64_MAX; if (failed) { if (each) each[i] = {UINT64_MAX, one.Alignment, UINT64_MAX}; @@ -8096,7 +8128,8 @@ class Device final HRESULT create_committed_validated(const char* method, const D3D12_HEAP_PROPERTIES* heap, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, - UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out) { + UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out, + std::optional storage_heap_flags = std::nullopt) { const auto finish = [&](HRESULT hr) { return method ? d3d12_trace::result(method, hr) : hr; }; if (out) *out = nullptr; if (!heap || !desc) return finish(E_INVALIDARG); @@ -8118,7 +8151,8 @@ class Device final int(desc->Dimension)); return finish(E_INVALIDARG); } - return finish(create_committed(heap, heap_flags, desc, state, castable_count, castable, riid, out)); + return finish(create_committed(heap, heap_flags, desc, state, castable_count, castable, riid, out, + storage_heap_flags)); } // Shared by CreateCommittedResource, CreateCommittedResource3 and CreateReservedResource*. A castable-format list @@ -8127,7 +8161,8 @@ class Device final // runtime. HRESULT create_committed(const D3D12_HEAP_PROPERTIES* heap, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES initial_state, - UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out) { + UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out, + std::optional storage_heap_flags) { if (out) *out = nullptr; if (!heap || !desc) return E_INVALIDARG; if (castable_count && castable && desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { @@ -8171,9 +8206,10 @@ class Device final hr = E_INVALIDARG; } else { std::vector cast_formats; - hr = castable_view_formats(format, castable_count, castable, cast_formats); + hr = castable_view_formats(format, castable_count, castable, cast_formats, storage_heap_flags.has_value()); if (SUCCEEDED(hr)) hr = resource->create_texture(format, cast_formats); if (SUCCEEDED(hr)) resource->keep_castable_formats(castable_count, castable); + if (SUCCEEDED(hr) && storage_heap_flags) hr = resource->enable_depth_stencil_uav(*storage_heap_flags); } } if (FAILED(hr)) { diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 2219dfe33f..7581482757 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -1458,11 +1458,7 @@ HRESULT proxy_create_compute_pipeline_from_native_code(DeviceProxy* self, const } bool supports_depth_uav(const DeviceProxy* self, const D3D12_RESOURCE_DESC& desc) { - constexpr auto flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; - return self->depth_stencil_uav_provider && (desc.Flags & flags) == flags && - desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && - (desc.Format == DXGI_FORMAT_R32G8X24_TYPELESS || desc.Format == DXGI_FORMAT_R16_TYPELESS) && - desc.DepthOrArraySize && desc.MipLevels == 1 && desc.SampleDesc.Count == 1; + return self->depth_stencil_uav_provider && depth_uav_description(desc); } D3D12_RESOURCE_DESC depth_image_desc(D3D12_RESOURCE_DESC desc) { diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index bd04b323d7..43dcfcce86 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -77,6 +77,12 @@ using DxgiAdapterProvider = HRESULT (*)(ID3D12Device* real, REFIID riid, void** bool set_device_adapter_provider(void* device, DxgiAdapterProvider provider); // Called before publishing an Xbox resource when the backend can implement its depth/stencil UAV views. using DepthStencilUavProvider = HRESULT (*)(ID3D12Resource* resource, D3D12_HEAP_FLAGS storage_heap_flags); +inline bool depth_uav_description(const D3D12_RESOURCE_DESC& desc) { + constexpr auto flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + return (desc.Flags & flags) == flags && desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && + (desc.Format == DXGI_FORMAT_R32G8X24_TYPELESS || desc.Format == DXGI_FORMAT_R16_TYPELESS) && + desc.DepthOrArraySize && desc.MipLevels == 1 && desc.SampleDesc.Count == 1; +} using ValidateDepthPlacement = bool (*)(const D3D12_RESOURCE_DESC&, D3D12_RESOURCE_STATES, const D3D12_CLEAR_VALUE*); bool set_depth_stencil_uav_provider(void* device, DepthStencilUavProvider provider, ValidateDepthPlacement validate_placement = nullptr); diff --git a/runtime/test/d3d12_depth_stencil_uav_test.cpp b/runtime/test/d3d12_depth_stencil_uav_test.cpp index ff34f90107..b820839f03 100644 --- a/runtime/test/d3d12_depth_stencil_uav_test.cpp +++ b/runtime/test/d3d12_depth_stencil_uav_test.cpp @@ -78,13 +78,40 @@ struct GuestAllocation { ~GuestAllocation() { if (address) VirtualFree(address, 0, MEM_RELEASE); } }; -enum class Texture { committed, committed_array, placed, placed_array }; +enum class Texture { committed, committed3, placed }; -int run(vktest::Device& vk, UINT width, UINT height, bool enhanced, Texture kind, DXGI_FORMAT format, Handoff handoff) { - const bool array = kind == Texture::committed_array || kind == Texture::placed_array; - const bool placed = kind == Texture::placed || kind == Texture::placed_array; +// The boot stack's Xbox slot 127 forwards this call to the real device's CreateCommittedResource3. +// Test the actual thunk when present, or the same normalized input at its destination on a standalone build. +HRESULT create_committed3(ID3D12Device* device, ID3D12Device* xbox, const D3D12_HEAP_PROPERTIES& heap, + const D3D12_RESOURCE_DESC& desc, D3D12_BARRIER_LAYOUT initial, + const D3D12_CLEAR_VALUE& clear, ID3D12Resource** out, + UINT castable_count = 0, const DXGI_FORMAT* castable = nullptr) { + D3D12_RESOURCE_DESC1 input{desc.Dimension, desc.Alignment, desc.Width, desc.Height, desc.DepthOrArraySize, + desc.MipLevels, desc.Format, desc.SampleDesc, desc.Layout, desc.Flags, {}}; + if (xbox && rt::d3d12_xs::device_slot_overridden(127)) { + using Slot127 = HRESULT(WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS, + const D3D12_RESOURCE_DESC1*, D3D12_BARRIER_LAYOUT, const D3D12_CLEAR_VALUE*, + ID3D12ProtectedResourceSession*, UINT, const DXGI_FORMAT*, REFIID, void**); + const auto create = reinterpret_cast(d3d12test::slot(xbox, 127)); + return create(xbox, &heap, D3D12_HEAP_FLAG_NONE, &input, initial, &clear, nullptr, + castable_count, castable, IID_PPV_ARGS(out)); + } + Ref device10; + const HRESULT hr = device->QueryInterface(IID_PPV_ARGS(&device10.p)); + if (FAILED(hr)) return hr; + input.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + return device10->CreateCommittedResource3(&heap, D3D12_HEAP_FLAG_NONE, &input, initial, &clear, nullptr, + castable_count, castable, IID_PPV_ARGS(out)); +} + +int run(vktest::Device& vk, UINT width, UINT height, bool enhanced, Texture kind, UINT16 layers, + DXGI_FORMAT format, Handoff handoff) { + const bool array = layers > 1; + // Array views cover the last two layers so the shader reaches slice 5 in the six-layer case. + const UINT first_slice = array ? layers - 2u : 0; + const bool placed = kind == Texture::placed; + const bool modern = kind == Texture::committed3; const bool depth16 = format == DXGI_FORMAT_R16_TYPELESS; - const UINT layers = array ? 3 : 1; const UINT planes = depth16 ? 1 : 2; const UINT subresources = planes * layers; const char* fixture = array ? LEONIDA_DEPTH_STENCIL_ARRAY_SPV : LEONIDA_DEPTH_STENCIL_2D_SPV; @@ -122,29 +149,44 @@ int run(vktest::Device& vk, UINT width, UINT height, bool enhanced, Texture kind CHECK(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device)))); Ref xbox; CHECK(SUCCEEDED(rt::d3d12_xs::create_device_proxy(device, IID_PPV_ARGS(&xbox.p)))); // takes ownership - rt::d3d12::set_device_outer(device, xbox.p); - if (!enhanced && !array && !depth16) CHECK(placeddepthtest::check_alias_lifetime(device, xbox.p)); - D3D12_RESOURCE_DESC desc{}; desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; desc.Width = width; desc.Height = height; desc.MipLevels = 1; - desc.DepthOrArraySize = static_cast(layers); + desc.DepthOrArraySize = layers; desc.SampleDesc.Count = 1; desc.Format = format; desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; desc.Layout = static_cast(0x101); + D3D12_HEAP_PROPERTIES props{}; + props.Type = D3D12_HEAP_TYPE_DEFAULT; + D3D12_CLEAR_VALUE optimized{}; + optimized.Format = depth16 ? DXGI_FORMAT_D16_UNORM : DXGI_FORMAT_D32_FLOAT_S8X24_UINT; + optimized.DepthStencil.Depth = 1.0f; + auto normalized = desc; + normalized.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + if (modern) { + // The standalone PC Device10 retains its ordinary rejection of the combined creation flags. + Ref refused; + CHECK(create_committed3(device, nullptr, props, desc, D3D12_BARRIER_LAYOUT_COMMON, + optimized, &refused.p) == E_INVALIDARG && !refused.p); + } + rt::d3d12::set_device_outer(device, xbox.p); + if (!enhanced && !array && !depth16) CHECK(placeddepthtest::check_alias_lifetime(device, xbox.p)); using CreateFn = HRESULT(WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS, const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_STATES, const D3D12_CLEAR_VALUE*, REFIID, void**); // The baseline uses PC sizing. In builds with the Xbox slot-25 dependency, size the placement through // the console's return-buffer-first ABI; keep native footprints for the host pixel readback. - auto native_depth = desc; - native_depth.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + auto native_depth = normalized; native_depth.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; auto size = device->GetResourceAllocationInfo(0, 1, &native_depth); CHECK(size.SizeInBytes > 0 && size.SizeInBytes != UINT64_MAX); + if (modern) { + const auto logical = device->GetResourceAllocationInfo(0, 1, &normalized); + CHECK(logical.SizeInBytes == size.SizeInBytes && logical.Alignment == size.Alignment); + } if (rt::d3d12_xs::device_slot_overridden(25)) { using SizeFn = D3D12_RESOURCE_ALLOCATION_INFO*(WINAPI*)(D3D12_RESOURCE_ALLOCATION_INFO*, void*, UINT, UINT, const D3D12_RESOURCE_DESC*); @@ -155,8 +197,6 @@ int run(vktest::Device& vk, UINT width, UINT height, bool enhanced, Texture kind xbox_size.Alignment >= size.Alignment); size = xbox_size; } - D3D12_HEAP_PROPERTIES props{}; - props.Type = D3D12_HEAP_TYPE_DEFAULT; GuestAllocation guest; Ref texture, alias; const auto create_texture = reinterpret_cast(d3d12test::slot(xbox.p, 76)); @@ -172,6 +212,30 @@ int run(vktest::Device& vk, UINT width, UINT height, bool enhanced, Texture kind CHECK(SUCCEEDED(place(xbox.p, va, &desc, D3D12_RESOURCE_STATE_DEPTH_WRITE, nullptr, IID_PPV_ARGS(&alias.p)))); CHECK(texture.p != alias.p && texture->GetGPUVirtualAddress() == va && alias->GetGPUVirtualAddress() == va); + } else if (modern) { + // Exercise the exact no-list overload as well as lists naming both the attachment and its writable planes. + const DXGI_FORMAT d16_views[] = {DXGI_FORMAT_D16_UNORM, DXGI_FORMAT_R16_UNORM, DXGI_FORMAT_R16_UINT}; + const DXGI_FORMAT d32s8_views[] = {DXGI_FORMAT_D32_FLOAT_S8X24_UINT, DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS, + DXGI_FORMAT_X32_TYPELESS_G8X24_UINT, DXGI_FORMAT_R32_FLOAT, DXGI_FORMAT_R8_UINT}; + const UINT count = layers == 3 ? UINT(depth16 ? std::size(d16_views) : std::size(d32s8_views)) : 0; + const DXGI_FORMAT* castable = count ? (depth16 ? d16_views : d32s8_views) : nullptr; + CHECK(SUCCEEDED(create_committed3(device, xbox.p, props, desc, D3D12_BARRIER_LAYOUT_COMMON, + optimized, &texture.p, count, castable)) && texture.p); + if (!array) { + Ref refused; + CHECK(create_committed3(device, xbox.p, props, desc, D3D12_BARRIER_LAYOUT_RENDER_TARGET, + optimized, &refused.p) == E_INVALIDARG && !refused.p); + auto wrong_clear = optimized; + wrong_clear.Format = DXGI_FORMAT_D32_FLOAT; + CHECK(create_committed3(device, xbox.p, props, desc, D3D12_BARRIER_LAYOUT_COMMON, + wrong_clear, &refused.p) == E_INVALIDARG && !refused.p); + const DXGI_FORMAT incompatible = DXGI_FORMAT_R32G32_FLOAT; + CHECK(create_committed3(device, xbox.p, props, desc, D3D12_BARRIER_LAYOUT_COMMON, + optimized, &refused.p, 1, &incompatible) == E_INVALIDARG && !refused.p); + // The PC Device10 endpoint returns S_FALSE for a successful validation-only call. + CHECK(create_committed3(device, nullptr, props, desc, D3D12_BARRIER_LAYOUT_COMMON, + optimized, nullptr) == S_FALSE); + } } else { const auto heap_flags = !enhanced && !array && !depth16 ? D3D12_HEAP_FLAG_ALLOW_SHADER_ATOMICS : D3D12_HEAP_FLAG_NONE; @@ -219,7 +283,7 @@ int run(vktest::Device& vk, UINT width, UINT height, bool enhanced, Texture kind D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; view.ViewDimension = array ? D3D12_UAV_DIMENSION_TEXTURE2DARRAY : D3D12_UAV_DIMENSION_TEXTURE2D; view.Format = depth16 ? DXGI_FORMAT_R16_UINT : plane == 0 ? DXGI_FORMAT_R32_FLOAT : DXGI_FORMAT_R8_UINT; - if (array) view.Texture2DArray = {0, 1, 2, plane}; + if (array) view.Texture2DArray = {0, first_slice, 2, plane}; else view.Texture2D.PlaneSlice = plane; const D3D12_CPU_DESCRIPTOR_HANDLE handle{base + plane * step}; device->CreateUnorderedAccessView(texture.p, nullptr, &view, handle); @@ -231,7 +295,7 @@ int run(vktest::Device& vk, UINT width, UINT height, bool enhanced, Texture kind srv.Format = depth16 ? DXGI_FORMAT_R16_UNORM : DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS; srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; srv.ViewDimension = array ? D3D12_SRV_DIMENSION_TEXTURE2DARRAY : D3D12_SRV_DIMENSION_TEXTURE2D; - if (array) srv.Texture2DArray = {0, 1, 1, 2, 0, 0.0f}; + if (array) srv.Texture2DArray = {0, 1, first_slice, 2, 0, 0.0f}; else srv.Texture2D.MipLevels = 1; const D3D12_CPU_DESCRIPTOR_HANDLE sampled{base + 2 * step}; device->CreateShaderResourceView(texture.p, &srv, sampled); @@ -245,7 +309,7 @@ int run(vktest::Device& vk, UINT width, UINT height, bool enhanced, Texture kind std::memset(reinterpret_cast(invalid.ptr), 0x55, sizeof(zero)); D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; view.ViewDimension = array ? D3D12_UAV_DIMENSION_TEXTURE2DARRAY : D3D12_UAV_DIMENSION_TEXTURE2D; - if (array) view.Texture2DArray = {0, 1, 2, plane}; + if (array) view.Texture2DArray = {0, first_slice, 2, plane}; else view.Texture2D.PlaneSlice = plane; view.Format = plane == 0 ? DXGI_FORMAT_R8_UINT : DXGI_FORMAT_R32_FLOAT; device->CreateUnorderedAccessView(texture.p, nullptr, &view, invalid); @@ -315,11 +379,19 @@ int run(vktest::Device& vk, UINT width, UINT height, bool enhanced, Texture kind const float depth_seed[] = {0.5f, 0.25f, 1.0f}; const UINT8 stencil_seed[] = {0x5a, 0x37, 0xcb}; - const UINT16 d16_seed[] = {0, 0xffff, 257}; + const UINT16 d16_seed[] = {0, 0xffff, 257, 514, 771, 1028}; const auto flags = depth16 ? D3D12_CLEAR_FLAG_DEPTH : D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL; + if (modern) { + Ref list; + CHECK(SUCCEEDED(graphics.list->QueryInterface(IID_PPV_ARGS(&list.p)))); + enhanced_transition(list.p, texture.p, D3D12_BARRIER_SYNC_ALL, + D3D12_BARRIER_ACCESS_COMMON, D3D12_BARRIER_LAYOUT_COMMON, D3D12_BARRIER_SYNC_DEPTH_STENCIL, + D3D12_BARRIER_ACCESS_DEPTH_STENCIL_WRITE, D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE); + } for (UINT layer = 0; layer < layers; ++layer) graphics.list->ClearDepthStencilView({depth_handle.ptr + dsv_step * layer}, flags, - depth16 ? float(d16_seed[layer]) / 65535.0f : depth_seed[layer], stencil_seed[layer], 0, nullptr); + depth16 ? float(d16_seed[layer]) / 65535.0f : depth_seed[layer], depth16 ? 0 : stencil_seed[layer], + 0, nullptr); const bool compute_copy = handoff == Handoff::compute_transitions; // Graphics-side transfers use ordinary cross-queue UAV layout. With maintenance10 the compute family can @@ -410,19 +482,19 @@ int run(vktest::Device& vk, UINT width, UINT height, bool enhanced, Texture kind const UINT bytes = plane ? 1 : depth16 ? 2 : 4; for (UINT y = 0; y < height; ++y) { for (UINT x = 0; x < width; ++x) { - const bool in_view = !array || layer >= 1; + const bool in_view = layer >= first_slice; const bool cleared = in_view && (plane ? x == 3 && y == 2 : x == 1 && y == 3); UINT32 expected = 0; if (depth16) { expected = cleared ? d16_clear[0] : d16_seed[layer]; - if (layer == (array ? 2u : 0u) && x == 2 && y == 1) expected ^= 0x1357u; + if (layer == layers - 1u && x == 2 && y == 1) expected ^= 0x1357u; } else if (plane == 0) { float depth = cleared ? depth_clear[0] : depth_seed[layer]; - if (layer == (array ? 1u : 0u) && x == 2 && y == 1) depth *= 0.25f; + if (layer == first_slice && x == 2 && y == 1) depth *= 0.25f; std::memcpy(&expected, &depth, sizeof(depth)); } else { expected = cleared ? stencil_clear[0] : stencil_seed[layer]; - if (layer == (array ? 2u : 0u) && x == 5 && y == 3) expected ^= 0xffu; + if (layer == layers - 1u && x == 5 && y == 3) expected ^= 0xffu; } UINT32 actual = 0; std::memcpy(&actual, mapped + layouts[sub].Offset + y * layouts[sub].Footprint.RowPitch + x * bytes, bytes); @@ -435,8 +507,10 @@ int run(vktest::Device& vk, UINT width, UINT height, bool enhanced, Texture kind } } readback->Unmap(0, nullptr); - std::printf("slot %u, %ux%u, %u layers, %u planes, %s barriers, graphics family %u, shader family %u, " - "plane transfers on %s: every pixel matched\n", placed ? 133u : 76u, width, height, layers, planes, + const char* path = placed ? "slot 133" : "slot 76"; + if (modern) path = rt::d3d12_xs::device_slot_overridden(127) ? "slot 127" : "CreateCommittedResource3"; + std::printf("%s, %ux%u, %u layers, %u planes, %s barriers, graphics family %u, shader family %u, " + "plane transfers on %s: every pixel matched\n", path, width, height, UINT(layers), planes, enhanced ? "enhanced" : "legacy", vk.family, handoff == Handoff::direct ? vk.family : vk.compute_family, compute_copy ? "compute" : "graphics"); return 0; @@ -455,19 +529,24 @@ int main() { return 77; } const auto d32s8 = DXGI_FORMAT_R32G8X24_TYPELESS, d16 = DXGI_FORMAT_R16_TYPELESS; - if (run(vk, 9, 7, false, Texture::committed, d32s8, Handoff::direct) || - run(vk, 2560, 1440, true, Texture::committed, d32s8, Handoff::direct) || - run(vk, 9, 7, true, Texture::placed, d16, Handoff::graphics_transitions)) return 1; + if (run(vk, 9, 7, false, Texture::committed, 1, d32s8, Handoff::direct) || + run(vk, 2560, 1440, true, Texture::committed, 1, d32s8, Handoff::direct) || + run(vk, 9, 7, true, Texture::placed, 1, d16, Handoff::graphics_transitions)) return 1; for (const auto format : {d32s8, d16}) { - if (run(vk, 9, 7, false, Texture::committed_array, format, Handoff::graphics_transitions) || - run(vk, 13, 9, true, Texture::placed_array, format, Handoff::graphics_transitions)) return 1; + if (run(vk, 9, 7, false, Texture::committed, 3, format, Handoff::graphics_transitions) || + run(vk, 13, 9, true, Texture::placed, 3, format, Handoff::graphics_transitions)) return 1; const auto vk_format = format == d16 ? VK_FORMAT_D16_UNORM : VK_FORMAT_D32_SFLOAT_S8_UINT; if (compute_transfers(vk, vk_format, format != d16)) { - if (run(vk, 9, 7, true, Texture::placed_array, format, Handoff::compute_transitions)) return 1; + if (run(vk, 9, 7, true, Texture::placed, 3, format, Handoff::compute_transitions)) return 1; } else { std::printf("compute-side depth transfers unavailable for VkFormat %u; graphics-side handoff tested\n", unsigned(vk_format)); } } + // Array lengths reported by the Xbox boot trace. The texels are synthetic. + constexpr UINT16 reported_layers[] = {1, 3, 6}; + for (const UINT16 layers : reported_layers) + if (run(vk, 9, 7, true, Texture::committed3, layers, d16, Handoff::graphics_transitions)) return 1; + if (run(vk, 9, 7, true, Texture::committed3, 3, d32s8, Handoff::graphics_transitions)) return 1; return vk.validation_errors() ? 1 : 0; } From 3a4ffa45048d2f385a1083ff2c6f654b5f1eac27 Mon Sep 17 00:00:00 2001 From: Mumogg <104529023+Mumogg@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:21:40 -0600 Subject: [PATCH 029/110] local: graphics stage layout experiment (s8), CB diagnostics --- runtime/shims/d3d12_com.cpp | 3 ++- runtime/shims/d3d12_com.h | 10 ++++++++++ runtime/shims/d3d12_vulkan_device.cpp | 9 +++++++++ runtime/shims/d3d12_xs_device.cpp | 12 ++++++++++++ runtime/src/vulkan_replay.h | 7 +++++++ 5 files changed, 40 insertions(+), 1 deletion(-) diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index bf51da8e09..a497827445 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -1274,7 +1274,8 @@ class GraphicsCommandList final write(state, first, std::uint32_t(va)); // In the compute layout a descriptor table is one dword, the 32-bit VA of its first descriptor (the heaps // live below 4 GiB); a root view keeps both halves. The graphics layout gives every address two dwords. - if (!(is_compute(state) && type == rt::rootsig::ParamType::Table)) write(state, first + 1, std::uint32_t(va >> 32)); + if (!((is_compute(state) || local_graphics_stage_layout()) && type == rt::rootsig::ParamType::Table)) + write(state, first + 1, std::uint32_t(va >> 32)); } D3D12_COMMAND_LIST_TYPE type_; diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index b5e99ea6df..ae62e4b111 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -10,6 +10,8 @@ // - the CPU handle of an RTV or DSV points at a leonida::TargetView in the device's descriptor heap. #pragma once +#include + #include #include #include @@ -371,6 +373,14 @@ std::unique_ptr create_window_presenter(ID3D12Device* device, H // exist, because a mesh shader (s16) and a pixel shader (s8) share one push-constant block); // - compute: rt::rootsig::pack_stage(Stage::Compute), the measured console layout (from s4, one dword per table). // A layout that refuses the signature is marked unusable; binding the signature there invalidates the list. +// LOCAL EXPERIMENT: LEONIDA_GRAPHICS_STAGE_LAYOUT=1 lays graphics root arguments out as the console does for the +// vertex, pixel and geometry stages (rt::rootsig::pack_stage: from s8, a descriptor table in one dword) instead of +// from s0 with two dwords per address. +inline bool local_graphics_stage_layout() { + static const bool on = [] { const char* v = std::getenv("LEONIDA_GRAPHICS_STAGE_LAYOUT"); return v && *v == '1'; }(); + return on; +} + struct RootArgumentLayout { struct Parameter { rt::rootsig::ParamType type; diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 0a75413d6c..788434419a 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -6710,6 +6710,14 @@ class Device final layout.flags = parsed.sig.flags; layout.graphics_ok = packed.ok; layout.compute_ok = compute.ok; + const rt::rootsig::StagePackResult local_stage = rt::rootsig::pack_stage(parsed.sig, rt::rootsig::Stage::Vertex); + const bool local_stage_layout = local_graphics_stage_layout() && local_stage.ok; + if (local_graphics_stage_layout()) { + static std::atomic said{0}; + if (said.fetch_add(1) < 3) + std::fprintf(stderr, "[rt] d3d12: local: graphics root arguments in the console stage layout (from s%u): %s\n", + local_stage.base, local_stage.ok ? "ok" : local_stage.error.c_str()); + } for (std::size_t i = 0; i < parsed.sig.params.size(); ++i) { std::uint32_t first = UINT32_MAX; for (std::uint32_t d = 0; packed.ok && d < packed.dword_count; ++d) @@ -6717,6 +6725,7 @@ class Device final first = d; break; } + if (local_stage_layout) first = local_stage.first_sgpr[i]; layout.parameters.push_back({parsed.sig.params[i].type, first, parsed.sig.params[i].num_values, compute.ok ? compute.first_sgpr[i] : rt::rootsig::kNoSgpr, table_view_descriptors(parsed.sig.params[i])}); diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 2d00e00c9b..56b2863386 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -24,6 +24,7 @@ // 78 SetFrameIntervalX, 79 ScheduleFrameEventX and 80 WaitFrameEventX. The slots can be moved with LEONIDA_XS_*_SLOT // for a trace that disagrees. The frame-event calls answer from a per-device token counter: there is no vblank source // behind the device before a presenter exists, so WaitFrameEventX returns at once with a fresh non-zero token. +#include "../src/vulkan_replay.h" #include "title_window.h" #include "d3d12_xs_device.h" #include "d3d12_trace.h" @@ -2750,6 +2751,8 @@ HRESULT proxy_create_descriptor_heap(DeviceProxy* self, const D3D12_DESCRIPTOR_H void proxy_create_cbv(DeviceProxy* self, const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE dest) { note_slot(17); + if (desc && desc->SizeInBytes == 96 && desc->BufferLocation < 0x100000000ull) + leonida::g_local_last_cb96.store(desc->BufferLocation); { // LOCAL DIAGNOSTIC static std::atomic said{0}; const int n = said.fetch_add(1); @@ -2758,6 +2761,15 @@ void proxy_create_cbv(DeviceProxy* self, const D3D12_CONSTANT_BUFFER_VIEW_DESC* std::fprintf(stderr, "[rt] localdbg: CreateCBV #%d dest=0x%llx -> 0x%llx location=0x%llx size=%u\n", n, static_cast(dest.ptr), static_cast(t.ptr), desc ? static_cast(desc->BufferLocation) : 0ull, desc ? desc->SizeInBytes : 0u); + MEMORY_BASIC_INFORMATION q{}; + if (desc && desc->BufferLocation && desc->BufferLocation < 0x100000000ull && + VirtualQuery(reinterpret_cast(desc->BufferLocation), &q, sizeof(q)) && q.State == MEM_COMMIT && + !(q.Protect & (PAGE_NOACCESS | PAGE_GUARD))) { + const float* f = reinterpret_cast(desc->BufferLocation); + std::fprintf(stderr, "[rt] localdbg: constants now:"); + for (int w = 0; w < 24 && w * 4u < desc->SizeInBytes; ++w) std::fprintf(stderr, " %g", f[w]); + std::fprintf(stderr, "\n"); + } } } self->real->CreateConstantBufferView(desc, translate_cpu_handle(self, dest)); diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index c4dac14349..285159c602 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -812,6 +812,7 @@ enum class ReplayResult { // LOCAL DIAGNOSTIC: the arena's host mapping and size, for dumps of what a shader would read. inline std::uint8_t* g_local_arena_mapped = nullptr; inline std::uint64_t g_local_arena_size = 0; +inline std::atomic g_local_last_cb96{0}; // title address of the last 96-byte constant view created // LOCAL DIAGNOSTIC: which check returned unresolved_resource (first 3 times per source line). inline ReplayResult local_unresolved_at(int line) { @@ -2266,6 +2267,12 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct std::fprintf(stderr, "[rt] localdbg: title table guess is not readable title memory\n"); } } + if (const std::uint64_t cb = g_local_last_cb96.load()) { + const float* f3 = reinterpret_cast(cb); + std::fprintf(stderr, "[rt] localdbg: 96-byte constants in title memory at draw time:"); + for (int w = 0; w < 24; ++w) std::fprintf(stderr, " %g", f3[w]); + std::fprintf(stderr, "\n"); + } { // what sits just before the vertices in the title's ring const std::uint32_t* t = reinterpret_cast(view.va - 0x60); for (int e = 0; e < 3; ++e) { From 902d594127bd7355ebe9fb0aad84dcca5acd4dd7 Mon Sep 17 00:00:00 2001 From: Mumogg <104529023+Mumogg@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:00:51 -0600 Subject: [PATCH 030/110] local: slot 70 title views, rect fourth corner v1+v3-v2, diagnostics --- runtime/shims/d3d12_xs_device.cpp | 33 +++++++++++++++++++++++++++++++ runtime/src/rect_list_geometry.h | 18 ++++++++++++++--- runtime/src/vulkan_replay.h | 9 +++++---- 3 files changed, 53 insertions(+), 7 deletions(-) diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 56b2863386..99d70e4085 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -2533,6 +2533,18 @@ void proxy_create_srv_from_raw_x(DeviceProxy* self, std::uint64_t texture_words, note_slot(70); log_xbox_route_once(70, "CreateShaderResourceView from raw words", texture_words, view_desc, destination, 0, 0); if (!destination) return; + // LOCAL: whatever this call writes to the real slot is stored at the title's address too when it returns. + struct LocalWriteThrough { + DeviceProxy* self; + std::uint64_t custom; + ~LocalWriteThrough() { local_write_through(self, D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(custom)}, 1); } + } local_write_back{self, destination}; + { + static std::atomic calls{0}; + const int n = calls.fetch_add(1); + if (n < 4 || n % 5000 == 0) + std::fprintf(stderr, "[rt] localdbg: slot 70 call #%d dest=0x%llx\n", n, static_cast(destination)); + } // The console hands a CPU descriptor handle in the title's heap memory; #7021 translates it to the real heap's. destination = translate_cpu_handle(self, D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(destination)}).ptr; @@ -2547,7 +2559,28 @@ void proxy_create_srv_from_raw_x(DeviceProxy* self, std::uint64_t texture_words, ID3D12Resource* resource = self->resource_provider(self->real, shape.va, shape.resource.Width, &start, &size); if (!resource || shape.va < start || shape.va - start >= size) { if (resource) resource->Release(); + // LOCAL: a small raw view over the title's own memory becomes a raw buffer V# through the constant-view path, + // which resolves a title address to its GPU copy (#9137). LEONIDA_SLOT70_TITLE=0 keeps the null view. + static const bool title_views = [] { const char* v = std::getenv("LEONIDA_SLOT70_TITLE"); return !(v && *v == '0'); }(); + if (title_views && shape.va && shape.va < 0x100000000ull && shape.resource.Width && shape.resource.Width <= 65536) { + D3D12_CONSTANT_BUFFER_VIEW_DESC constants{}; + constants.BufferLocation = shape.va; + constants.SizeInBytes = static_cast(shape.resource.Width); + self->real->CreateConstantBufferView(&constants, D3D12_CPU_DESCRIPTOR_HANDLE{destination}); + static std::atomic said{false}; + if (!said.exchange(true)) + std::fprintf(stderr, "[rt] d3d12_xs: local: slot 70 view over title memory (%llu bytes) written as a raw " + "buffer V# on its GPU copy\n", static_cast(shape.resource.Width)); + return; + } log_slot70_null_once("no buffer holds the address", texture_words, view_desc); + { + static std::atomic nulls{0}; + const int n = nulls.fetch_add(1); + if (n < 3 || n % 5000 == 0) + std::fprintf(stderr, "[rt] localdbg: slot 70 null #%d: no buffer holds va=0x%llx width=%llu\n", n, + static_cast(shape.va), static_cast(shape.resource.Width)); + } write_null_srv(self, destination); return; } diff --git a/runtime/src/rect_list_geometry.h b/runtime/src/rect_list_geometry.h index 15d7368d34..1300c041ec 100644 --- a/runtime/src/rect_list_geometry.h +++ b/runtime/src/rect_list_geometry.h @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -168,15 +169,26 @@ inline std::vector rect_list_geometry(const std::vector(g_local_arena_mapped + draw.user_data[0]); + const std::uint32_t local_table = draw.user_data[0] ? draw.user_data[0] : draw.user_data[8]; + if (g_local_arena_mapped && local_table && local_table + 256ull <= g_local_arena_size) { + const std::uint32_t* t = reinterpret_cast(g_local_arena_mapped + local_table); for (int e = 0; e < 4; ++e) { std::fprintf(stderr, "[rt] localdbg: table[%d]:", e); for (int w = 0; w < 8; ++w) std::fprintf(stderr, " %08x", t[e * 8 + w]); std::fprintf(stderr, "\n"); const std::uint64_t va = (std::uint64_t(t[e * 8 + 1] & 0xffff) << 32) | t[e * 8]; - if (va && va + 64 <= g_local_arena_size) { + if (va && va + 128 <= g_local_arena_size) { const float* f2 = reinterpret_cast(g_local_arena_mapped + va); std::fprintf(stderr, "[rt] localdbg: at va 0x%llx:", static_cast(va)); - for (int w = 0; w < 16; ++w) std::fprintf(stderr, " %g", f2[w]); + for (int w = 0; w < 32; ++w) std::fprintf(stderr, " %g", f2[w]); std::fprintf(stderr, "\n"); } } From 1d5f9b0807e2a9e0947a5cee0ba4af08a7c2add1 Mon Sep 17 00:00:00 2001 From: channa317 <183341518+channa317@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:11:26 +0800 Subject: [PATCH 031/110] Preserve generic placed resource handling with a committed-only depth provider (D3D-991) --- runtime/shims/d3d12_xs_device.cpp | 6 +++--- runtime/test/xs_proxy_mock_test.cpp | 15 ++++++++++++++- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 7139ba2776..82395353a7 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -1759,7 +1759,6 @@ HRESULT create_depth_uav_backing(DeviceProxy* self, const D3D12_HEAP_PROPERTIES* HRESULT proxy_create_placed_depth(DeviceProxy* self, UINT64 address, const D3D12_RESOURCE_DESC& desc, std::uint32_t layout, const D3D12_CLEAR_VALUE* clear, REFIID riid, void** out) { - if (!self->validate_depth_placement) return E_NOTIMPL; const auto native = depth_image_desc(desc); if (!self->validate_depth_placement(native, layout, clear)) return E_INVALIDARG; const auto alloc = self->real->GetResourceAllocationInfo(0, 1, &native); @@ -1820,9 +1819,10 @@ HRESULT proxy_create_placed_resource_x(DeviceProxy* self, void* va, const D3D12_ if (out) *out = nullptr; // An unhandled slot past the PC vtable is refused before inspecting any of its arguments. const PlacedAtVaHandler handler = g_placed_at_va.load(std::memory_order_acquire); - if (!handler && !self->validate_depth_placement) return E_NOTIMPL; + const bool can_place_depth = self->depth_stencil_uav_provider && self->validate_depth_placement; + if (!handler && !can_place_depth) return E_NOTIMPL; if (!out || !xbox_desc || !riid) return E_POINTER; - if (supports_depth_uav(self, *xbox_desc)) + if (can_place_depth && depth_uav_description(*xbox_desc)) return proxy_create_placed_depth(self, reinterpret_cast(va), *xbox_desc, layout, clear, *riid, out); if (!handler) return E_NOTIMPL; // An integer mask: a D3D12_RESOURCE_FLAGS constant past the SDK's last enumerator is not a constant expression diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 6af7ad8046..c9f48da4a0 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -434,7 +434,6 @@ int check_levels() { void* const va = reinterpret_cast(0x7f0000000000ull); const HRESULT r133 = hr_of(raw(device, 133, word(va), word(&xbox_desc), 0xFFFFFFFFull, 0, word(&resource_iid), word(&placed))); - xs::set_placed_at_va_handler(nullptr); EXPECT(r133 == S_OK && placed == reinterpret_cast(0x1330)); EXPECT(seen_real == xs::device_proxy_real_device(device) && seen_va == va); EXPECT(static_cast(seen_desc.Flags) == 0x4); @@ -442,6 +441,20 @@ int check_levels() { EXPECT(std::memcmp(&seen_iid, &resource_iid, sizeof(GUID)) == 0); EXPECT(seen_layout == 0xFFFFFFFFu); // the title's third word, passed through as the barrier layout EXPECT(xs::device_slot_overridden(133)); + + // A committed depth provider without a placement validator leaves slot 133 to the generic handler. + EXPECT(xs::set_depth_stencil_uav_provider(device, [](ID3D12Resource*, D3D12_HEAP_FLAGS) -> HRESULT { + return E_UNEXPECTED; + })); + xbox_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + xbox_desc.Format = DXGI_FORMAT_R16_TYPELESS; + xbox_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + placed = nullptr; + EXPECT(hr_of(raw(device, 133, word(va), word(&xbox_desc), 3, 0, word(&resource_iid), word(&placed))) == S_OK); + EXPECT(placed == reinterpret_cast(0x1330) && seen_layout == 3 && seen_desc.Flags == xbox_desc.Flags); + xs::set_placed_at_va_handler(nullptr); + EXPECT(hr_of(raw(device, 133)) == E_NOTIMPL); + EXPECT(xs::set_depth_stencil_uav_provider(device, nullptr)); } // 133 with a pages hook (set_placed_at_va_pages_hook): a buffer's range [va, va + width) is handed to it From 4e4970956afa8f19d11f1c3c92a8f203baf04a87 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Mon, 23 Nov 2026 23:35:37 +0100 Subject: [PATCH 032/110] fix: shader_disasm prints the v_dot4_i32_i8 op_sel 2 / op_sel_hi 5 words llvm-mc rejects, so the FSR4 FSPX programs translate The FidelityFX upscaler programs hold 89 such words in 8 programs (docs/fspx.md); the translator already models the form but the listing could not carry it, so the programs were refused as a fall-through into undecodable words. --- docs/fspx.md | 9 + tests/semantic/test_alu_dot4_i8.py | 4 +- .../semantic/test_fspx_dot4_op_sel_disasm.py | 157 ++++++++++++++++++ tools/shader_disasm.py | 84 +++++++++- 4 files changed, 248 insertions(+), 6 deletions(-) create mode 100644 tests/semantic/test_fspx_dot4_op_sel_disasm.py diff --git a/docs/fspx.md b/docs/fspx.md index 7550a2cc8c..957fa3c49c 100644 --- a/docs/fspx.md +++ b/docs/fspx.md @@ -149,6 +149,15 @@ program whose kind 0 is too short for word 4 keeps the code heuristic. `op_sel` 2 and `op_sel_hi` 5 the result is the dot product with the two 16-bit halves of the second source exchanged, in all 5 operand sets (4 of them give another word under the plain rule). So `op_sel` selects halves here as it does for the packed 16-bit ops. The words are in `tests/semantic/test_alu_dot4_i8.py`. + - `tools/shader_disasm.py` (so `fspx_unpack.py --disasm` and `make_game.py`) prints such a word as + `v_dot4_i32_i8 vD, a, b, c op_sel:[0,1,0] op_sel_hi:[1,0,1]` with its real encoding. A dword pair that llvm-mc + rejected, with exactly opcode 0x16, `op_sel` 2, `op_sel_hi` 5, no `clamp` and no `neg`, is decoded with the two + fields at their defaults and then given the fields and the encoding back, so the translator reads it and its + encoding check against the blob passes. Any other `op_sel`/`op_sel_hi` value, `clamp` or `neg` is still + undecodable (only this one was measured). A pair llvm-mc accepted, such as a literal followed by an instruction, + is never touched. `tests/semantic/test_fspx_dot4_op_sel_disasm.py` checks it with llvm-mc (the 5 measured + operand sets, and the forms that stay refused); the 89 words of the real programs are not re-run here, because + that needs the package's DLL. ## Kind 7: records diff --git a/tests/semantic/test_alu_dot4_i8.py b/tests/semantic/test_alu_dot4_i8.py index 23c73bdaa0..ffefcbbd48 100644 --- a/tests/semantic/test_alu_dot4_i8.py +++ b/tests/semantic/test_alu_dot4_i8.py @@ -15,8 +15,8 @@ op_sel 2 and op_sel_hi 5, which llvm-mc does not decode (docs/fspx.md). Run on the same hardware as two raw words (0xCC165008 0x0C0E0501: v8 = v1 . v2 + v3 with those fields), that form gave the words of MEASURED_OP_SEL: the dot product with the two 16-bit halves of the second source exchanged, as op_sel selects halves for the packed 16-bit -ops. `ref_op_sel` reproduces them; the translator refuses any op_sel on these two instructions until a listing can -carry it. +ops. `ref_op_sel` reproduces them. A listing carries the form since tools/shader_disasm.py prints it +(tests/semantic/test_fspx_dot4_op_sel_disasm.py). neg_lo and neg_hi. llvm-mc accepts them on v_dot4_i32_i8 for gfx1036 (not on v_dot4c_i32_i8), and the hardware does not ignore them: on the same GPU, 5 operand sets with 8 forms each gave the words of `ref_neg`, 9 of which are in diff --git a/tests/semantic/test_fspx_dot4_op_sel_disasm.py b/tests/semantic/test_fspx_dot4_op_sel_disasm.py new file mode 100644 index 0000000000..7ff52527f4 --- /dev/null +++ b/tests/semantic/test_fspx_dot4_op_sel_disasm.py @@ -0,0 +1,157 @@ +"""The FidelityFX upscaler's programs (docs/fspx.md) hold 89 v_dot4_i32_i8 words with op_sel 2 and op_sel_hi 5, which +llvm-mc does not decode: it rejects the first dword, reads the second as another instruction, and the translator then +refuses the program ("fall-through into undecodable words"), so 9 of the 29 programs had no pipeline and the DLL's +next pipeline call faulted. tools/shader_disasm.py now prints such a word as the instruction it is, with its +op_sel/op_sel_hi fields and its real encoding, so the translator reads it and checks it against the blob. + +Each case assembles a small program with llvm-mc, turns one v_dot4_i32_i8 into the op_sel 2 / op_sel_hi 5 form by +setting those fields in its two dwords, disassembles the bytes with shader_disasm, and translates the listing in the +FSPX layout (disasm/, fspx/.code and .json). The expected words are the ones measured on gfx1036 +(MEASURED_OP_SEL in test_alu_dot4_i8.py). They need llvm-mc with the AMDGPU target (LLVM_MC, or llvm-mc on PATH) and +skip without it. No GPU and no game files. + + python -I tests/semantic/test_fspx_dot4_op_sel_disasm.py +""" +import json +import os +import struct +import subprocess +import sys +import tempfile +import unittest +import warnings + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +sys.dont_write_bytecode = True +sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) +sys.path.insert(0, HERE) + +import rdna2spirv # noqa: E402 +import shader_disasm # noqa: E402 +import spirv_mini_interp as si # noqa: E402 +from test_alu_dot4_i8 import MEASURED_OP_SEL, ref # noqa: E402 + +MCPU = "gfx1030" # fspx_unpack.py's default: LLVM decodes v_dot4_i32_i8 for it and not for gfx1013 +STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> 2) << 14 + w1 = w1 & ~(3 << 27) | (op_sel_hi & 3) << 27 + return struct.pack("<2I", w0, w1) + + +def program(a, b, addend, middle): + """Code bytes of: v8 = the v_dot4_i32_i8 given by `middle` (its two dwords), v9 = the plain v_dot4_i32_i8 on the + same registers, both written to mrt0. Returns (code, byte offset of the first dot4).""" + head = b"".join(assemble(line) for line in ( + f"v_mov_b32_e32 v1, 0x{a:08x}", f"v_mov_b32_e32 v2, 0x{b:08x}", f"v_mov_b32_e32 v3, 0x{addend:08x}")) + tail = b"".join(assemble(line) for line in ( + "v_dot4_i32_i8 v9, v1, v2, v3", "exp mrt0 v8, v9, v8, v9 done vm", "s_endpgm")) + return head + middle + tail, len(head) + + +def translate_fspx(name, listing, code): + """SPIR-V assembly for a listing in the FSPX layout, with the code bytes it was disassembled from beside it.""" + with tempfile.TemporaryDirectory() as tmp: + for d in ("disasm", "fspx"): + os.mkdir(os.path.join(tmp, d)) + with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: + f.write(STUB_DXBC) + with open(os.path.join(tmp, "fspx", name + ".code"), "wb") as f: + f.write(code) + with open(os.path.join(tmp, "fspx", name + ".json"), "w", encoding="utf-8") as f: + json.dump({}, f) + src = os.path.join(tmp, "disasm", name + ".s") + with open(src, "w", encoding="utf-8", newline="\n") as f: + f.write(listing) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ResourceWarning) + return rdna2spirv.translate(src) + + +def listing_of(name, code): + asm, bad, err = shader_disasm.disasm(code, MCPU) + return f"; {name} code 0x0..0x{len(code):x} (fspx), {MCPU}, {bad} invalid words\n" + asm, bad + + +@unittest.skipUnless(llvm_decodes_v_dot4(), "needs llvm-mc with the AMDGPU target that decodes v_dot4_i32_i8") +class Dot4OpSelListing(unittest.TestCase): + def plain_pair(self): + return assemble("v_dot4_i32_i8 v8, v1, v2, v3") + + def test_the_listing_carries_the_op_sel_word_and_the_program_runs(self): + for a, b, addend, measured in MEASURED_OP_SEL: + with self.subTest(a=f"{a:#010x}", b=f"{b:#010x}", addend=f"{addend:#010x}"): + middle = with_op_sel(self.plain_pair(), 2, 5) + code, at = program(a, b, addend, middle) + listing, bad = listing_of("ps_fspx_dot4_op_sel", code) + self.assertEqual(bad, 0, listing) + lines = [ln for ln in listing.splitlines() if "v_dot4_i32_i8" in ln] + self.assertEqual(len(lines), 2, listing) + self.assertIn("v_dot4_i32_i8 v8, v1, v2, v3 op_sel:[0,1,0] op_sel_hi:[1,0,1]", lines[0]) + self.assertIn("encoding: [" + ",".join(f"0x{x:02x}" for x in middle) + "]", lines[0]) + self.assertNotIn("op_sel", lines[1]) # the plain instruction next to it stays plain + words = support_words(translate_fspx("ps_fspx_dot4_op_sel", listing, code)) + self.assertEqual(words, [measured, ref(a, b, addend), measured, ref(a, b, addend)]) + + def test_other_op_sel_values_stay_undecodable(self): + # Only op_sel 2 / op_sel_hi 5 was measured on hardware; anything else is still rejected, never guessed. + for op_sel, op_sel_hi in ((1, 5), (4, 5), (2, 7), (0, 5), (2, 4)): + with self.subTest(op_sel=op_sel, op_sel_hi=op_sel_hi): + code, _ = program(1, 1, 0, with_op_sel(self.plain_pair(), op_sel, op_sel_hi)) + listing, bad = listing_of("ps_fspx_dot4_other", code) + self.assertNotIn("op_sel:[0,1,0] op_sel_hi:[1,0,1]", listing) + with self.assertRaises(rdna2spirv.Unsupported): # undecodable, or printed without a dropped field + translate_fspx("ps_fspx_dot4_other", listing, code) + + def test_a_clamp_or_neg_bit_on_the_word_stays_undecodable(self): + for name, shift, dword in (("clamp", 15, 0), ("neg_hi", 8, 0), ("neg_lo", 29, 1)): + with self.subTest(field=name): + middle = list(struct.unpack("<2I", with_op_sel(self.plain_pair(), 2, 5))) + middle[dword] |= 1 << shift + code, _ = program(1, 1, 0, struct.pack("<2I", *middle)) + listing, bad = listing_of("ps_fspx_dot4_mods", code) + self.assertGreaterEqual(bad, 1) + self.assertNotIn("op_sel:[0,1,0]", listing) + + def test_data_that_looks_like_the_word_is_left_alone(self): + # The same two dwords as a 32-bit literal and the instruction after it decode with no invalid word, so they + # are not touched: only a word llvm-mc rejected is read as v_dot4_i32_i8. + pair = struct.unpack("<2I", with_op_sel(self.plain_pair(), 2, 5)) + code = (assemble("v_mov_b32_e32 v4, 0x%08x" % pair[0]) + assemble("v_fmac_legacy_f32 v7, v1, v2") + + assemble("s_endpgm")) + self.assertEqual(struct.unpack_from("<2I", code, 4), pair) + listing, bad = listing_of("ps_fspx_dot4_literal", code) + self.assertEqual(bad, 0, listing) + self.assertNotIn("op_sel", listing) + + +def support_words(spv): + out = si.run_fragment(spv) + return list(out["%out_mrt0"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/shader_disasm.py b/tools/shader_disasm.py index 373d36f144..682e867d39 100644 --- a/tools/shader_disasm.py +++ b/tools/shader_disasm.py @@ -13,6 +13,7 @@ """ import argparse import os +import re import struct import subprocess import sys @@ -28,6 +29,7 @@ TRIPLE = "amdgcn--amdpal" ENDPGM = b"\x00\x00\x81\xbf" +DOT4_I8_OPCODE = 0x16 # VOP3P v_dot4_i32_i8 PROBE = "0x00 0x00 0x81 0xbf" # s_endpgm: the one instruction every shader ends with FAILED = [] # (path, first stderr line) for shaders that produced no disassembly @@ -90,10 +92,8 @@ def probe(mcpu: str) -> None: f" LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc") -def disasm(code: bytes, mcpu: str, backend: str = "llvm-mc", wave32: bool = True): - if backend == "python": - asm, bad = rdna2_decode.disasm_bytes(code, mcpu=mcpu, wave32=wave32) - return asm, bad, "" +def run_mc(code: bytes, mcpu: str): + """One llvm-mc pass over `code`: (listing, invalid word count, stderr), or ("", count, reason) when it failed.""" text = " ".join(f"0x{b:02x}" for b in code) try: p = subprocess.run(MC + ["--disassemble", f"-triple={TRIPLE}", f"-mcpu={mcpu}", "-show-encoding"], @@ -107,6 +107,82 @@ def disasm(code: bytes, mcpu: str, backend: str = "llvm-mc", wave32: bool = True return p.stdout, bad, p.stderr +ENCODING = re.compile(r"; encoding: \[([^\]]*)\]") +INVALID_AT = re.compile(r":1:(\d+): warning: invalid instruction encoding") + + +def invalid_offsets(err: str) -> set: + """Byte offsets llvm-mc rejected: its warning names the column of the word in the one line of 5-character + "0xNN " tokens it was given.""" + return {(int(col) - 1) // 5 for col in INVALID_AT.findall(err)} + + +def dot4_op_sel_words(code: bytes, offsets) -> dict: + """{offset: (word0, word1)} of the dword pairs at `offsets` that are v_dot4_i32_i8 with op_sel 2 and op_sel_hi 5, + no clamp and no neg: the form 89 words of the FidelityFX upscaler's programs take (docs/fspx.md). llvm-mc has no + decoding for it, and a plain v_dot4_i32_i8 has op_sel 0 and op_sel_hi 7. Only this combination is recognised: + its result was measured on hardware (tests/semantic/test_alu_dot4_i8.py), the other op_sel values were not.""" + found = {} + for at in sorted(offsets): + if at % 4 or at + 8 > len(code): + continue + w0, w1 = struct.unpack_from("<2I", code, at) + if (w0 >> 23 == 0x198 and (w0 >> 16) & 0x7F == DOT4_I8_OPCODE and (w0 >> 8) & 7 == 0 # VOP3P, neg_hi + and (w0 >> 11) & 7 == 2 and (w0 >> 14) & 1 == 1 and (w0 >> 15) & 1 == 0 # op_sel, hi[2], clamp + and (w1 >> 27) & 3 == 1 and (w1 >> 29) & 7 == 0): # op_sel_hi[1:0], neg_lo + found[at] = (w0, w1) + return found + + +def with_dot4_op_sel(code: bytes, mcpu: str, bad: int, err: str): + """The listing of `code` with each rejected v_dot4_i32_i8 op_sel 2 / op_sel_hi 5 word printed as the instruction + it is, or None when there is none. llvm-mc rejects the pair, so it is decoded with the two fields at their + defaults (op_sel 0, op_sel_hi 7), and each such line gets the real fields and the real encoding back: the + translator then reads the instruction and checks its encoding against the blob. A word that is not printed as + v_dot4_i32_i8 at an instruction boundary was not an instruction (it sits in a literal or in data), so it is + left as it was and the pass runs again without it.""" + words = dot4_op_sel_words(code, invalid_offsets(err)) + while words and bad: + patched = bytearray(code) + for at, (w0, w1) in words.items(): + struct.pack_into("<2I", patched, at, w0 & ~(7 << 11), w1 | (2 << 27)) + asm, bad2, err2 = run_mc(bytes(patched), mcpu) + if not asm.strip(): + return None + invalid, pos, hit, lines = invalid_offsets(err2), 0, set(), [] + for line in asm.split("\n"): + enc = ENCODING.search(line) + if not enc: + lines.append(line) + continue + while pos in invalid: + pos += 4 + if pos in words and line.lstrip("\t").startswith("v_dot4_i32_i8 "): + hit.add(pos) + w0, w1 = words[pos] + original = ",".join(f"0x{b:02x}" for b in struct.pack("<2I", w0, w1)) + line = line[:enc.start()].rstrip() + " op_sel:[0,1,0] op_sel_hi:[1,0,1]" + line = f"{line:<40}; encoding: [{original}]" + lines.append(line) + pos += len(enc.group(1).split(",")) + if hit == set(words): + return "\n".join(lines), bad2, err2 + words = {at: w for at, w in words.items() if at in hit} + return None + + +def disasm(code: bytes, mcpu: str, backend: str = "llvm-mc", wave32: bool = True): + if backend == "python": + asm, bad = rdna2_decode.disasm_bytes(code, mcpu=mcpu, wave32=wave32) + return asm, bad, "" + asm, bad, err = run_mc(code, mcpu) + if bad and asm.strip(): + fixed = with_dot4_op_sel(code, mcpu, bad, err) + if fixed: + return fixed + return asm, bad, err + + MAX_DATA_DWORDS = 1 << 16 From 74bf391fdae4e5d5c81314b8abe05412807d4f69 Mon Sep 17 00:00:00 2001 From: Mumogg <104529023+Mumogg@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:46:46 -0600 Subject: [PATCH 033/110] merge follow-up: the test tree builds again - xmem.cpp: rt::xmem::commit_physical_range and commit_physical_pages exist for the run-mapped xmem too (pages are committed when allocated, so they only check the range), and main.cpp registers the slot 133 hook as main does. - vk_test_device.h: VK_EXT_external_memory_host and host_pointer_alignment are back next to the A8 render target probe; d3d12_existing_heap_test and d3d12_xmem_placed_test use them. - xs_proxy_mock_test.cpp: the stack's version, which tests the proxy that is in the tree (the automatic merge left two list mocks in one switch). - d3d12_xs_device.cpp: no include of vulkan_replay.h, which the proxy tests without Vulkan headers could not compile, and the diagnostic that needed it is gone. Every target builds with clang-cl 22.1.8 + xwin. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01HxBQf4pXH8PWpC5oZsM4bt --- runtime/shims/d3d12_xs_device.cpp | 3 - runtime/shims/xmem.cpp | 31 ++++ runtime/src/main.cpp | 3 +- runtime/test/vk_test_device.h | 13 ++ runtime/test/xs_proxy_mock_test.cpp | 253 +--------------------------- 5 files changed, 47 insertions(+), 256 deletions(-) diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 7b0953382c..09d753a86a 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -24,7 +24,6 @@ // 78 SetFrameIntervalX, 79 ScheduleFrameEventX and 80 WaitFrameEventX. The slots can be moved with LEONIDA_XS_*_SLOT // for a trace that disagrees. The frame-event calls answer from a per-device token counter: there is no vblank source // behind the device before a presenter exists, so WaitFrameEventX returns at once with a fresh non-zero token. -#include "../src/vulkan_replay.h" #include "title_window.h" #include "d3d12_xs_device.h" #include "d3d12_trace.h" @@ -2784,8 +2783,6 @@ HRESULT proxy_create_descriptor_heap(DeviceProxy* self, const D3D12_DESCRIPTOR_H void proxy_create_cbv(DeviceProxy* self, const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE dest) { note_slot(17); - if (desc && desc->SizeInBytes == 96 && desc->BufferLocation < 0x100000000ull) - leonida::g_local_last_cb96.store(desc->BufferLocation); { // LOCAL DIAGNOSTIC static std::atomic said{0}; const int n = said.fetch_add(1); diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp index e5db2ce6d2..e8988c0461 100644 --- a/runtime/shims/xmem.cpp +++ b/runtime/shims/xmem.cpp @@ -37,6 +37,7 @@ #include "shims.h" #include "startup_trace.h" #include "../src/title_va_alias.h" +#include "xmem.h" namespace { @@ -801,6 +802,36 @@ LPVOID WINAPI TitleVirtualAlloc(LPVOID address, SIZE_T size, DWORD allocation_ty } // namespace +namespace rt::xmem { + +// main's xmem commits physical pages on first touch and exposes these two for code that must see them committed +// (slot 133's import, d3d12_xmem_placed_test). Here a physical page is committed when it is allocated, so there is +// nothing to do: the range only has to be mapped, readable memory, and the page array non-null. +bool commit_physical_range(const void* address, std::size_t size) { + if (size == 0) return true; + const auto* at = static_cast(address); + const auto* const end = at + size; + while (at < end) { + MEMORY_BASIC_INFORMATION info{}; + if (!VirtualQuery(at, &info, sizeof(info)) || info.State != MEM_COMMIT) { + SetLastError(ERROR_INVALID_ADDRESS); + return false; + } + at = static_cast(info.BaseAddress) + info.RegionSize; + } + return true; +} + +bool commit_physical_pages(const std::uint64_t* page_array, std::size_t count) { + if (count && !page_array) { + SetLastError(ERROR_INVALID_PARAMETER); + return false; + } + return true; +} + +} // namespace rt::xmem + #define TITLE_VIRTUAL_ALLOC(dll) {dll, "VirtualAlloc", reinterpret_cast(&TitleVirtualAlloc)} // The classic libraries and the memory api sets a title's imports name. diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp index 7d0dbfd88a..63bd016e8a 100644 --- a/runtime/src/main.cpp +++ b/runtime/src/main.cpp @@ -177,8 +177,7 @@ int wmain(int argc, wchar_t** argv) { } rt::d3d12_trace::set_enabled(trace_d3d12); // Slot 133 imports the title's pages; xmem commits them on first touch, so they are committed first. - // MERGE NOTE: main registers rt::xmem::commit_physical_range here for its commit-on-touch xmem. This branch keeps - // the run-mapped xmem (pages are committed when allocated), so there is nothing to commit before slot 133. + rt::d3d12_xs::set_placed_at_va_pages_hook(&rt::xmem::commit_physical_range); if (int trace_error = 0; !trace_file.empty() && !rt::startup_trace::open(trace_file.c_str(), &trace_error)) { std::fprintf(stderr, trace_error == EEXIST ? "error: the trace file already exists; --trace only creates a new file\n" : "error: cannot create the trace file\n"); diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h index 391ee5d097..0aca467878 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h @@ -109,6 +109,8 @@ class Device { // VK_KHR_maintenance5 enabled, where VK_FORMAT_A8_UNORM_KHR can be sampled and blended as a colour attachment, as // gta6rt enables it (VulkanDeviceInfo::a8_render_target). bool a8_render_target = false; + // VK_EXT_external_memory_host is enabled when non-zero: its minImportedHostPointerAlignment. + VkDeviceSize host_pointer_alignment = 0; // create(true) only: VK_KHR (else EXT) swapchain_maintenance1 and its feature enabled, with the surface half on the // instance, so a vsync swapchain can switch to IMMEDIATE or FIFO_RELAXED per present. bool swapchain_maintenance1 = false; @@ -500,6 +502,16 @@ class Device { host_copy.pNext = *v13_.next(); // after the conditional rendering features, if any *v13_.next() = &host_copy; } + // VK_EXT_external_memory_host where the device has it (OpenExistingHeapFromAddress). + for (const auto& extension : extensions) { + if (std::strcmp(extension.extensionName, VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME) != 0) continue; + VkPhysicalDeviceExternalMemoryHostPropertiesEXT host_memory{ + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT}; + VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &host_memory}; + instance_fn("vkGetPhysicalDeviceProperties2")(physical, &properties); + host_pointer_alignment = host_memory.minImportedHostPointerAlignment; + } + #ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME VkPhysicalDeviceMaintenance5FeaturesKHR maintenance5{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_5_FEATURES_KHR}; @@ -592,6 +604,7 @@ class Device { #ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME if (a8_render_target) device_extensions.push_back(VK_KHR_MAINTENANCE_5_EXTENSION_NAME); #endif + if (host_pointer_alignment) device_extensions.push_back(VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME); const char* swapchain = "VK_KHR_swapchain"; if (presentation) device_extensions.push_back(swapchain); #if defined(VK_KHR_swapchain_maintenance1) diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index bd89438cfd..5592d5875f 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -90,7 +90,6 @@ struct Mock { Kind kind; long refs; int device_level; // device: highest ID3D12DeviceN it answers (0 = ID3D12Device only) - int list_level; // command_list: 0=base (60 slots), 7=GCL7 (81 slots), 8=GCL8 (82 slots) bool fence1; // fence: answers ID3D12Fence1; device: the fences it makes do bool allocator_tag; // allocator: answers kLeonidaCommandAllocatorTag; device: the allocators it makes do bool full_chain_lists; // device: CreateCommandList makes a full-chain list mock (Kind::list), else command_list @@ -205,21 +204,9 @@ bool mock_has(const Mock* m, REFIID iid) { case Kind::fence: return IsEqualIID(iid, __uuidof(ID3D12Fence)) || (m->fence1 && IsEqualIID(iid, __uuidof(ID3D12Fence1))); case Kind::resource: return IsEqualIID(iid, __uuidof(ID3D12Resource)); - case Kind::heap: return IsEqualIID(iid, __uuidof(ID3D12DescriptorHeap)); case Kind::command_list: - if (IsEqualIID(iid, __uuidof(ID3D12CommandList)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList))) return true; -#ifdef __ID3D12GraphicsCommandList7_INTERFACE_DEFINED__ - if (m->list_level >= 7 && (IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList7)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList6)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList5)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList4)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList3)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList2)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList1)))) - return true; -#endif - return false; + return IsEqualIID(iid, __uuidof(ID3D12CommandList)) || + IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList)); case Kind::allocator: return IsEqualIID(iid, __uuidof(ID3D12CommandAllocator)) || (m->allocator_tag && IsEqualIID(iid, xs::kLeonidaCommandAllocatorTag)); @@ -775,65 +762,6 @@ int check_levels() { mock->calls[68] == 0 && mock->calls[108] == 0); } - // 133 with a pages hook (set_placed_at_va_pages_hook): a buffer's range [va, va + width) is handed to it - // before the handler runs; a texture is not; a hook that fails still leaves the call to the handler. - { - static int order = 0; - static int hook_at = 0; - static int handler_at = 0; - static const void* hook_va = nullptr; - static std::size_t hook_bytes = 0; - static bool hook_result = true; - order = hook_at = handler_at = 0; - const xs::PlacedAtVaPagesHook hook = [](const void* va, std::size_t bytes) -> bool { - hook_at = ++order; - hook_va = va; - hook_bytes = bytes; - return hook_result; - }; - const xs::PlacedAtVaHandler handler = [](ID3D12Device*, void*, const D3D12_RESOURCE_DESC&, std::uint32_t, - REFIID, void** out) -> HRESULT { - handler_at = ++order; - *out = reinterpret_cast(0x1331); - return S_OK; - }; - xs::set_placed_at_va_handler(handler); - xs::set_placed_at_va_pages_hook(hook); - D3D12_RESOURCE_DESC xbox_desc{}; - xbox_desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - xbox_desc.Width = 0xadf0000; - xbox_desc.Height = xbox_desc.DepthOrArraySize = xbox_desc.MipLevels = 1; - xbox_desc.SampleDesc.Count = 1; - xbox_desc.Layout = static_cast(0x1); - const GUID resource_iid = __uuidof(ID3D12Resource); - void* placed = nullptr; - void* const va = reinterpret_cast(0x7f0000010000ull); - auto place = [&]() { - placed = nullptr; - return hr_of(raw(device, 133, word(va), word(&xbox_desc), 0xFFFFFFFFull, 0, word(&resource_iid), - word(&placed))); - }; - const HRESULT buffer_hr = place(); - EXPECT(buffer_hr == S_OK && placed == reinterpret_cast(0x1331)); - EXPECT(hook_at == 1 && handler_at == 2 && hook_va == va && hook_bytes == 0xadf0000); - - hook_result = false; - order = hook_at = handler_at = 0; - const HRESULT refused_hr = place(); - EXPECT(refused_hr == S_OK && hook_at == 1 && handler_at == 2); - hook_result = true; - - xbox_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; - xbox_desc.Width = 64; - xbox_desc.Height = 64; - order = hook_at = handler_at = 0; - const HRESULT texture_hr = place(); - EXPECT(texture_hr == S_OK && hook_at == 0 && handler_at == 1); - - xs::set_placed_at_va_pages_hook(nullptr); - xs::set_placed_at_va_handler(nullptr); - } - Mock* const queue_mock = reinterpret_cast(real_queue); Mock* const fence_mock = reinterpret_cast(real_fence); EXPECT(release(queue) == 0 && release(fence) == 0); @@ -2833,183 +2761,6 @@ static void no_dialogs() { SetErrorMode(GetErrorMode() | SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX); } -int check_console_command_list() { - // 1. Slot mapping checks - EXPECT(xs::console_to_pc_list_slot(14) == 14); // Dispatch - EXPECT(xs::console_to_pc_list_slot(26) == 26); // ResourceBarrier - EXPECT(xs::console_to_pc_list_slot(31) == 27); // ExecuteBundle - EXPECT(xs::console_to_pc_list_slot(32) == 28); // SetDescriptorHeaps - EXPECT(xs::console_to_pc_list_slot(33) == 29); // SetComputeRootSignature - EXPECT(xs::console_to_pc_list_slot(35) == 31); // SetComputeRootDescriptorTable - EXPECT(xs::console_to_pc_list_slot(60) == 58); // EndEvent - EXPECT(xs::console_to_pc_list_slot(61) == 59); // ExecuteIndirect - EXPECT(xs::console_to_pc_list_slot(85) == 16); // CopyTextureRegion - EXPECT(xs::console_to_pc_list_slot(146) == 80); // GCL7 Barrier - EXPECT(xs::console_to_pc_list_slot(148) == xs::kListNotForwarded); // AllocateUploadMemory - - Mock* mock_device = nullptr; - void* device = make_device(mock_device, 11, true); - EXPECT(device != nullptr); - - // 2. PC Slot 12 vs Xbox Slot 73 - // PC Slot 12 returns unwrapped list directly, so PC tests like tiny_frame can call slot 48 (ClearRenderTargetView) - void* pc_list = nullptr; - const IID list_iid = __uuidof(ID3D12GraphicsCommandList); - EXPECT(hr_of(raw(device, 12, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, word(&list_iid), word(&pc_list))) == S_OK); - EXPECT(pc_list != nullptr); - EXPECT(!xs::is_command_list_proxy(pc_list)); - Mock* real_pc_list = reinterpret_cast(pc_list); - EXPECT(real_pc_list->kind == Kind::command_list); - // In PC ABI, slot 48 is ClearRenderTargetView - raw(pc_list, 48, 0x1111, 0x2222, 0, 0); - EXPECT(real_pc_list->calls[48] == 1); - EXPECT(release(pc_list) == 0); - - // Xbox Slot 73 returns wrapped console command list proxy - void* allocator = nullptr; - const IID alloc_iid = __uuidof(ID3D12CommandAllocator); - EXPECT(hr_of(raw(device, 9, 0, word(&alloc_iid), word(&allocator))) == S_OK); - EXPECT(xs::is_allocator_proxy(allocator)); - Mock* real_allocator = reinterpret_cast(xs::allocator_proxy_real_allocator(allocator)); - - struct XboxCommandListDesc { - std::uint32_t type; - std::uint32_t node_mask; - std::uint64_t reserved[2]; - } desc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, {0, 0}}; - - void* list_proxy = nullptr; - EXPECT(hr_of(raw(device, 73, word(&desc), word(allocator), 0, word(&list_iid), word(&list_proxy))) == S_OK); - EXPECT(xs::is_command_list_proxy(list_proxy)); - EXPECT(xs::command_list_proxy_table_size() == 160); - - // 3. Inline cursor pinning: +0x18, +0x28, +0x30 - const auto base = reinterpret_cast(list_proxy); - std::uint64_t c18 = 0, c28 = 0, c30 = 0; - std::memcpy(&c18, reinterpret_cast(base + 0x18), sizeof(c18)); - std::memcpy(&c28, reinterpret_cast(base + 0x28), sizeof(c28)); - std::memcpy(&c30, reinterpret_cast(base + 0x30), sizeof(c30)); - const std::uint64_t expected_limit = static_cast(base + 0x18 + 0x500); - EXPECT(c18 == expected_limit); - EXPECT(c28 == expected_limit); - EXPECT(c30 == expected_limit); - - // 4. Console slot routing on ListProxy - Mock* real_list = reinterpret_cast(xs::command_list_proxy_real_list(list_proxy)); - EXPECT(real_list != nullptr && real_list->kind == Kind::command_list); - - // Console slot 32 (SetDescriptorHeaps) -> PC slot 28 - // Pass descriptor heap proxy to ensure UnwrappedArray unwrap_object works - D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 16, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; - void* heap_proxy = nullptr; - const IID heap_iid = __uuidof(ID3D12DescriptorHeap); - EXPECT(hr_of(raw(device, 14, word(&heap_desc), word(&heap_iid), word(&heap_proxy))) == S_OK); - EXPECT(heap_proxy != nullptr && xs::is_heap_proxy(heap_proxy)); - ID3D12DescriptorHeap* real_heap = xs::heap_proxy_real_heap(heap_proxy); - void* heap_ptrs[2] = {heap_proxy, real_heap}; - raw(list_proxy, 32, 2, word(heap_ptrs), 0, 0); - EXPECT(real_list->calls[28] == 1); - EXPECT(real_list->args[28][0] == 2); - // The heap proxy should have been unwrapped in the array passed to PC slot 28: - EXPECT(real_list->array[28][0] == word(real_heap)); - EXPECT(real_list->array[28][1] == word(real_heap)); - EXPECT(xs::list_slot_hits(32) == 1); - EXPECT(xs::list_slot_first_call_seen(32)); - - // Console slot 33 (SetComputeRootSignature) -> PC slot 29 - raw(list_proxy, 33, 0x5555, 0, 0, 0); - EXPECT(real_list->calls[29] == 1); - EXPECT(real_list->args[29][0] == 0x5555); - EXPECT(xs::list_slot_hits(33) == 1); - EXPECT(xs::list_slot_first_call_seen(33)); - - // Console slot 60 (EndEvent) -> PC slot 58 - raw(list_proxy, 60, 0, 0, 0, 0); - EXPECT(real_list->calls[58] == 1); - - // Console slot 61 (ExecuteIndirect) -> PC slot 59 - raw(list_proxy, 61, 0x10, 0x20, 0x30, 0x40); - EXPECT(real_list->calls[59] == 1); - EXPECT(real_list->args[59][0] == 0x10); - - // Console slot 148 (AllocateUploadMemory stub) -> returns 0 without faulting - EXPECT(raw(list_proxy, 148, 2048, 512, 0, 0) == 0); - EXPECT(xs::list_slot_hits(148) == 1); - EXPECT(xs::list_slot_first_call_seen(148)); - - // Console slot 146 (Barrier) on base 60-slot list returns E_NOTIMPL (PC slot 80 >= 60) - EXPECT(hr_of(raw(list_proxy, 146, 0, 0, 0, 0)) == E_NOTIMPL); - - // Console slot 10 (Reset) unwraps allocator proxy and re-pins inline cursor - std::uint64_t zero = 0; - std::memcpy(reinterpret_cast(base + 0x18), &zero, sizeof(zero)); - EXPECT(hr_of(raw(list_proxy, 10, word(allocator), 0, 0, 0)) == S_OK); - EXPECT(real_list->calls[10] == 1); - EXPECT(real_list->args[10][0] == word(real_allocator)); - std::memcpy(&c18, reinterpret_cast(base + 0x18), sizeof(c18)); - EXPECT(c18 == expected_limit); - - // Console slot 7 (GetDevice) returns device proxy - void* list_dev = nullptr; - const IID dev_iid = __uuidof(ID3D12Device); - const auto dev_refs_before = xs::device_proxy_ref_count(device); - EXPECT(hr_of(raw(list_proxy, 7, word(&dev_iid), word(&list_dev))) == S_OK); - EXPECT(list_dev == device); - EXPECT(xs::device_proxy_ref_count(device) == dev_refs_before + 1); - EXPECT(release(list_dev) == dev_refs_before); - - // Console slot 0 (QueryInterface) - void* list_qi = nullptr; - EXPECT(hr_of(raw(list_proxy, 0, word(&list_iid), word(&list_qi))) == S_OK); - EXPECT(list_qi == list_proxy); - EXPECT(release(list_qi) == 1); - - // 5. Queue slot 10 (ExecuteCommandLists) unwraps ListProxy in array - void* queue = nullptr; - D3D12_COMMAND_QUEUE_DESC qdesc{}; - const IID queue_iid = __uuidof(ID3D12CommandQueue); - EXPECT(hr_of(raw(device, 8, word(&qdesc), word(&queue_iid), word(&queue))) == S_OK); - EXPECT(xs::is_queue_proxy(queue)); - Mock* real_queue = reinterpret_cast(xs::queue_proxy_real_queue(queue)); - - Mock* unwrapped_list = new_mock(Kind::command_list); - void* lists_to_exec[2] = {unwrapped_list, list_proxy}; - raw(queue, 10, 2, word(lists_to_exec), 0, 0); - EXPECT(real_queue->calls[10] == 1); - EXPECT(real_queue->args[10][0] == 2); - EXPECT(real_queue->array[10][0] == word(unwrapped_list)); - EXPECT(real_queue->array[10][1] == word(real_list)); - - // 6. Test with list_level = 7 (supporting ID3D12GraphicsCommandList7, 81 slots) - mock_device->list_level = 7; - void* list7_proxy = nullptr; - EXPECT(hr_of(raw(device, 73, word(&desc), word(allocator), 0, word(&list_iid), word(&list7_proxy))) == S_OK); - EXPECT(xs::is_command_list_proxy(list7_proxy)); - Mock* real_list7 = reinterpret_cast(xs::command_list_proxy_real_list(list7_proxy)); - EXPECT(real_list7 != nullptr); - // Console slot 146 -> PC slot 80 (since 80 < 81 slots) - raw(list7_proxy, 146, 0x9999, 0, 0, 0); - EXPECT(real_list7->calls[80] == 1); - EXPECT(real_list7->args[80][0] == 0x9999); - EXPECT(release(list7_proxy) == 0 && real_list7->refs == 0); - - // Clean up - EXPECT(release(list_proxy) == 0 && real_list->refs == 0); - EXPECT(release(heap_proxy) == 0); - EXPECT(release(allocator) == 0 && real_allocator->refs == 0); - EXPECT(release(queue) == 0 && real_queue->refs == 0); - EXPECT(release(device) == 0 && mock_device->refs == 0); - - // 7. Verify stats reset - EXPECT(xs::list_slot_hits(32) > 0); - xs::reset_device_proxy_stats(); - EXPECT(xs::list_slot_hits(32) == 0); - EXPECT(!xs::list_slot_first_call_seen(32)); - - std::printf("%s: console command list routing, cursor pinning, queue unwrapping, and slot mapping passed\n", g_label); - return 0; -} - int main(int argc, char** argv) { no_dialogs(); std::setvbuf(stdout, nullptr, _IONBF, 0); From 35a925252127b61bdca2796c5d47e5e86de6ea44 Mon Sep 17 00:00:00 2001 From: Mumogg <104529023+Mumogg@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:59:52 -0600 Subject: [PATCH 034/110] rect_list_geometry: the tested fourth-corner rule is the default again; v1 + v3 - v2 is opt-in (LEONIDA_RECT_FOURTH=v1v3) d3d12_rect_list passes again. The other rule stays behind the switch as an open question: it is the one that covers the target for the retail title's full-screen rectangle draws. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01HxBQf4pXH8PWpC5oZsM4bt --- runtime/src/rect_list_geometry.h | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/runtime/src/rect_list_geometry.h b/runtime/src/rect_list_geometry.h index 1300c041ec..0049394cf4 100644 --- a/runtime/src/rect_list_geometry.h +++ b/runtime/src/rect_list_geometry.h @@ -169,9 +169,10 @@ inline std::vector rect_list_geometry(const std::vector rect_list_geometry(const std::vector Date: Mon, 23 Nov 2026 21:31:53 -0600 Subject: [PATCH 035/110] runtime: remove the local diagnostics and experiments; descriptor copies check their memory - The "[rt] localdbg:" lines and the experiment switches are gone: LEONIDA_RECT_GREEN, LEONIDA_RECT_VS, LEONIDA_RECT_NOGS, LEONIDA_RECT_NOCULL, LEONIDA_RECT_FORCE, LEONIDA_VTX_TEST and LEONIDA_DEBUG_CLEAR, with the hard-coded test shader words. vulkan_replay.h returns unresolved_resource directly again. - The descriptor write-through and the table mirror for title-backed heaps only copy between committed memory they may read and write. A handle that is only a number (xs_proxy_mock's heaps) is left alone; the test crashed there before. - A slot 70 view over memory no buffer holds becomes a raw buffer view only when the title-memory registry (title_va_alias.h) holds the whole range, instead of any address below 4 GiB. xs_proxy_mock's null-view case passes again. Still switches: LEONIDA_GRAPHICS_STAGE_LAYOUT, LEONIDA_DESC_MIRROR, LEONIDA_SLOT70_TITLE, LEONIDA_RECT_FOURTH. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01HxBQf4pXH8PWpC5oZsM4bt --- runtime/shims/d3d12_com.cpp | 11 -- runtime/shims/d3d12_vulkan_device.cpp | 108 +----------------- runtime/shims/d3d12_xs_device.cpp | 77 +++++-------- runtime/shims/xbox_present.cpp | 9 -- runtime/src/vulkan_replay.h | 157 +++++--------------------- 5 files changed, 65 insertions(+), 297 deletions(-) diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 89b87e004a..a1aa3ccc55 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -705,17 +705,6 @@ class GraphicsCommandList final d3d12_trace::record("ID3D12GraphicsCommandList::ClearRenderTargetView"); if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); if (!view.ptr || !color) return check(false); - // LOCAL DIAGNOSTIC: LEONIDA_DEBUG_CLEAR=1 clears to magenta; the first clears are logged. - static const bool magenta = [] { const char* v = std::getenv("LEONIDA_DEBUG_CLEAR"); return v && *v == '1'; }(); - const auto* target = reinterpret_cast(view.ptr); - static std::atomic shown{0}; - if (shown.fetch_add(1, std::memory_order_relaxed) < 6) - std::fprintf(stderr, "[rt] localdbg: clear resource=0x%llx colour=%g %g %g %g rects=%u\n", - static_cast(target->resource), color[0], color[1], color[2], color[3], count); - if (magenta) { - check(list_.clear_render_target(*target, {1.0f, 0.0f, 1.0f, 1.0f}, to_rects(count, rects))); - return; - } check(list_.clear_render_target(*reinterpret_cast(view.ptr), {color[0], color[1], color[2], color[3]}, to_rects(count, rects))); } diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index d82ba6f5d5..1a9f1d6e48 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -4142,18 +4142,6 @@ class PipelineState final stage.words = std::move(patched); } } - { // LOCAL EXPERIMENT: LEONIDA_RECT_GREEN=1 gives rectangle-list pipelines a solid green pixel stage, to - // tell "no fragments" from "the pixel shader writes nothing". - static const bool green = [] { const char* v = std::getenv("LEONIDA_RECT_GREEN"); return v && *v == '1'; }(); - static const bool trivial_vs = [] { const char* v = std::getenv("LEONIDA_RECT_VS"); return v && *v == '1'; }(); - if (trivial_vs && rect_list && stage.bit == VK_SHADER_STAGE_VERTEX_BIT) - stage.words = {0x7230203,0x10500,0x70000,0x1d,0x0,0x20011,0x1,0x3000e,0x0,0x1,0x7000f,0x0,0x1,0x6e69616d,0x0,0x2,0x3,0x40047,0x2,0xb,0x2a,0x40047,0x3,0xb,0x0,0x20013,0x4,0x30021,0x5,0x4,0x30016,0x6,0x20,0x40015,0x7,0x20,0x1,0x40017,0x8,0x6,0x4,0x40020,0x9,0x1,0x7,0x40020,0xa,0x3,0x8,0x4003b,0x9,0x2,0x1,0x4003b,0xa,0x3,0x3,0x4002b,0x7,0xb,0x1,0x4002b,0x7,0xc,0x2,0x4002b,0x6,0xd,0x0,0x4002b,0x6,0xe,0x3f800000,0x4002b,0x6,0xf,0x40800000,0x4002b,0x6,0x10,0xbf800000,0x50036,0x4,0x1,0x0,0x5,0x200f8,0x11,0x4003d,0x7,0x12,0x2,0x500c7,0x7,0x13,0x12,0xb,0x500c3,0x7,0x14,0x12,0xb,0x500c7,0x7,0x15,0x14,0xb,0x4006f,0x6,0x16,0x13,0x4006f,0x6,0x17,0x15,0x50085,0x6,0x18,0x16,0xf,0x50085,0x6,0x19,0x17,0xf,0x50081,0x6,0x1a,0x18,0x10,0x50081,0x6,0x1b,0x19,0x10,0x70050,0x8,0x1c,0x1a,0x1b,0xd,0xe,0x3003e,0x3,0x1c,0x100fd,0x10038}; - static const bool passthrough_vs = [] { const char* v = std::getenv("LEONIDA_RECT_VS"); return v && *v == '2'; }(); - if (passthrough_vs && rect_list && stage.bit == VK_SHADER_STAGE_VERTEX_BIT) - stage.words = {0x7230203,0x10500,0x70000,0x11,0x0,0x20011,0x1,0x3000e,0x0,0x1,0x7000f,0x0,0x1,0x6e69616d,0x0,0x2,0x3,0x40047,0x2,0x1e,0x0,0x40047,0x3,0xb,0x0,0x20013,0x4,0x30021,0x5,0x4,0x30016,0x6,0x20,0x40017,0x7,0x6,0x4,0x40020,0x8,0x1,0x7,0x40020,0x9,0x3,0x7,0x4003b,0x8,0x2,0x1,0x4003b,0x9,0x3,0x3,0x4002b,0x6,0xa,0x0,0x4002b,0x6,0xb,0x3f800000,0x50036,0x4,0x1,0x0,0x5,0x200f8,0xc,0x4003d,0x7,0xd,0x2,0x50051,0x6,0xe,0xd,0x0,0x50051,0x6,0xf,0xd,0x1,0x70050,0x7,0x10,0xe,0xf,0xa,0xb,0x3003e,0x3,0x10,0x100fd,0x10038}; - if (green && rect_list && stage.bit == VK_SHADER_STAGE_FRAGMENT_BIT) - stage.words = {0x7230203,0x10500,0x70000,0xc,0x0,0x20011,0x1,0x3000e,0x0,0x1,0x6000f,0x4,0x1,0x6e69616d,0x0,0x2,0x30010,0x1,0x7,0x40047,0x2,0x1e,0x0,0x20013,0x3,0x30021,0x4,0x3,0x30016,0x5,0x20,0x40017,0x6,0x5,0x4,0x40020,0x7,0x3,0x6,0x4003b,0x7,0x2,0x3,0x4002b,0x5,0x8,0x0,0x4002b,0x5,0x9,0x3f800000,0x7002c,0x6,0xa,0x8,0x9,0x8,0x9,0x50036,0x3,0x1,0x0,0x4,0x200f8,0xb,0x3003e,0x2,0xa,0x100fd,0x10038}; - } VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; module_info.codeSize = stage.words.size() * 4; module_info.pCode = stage.words.data(); @@ -4167,9 +4155,7 @@ class PipelineState final subgroup_size_for(*stage.entry, required_sizes[stage_infos.size()], info); stage_infos.push_back(info); } - // LOCAL EXPERIMENT: LEONIDA_RECT_NOGS=1 draws the rectangle list's three corners as a plain triangle. - static const bool local_no_gs = [] { const char* v = std::getenv("LEONIDA_RECT_NOGS"); return v && *v == '1'; }(); - if (rect_list && !local_no_gs) { // the stage that adds each rectangle's fourth corner, from the vertex shader's outputs + if (rect_list) { // the stage that adds each rectangle's fourth corner, from the vertex shader's outputs std::string why; const std::vector words = leonida::rect_list_geometry(vs_stage.words, why); if (words.empty()) { @@ -4230,16 +4216,6 @@ class PipelineState final if (e.system_value == 0 && e.semantic_index == element.SemanticIndex && equal_semantic(e.semantic, element.SemanticName)) input = &e; - { // LOCAL DIAGNOSTIC: the input layout of the first graphics pipelines with one - static std::atomic said{0}; - const std::string& vsn = stages[0].entry->name; - if ((vsn.find("Blit") != std::string::npos || vsn.find("sga_dr") != std::string::npos) && said.fetch_add(1) < 24) - std::fprintf(stderr, "[rt] localdbg: input element %u/%u %s%u dxgi=%d slot=%u offset=%u -> %s (vs %s)\n", i, - desc.InputLayout.NumElements, element.SemanticName ? element.SemanticName : "?", - element.SemanticIndex, int(element.Format), element.InputSlot, offset, - input ? ("location " + std::to_string(input->register_index)).c_str() : "not read", - stages[0].entry->name.c_str()); - } if (!input) continue; // the shader does not read this element attributes.push_back({input->register_index, element.InputSlot, format, offset}); const bool instance = element.InputSlotClass == D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA; @@ -4262,13 +4238,6 @@ class PipelineState final instance ? VK_VERTEX_INPUT_RATE_INSTANCE : VK_VERTEX_INPUT_RATE_VERTEX}); } } - { // LOCAL DIAGNOSTIC - static std::atomic said2{0}; - const std::string& vsn = stages[0].entry->name; - if (!mesh && (vsn.find("Blit") != std::string::npos || vsn.find("sga_dr") != std::string::npos) && said2.fetch_add(1) < 8) - std::fprintf(stderr, "[rt] localdbg: %s input layout elements=%u attributes=%zu signature=%zu\n", vsn.c_str(), - desc.InputLayout.NumElements, attributes.size(), stages[0].entry->input_signature.size()); - } for (const auto& e : stages[0].entry->input_signature) { if (e.system_value) continue; const bool fed = std::any_of(attributes.begin(), attributes.end(), @@ -4319,16 +4288,6 @@ class PipelineState final : VK_CULL_MODE_NONE; // With the negative-height viewport, framebuffer winding matches D3D12's screen-space winding. raster.frontFace = r.FrontCounterClockwise ? VK_FRONT_FACE_COUNTER_CLOCKWISE : VK_FRONT_FACE_CLOCKWISE; - // LOCAL EXPERIMENT: LEONIDA_RECT_NOCULL=1 draws rectangle lists without face culling (hypothesis: the - // console's rectangle primitive has no facing, so the PSO's cull mode does not apply to it). - if (rect_list) { - static const bool no_cull = [] { const char* v = std::getenv("LEONIDA_RECT_NOCULL"); return v && *v == '1'; }(); - static std::atomic said{0}; - if (said.fetch_add(1) < 4) - std::fprintf(stderr, "[rt] localdbg: rect-list pipeline cull=%u frontCCW=%d depthClip=%d no_cull=%d\n", - unsigned(r.CullMode), int(r.FrontCounterClockwise), int(r.DepthClipEnable), int(no_cull)); - if (no_cull) raster.cullMode = VK_CULL_MODE_NONE; - } // The D24-as-D32 pixel stage applies the bias itself, in D24 units (depth24_fragment above): the // rasterizer's bias stays off and zero, so its clamp needs no depthBiasClamp feature either. raster.depthBiasEnable = !depth24_fragment && (r.DepthBias || r.SlopeScaledDepthBias != 0.0f); @@ -4369,31 +4328,6 @@ class PipelineState final blends[i].dstAlphaBlendFactor = blend_factor(b.DestBlendAlpha); blends[i].alphaBlendOp = blend_op(b.BlendOpAlpha); blends[i].colorWriteMask = b.RenderTargetWriteMask & 0xf; // R, G, B, A in both APIs - if (rect_list) { // LOCAL DIAGNOSTIC / EXPERIMENT (LEONIDA_RECT_FORCE=1: opaque, no depth or stencil test) - static const bool force = [] { const char* v = std::getenv("LEONIDA_RECT_FORCE"); return v && *v == '1'; }(); - static std::atomic said{0}; - if (said.load() < 6) - for (const auto& st : stages) - if (st.entry) - std::fprintf(stderr, "[rt] localdbg: rect pipeline stage %s = %s wave64=%d emulated=%d push=%u\n", - st.entry->stage.c_str(), st.entry->name.c_str(), int(st.entry->wave64), - int(st.entry->emulated()), st.entry->push_constant_bytes); - if (said.fetch_add(1) < 6) - std::fprintf(stderr, "[rt] localdbg: rect pipeline rt%u/%u blend=%d src=%d dst=%d op=%d srcA=%d dstA=%d " - "mask=0x%x depth=%d write=%d func=%d stencil=%d samplemask=0x%x fmt=%d a2c=%d force=%d\n", - i, desc.NumRenderTargets, int(b.BlendEnable), int(b.SrcBlend), int(b.DestBlend), - int(b.BlendOp), int(b.SrcBlendAlpha), int(b.DestBlendAlpha), - unsigned(b.RenderTargetWriteMask), int(ds.DepthEnable), int(ds.DepthWriteMask), - int(ds.DepthFunc), int(ds.StencilEnable), unsigned(desc.SampleMask), - int(desc.RTVFormats[i]), int(desc.BlendState.AlphaToCoverageEnable), int(force)); - if (force) { - blends[i].blendEnable = VK_FALSE; - blends[i].colorWriteMask = 0xf; - depth.depthTestEnable = VK_FALSE; - depth.depthWriteEnable = VK_FALSE; - depth.stencilTestEnable = VK_FALSE; - } - } // B8G8R8X8 has no alpha, so blending reads destination alpha as 1 there (WARP and AMD's D3D12 driver), // where its BGRA8 Vulkan image would read the X byte. For colour SRC_ALPHA_SAT is min(As, 1 - Ad), so 0; // for alpha it is 1 in both APIs already. @@ -6099,10 +6033,7 @@ class Device final state_.context->set_heap_base(arena.address); state_.context->set_zero_page(arena.buffer, 0, kZeroPage); state_.context->set_quad_indices(arena.buffer, kZeroPage, kQuadIndexCount); - leonida::g_local_arena_mapped = arena.mapped; // LOCAL DIAGNOSTIC - std::fprintf(stderr, "[rt] localdbg: arena mapped at %p\n", static_cast(arena.mapped)); - leonida::g_local_arena_size = arena.size; - // LOCAL: vertex and index views that name the title's own CPU memory are copied into a ring carved from the + // Vertex and index views that name the title's own CPU memory are copied into a ring carved from the // arena at replay (not fence-tracked: the ring is large against a frame's few KiB of immediate geometry). state_.context->set_title_memory( [st = &state_](std::uint64_t va, std::uint64_t size, VkBuffer& buffer, VkDeviceSize& offset) { @@ -6110,16 +6041,6 @@ class Device final static std::mutex mutex; static VkDeviceSize ring_base = 0, ring_next = 0; static bool tried = false, logged = false; - static std::atomic dbg{0}; - if (dbg.fetch_add(1) < 6) { - MEMORY_BASIC_INFORMATION q{}; - const SIZE_T got = VirtualQuery(reinterpret_cast(va), &q, sizeof(q)); - std::fprintf(stderr, "[rt] localdbg: title_memory va=0x%llx size=0x%llx query=%zu state=0x%lx " - "protect=0x%lx type=0x%lx region=0x%llx mapped=%d\n", - static_cast(va), static_cast(size), - static_cast(got), q.State, q.Protect, q.Type, - static_cast(q.RegionSize), st->arena.mapped != nullptr); - } if (!va || !size || size > kRing / 4 || !st->arena.mapped) return false; // The whole range must be committed, readable host memory. for (std::uint64_t at = va; at < va + size;) { @@ -6139,35 +6060,12 @@ class Device final if (ring_next + aligned > kRing) ring_next = 0; std::memcpy(st->arena.mapped + ring_base + ring_next, reinterpret_cast(va), std::size_t(size)); - { // LOCAL EXPERIMENT: LEONIDA_VTX_TEST=1 overwrites the copy with a screen-covering triangle (stride 24) - static const char mode = [] { const char* v = std::getenv("LEONIDA_VTX_TEST"); return v ? *v : '0'; }(); - const float second_y = reinterpret_cast(st->arena.mapped + ring_base + ring_next)[7]; - const bool test = mode == '1' || (mode == 'A' && second_y < 100.f) || (mode == 'B' && second_y >= 100.f); - if (test && size >= 72) { - const float tri[3][2] = {{-1.f, -1.f}, {3.f, -1.f}, {-1.f, 3.f}}; - for (int v = 0; v < 3; ++v) { - float* q = reinterpret_cast(st->arena.mapped + ring_base + ring_next + v * 24); - q[0] = tri[v][0]; q[1] = tri[v][1]; q[2] = 0.f; - } - } - static std::atomic said{0}; - if (said.load() < 6) { - const float* q = reinterpret_cast(st->arena.mapped + ring_base + ring_next); - std::fprintf(stderr, "[rt] localdbg: ring copy holds %g,%g | %g,%g | %g,%g (size %llu)\n", q[0], q[1], - q[6], q[7], q[12], q[13], static_cast(size)); - } - if (said.fetch_add(1) < 3) - std::fprintf(stderr, "[rt] localdbg: ring copy at arena offset 0x%llx (ring_base 0x%llx) arena size 0x%llx\n", - static_cast(ring_base + ring_next), - static_cast(ring_base), - static_cast(st->arena.size)); - } buffer = st->arena.buffer; offset = ring_base + ring_next; ring_next += aligned; if (!logged) { logged = true; - std::fprintf(stderr, "[rt] d3d12: local: vertex/index views in title memory are copied into a " + std::fprintf(stderr, "[rt] d3d12: vertex/index views in title memory are copied into a " "%llu MiB ring (first: %llu bytes)\n", static_cast(kRing >> 20), static_cast(size)); } diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 09d753a86a..9bfa5ea7f4 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -24,6 +24,7 @@ // 78 SetFrameIntervalX, 79 ScheduleFrameEventX and 80 WaitFrameEventX. The slots can be moved with LEONIDA_XS_*_SLOT // for a trace that disagrees. The frame-event calls answer from a per-device token counter: there is no vblank source // behind the device before a presenter exists, so WaitFrameEventX returns at once with a fresh non-zero token. +#include "../src/title_va_alias.h" #include "title_window.h" #include "d3d12_xs_device.h" #include "d3d12_trace.h" @@ -166,9 +167,6 @@ bool register_descriptor_range(const DeviceProxy* device, const HeapProxy* heap, return false; try { std::lock_guard lock(descriptor_range_mutex()); - std::fprintf(stderr, "[rt] localdbg: descriptor range custom=0x%llx..0x%llx real_cpu=0x%llx heap=%p\n", - static_cast(custom_start), static_cast(custom_start + byte_size), - static_cast(real_start), static_cast(heap)); descriptor_ranges().push_back({custom_start, custom_start + byte_size, real_start, device, heap}); g_custom_range_count.store(descriptor_ranges().size(), std::memory_order_release); return true; @@ -216,10 +214,33 @@ bool local_desc_mirror() { return on; } +// Whether [address, address + bytes) is committed memory that can be read (and, with `write`, written). A handle +// that is only a number (a mock's, or a range the title has released) is left alone instead of faulting. +bool local_accessible(std::uint64_t address, std::uint64_t bytes, bool write) { + const std::uint64_t end = address + bytes; + if (!address || end < address) return false; + while (address < end) { + MEMORY_BASIC_INFORMATION info{}; + if (!VirtualQuery(reinterpret_cast(address), &info, sizeof(info)) || info.State != MEM_COMMIT) + return false; + const DWORD protect = info.Protect & 0xff; + if (info.Protect & PAGE_GUARD) return false; + const bool writable = protect == PAGE_READWRITE || protect == PAGE_WRITECOPY || + protect == PAGE_EXECUTE_READWRITE || protect == PAGE_EXECUTE_WRITECOPY; + const bool readable = writable || protect == PAGE_READONLY || protect == PAGE_EXECUTE_READ; + if (write ? !writable : !readable) return false; + address = reinterpret_cast(info.BaseAddress) + info.RegionSize; + } + return true; +} + void local_write_through(const DeviceProxy* device, D3D12_CPU_DESCRIPTOR_HANDLE custom, SIZE_T count) { if (!local_desc_mirror() || !custom.ptr || !count) return; const D3D12_CPU_DESCRIPTOR_HANDLE real = translate_cpu_handle(device, custom); if (real.ptr == custom.ptr) return; + if (!local_accessible(real.ptr, count * kLocalDescriptorBytes, false) || + !local_accessible(custom.ptr, count * kLocalDescriptorBytes, true)) + return; std::memcpy(reinterpret_cast(custom.ptr), reinterpret_cast(real.ptr), count * kLocalDescriptorBytes); static std::atomic said{false}; @@ -240,6 +261,9 @@ void local_mirror_table(const DeviceProxy* device, std::uint64_t gpu_handle) { if (!gpu_start || gpu_handle < gpu_start || gpu_handle >= gpu_start + bytes) continue; const std::uint64_t offset = (gpu_handle - gpu_start) / kLocalDescriptorBytes * kLocalDescriptorBytes; const std::uint64_t slots = (std::min)(kLocalMirrorSlots, (bytes - offset) / kLocalDescriptorBytes); + if (!local_accessible(range.custom_start + offset, slots * kLocalDescriptorBytes, false) || + !local_accessible(range.real_start + offset, slots * kLocalDescriptorBytes, true)) + return; std::uint64_t copied = 0; for (std::uint64_t i = 0; i < slots; ++i) { const auto* from = reinterpret_cast(range.custom_start + offset + i * kLocalDescriptorBytes); @@ -740,22 +764,12 @@ D3D12_CPU_DESCRIPTOR_HANDLE heap_get_cpu_handle(HeapProxy* self) { D3D12_GPU_DESCRIPTOR_HANDLE heap_get_gpu_handle(HeapProxy* self) { note_heap_slot(10); - { - static std::atomic said{0}; - if (said.fetch_add(1) < 8) std::fprintf(stderr, "[rt] localdbg: heap slot 10 (GPU handle) asked on heap %p\n", static_cast(self)); - } constexpr UINT64 kUnset = ~static_cast(0); D3D12_GPU_DESCRIPTOR_HANDLE handle{}; handle.ptr = kUnset; using Fn = D3D12_GPU_DESCRIPTOR_HANDLE(WINAPI*)(ID3D12DescriptorHeap*, D3D12_GPU_DESCRIPTOR_HANDLE*); const D3D12_GPU_DESCRIPTOR_HANDLE returned = reinterpret_cast(self->real_vtable[10])(self->real, &handle); - { - static std::atomic said{0}; - if (said.fetch_add(1) < 4) - std::fprintf(stderr, "[rt] localdbg: heap %p slot 10 answers GPU handle 0x%llx\n", static_cast(self), - static_cast(handle.ptr != kUnset ? handle.ptr : returned.ptr)); - } return handle.ptr != kUnset ? handle : returned; } @@ -2538,12 +2552,6 @@ void proxy_create_srv_from_raw_x(DeviceProxy* self, std::uint64_t texture_words, std::uint64_t custom; ~LocalWriteThrough() { local_write_through(self, D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(custom)}, 1); } } local_write_back{self, destination}; - { - static std::atomic calls{0}; - const int n = calls.fetch_add(1); - if (n < 4 || n % 5000 == 0) - std::fprintf(stderr, "[rt] localdbg: slot 70 call #%d dest=0x%llx\n", n, static_cast(destination)); - } // The console hands a CPU descriptor handle in the title's heap memory; #7021 translates it to the real heap's. destination = translate_cpu_handle(self, D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(destination)}).ptr; @@ -2561,7 +2569,10 @@ void proxy_create_srv_from_raw_x(DeviceProxy* self, std::uint64_t texture_words, // LOCAL: a small raw view over the title's own memory becomes a raw buffer V# through the constant-view path, // which resolves a title address to its GPU copy (#9137). LEONIDA_SLOT70_TITLE=0 keeps the null view. static const bool title_views = [] { const char* v = std::getenv("LEONIDA_SLOT70_TITLE"); return !(v && *v == '0'); }(); - if (title_views && shape.va && shape.va < 0x100000000ull && shape.resource.Width && shape.resource.Width <= 65536) { + std::uint64_t title_lo = 0, title_hi = 0; + if (title_views && shape.resource.Width && shape.resource.Width <= 65536 && + leonida::title_va_aliases().title_memory(shape.va, title_lo, title_hi) && + shape.resource.Width <= title_hi - shape.va) { D3D12_CONSTANT_BUFFER_VIEW_DESC constants{}; constants.BufferLocation = shape.va; constants.SizeInBytes = static_cast(shape.resource.Width); @@ -2573,13 +2584,6 @@ void proxy_create_srv_from_raw_x(DeviceProxy* self, std::uint64_t texture_words, return; } log_slot70_null_once("no buffer holds the address", texture_words, view_desc); - { - static std::atomic nulls{0}; - const int n = nulls.fetch_add(1); - if (n < 3 || n % 5000 == 0) - std::fprintf(stderr, "[rt] localdbg: slot 70 null #%d: no buffer holds va=0x%llx width=%llu\n", n, - static_cast(shape.va), static_cast(shape.resource.Width)); - } write_null_srv(self, destination); return; } @@ -2783,25 +2787,6 @@ HRESULT proxy_create_descriptor_heap(DeviceProxy* self, const D3D12_DESCRIPTOR_H void proxy_create_cbv(DeviceProxy* self, const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE dest) { note_slot(17); - { // LOCAL DIAGNOSTIC - static std::atomic said{0}; - const int n = said.fetch_add(1); - if (n < 6 || (n > 3000 && n < 3008)) { - const D3D12_CPU_DESCRIPTOR_HANDLE t = translate_cpu_handle(self, dest); - std::fprintf(stderr, "[rt] localdbg: CreateCBV #%d dest=0x%llx -> 0x%llx location=0x%llx size=%u\n", n, - static_cast(dest.ptr), static_cast(t.ptr), - desc ? static_cast(desc->BufferLocation) : 0ull, desc ? desc->SizeInBytes : 0u); - MEMORY_BASIC_INFORMATION q{}; - if (desc && desc->BufferLocation && desc->BufferLocation < 0x100000000ull && - VirtualQuery(reinterpret_cast(desc->BufferLocation), &q, sizeof(q)) && q.State == MEM_COMMIT && - !(q.Protect & (PAGE_NOACCESS | PAGE_GUARD))) { - const float* f = reinterpret_cast(desc->BufferLocation); - std::fprintf(stderr, "[rt] localdbg: constants now:"); - for (int w = 0; w < 24 && w * 4u < desc->SizeInBytes; ++w) std::fprintf(stderr, " %g", f[w]); - std::fprintf(stderr, "\n"); - } - } - } self->real->CreateConstantBufferView(desc, translate_cpu_handle(self, dest)); local_write_through(self, dest, 1); } diff --git a/runtime/shims/xbox_present.cpp b/runtime/shims/xbox_present.cpp index 56299afe27..6fbed007d4 100644 --- a/runtime/shims/xbox_present.cpp +++ b/runtime/shims/xbox_present.cpp @@ -154,15 +154,6 @@ HRESULT XboxPresentation::present_x(UINT plane_count, const XboxPresentPlanePara return result; } - { // LOCAL DIAGNOSTIC: what the first presents show - static std::atomic shown{0}; - if (shown.fetch_add(1, std::memory_order_relaxed) < 8) - for (UINT i = 0; i < plane_count; ++i) - std::fprintf(stderr, "[rt] localdbg: PresentX plane %u/%u resource=%p count=%u src=%p dest=%p cs=%d flags=0x%x\n", - i, plane_count, planes[i].ppResources ? static_cast(planes[i].ppResources[0]) : nullptr, - planes[i].ResourceCount, static_cast(planes[i].pSrcViewRects), - static_cast(planes[i].pDestPlacementBase), planes[i].ColorSpace, planes[i].Flags); - } // All planes carry the token of one frame. const std::uint64_t token = planes[0].Token; for (UINT i = 0; i < plane_count; ++i) { diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index a531c9e72f..cdc6b5bfe8 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -809,20 +809,6 @@ enum class ReplayResult { invalid_draw, // DispatchMesh with a pipeline that has no mesh shader, or a vertex draw with one that has unsupported }; -// LOCAL DIAGNOSTIC: the arena's host mapping and size, for dumps of what a shader would read. -inline std::uint8_t* g_local_arena_mapped = nullptr; -inline std::uint64_t g_local_arena_size = 0; -inline std::atomic g_local_last_cb96{0}; // title address of the last 96-byte constant view created - -// LOCAL DIAGNOSTIC: which check returned unresolved_resource (first 3 times per source line). -inline ReplayResult local_unresolved_at(int line) { - static std::atomic seen[8192]; - if (line >= 0 && line < 8192 && seen[line].fetch_add(1, std::memory_order_relaxed) < 3) - std::fprintf(stderr, "[rt] localdbg: unresolved_resource at vulkan_replay.h:%d\n", line); - return ReplayResult::unresolved_resource; -} - - struct ReplayFunctions { // Set 0 for the pipelines that declare one (their own `bindless_set` is only the marker): the device's current // generation of it, which a flush may have replaced since the pipeline was made. Null: the pipeline's. @@ -882,7 +868,7 @@ struct ReplayFunctions { // cut to what the buffer holds from there: vertex and index views use what fits, WriteBufferImmediate needs all // of it. std::function buffer_at; - // LOCAL: a vertex or index view whose VA is the title's own CPU memory, not a registered buffer (on the console + // A vertex or index view whose VA is the title's own CPU memory, not a registered buffer (on the console // the GPU reads title memory directly). Copies [va, va + size) into a GPU-visible ring and names the copy; false // when the range is not readable host memory. std::function title_memory; @@ -2131,7 +2117,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct !vk.draw_indexed || !vk.bind_pipeline || !vk.push_constants) return ReplayResult::unsupported; const GraphicsPipeline* pipeline = vk.graphics_pipeline(draw.pipeline); - if (!pipeline || !pipeline->pipeline) return local_unresolved_at(__LINE__); + if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; if (pipeline->mesh != draw.mesh) return ReplayResult::invalid_draw; if (draw.mesh && !vk.draw_mesh_tasks) return ReplayResult::unsupported; if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; @@ -2152,7 +2138,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct const TargetView& target = draw.views->render_targets[slot]; if (!target.resource) continue; const ResourceBinding* binding = resolve(target.resource); - if (!binding) return local_unresolved_at(__LINE__); + if (!binding) return ReplayResult::unresolved_resource; auto& a = p.colors[slot]; a.binding = *binding; a.id = target.resource; @@ -2169,7 +2155,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct } if (draw.depth.resource && pipeline->depth_format != VK_FORMAT_UNDEFINED) { const ResourceBinding* binding = resolve(draw.depth.resource); - if (!binding) return local_unresolved_at(__LINE__); + if (!binding) return ReplayResult::unresolved_resource; auto& a = p.depth; a.binding = *binding; a.id = draw.depth.resource; @@ -2210,7 +2196,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct const bool bound = draw.views && slot < draw.views->vertex_buffers.size() && draw.views->vertex_buffers[slot].va; if (!bound) { - if (!vk.zero_buffer) return local_unresolved_at(__LINE__); + if (!vk.zero_buffer) return ReplayResult::unresolved_resource; p.vertex_buffers[slot] = vk.zero_buffer; p.vertex_offsets[slot] = vk.zero_offset; p.vertex_sizes[slot] = vk.zero_size; @@ -2222,101 +2208,20 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct if (!vk.buffer_at(view.va, size, p.vertex_buffers[slot], p.vertex_offsets[slot])) { size = view.size; if (!vk.title_memory || !vk.title_memory(view.va, size, p.vertex_buffers[slot], p.vertex_offsets[slot])) - return local_unresolved_at(__LINE__); - { // LOCAL DIAGNOSTIC: the first draws that read title memory - static std::atomic shown{0}; - const int nth = shown.fetch_add(1, std::memory_order_relaxed); - if (nth < 12 || (nth % 20000) < 3) { - const float* f = reinterpret_cast(view.va); - std::fprintf(stderr, "[rt] localdbg: draw slot=%u topology=%u count=%u instances=%u first=%u stride=%u " - "bytes=%llu viewport=%.0f,%.0f %.0fx%.0f depth %.2f..%.2f\n", slot, draw.topology, - draw.count, draw.instances, draw.first, view.stride, - static_cast(view.size), draw.viewport.x, draw.viewport.y, - draw.viewport.width, draw.viewport.height, draw.viewport.min_depth, draw.viewport.max_depth); - for (std::uint32_t t = 0; draw.views && t < draw.views->render_target_count; ++t) - std::fprintf(stderr, "[rt] localdbg: target %u resource=0x%llx mip=%u pipeline=0x%llx depth=0x%llx " - "scissor=%d,%d..%d,%d\n", t, - static_cast(draw.views->render_targets[t].resource), - draw.views->render_targets[t].mip, static_cast(draw.pipeline), - static_cast(draw.depth.resource), draw.scissor.left, - draw.scissor.top, draw.scissor.right, draw.scissor.bottom); - std::fprintf(stderr, "[rt] localdbg: heap_base=0x%llx user_data:", static_cast(vk.heap_base)); - for (int w = 0; w < 16; ++w) std::fprintf(stderr, " %08x", draw.user_data[w]); - std::fprintf(stderr, "\n"); - for (int w = 0; w < 16; ++w) { // which root words name a registered buffer - std::uint64_t room = 1; VkBuffer bb = VK_NULL_HANDLE; VkDeviceSize bo = 0; - if (draw.user_data[w] && vk.buffer_at(draw.user_data[w], room, bb, bo)) - std::fprintf(stderr, "[rt] localdbg: user_data[%d] is a registered buffer VA\n", w); - } - const std::uint32_t local_table = draw.user_data[0] ? draw.user_data[0] : draw.user_data[8]; - if (g_local_arena_mapped && local_table && local_table + 256ull <= g_local_arena_size) { - const std::uint32_t* t = reinterpret_cast(g_local_arena_mapped + local_table); - for (int e = 0; e < 4; ++e) { - std::fprintf(stderr, "[rt] localdbg: table[%d]:", e); - for (int w = 0; w < 8; ++w) std::fprintf(stderr, " %08x", t[e * 8 + w]); - std::fprintf(stderr, "\n"); - const std::uint64_t va = (std::uint64_t(t[e * 8 + 1] & 0xffff) << 32) | t[e * 8]; - if (va && va + 128 <= g_local_arena_size) { - const float* f2 = reinterpret_cast(g_local_arena_mapped + va); - std::fprintf(stderr, "[rt] localdbg: at va 0x%llx:", static_cast(va)); - for (int w = 0; w < 32; ++w) std::fprintf(stderr, " %g", f2[w]); - std::fprintf(stderr, "\n"); - } - } - } - { // the same table read from the title's memory, taking the high dword from the vertex view's VA - const std::uint64_t guess = (view.va & 0xffffffff00000000ull) | draw.user_data[0]; - std::fprintf(stderr, "[rt] localdbg: vertex va=0x%llx table guess=0x%llx delta=%lld\n", - static_cast(view.va), static_cast(guess), - static_cast(view.va - guess)); - std::uint64_t probe = 256; VkBuffer pb = VK_NULL_HANDLE; VkDeviceSize po = 0; - if (draw.user_data[0] && vk.title_memory && vk.title_memory(guess, probe, pb, po)) { - const std::uint32_t* t = reinterpret_cast(guess); - for (int e = 0; e < 3; ++e) { - std::fprintf(stderr, "[rt] localdbg: title table[%d]:", e); - for (int w = 0; w < 8; ++w) std::fprintf(stderr, " %08x", t[e * 8 + w]); - std::fprintf(stderr, "\n"); - } - } else { - std::fprintf(stderr, "[rt] localdbg: title table guess is not readable title memory\n"); - } - } - if (const std::uint64_t cb = g_local_last_cb96.load()) { - const float* f3 = reinterpret_cast(cb); - std::fprintf(stderr, "[rt] localdbg: 96-byte constants in title memory at draw time:"); - for (int w = 0; w < 24; ++w) std::fprintf(stderr, " %g", f3[w]); - std::fprintf(stderr, "\n"); - } - { // what sits just before the vertices in the title's ring - const std::uint32_t* t = reinterpret_cast(view.va - 0x60); - for (int e = 0; e < 3; ++e) { - std::fprintf(stderr, "[rt] localdbg: before vertices[-0x%x]:", 0x60 - e * 0x20); - for (int w = 0; w < 8; ++w) std::fprintf(stderr, " %08x", t[e * 8 + w]); - std::fprintf(stderr, "\n"); - } - } - const std::uint32_t words = view.stride / 4 ? view.stride / 4 : 1; - for (std::uint32_t v = 0; v < 4 && (draw.first + v + 1) * view.stride <= view.size; ++v) { - const float* q = f + (draw.first + v) * words; - std::fprintf(stderr, "[rt] localdbg: v%u = %g %g %g %g %g %g\n", v, q[0], q[1], - words > 2 ? q[2] : 0.f, words > 3 ? q[3] : 0.f, words > 4 ? q[4] : 0.f, - words > 5 ? q[5] : 0.f); - } - } - } + return ReplayResult::unresolved_resource; } p.vertex_sizes[slot] = size; p.vertex_strides[slot] = (pipeline->zero_step_slots & (1u << slot)) ? 0 : view.stride; } // A non-indexed quad list is drawn from the shared triangle index buffer (emit). if (!draw.indexed && !draw.mesh && draw.topology == topology_quad_list && !vk.quad_indices) - return local_unresolved_at(__LINE__); + return ReplayResult::unresolved_resource; if (draw.indexed) { if (draw.index.format == 57) p.index_type = VK_INDEX_TYPE_UINT16; else if (draw.index.format == 42) p.index_type = VK_INDEX_TYPE_UINT32; else if (draw.index.va) return ReplayResult::unsupported; if (!draw.index.va) { // no index buffer: every index reads 0 - if (!vk.zero_buffer) return local_unresolved_at(__LINE__); + if (!vk.zero_buffer) return ReplayResult::unresolved_resource; p.index_buffer = vk.zero_buffer; p.index_offset = vk.zero_offset; } else { @@ -2324,7 +2229,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct if (!vk.buffer_at(draw.index.va, size, p.index_buffer, p.index_offset)) { size = draw.index.size; if (!vk.title_memory || !vk.title_memory(draw.index.va, size, p.index_buffer, p.index_offset)) - return local_unresolved_at(__LINE__); + return ReplayResult::unresolved_resource; } } } @@ -2746,7 +2651,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun }; if (const auto* transition = std::get_if(&command)) { - if (!bind(transition->resource)) return local_unresolved_at(__LINE__); + if (!bind(transition->resource)) return ReplayResult::unresolved_resource; if (p.binding.image == VK_NULL_HANDLE) { if (transition->subresource != 0 && transition->subresource != all_subresources) return ReplayResult::invalid_subresource; @@ -2756,14 +2661,14 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun } else if (std::holds_alternative(command) || std::holds_alternative(command)) { if (!vk.pipeline_barrier2) return ReplayResult::unsupported; if (const auto* buffer_barrier = std::get_if(&command)) - if (!bind(buffer_barrier->resource)) return local_unresolved_at(__LINE__); + if (!bind(buffer_barrier->resource)) return ReplayResult::unresolved_resource; } else if (const auto* texture = std::get_if(&command)) { if (!vk.pipeline_barrier2) return ReplayResult::unsupported; - if (!bind(texture->resource)) return local_unresolved_at(__LINE__); + if (!bind(texture->resource)) return ReplayResult::unresolved_resource; if (!p.binding.image || !barrier_range(p.binding, texture->range, p.range)) return ReplayResult::invalid_subresource; } else if (const auto* color_clear = std::get_if(&command)) { - if (!bind(color_clear->target.resource)) return local_unresolved_at(__LINE__); + if (!bind(color_clear->target.resource)) return ReplayResult::unresolved_resource; if (!p.binding.image || p.binding.aspects != VK_IMAGE_ASPECT_COLOR_BIT) return ReplayResult::invalid_clear; if (!detail::view_range(p.binding, color_clear->target, VK_IMAGE_ASPECT_COLOR_BIT, p.range)) return ReplayResult::invalid_subresource; @@ -2785,7 +2690,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun r != ReplayResult::success) return r; if (!p.skip && p.rects.empty() && !vk.clear_color_image) return ReplayResult::unsupported; } else if (const auto* depth_clear = std::get_if(&command)) { - if (!bind(depth_clear->target.resource)) return local_unresolved_at(__LINE__); + if (!bind(depth_clear->target.resource)) return ReplayResult::unresolved_resource; VkImageAspectFlags aspects = 0; if (depth_clear->flags & clear_depth) aspects |= VK_IMAGE_ASPECT_DEPTH_BIT; if (depth_clear->flags & clear_stencil) aspects |= VK_IMAGE_ASPECT_STENCIL_BIT; @@ -2805,7 +2710,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!p.skip && p.rects.empty() && !vk.clear_depth_stencil_image) return ReplayResult::unsupported; } else if (const auto* uav = std::get_if(&command)) { const UavView& view = uav->view; - if (!bind(view.resource)) return local_unresolved_at(__LINE__); + if (!bind(view.resource)) return ReplayResult::unresolved_resource; if (view.buffer) { if (!vk.fill_buffer || !vk.update_buffer || !vk.copy_buffer) return ReplayResult::unsupported; if (predicated) ++out.unpredicated_copies; // fills and copies are transfer commands @@ -2865,7 +2770,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (predicated && !std::holds_alternative(command)) ++out.unpredicated_copies; const auto [dst_id, src_id] = copy_ids(command); const ResourceBinding* source = resolve(src_id); - if (!bind(dst_id) || !source) return local_unresolved_at(__LINE__); + if (!bind(dst_id) || !source) return ReplayResult::unresolved_resource; p.source = *source; ReplayResult result = ReplayResult::success; if (const auto* buffer_copy = std::get_if(&command)) { @@ -2998,7 +2903,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!vk.resolve_image) return ReplayResult::unsupported; if (predicated) ++out.unpredicated_copies; // a transfer command, like the copies const ResourceBinding* source = resolve(resolve_command->src); - if (!bind(resolve_command->dst) || !source) return local_unresolved_at(__LINE__); + if (!bind(resolve_command->dst) || !source) return ReplayResult::unresolved_resource; p.source = *source; if (const auto result = detail::prepare_resolve(*resolve_command, p); result != ReplayResult::success) return result; @@ -3029,7 +2934,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun } } else if (const auto* discard = std::get_if(&command)) { // Buffers and partial (rectangle) discards keep their contents, which "undefined" allows. - if (!bind(discard->resource)) return local_unresolved_at(__LINE__); + if (!bind(discard->resource)) return ReplayResult::unresolved_resource; const std::uint64_t end = std::uint64_t(discard->first_subresource) + discard->count; if (!p.binding.image) { if (!discard->whole && end > 1) return ReplayResult::invalid_subresource; @@ -3049,7 +2954,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!vk.update_buffer || !vk.buffer_at) return ReplayResult::unsupported; std::uint64_t bytes = 4; if (!vk.buffer_at(write->address, bytes, p.write_buffer, p.write_offset) || bytes < 4) - return local_unresolved_at(__LINE__); + return ReplayResult::unresolved_resource; if (p.write_offset % 4) return ReplayResult::invalid_copy; // WriteBufferImmediate resolves by VA and may target a readback buffer in COPY_DEST. out.wrote_readback = true; @@ -3058,14 +2963,14 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!vk.copy_buffer) return ReplayResult::unsupported; if (predicated) ++out.unpredicated_copies; // a transfer command, like the copies const ResourceBinding* source = resolve(atomic->src); - if (!bind(atomic->dst) || !source) return local_unresolved_at(__LINE__); + if (!bind(atomic->dst) || !source) return ReplayResult::unresolved_resource; p.source = *source; if (!p.binding.buffer || !p.source.buffer || !detail::within(atomic->dst_offset, atomic->bytes, p.binding.size) || !detail::within(atomic->src_offset, atomic->bytes, p.source.size)) return ReplayResult::invalid_copy; for (const auto& d : atomic->dependencies) { const ResourceBinding* dependent = resolve(d.resource); - if (!dependent) return local_unresolved_at(__LINE__); + if (!dependent) return ReplayResult::unresolved_resource; if (!dependent->image) { const std::uint64_t end = d.end == UINT64_MAX ? dependent->size : d.end; if (d.subresource != 0 || d.begin >= end || end > dependent->size) @@ -3084,7 +2989,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!conditional) return ReplayResult::unsupported; // Without physical segments the capture dispatch would pollute CSInvocations. if (statistics_active && !statistics_helpers) return ReplayResult::unsupported; - if (!bind(predication->buffer)) return local_unresolved_at(__LINE__); + if (!bind(predication->buffer)) return ReplayResult::unresolved_resource; if (!p.binding.buffer || !detail::within(predication->offset, 8, p.binding.size) || predication->offset > UINT64_MAX - p.binding.buffer_offset) return ReplayResult::invalid_predication; @@ -3096,7 +3001,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun // not suppress them (emit_query suspends conditional rendering around ResolveQueryData). if (!queries) return ReplayResult::unsupported; QueryPool* heap = vk.query_pool(range.heap); - if (!heap) return local_unresolved_at(__LINE__); + if (!heap) return ReplayResult::unresolved_resource; if (!query_fits_heap(heap->heap_type, range.type)) return ReplayResult::invalid_query; if (range.first >= heap->count || range.count > heap->count - range.first) return ReplayResult::invalid_query; @@ -3119,7 +3024,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun } if (const auto* resolve_queries = std::get_if(&command)) { // The destination is a buffer, as D3D12 requires, large enough for every result. - if (!bind(resolve_queries->dst)) return local_unresolved_at(__LINE__); + if (!bind(resolve_queries->dst)) return ReplayResult::unresolved_resource; const std::uint64_t bytes = std::uint64_t(range.count) * query_result_size(range.type); if (!p.binding.buffer || p.binding.buffer_offset % 8 || !detail::within(resolve_queries->offset, bytes, p.binding.size) || @@ -3137,7 +3042,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun } out.queries.push_back({i, heap, statistics_active}); } else if (const auto* ind = std::get_if(&command)) { - if (!bind(ind->argument_buffer) || !p.binding.buffer) return local_unresolved_at(__LINE__); + if (!bind(ind->argument_buffer) || !p.binding.buffer) return ReplayResult::unresolved_resource; const VkDeviceSize record_size = detail::indirect_record_size(ind->kind); if (!record_size || ind->stride < record_size || ind->stride % sizeof(std::uint32_t)) return ReplayResult::invalid_indirect_arguments; @@ -3151,7 +3056,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun return ReplayResult::invalid_indirect_arguments; if (ind->count_buffer) { const ResourceBinding* cnt = resolve(ind->count_buffer); - if (!cnt || !cnt->buffer) return local_unresolved_at(__LINE__); + if (!cnt || !cnt->buffer) return ReplayResult::unresolved_resource; if (!detail::indirect_range(*cnt, ind->count_offset, sizeof(std::uint32_t))) return ReplayResult::invalid_indirect_arguments; p.source = *cnt; @@ -3177,7 +3082,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (ind->kind == IndirectKind::dispatch && ind->pipeline) { // the pipeline and root arguments it was recorded if (!vk.bind_pipeline || !vk.push_constants || !vk.compute_pipeline) return ReplayResult::unsupported; const ComputePipeline* pipeline = vk.compute_pipeline(ind->pipeline); - if (!pipeline || !pipeline->pipeline) return local_unresolved_at(__LINE__); + if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; p.pipeline = *pipeline; } @@ -3189,10 +3094,10 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!vk.build_acceleration_structures || !vk.resolve_acceleration_structure) return ReplayResult::unsupported; p.accel_dst = vk.resolve_acceleration_structure(build->dst_va); - if (!p.accel_dst) return local_unresolved_at(__LINE__); + if (!p.accel_dst) return ReplayResult::unresolved_resource; if (build->update && build->src_va) { p.accel_src = vk.resolve_acceleration_structure(build->src_va); - if (!p.accel_src) return local_unresolved_at(__LINE__); + if (!p.accel_src) return ReplayResult::unresolved_resource; } if (build->is_tlas && build->instance_pointers && build->instance_count) { if (!vk.prepare_khr_instances || !vk.host_at || !vk.buffer_at) return ReplayResult::unsupported; @@ -3226,7 +3131,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun std::uint64_t room = 8 * info->sources.size(); VkBuffer buffer = VK_NULL_HANDLE; VkDeviceSize offset = 0; - if (!vk.buffer_at(info->dest_va, room, buffer, offset)) return local_unresolved_at(__LINE__); + if (!vk.buffer_at(info->dest_va, room, buffer, offset)) return ReplayResult::unresolved_resource; if (room < 8 * info->sources.size()) return ReplayResult::invalid_copy; } else if (info->type == 0 && vk.write_acceleration_structures_properties && vk.resolve_acceleration_structure && vk.reset_query_pool && vk.copy_query_pool_results && @@ -3265,7 +3170,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!vk.bind_pipeline || !vk.push_constants || !vk.dispatch || !vk.compute_pipeline) return ReplayResult::unsupported; const ComputePipeline* pipeline = vk.compute_pipeline(dispatch->pipeline); - if (!pipeline || !pipeline->pipeline) return local_unresolved_at(__LINE__); + if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; p.pipeline = *pipeline; } else if (const auto* draw = std::get_if(&command)) { From 0a714544d64974ad43ad26b6de533bc3b15d2c0d Mon Sep 17 00:00:00 2001 From: Khuraie <83483964+Khuraie@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:42:39 +0800 Subject: [PATCH 036/110] d3d12_xs: honour __XMemAllocationHooks__ for descriptor heaps and translate CPU handles (cherry picked from commit 355201c51e6aba95c582e2df344782b22e97bb31) --- runtime/shims/d3d12_xs.cpp | 11 + runtime/shims/d3d12_xs_device.cpp | 306 +++++++++++++++++++++++++++- runtime/shims/d3d12_xs_device.h | 17 +- runtime/shims/registry.cpp | 39 ++++ runtime/shims/shims.h | 13 ++ runtime/src/pe_loader.cpp | 7 + runtime/test/device_proxy_test.cpp | 65 ++++++ runtime/test/xs_proxy_mock_test.cpp | 140 ++++++++++++- 8 files changed, 586 insertions(+), 12 deletions(-) diff --git a/runtime/shims/d3d12_xs.cpp b/runtime/shims/d3d12_xs.cpp index 8e54c3fd56..67ac93dd0d 100644 --- a/runtime/shims/d3d12_xs.cpp +++ b/runtime/shims/d3d12_xs.cpp @@ -117,11 +117,22 @@ HRESULT WINAPI create_root_signature_deserializer(const void* data, SIZE_T size, return fn(data, size, iid, out); } +void* xmem_descriptor_heap_alloc(std::size_t byte_size, std::uint64_t attributes) { + const rt::shims::XMemAllocationHooks* hooks = rt::shims::xmem_allocation_hooks(); + return (hooks && hooks->alloc) ? hooks->alloc(byte_size, attributes) : nullptr; +} + +void xmem_descriptor_heap_free(void* ptr, std::uint64_t attributes) { + const rt::shims::XMemAllocationHooks* hooks = rt::shims::xmem_allocation_hooks(); + if (hooks && hooks->free) hooks->free(ptr, attributes); +} + // Measured shape: D3D12XboxCreateDevice(adapter, params, riid, out), where params is a 24-word block that is only // logged and not used to create the device. The struct's total size is unknown, so the log reads 24 x 32-bit words // (96 bytes) and no more. The PC D3D12CreateDevice needs a minimum feature level instead, so 12_0 is used as the // least restrictive floor; higher feature levels are still exposed by the created device. HRESULT WINAPI D3D12XboxCreateDevice(IUnknown* adapter, const void* params, const IID* riid, void** out) { + rt::d3d12_xs::set_default_descriptor_heap_allocator(&xmem_descriptor_heap_alloc, &xmem_descriptor_heap_free); constexpr auto method = "D3D12XboxCreateDevice"; using rt::d3d12_trace::result; if (!out) return result(method, E_POINTER); diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 7f7040fdd9..91e8fcf055 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -38,9 +38,12 @@ #include #include #include -#include +#include #include +#include +#include #include +#include namespace rt::d3d12_xs { namespace { @@ -86,8 +89,85 @@ struct HeapProxy { DeviceProxy* device; // keeps the Xbox-ABI device alive; GetDevice returns it void** real_vtable; std::atomic refs; + // Non-zero when the title's XMem allocation hook supplied the heap's backing address: slot 9 returns + // custom_cpu_start and device descriptor calls translate [custom_cpu_start, +custom_byte_size) to real_cpu_start. + SIZE_T custom_cpu_start; + SIZE_T custom_byte_size; + SIZE_T real_cpu_start; + DescriptorHeapBackingFree custom_free; +}; + +struct DescriptorRange { + SIZE_T custom_start; + SIZE_T custom_end; // exclusive + SIZE_T real_start; + const DeviceProxy* device; + const HeapProxy* heap; }; +// Immortal: late COM Release calls during process teardown may still unregister a heap or check the table. +std::mutex& descriptor_range_mutex() { + static auto* m = new std::mutex; + return *m; +} + +std::vector& descriptor_ranges() { + static auto* v = new std::vector; + return *v; +} + +std::atomic g_custom_range_count{0}; + +std::mutex& heap_alloc_mutex() { + static auto* m = new std::mutex; + return *m; +} + +DescriptorHeapBackingAlloc g_heap_alloc = nullptr; +DescriptorHeapBackingFree g_heap_free = nullptr; +bool g_heap_alloc_explicit = false; + +bool register_descriptor_range(const DeviceProxy* device, const HeapProxy* heap, SIZE_T custom_start, + SIZE_T byte_size, SIZE_T real_start) { + if (custom_start == 0 || byte_size == 0 || custom_start > (std::numeric_limits::max)() - byte_size) + return false; + try { + std::lock_guard lock(descriptor_range_mutex()); + descriptor_ranges().push_back({custom_start, custom_start + byte_size, real_start, device, heap}); + g_custom_range_count.store(descriptor_ranges().size(), std::memory_order_release); + return true; + } catch (const std::bad_alloc&) { + return false; + } +} + +void unregister_descriptor_range(const HeapProxy* heap) { + if (g_custom_range_count.load(std::memory_order_acquire) == 0) return; + std::lock_guard lock(descriptor_range_mutex()); + auto& ranges = descriptor_ranges(); + for (auto it = ranges.begin(); it != ranges.end();) { + if (it->heap == heap) { + it = ranges.erase(it); + } else { + ++it; + } + } + g_custom_range_count.store(ranges.size(), std::memory_order_release); +} + +D3D12_CPU_DESCRIPTOR_HANDLE translate_cpu_handle(const DeviceProxy* device, D3D12_CPU_DESCRIPTOR_HANDLE handle) { + if (handle.ptr == 0 || g_custom_range_count.load(std::memory_order_acquire) == 0) return handle; + std::lock_guard lock(descriptor_range_mutex()); + const auto& ranges = descriptor_ranges(); + for (auto it = ranges.rbegin(); it != ranges.rend(); ++it) { + if (device && it->device != device) continue; + if (handle.ptr >= it->custom_start && handle.ptr < it->custom_end) { + return D3D12_CPU_DESCRIPTOR_HANDLE{it->real_start + (handle.ptr - it->custom_start)}; + } + } + return handle; +} + std::atomic g_hits[kMaxSlots]; std::atomic g_first[kMaxSlots]; std::atomic g_beyond_warned[kMaxSlots]; @@ -134,6 +214,14 @@ const char* slot_name(unsigned slot) { case 11: return "CreateComputePipelineState (PC slot 11)"; case 14: return "CreateDescriptorHeap"; case 16: return "CreateRootSignature"; + case 17: return "CreateConstantBufferView (CPU handle translated)"; + case 18: return "CreateShaderResourceView (CPU handle translated)"; + case 19: return "CreateUnorderedAccessView (CPU handle translated)"; + case 20: return "CreateRenderTargetView (CPU handle translated)"; + case 21: return "CreateDepthStencilView (CPU handle translated)"; + case 22: return "CreateSampler (CPU handle translated)"; + case 23: return "CopyDescriptors (CPU handles translated)"; + case 24: return "CopyDescriptorsSimple (CPU handles translated)"; case 25: return "GetResourceAllocationInfo (C or PC form)"; case 26: return "GetCustomHeapProperties"; case 27: return "CreateCommittedResource (PC slot 27)"; @@ -494,11 +582,15 @@ unsigned long heap_release(HeapProxy* self) { note_heap_slot(2); const unsigned long refs = self->refs.fetch_sub(1, std::memory_order_acq_rel) - 1; if (refs == 0) { + if (self->custom_cpu_start != 0) unregister_descriptor_range(self); + void* const backing = reinterpret_cast(self->custom_cpu_start); + const DescriptorHeapBackingFree free_fn = self->custom_free; ID3D12DescriptorHeap* real = self->real; DeviceProxy* device = self->device; delete self; if (real) real->Release(); if (device) proxy_release(device); + if (backing && free_fn) free_fn(backing, kXmemDescriptorHeapAttributes); } return refs; } @@ -533,17 +625,21 @@ HRESULT heap_get_device(HeapProxy* self, const IID* riid, void** out) { // The PC methods write through the hidden return pointer (RDX) on the measured runtime; the Xbox ABI wants the // 8-byte value in RAX. Call with both conventions and keep whichever produced a value, so a runtime that really // returns in RAX also works. The extra register is harmless when the callee ignores it. -D3D12_CPU_DESCRIPTOR_HANDLE heap_get_cpu_handle(HeapProxy* self) { - note_heap_slot(9); +D3D12_CPU_DESCRIPTOR_HANDLE raw_heap_get_cpu_handle(ID3D12DescriptorHeap* real, void** real_vtable) { constexpr SIZE_T kUnset = ~static_cast(0); D3D12_CPU_DESCRIPTOR_HANDLE handle{}; handle.ptr = kUnset; using Fn = D3D12_CPU_DESCRIPTOR_HANDLE(WINAPI*)(ID3D12DescriptorHeap*, D3D12_CPU_DESCRIPTOR_HANDLE*); - const D3D12_CPU_DESCRIPTOR_HANDLE returned = - reinterpret_cast(self->real_vtable[9])(self->real, &handle); + const D3D12_CPU_DESCRIPTOR_HANDLE returned = reinterpret_cast(real_vtable[9])(real, &handle); return handle.ptr != kUnset ? handle : returned; } +D3D12_CPU_DESCRIPTOR_HANDLE heap_get_cpu_handle(HeapProxy* self) { + note_heap_slot(9); + if (self->custom_cpu_start != 0) return D3D12_CPU_DESCRIPTOR_HANDLE{self->custom_cpu_start}; + return raw_heap_get_cpu_handle(self->real, self->real_vtable); +} + D3D12_GPU_DESCRIPTOR_HANDLE heap_get_gpu_handle(HeapProxy* self) { note_heap_slot(10); constexpr UINT64 kUnset = ~static_cast(0); @@ -599,7 +695,9 @@ void** get_heap_vtable() { return vtable; } -HRESULT create_heap_proxy(ID3D12DescriptorHeap* real, DeviceProxy* device, REFIID riid, void** out) { +HRESULT create_heap_proxy(ID3D12DescriptorHeap* real, DeviceProxy* device, REFIID riid, void** out, + SIZE_T custom_cpu_start = 0, SIZE_T custom_byte_size = 0, SIZE_T real_cpu_start = 0, + DescriptorHeapBackingFree custom_free = nullptr) { if (!real || !device) return E_POINTER; if (!out) return E_POINTER; *out = nullptr; @@ -611,11 +709,23 @@ HRESULT create_heap_proxy(ID3D12DescriptorHeap* real, DeviceProxy* device, REFII proxy->device = device; proxy->real_vtable = *reinterpret_cast(real); proxy->refs.store(1, std::memory_order_relaxed); + proxy->custom_cpu_start = custom_cpu_start; + proxy->custom_byte_size = custom_byte_size; + proxy->real_cpu_start = real_cpu_start; + proxy->custom_free = custom_free; proxy_add_ref(device); // the heap keeps its Xbox-ABI device alive for GetDevice + if (custom_cpu_start != 0 && + !register_descriptor_range(device, proxy, custom_cpu_start, custom_byte_size, real_cpu_start)) { + delete proxy; + proxy_release(device); + return E_OUTOFMEMORY; + } + const HRESULT hr = heap_query_interface(proxy, &riid, out); if (FAILED(hr)) { // No reference escaped, and the caller still owns its references to `real` and `device`. + if (custom_cpu_start != 0) unregister_descriptor_range(proxy); delete proxy; proxy_release(device); return hr; @@ -1676,11 +1786,129 @@ HRESULT proxy_create_descriptor_heap(DeviceProxy* self, const D3D12_DESCRIPTOR_H if (FAILED(hr) || !created) return FAILED(hr) ? hr : E_FAIL; ID3D12DescriptorHeap* heap = static_cast(created); - hr = create_heap_proxy(heap, self, *riid, out); - if (FAILED(hr)) heap->Release(); + SIZE_T custom_cpu_start = 0; + SIZE_T custom_byte_size = 0; + SIZE_T real_cpu_start = 0; + DescriptorHeapBackingAlloc alloc_fn = nullptr; + DescriptorHeapBackingFree free_fn = nullptr; + { + std::lock_guard lock(heap_alloc_mutex()); + alloc_fn = g_heap_alloc; + free_fn = g_heap_free; + } + if (alloc_fn && desc && desc->NumDescriptors > 0) { + const UINT inc = self->real->GetDescriptorHandleIncrementSize(desc->Type); + if (inc > 0 && desc->NumDescriptors <= (std::numeric_limits::max)() / inc) { + const SIZE_T byte_size = static_cast(desc->NumDescriptors) * static_cast(inc); + void* backing = alloc_fn(byte_size, kXmemDescriptorHeapAttributes); + if (backing) { + const auto addr = reinterpret_cast(backing); + if (addr <= (std::numeric_limits::max)() - byte_size) { + custom_cpu_start = addr; + custom_byte_size = byte_size; + real_cpu_start = raw_heap_get_cpu_handle(heap, *reinterpret_cast(heap)).ptr; + } else if (free_fn) { + free_fn(backing, kXmemDescriptorHeapAttributes); + } + } + } + } + + hr = create_heap_proxy(heap, self, *riid, out, custom_cpu_start, custom_byte_size, real_cpu_start, + custom_cpu_start ? free_fn : nullptr); + if (FAILED(hr)) { + heap->Release(); + if (custom_cpu_start && free_fn) + free_fn(reinterpret_cast(custom_cpu_start), kXmemDescriptorHeapAttributes); + } return hr; } +// Device slots 17-24 write or copy descriptors using CPU handles. When a title supplies its own descriptor-heap base +// via __XMemAllocationHooks__, those handles fall in [custom_start, custom_end) and must be translated back to the +// underlying PC/Vulkan heap before forwarding. +void proxy_create_cbv(DeviceProxy* self, const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc, + D3D12_CPU_DESCRIPTOR_HANDLE dest) { + note_slot(17); + self->real->CreateConstantBufferView(desc, translate_cpu_handle(self, dest)); +} + +void proxy_create_srv(DeviceProxy* self, ID3D12Resource* resource, const D3D12_SHADER_RESOURCE_VIEW_DESC* desc, + D3D12_CPU_DESCRIPTOR_HANDLE dest) { + note_slot(18); + self->real->CreateShaderResourceView(resource, desc, translate_cpu_handle(self, dest)); +} + +void proxy_create_uav(DeviceProxy* self, ID3D12Resource* resource, ID3D12Resource* counter, + const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE dest) { + note_slot(19); + self->real->CreateUnorderedAccessView(resource, counter, desc, translate_cpu_handle(self, dest)); +} + +void proxy_create_rtv(DeviceProxy* self, ID3D12Resource* resource, const D3D12_RENDER_TARGET_VIEW_DESC* desc, + D3D12_CPU_DESCRIPTOR_HANDLE dest) { + note_slot(20); + self->real->CreateRenderTargetView(resource, desc, translate_cpu_handle(self, dest)); +} + +void proxy_create_dsv(DeviceProxy* self, ID3D12Resource* resource, const D3D12_DEPTH_STENCIL_VIEW_DESC* desc, + D3D12_CPU_DESCRIPTOR_HANDLE dest) { + note_slot(21); + self->real->CreateDepthStencilView(resource, desc, translate_cpu_handle(self, dest)); +} + +void proxy_create_sampler(DeviceProxy* self, const D3D12_SAMPLER_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE dest) { + note_slot(22); + self->real->CreateSampler(desc, translate_cpu_handle(self, dest)); +} + +void proxy_copy_descriptors(DeviceProxy* self, UINT num_dest, const D3D12_CPU_DESCRIPTOR_HANDLE* dest_starts, + const UINT* dest_sizes, UINT num_src, const D3D12_CPU_DESCRIPTOR_HANDLE* src_starts, + const UINT* src_sizes, D3D12_DESCRIPTOR_HEAP_TYPE type) { + note_slot(23); + if (g_custom_range_count.load(std::memory_order_acquire) == 0) { + self->real->CopyDescriptors(num_dest, dest_starts, dest_sizes, num_src, src_starts, src_sizes, type); + return; + } + constexpr UINT kInline = 32; + D3D12_CPU_DESCRIPTOR_HANDLE dest_inline[kInline]; + D3D12_CPU_DESCRIPTOR_HANDLE src_inline[kInline]; + std::vector dest_heap; + std::vector src_heap; + const D3D12_CPU_DESCRIPTOR_HANDLE* dest_out = dest_starts; + const D3D12_CPU_DESCRIPTOR_HANDLE* src_out = src_starts; + try { + if (dest_starts && num_dest > 0) { + D3D12_CPU_DESCRIPTOR_HANDLE* dst = dest_inline; + if (num_dest > kInline) { + dest_heap.resize(num_dest); + dst = dest_heap.data(); + } + for (UINT i = 0; i < num_dest; ++i) dst[i] = translate_cpu_handle(self, dest_starts[i]); + dest_out = dst; + } + if (src_starts && num_src > 0) { + D3D12_CPU_DESCRIPTOR_HANDLE* src = src_inline; + if (num_src > kInline) { + src_heap.resize(num_src); + src = src_heap.data(); + } + for (UINT i = 0; i < num_src; ++i) src[i] = translate_cpu_handle(self, src_starts[i]); + src_out = src; + } + } catch (const std::bad_alloc&) { + return; + } + self->real->CopyDescriptors(num_dest, dest_out, dest_sizes, num_src, src_out, src_sizes, type); +} + +void proxy_copy_descriptors_simple(DeviceProxy* self, UINT num_descriptors, D3D12_CPU_DESCRIPTOR_HANDLE dest_start, + D3D12_CPU_DESCRIPTOR_HANDLE src_start, D3D12_DESCRIPTOR_HEAP_TYPE type) { + note_slot(24); + self->real->CopyDescriptorsSimple(num_descriptors, translate_cpu_handle(self, dest_start), + translate_cpu_handle(self, src_start), type); +} + // The Xbox slot 62 takes two more words between the description and the IID: (desc, w2, w3, riid, out). Measured // on the package's XboxBvhBuilder.dll (its constructor passes w2 = w3 = 0 and IID_ID3D12PipelineState in the fourth // argument), as the prior art had recorded. Their meaning is unknown; non-zero values are logged once. @@ -1986,6 +2214,47 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64 return hr_to_u64(proxy_create_descriptor_heap( self, reinterpret_cast(a1), reinterpret_cast(a2), reinterpret_cast(a3))); + } else if constexpr (Slot == 17) { + proxy_create_cbv(self, reinterpret_cast(a1), + D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(a2)}); + return 0; + } else if constexpr (Slot == 18) { + proxy_create_srv(self, reinterpret_cast(a1), + reinterpret_cast(a2), + D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(a3)}); + return 0; + } else if constexpr (Slot == 19) { + proxy_create_uav(self, reinterpret_cast(a1), reinterpret_cast(a2), + reinterpret_cast(a3), + D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(a4)}); + return 0; + } else if constexpr (Slot == 20) { + proxy_create_rtv(self, reinterpret_cast(a1), + reinterpret_cast(a2), + D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(a3)}); + return 0; + } else if constexpr (Slot == 21) { + proxy_create_dsv(self, reinterpret_cast(a1), + reinterpret_cast(a2), + D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(a3)}); + return 0; + } else if constexpr (Slot == 22) { + proxy_create_sampler(self, reinterpret_cast(a1), + D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(a2)}); + return 0; + } else if constexpr (Slot == 23) { + proxy_copy_descriptors(self, static_cast(a1), reinterpret_cast(a2), + reinterpret_cast(a3), static_cast(a4), + reinterpret_cast(a5), + reinterpret_cast(a6), + static_cast(static_cast(a7))); + return 0; + } else if constexpr (Slot == 24) { + proxy_copy_descriptors_simple(self, static_cast(a1), + D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(a2)}, + D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(a3)}, + static_cast(static_cast(a4))); + return 0; } else if constexpr (Slot == 62) { return hr_to_u64(proxy_create_compute_pipeline_state( self, reinterpret_cast(a1), a2, a3, @@ -2229,6 +2498,25 @@ ID3D12DescriptorHeap* heap_proxy_real_heap(const void* heap) { return static_cast(heap)->real; } +void set_descriptor_heap_allocator(DescriptorHeapBackingAlloc alloc, DescriptorHeapBackingFree free) { + std::lock_guard lock(heap_alloc_mutex()); + g_heap_alloc = alloc; + g_heap_free = free; + g_heap_alloc_explicit = (alloc != nullptr || free != nullptr); +} + +void set_default_descriptor_heap_allocator(DescriptorHeapBackingAlloc alloc, DescriptorHeapBackingFree free) { + std::lock_guard lock(heap_alloc_mutex()); + if (g_heap_alloc_explicit) return; + g_heap_alloc = alloc; + g_heap_free = free; +} + +D3D12_CPU_DESCRIPTOR_HANDLE translate_cpu_descriptor_handle(const void* device, D3D12_CPU_DESCRIPTOR_HANDLE handle) { + const auto* proxy = is_device_proxy(device) ? static_cast(device) : nullptr; + return translate_cpu_handle(proxy, handle); +} + unsigned device_proxy_slot_count(const void* device) { if (!is_device_proxy(device)) return 0; return static_cast(device)->slot_count; @@ -2252,7 +2540,7 @@ ID3D12Device* device_proxy_real_device(const void* device) { } bool device_slot_overridden(unsigned slot) { - if (slot <= 2 || slot == 8 || slot == 9 || slot == 14 || slot == 25 || slot == 26 || slot == 31 || slot == 32 || slot == 34 || slot == 35 || + if (slot <= 2 || slot == 8 || slot == 9 || slot == 14 || (slot >= 17 && slot <= 24) || slot == 25 || slot == 26 || slot == 31 || slot == 32 || slot == 34 || slot == 35 || slot == 36 || slot == 45 || slot == 46 || slot == 50 || slot == 62 || slot == 67 || slot == 70 || slot == 75 || slot == 76 || slot == 133 || slot == kCreateCommittedResource3X) return true; diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index 7ee8809397..8d474dd1d5 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -99,6 +99,20 @@ void* device_proxy_primary(void* device); bool is_heap_proxy(const void* heap); ID3D12DescriptorHeap* heap_proxy_real_heap(const void* heap); +// Console D3D12 descriptor heaps allocate their backing through XMem (allocator ID 0x80 = eXALLOCAllocatorId_D3D in +// bits 16..23, object type 4 in the low 14 bits). A title that intercepts this allocation via __XMemAllocationHooks__ +// returns its own virtual address and expects GetCPUDescriptorHandleForHeapStart() to return that address. +inline constexpr std::uint64_t kXmemDescriptorHeapAttributes = (0x80ULL << 16) | 4ULL; +using DescriptorHeapBackingAlloc = void* (*)(std::size_t byte_size, std::uint64_t attributes); +using DescriptorHeapBackingFree = void (*)(void* ptr, std::uint64_t attributes); +// Installs (or clears when both are null) the backing allocator consulted by CreateDescriptorHeap (slot 14). +void set_descriptor_heap_allocator(DescriptorHeapBackingAlloc alloc, DescriptorHeapBackingFree free); +// Installs the default bridge (used by D3D12XboxCreateDevice) only when no explicit allocator has been set. +void set_default_descriptor_heap_allocator(DescriptorHeapBackingAlloc alloc, DescriptorHeapBackingFree free); +// Translates a CPU descriptor handle from a title-backed descriptor heap to the underlying PC/Vulkan heap handle. +// Returns `handle` unchanged when it does not fall inside any active custom-backed heap. +D3D12_CPU_DESCRIPTOR_HANDLE translate_cpu_descriptor_handle(const void* device, D3D12_CPU_DESCRIPTOR_HANDLE handle); + // Number of PC vtable slots the proxy forwards (detected from the interfaces the PC device supports). unsigned device_proxy_slot_count(const void* device); @@ -133,7 +147,8 @@ using ConsoleDescriptorHeapHandler = HRESULT (*)(ID3D12Device* real, const D3D12 void set_console_descriptor_heap_handler(ConsoleDescriptorHeapHandler handler); // True for slots the proxy handles itself rather than forwarding verbatim: IUnknown (0-2), 8 and 75 (queue -// proxies), 9 (allocator proxies), 14, 26 (the console's struct-return form), +// proxies), 9 (allocator proxies), 14 (descriptor heap proxy), 17-24 (CPU descriptor handle translation), 26 (the +// console's struct-return form), // 31/34/35/45/46/50 (proxies unwrapped), 32 and 36 (fence proxies), 48/73 and // 78/79/80 (the Xbox slots above, at their configured indices), 62, 67, 70, 76 and 127. Slot 10 is intentionally false: the // measured 9/10 handle conversion is on the heap proxy, and device slot 9 is CreateCommandAllocator, which the proxy diff --git a/runtime/shims/registry.cpp b/runtime/shims/registry.cpp index 6ec36e31cc..c0d826e311 100644 --- a/runtime/shims/registry.cpp +++ b/runtime/shims/registry.cpp @@ -390,6 +390,11 @@ struct BundledLoaderEntry { const BundledModuleOps* ops; }; +struct XMemHooksEntry { + const void* owner; + const XMemAllocationHooks* hooks; +}; + // Immortal: late mapped-DLL detach or atexit handlers may call GetProcAddress/FreeLibrary during process teardown. std::mutex& bundled_loader_mutex() { static auto* m = new std::mutex; @@ -401,6 +406,16 @@ std::vector& bundled_loaders() { return *v; } +std::mutex& xmem_hooks_mutex() { + static auto* m = new std::mutex; + return *m; +} + +std::vector& xmem_hooks_entries() { + static auto* v = new std::vector; + return *v; +} + std::vector snapshot_bundled_loaders() { std::lock_guard lock(bundled_loader_mutex()); return bundled_loaders(); @@ -483,6 +498,30 @@ bool owns_bundled_module_handle(void* module) { return false; } +void add_xmem_allocation_hooks(const void* owner, const XMemAllocationHooks* hooks) { + if (!owner || !hooks) return; + std::lock_guard lock(xmem_hooks_mutex()); + xmem_hooks_entries().push_back({owner, hooks}); +} + +void remove_xmem_allocation_hooks(const void* owner) { + std::lock_guard lock(xmem_hooks_mutex()); + auto& list = xmem_hooks_entries(); + for (auto it = list.begin(); it != list.end();) { + if (it->owner == owner) { + it = list.erase(it); + } else { + ++it; + } + } +} + +const XMemAllocationHooks* xmem_allocation_hooks() { + std::lock_guard lock(xmem_hooks_mutex()); + const auto& list = xmem_hooks_entries(); + return list.empty() ? nullptr : list.back().hooks; +} + Table::Table(const Entry* entries, size_t count) { for (size_t i = 0; i < count; ++i) table()[lower_ascii(entries[i].dll) + "!" + entries[i].name] = entries[i].fn; } diff --git a/runtime/shims/shims.h b/runtime/shims/shims.h index 76a7e761f8..a7fa7b9ced 100644 --- a/runtime/shims/shims.h +++ b/runtime/shims/shims.h @@ -80,6 +80,19 @@ void* load_bundled_module_w(const std::wstring& basename, uint32_t flags, bool& void* get_bundled_proc_address(void* module, const std::string& sym, bool& owns_handle); bool owns_bundled_module_handle(void* module); +// Title-exported __XMemAllocationHooks__ (GDK XMEM_ALLOCATION_HOOKS): the console runtime routes internal +// allocations (including D3D12 descriptor heaps) through these callbacks when the mapped image exports the struct. +// Registered by Loader after relocations and removed in Loader::~Loader. +using XMemAllocHookFn = void*(__stdcall*)(size_t size, uint64_t attributes); +using XMemFreeHookFn = void(__stdcall*)(void* ptr, uint64_t attributes); +struct XMemAllocationHooks { + XMemAllocHookFn alloc; + XMemFreeHookFn free; +}; +void add_xmem_allocation_hooks(const void* owner, const XMemAllocationHooks* hooks); +void remove_xmem_allocation_hooks(const void* owner); +const XMemAllocationHooks* xmem_allocation_hooks(); + // Test seam: called at the top of every unimplemented-import call with the address of rt_unimplemented's return // address slot (so a test can check stack alignment) and from inside the call (so it can walk the stack). using TestHook = void (*)(const void* return_address_slot); diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index ff0693a153..bf44cea79d 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -1094,6 +1094,7 @@ Loader::~Loader() { entry(m.base, DLL_PROCESS_DETACH, nullptr); // explicit unload; the return value is ignored } } + shims::remove_xmem_allocation_hooks(this); shims::remove_bundled_loader(this); shims::remove_module_lookup(this); for (auto* m : order_) { @@ -1498,6 +1499,12 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string& // installed here, before bind_imports can return control to the caller and before any image code can run. initialize_tls(*m); parse_exports(*m); + if (auto it = m->exports.find("__XMemAllocationHooks__"); it != m->exports.end()) { + const auto offset = static_cast(static_cast(it->second) - m->base); + if (offset <= m->size && m->size - offset >= sizeof(shims::XMemAllocationHooks)) { + shims::add_xmem_allocation_hooks(this, static_cast(it->second)); + } + } return *m; } diff --git a/runtime/test/device_proxy_test.cpp b/runtime/test/device_proxy_test.cpp index b3b3f0fc3e..6b91a7a1f8 100644 --- a/runtime/test/device_proxy_test.cpp +++ b/runtime/test/device_proxy_test.cpp @@ -577,6 +577,71 @@ int main(int argc, char** argv) { } } + // Title-exported __XMemAllocationHooks__ backing for CreateDescriptorHeap (slot 14) + CPU handle translation + // against the real WARP D3D12 runtime. + { + struct HookState { + alignas(64) std::uint8_t backing[4096]{}; + std::size_t alloc_size = 0; + std::uint64_t alloc_attr = 0; + void* freed_ptr = nullptr; + std::uint64_t freed_attr = 0; + int alloc_count = 0; + int free_count = 0; + }; + static HookState hook_state; + hook_state = {}; + struct HookCallbacks { + static void* __stdcall alloc(std::size_t size, std::uint64_t attr) { + ++hook_state.alloc_count; + hook_state.alloc_size = size; + hook_state.alloc_attr = attr; + if ((attr & 0x3FFFull) == 4 && size <= sizeof(hook_state.backing)) return hook_state.backing; + return nullptr; + } + static void __stdcall free(void* ptr, std::uint64_t attr) { + ++hook_state.free_count; + hook_state.freed_ptr = ptr; + hook_state.freed_attr = attr; + } + }; + const rt::shims::XMemAllocationHooks title_hooks{&HookCallbacks::alloc, &HookCallbacks::free}; + rt::shims::add_xmem_allocation_hooks(&title_hooks, &title_hooks); + + D3D12_DESCRIPTOR_HEAP_DESC hooked_desc{}; + hooked_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; + hooked_desc.NumDescriptors = 4; + hooked_desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; + const UINT inc = device->GetDescriptorHandleIncrementSize(hooked_desc.Type); + ComPtr hooked_heap; + hr = device->CreateDescriptorHeap(&hooked_desc, IID_PPV_ARGS(hooked_heap.GetAddressOf())); + check(SUCCEEDED(hr) && hooked_heap != nullptr, "hooked slot 14 creates a descriptor heap"); + check(hook_state.alloc_count == 1 && hook_state.alloc_size == hooked_desc.NumDescriptors * inc && + hook_state.alloc_attr == rt::d3d12_xs::kXmemDescriptorHeapAttributes, + "slot 14 invokes __XMemAllocationHooks__ with heap byte size and D3D descriptor-heap attributes"); + if (hooked_heap) { + void** hooked_vtbl = *reinterpret_cast(hooked_heap.Get()); + const auto hooked_cpu = reinterpret_cast(hooked_vtbl[9])(hooked_heap.Get()); + const auto hooked_gpu = reinterpret_cast(hooked_vtbl[10])(hooked_heap.Get()); + const auto expected_base = reinterpret_cast(hook_state.backing); + check(hooked_cpu.ptr == expected_base, + "hooked heap slot 9 returns the title-supplied CPU descriptor base"); + check(hooked_gpu.ptr != 0, "hooked heap slot 10 returns a valid GPU descriptor start"); + + // Create a CBV at slot 1 of the title-backed heap; WARP validates the translated real handle. + D3D12_CONSTANT_BUFFER_VIEW_DESC cbv{}; + cbv.BufferLocation = 0; + cbv.SizeInBytes = 256; + device->CreateConstantBufferView(&cbv, D3D12_CPU_DESCRIPTOR_HANDLE{expected_base + inc}); + check(true, "CreateConstantBufferView translates a title-backed CPU descriptor handle on WARP"); + } + hooked_heap.Reset(); + check(hook_state.free_count == 1 && hook_state.freed_ptr == hook_state.backing && + hook_state.freed_attr == rt::d3d12_xs::kXmemDescriptorHeapAttributes, + "releasing the hooked heap frees its backing through __XMemAllocationHooks__"); + rt::shims::remove_xmem_allocation_hooks(&title_hooks); + } + // Hold a reference to the PC device so the final check can prove the proxy's Release balances its own. if (real) real->AddRef(); // Drop every device child before the proxy so the PC device is not released first. diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 224030247c..8991a2114b 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -78,6 +78,9 @@ constexpr std::uint64_t kFenceHandle = 0x1000, kResourceHandle = 0x2000; // the constexpr std::uint64_t kCompletedValue = 7; // what a mock fence's slot 8 returns constexpr UINT kHeapMarker = 0x26262626; // the VisibleNodeMask a mock device's slot 26 answers constexpr UINT64 kAllocationMarker = 0x2525252500000000ull; // in the SizeInBytes a mock device's slot 25 answers +constexpr SIZE_T kMockHeapCpuStart = 0x55550000ull; +constexpr UINT64 kMockHeapGpuStart = 0x66660000ull; +constexpr UINT kMockDescriptorInc = 32; // {5d1e0c4a-2b7f-4e61-9a3d-8c4b2f1e6a70}: an interface the mock queue implements that the proxy does not model. constexpr GUID kExtraIid{0x5d1e0c4a, 0x2b7f, 0x4e61, {0x9a, 0x3d, 0x8c, 0x4b, 0x2f, 0x1e, 0x6a, 0x70}}; @@ -207,7 +210,12 @@ std::uint64_t mock_call(Mock* m, unsigned slot, const std::uint64_t* words) { if (a1) std::memcpy(&m->queue_desc, reinterpret_cast(a1), sizeof(m->queue_desc)); return static_cast(mock_create(m, Kind::queue, a2, a3)); case 9: return static_cast(mock_create(m, Kind::allocator, a2, a3)); // CreateCmdAllocator - case 14: return static_cast(mock_create(m, Kind::heap, a2, a3)); // CreateDescriptorHeap + case 14: return static_cast(mock_create(m, Kind::heap, a2, a3)); // CreateDescriptorHeap + case 15: return kMockDescriptorInc; // GetDescriptorHandleIncrementSize + case 23: // CopyDescriptors + copy_array(m, 23, a2, a1); // dest starts + copy_array(m, 24, words[4], a4); // src starts (recorded in slot 24's array) + break; case 75: return static_cast(mock_create(m, Kind::queue, a3, a4)); // CreateCommandQueue1 case 36: return static_cast(mock_create(m, Kind::fence, a3, a4)); // CreateFence case 32: // OpenSharedHandle @@ -240,6 +248,14 @@ std::uint64_t mock_call(Mock* m, unsigned slot, const std::uint64_t* words) { if (m->kind == Kind::fence && slot == 8) return kCompletedValue; // GetCompletedValue if (m->kind == Kind::queue && slot == 10) copy_array(m, slot, a2, a1); // ExecuteCommandLists(count, lists) if (m->kind == Kind::command_list && slot == 28) copy_array(m, slot, a2, a1); // SetDescriptorHeaps(count, heaps) + if (m->kind == Kind::heap && slot == 9) { + if (a1) reinterpret_cast(a1)->ptr = kMockHeapCpuStart; + return kMockHeapCpuStart; + } + if (m->kind == Kind::heap && slot == 10) { + if (a1) reinterpret_cast(a1)->ptr = kMockHeapGpuStart; + return kMockHeapGpuStart; + } return S_OK; } @@ -1165,6 +1181,125 @@ int check_tail(bool want_guarded) { return 0; } +struct HeapHookState { + void* next_ptr = nullptr; + std::size_t last_alloc_size = 0; + std::uint64_t last_alloc_attr = 0; + int alloc_calls = 0; + void* last_free_ptr = nullptr; + std::uint64_t last_free_attr = 0; + int free_calls = 0; +} g_heap_hook; + +void* mock_heap_alloc(std::size_t byte_size, std::uint64_t attributes) { + ++g_heap_hook.alloc_calls; + g_heap_hook.last_alloc_size = byte_size; + g_heap_hook.last_alloc_attr = attributes; + return g_heap_hook.next_ptr; +} + +void mock_heap_free(void* ptr, std::uint64_t attributes) { + ++g_heap_hook.free_calls; + g_heap_hook.last_free_ptr = ptr; + g_heap_hook.last_free_attr = attributes; +} + +int check_descriptor_heap_hooks() { + g_heap_hook = {}; + xs::set_descriptor_heap_allocator(&mock_heap_alloc, &mock_heap_free); + + Mock* real = new_mock(Kind::device); + real->refs = 1; + real->device_level = 9; + void* device = nullptr; + EXPECT(SUCCEEDED(xs::create_device_proxy(reinterpret_cast(real), __uuidof(ID3D12Device), &device))); + + constexpr SIZE_T kCustomBase = 0x77770000ull; + g_heap_hook.next_ptr = reinterpret_cast(kCustomBase); + D3D12_DESCRIPTOR_HEAP_DESC desc{}; + desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; + desc.NumDescriptors = 8; + desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; + const IID iid_heap = __uuidof(ID3D12DescriptorHeap); + void* heap = nullptr; + EXPECT(SUCCEEDED(hr_of(raw(device, 14, word(&desc), word(&iid_heap), word(&heap))))); + EXPECT(heap != nullptr && xs::is_heap_proxy(heap)); + EXPECT(g_heap_hook.alloc_calls == 1); + EXPECT(g_heap_hook.last_alloc_size == desc.NumDescriptors * kMockDescriptorInc); + EXPECT(g_heap_hook.last_alloc_attr == xs::kXmemDescriptorHeapAttributes); + + // Slot 9 returns the title-supplied base; slot 10 keeps the real GPU start so (gpu - cpu) delta stays exact. + EXPECT(raw(heap, 9) == kCustomBase); + EXPECT(raw(heap, 10) == kMockHeapGpuStart); + + // Public translator and device slots 17-24 remap handles in [kCustomBase, +256) to kMockHeapCpuStart + offset. + const SIZE_T off3 = 3 * kMockDescriptorInc; + const SIZE_T off7 = 7 * kMockDescriptorInc; + const SIZE_T outside = kCustomBase + desc.NumDescriptors * kMockDescriptorInc; + EXPECT(xs::translate_cpu_descriptor_handle(device, D3D12_CPU_DESCRIPTOR_HANDLE{kCustomBase + off3}).ptr == + kMockHeapCpuStart + off3); + EXPECT(xs::translate_cpu_descriptor_handle(device, D3D12_CPU_DESCRIPTOR_HANDLE{outside}).ptr == outside); + + raw(device, 17, 0x11, kCustomBase + off3); // CreateConstantBufferView + EXPECT(real->args[17][1] == kMockHeapCpuStart + off3); + raw(device, 18, 0x22, 0x33, kCustomBase + off3); // CreateShaderResourceView + EXPECT(real->args[18][2] == kMockHeapCpuStart + off3); + raw(device, 19, 0x22, 0x33, 0x44, kCustomBase + off7); // CreateUnorderedAccessView + EXPECT(real->args[19][3] == kMockHeapCpuStart + off7); + raw(device, 20, 0x22, 0x33, kCustomBase + off3); // CreateRenderTargetView + EXPECT(real->args[20][2] == kMockHeapCpuStart + off3); + raw(device, 21, 0x22, 0x33, kCustomBase + off7); // CreateDepthStencilView + EXPECT(real->args[21][2] == kMockHeapCpuStart + off7); + raw(device, 22, 0x55, kCustomBase + off3); // CreateSampler + EXPECT(real->args[22][1] == kMockHeapCpuStart + off3); + raw(device, 24, 1, kCustomBase + off7, kCustomBase + off3, 0); // CopyDescriptorsSimple + EXPECT(real->args[24][1] == kMockHeapCpuStart + off7); + EXPECT(real->args[24][2] == kMockHeapCpuStart + off3); + { + D3D12_CPU_DESCRIPTOR_HANDLE dsts[2] = {{kCustomBase + off3}, {outside}}; + D3D12_CPU_DESCRIPTOR_HANDLE srcs[2] = {{kCustomBase + off7}, {0x99990000ull}}; + UINT sizes[2] = {1, 1}; + static_cast(device)->CopyDescriptors(2, dsts, sizes, 2, srcs, sizes, + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + EXPECT(real->array[23][0] == kMockHeapCpuStart + off3 && real->array[23][1] == outside); + EXPECT(real->array[24][0] == kMockHeapCpuStart + off7 && real->array[24][1] == 0x99990000ull); + } + + // Releasing the heap unregisters the range and invokes the free callback with the same attribute word. + EXPECT(raw(heap, 2) == 0); + EXPECT(g_heap_hook.free_calls == 1); + EXPECT(g_heap_hook.last_free_ptr == reinterpret_cast(kCustomBase)); + EXPECT(g_heap_hook.last_free_attr == xs::kXmemDescriptorHeapAttributes); + EXPECT(xs::translate_cpu_descriptor_handle(device, D3D12_CPU_DESCRIPTOR_HANDLE{kCustomBase + off3}).ptr == + kCustomBase + off3); + + // Null return from the hook falls back cleanly to the PC heap's start and never calls free. + g_heap_hook.next_ptr = nullptr; + void* plain_heap = nullptr; + EXPECT(SUCCEEDED(hr_of(raw(device, 14, word(&desc), word(&iid_heap), word(&plain_heap))))); + EXPECT(plain_heap != nullptr && raw(plain_heap, 9) == kMockHeapCpuStart); + EXPECT(raw(plain_heap, 2) == 0); + EXPECT(g_heap_hook.free_calls == 1); + + // QI failure on heap proxy creation (unsupported IID) frees the hook backing immediately. + g_heap_hook.next_ptr = reinterpret_cast(kCustomBase); + void* bad_heap = nullptr; + EXPECT(hr_of(raw(device, 14, word(&desc), word(&kExtraIid), word(&bad_heap))) == E_NOINTERFACE); + EXPECT(bad_heap == nullptr && g_heap_hook.free_calls == 2); + EXPECT(g_heap_hook.last_free_ptr == reinterpret_cast(kCustomBase)); + + // OOM on HeapProxy allocation frees the hook backing and leaves no dangling range. + g_fail_news = 1; + void* oom_heap = nullptr; + EXPECT(hr_of(raw(device, 14, word(&desc), word(&iid_heap), word(&oom_heap))) == E_OUTOFMEMORY); + EXPECT(oom_heap == nullptr && g_heap_hook.free_calls == 3); + EXPECT(xs::translate_cpu_descriptor_handle(device, D3D12_CPU_DESCRIPTOR_HANDLE{kCustomBase}).ptr == kCustomBase); + + EXPECT(raw(device, 2) == 0 && real->refs == 0); + xs::set_descriptor_heap_allocator(nullptr, nullptr); + return 0; +} + // ---- Guard-region setup failures: this executable's import table, patched before the first proxy table ---- std::atomic g_injected{0}; @@ -1546,7 +1681,8 @@ int main(int argc, char** argv) { if (check_tail(true) || check_levels() || check_slot48() || check_fence1() || check_create_failures() || check_open_shared() || check_alloc_failures() || check_allocators() || check_xbox_slots() || check_console_command_list() || check_custom_heap_properties() || - check_resource_allocation_info() || check_slot70() || check_committed_resource3_x()) + check_resource_allocation_info() || check_slot70() || check_committed_resource3_x() || + check_descriptor_heap_hooks()) return 1; std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news); return 0; From 856334399de47b6f6f951a61333425dc3524585b Mon Sep 17 00:00:00 2001 From: tedin7 Date: Mon, 23 Nov 2026 16:52:16 +0100 Subject: [PATCH 037/110] d3d12_xs: device slot 25 pads a render target to whole console tiles (RT-5 stop 17) The retail title asserts when its first full-screen render targets leave more than 2 MiB of a fixed budget unused (docs/retail_boot_chain.md, #6982). The PC size is about width x height x element bytes; the console takes whole RDNA2 SW_64KB tiles. Slot 25 adds the difference per render target description and never lowers a size. Depends on #6973. (cherry picked from commit 88978553998b51e0e43733606fd67bb253c587ab) --- docs/d3d12_vulkan.md | 8 ++ runtime/shims/d3d12_xs_alloc_size.h | 117 +++++++++++++++++++++++ runtime/shims/d3d12_xs_device.cpp | 27 +++++- runtime/test/xs_proxy_mock_test.cpp | 141 +++++++++++++++++++++++++--- 4 files changed, 277 insertions(+), 16 deletions(-) create mode 100644 runtime/shims/d3d12_xs_alloc_size.h diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 3ae29163e5..6f378aebb8 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2247,6 +2247,14 @@ The trace will enumerate them. Intel Raptor Lake-S (101.7092) and RTX 5060 Laptop (621.24) hosts wrap, two 2^63 buffers to 0, and WARP on that PC still saturates. A wrapped total could make a caller allocate less than one of its resources, so the layer keeps saturating, and the test accepts a host that wraps. + Behind the Xbox-ABI proxy (device slot 25) a 2D render target of a listed colour format with one sample is padded to + whole console tiles: the size is the sum over its mips, each mip rounded up to the RDNA2 SW_64KB_D tile shape + (`runtime/src/gfx10_tiling.h`: 128 x 128 pixels for 4-byte elements, 128 x 64 for 8-byte ones), with the mips that + fit in one tile sharing one tail tile, times the array size. A 1920 x 1080 RGBA8 target is 135 tiles, 8,847,360 bytes, + where the PC answer is 8,323,072. The proxy adds the difference per description to the PC total when the console + size is larger and never lowers a size (`d3d12_xs_alloc_size.h`; `xs_proxy_mock_test`). **Assumption**: the + retail title's own sizes are not measured (#6982, stop 17), so that its allocation is these shapes and no DCC or + CMask memory is open until they are. - `GetAdapterLuid` (implemented): `VkPhysicalDeviceIDProperties::deviceLUID`, which on Windows is the DXGI adapter's LUID; `d3d12_fence_timing_test` finds it with `IDXGIFactory4::EnumAdapterByLuid` (RTX 4090, driver 621.14). A driver that reports `deviceLUIDValid = VK_FALSE` gets a zero LUID, logged. diff --git a/runtime/shims/d3d12_xs_alloc_size.h b/runtime/shims/d3d12_xs_alloc_size.h new file mode 100644 index 0000000000..8caead8d70 --- /dev/null +++ b/runtime/shims/d3d12_xs_alloc_size.h @@ -0,0 +1,117 @@ +// Console allocation sizes for render targets, for the Xbox-ABI device proxy's slot 25 (GetResourceAllocationInfo). +// +// Why: the retail title checks a fixed memory budget against what its first full-screen render targets used and asserts +// when more than 2 MiB is left over (docs/retail_boot_chain.md, stop 17, #6982). The PC device sizes a 2D render target +// from the Vulkan driver's memory requirements, which is about width x height x element bytes. The console lays a +// render target out in 64 KiB tiles (the RDNA2 SW_64KB layouts), so its allocation is the surface padded to whole +// tiles: for 4-byte elements a tile is 128 x 128 pixels, and 1080 rows take nine tile rows, not 8.4. The PC size is +// smaller by that padding, summed over every full-screen target. +// +// What this is: the tile shapes are the RDNA2 SW_64KB_D shapes of runtime/src/gfx10_tiling.h (Mesa addrlib patterns, +// validated against real textures in docs/textures.md). That a console render target uses these shapes and no extra +// (DCC, CMask) memory in its allocation size is an assumption: the title's own sizes are not measured. The rule only +// ever makes a size larger than the PC device's own answer, never smaller. +#pragma once + +#include "../src/gfx10_tiling.h" + +#include +#include + +#include +#include +#include + +namespace rt::d3d12_xs { + +constexpr UINT64 kConsoleTileBytes = 64 * 1024; // one SW_64KB tile + +// Bytes per element of the colour formats a render target takes, or 0 for any other format (the PC size then stays). +inline std::size_t render_target_element_bytes(DXGI_FORMAT format) { + switch (format) { + case DXGI_FORMAT_R8_TYPELESS: case DXGI_FORMAT_R8_UNORM: case DXGI_FORMAT_R8_UINT: + case DXGI_FORMAT_R8_SNORM: case DXGI_FORMAT_R8_SINT: case DXGI_FORMAT_A8_UNORM: + return 1; + case DXGI_FORMAT_R8G8_TYPELESS: case DXGI_FORMAT_R8G8_UNORM: case DXGI_FORMAT_R8G8_UINT: + case DXGI_FORMAT_R8G8_SNORM: case DXGI_FORMAT_R8G8_SINT: case DXGI_FORMAT_R16_TYPELESS: + case DXGI_FORMAT_R16_FLOAT: case DXGI_FORMAT_R16_UNORM: case DXGI_FORMAT_R16_UINT: + case DXGI_FORMAT_R16_SNORM: case DXGI_FORMAT_R16_SINT: case DXGI_FORMAT_B5G6R5_UNORM: + return 2; + case DXGI_FORMAT_R10G10B10A2_TYPELESS: case DXGI_FORMAT_R10G10B10A2_UNORM: + case DXGI_FORMAT_R10G10B10A2_UINT: case DXGI_FORMAT_R11G11B10_FLOAT: + case DXGI_FORMAT_R8G8B8A8_TYPELESS: case DXGI_FORMAT_R8G8B8A8_UNORM: + case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: case DXGI_FORMAT_R8G8B8A8_UINT: + case DXGI_FORMAT_R8G8B8A8_SNORM: case DXGI_FORMAT_R8G8B8A8_SINT: + case DXGI_FORMAT_B8G8R8A8_TYPELESS: case DXGI_FORMAT_B8G8R8A8_UNORM: + case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: case DXGI_FORMAT_B8G8R8X8_TYPELESS: + case DXGI_FORMAT_B8G8R8X8_UNORM: case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: + case DXGI_FORMAT_R16G16_TYPELESS: case DXGI_FORMAT_R16G16_FLOAT: case DXGI_FORMAT_R16G16_UNORM: + case DXGI_FORMAT_R16G16_UINT: case DXGI_FORMAT_R16G16_SNORM: case DXGI_FORMAT_R16G16_SINT: + case DXGI_FORMAT_R32_TYPELESS: case DXGI_FORMAT_R32_FLOAT: case DXGI_FORMAT_R32_UINT: + case DXGI_FORMAT_R32_SINT: + return 4; + case DXGI_FORMAT_R16G16B16A16_TYPELESS: case DXGI_FORMAT_R16G16B16A16_FLOAT: + case DXGI_FORMAT_R16G16B16A16_UNORM: case DXGI_FORMAT_R16G16B16A16_UINT: + case DXGI_FORMAT_R16G16B16A16_SNORM: case DXGI_FORMAT_R16G16B16A16_SINT: + case DXGI_FORMAT_R32G32_TYPELESS: case DXGI_FORMAT_R32G32_FLOAT: case DXGI_FORMAT_R32G32_UINT: + case DXGI_FORMAT_R32G32_SINT: + return 8; + case DXGI_FORMAT_R32G32B32A32_TYPELESS: case DXGI_FORMAT_R32G32B32A32_FLOAT: + case DXGI_FORMAT_R32G32B32A32_UINT: case DXGI_FORMAT_R32G32B32A32_SINT: + return 16; + default: + return 0; + } +} + +// The console's allocation size for a single-sampled 2D render target, or 0 when the rule does not apply (not a 2D +// texture, not a render target, more than one sample, an unlisted format, an empty extent, or a size that overflows). +// Mips whose extent fits in one tile share the tail tile; every other mip is padded to whole tiles. Slices add up. +inline UINT64 console_render_target_size(const D3D12_RESOURCE_DESC& desc) { + if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return 0; + if (!(desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)) return 0; + if (desc.SampleDesc.Count > 1) return 0; + const std::size_t element_bytes = render_target_element_bytes(desc.Format); + if (!element_bytes || !desc.Width || !desc.Height || !desc.DepthOrArraySize) return 0; + + const UINT mips = desc.MipLevels ? desc.MipLevels : 1; + UINT64 slice = 0; + bool tail = false; + for (UINT mip = 0; mip < mips && mip < 32; ++mip) { + const UINT64 width = std::max(desc.Width >> mip, 1); + const UINT64 height = std::max(desc.Height >> mip, 1); + leonida::gfx10::TiledSurface2D surface; + if (width > UINT32_MAX || + !leonida::gfx10::TiledSurface2D::make(leonida::gfx10::TileMode::sw_64kb_d, element_bytes, + static_cast(width), static_cast(height), + surface)) + return 0; + if (width <= surface.tile_width() && height <= surface.tile_height()) { + tail = true; + break; + } + slice += surface.tiled_size(); + } + if (tail) slice += kConsoleTileBytes; + const UINT64 slices = desc.DepthOrArraySize; + if (slice > UINT64_MAX / slices) return 0; + return slice * slices; +} + +// What GetResourceAllocationInfo adds to the PC device's answer: for every description with a console size larger than +// the PC device's size for it alone, the difference. pc_size_of(i) is the PC device's size for description i alone. +// A description the PC device refuses (UINT64_MAX) or the rule does not cover adds nothing. +template +UINT64 console_render_target_extra(const D3D12_RESOURCE_DESC* descs, UINT count, PcSizeOf pc_size_of) { + UINT64 extra = 0; + for (UINT i = 0; descs && i < count; ++i) { + const UINT64 console = console_render_target_size(descs[i]); + if (!console) continue; + const UINT64 pc = pc_size_of(i); + if (pc == UINT64_MAX || pc >= console) continue; + extra += console - pc; + } + return extra; +} + +} // namespace rt::d3d12_xs diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 91e8fcf055..b6263491cc 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -25,6 +25,7 @@ // behind the device before a presenter exists, so WaitFrameEventX returns at once with a fresh non-zero token. #include "d3d12_xs_device.h" #include "d3d12_trace.h" +#include "d3d12_xs_alloc_size.h" #include "../src/shader_library.h" // leonida::fspx_payload_from_parts for slot 67 #include @@ -2371,12 +2372,34 @@ StructReturnCall struct_return_call(std::uint64_t a0, std::uint64_t a1) { return {reinterpret_cast(a1), reinterpret_cast(a0)}; // C form: return buffer, this } +// The size the PC device saturates a total at (docs/d3d12_vulkan.md, GetResourceAllocationInfo). +constexpr UINT64 kSizeSaturated = 0xFFFFFFFFFFFF0000ull; + void* WINAPI proxy_get_resource_allocation_info(std::uint64_t a0, std::uint64_t a1, std::uint64_t visible_mask, std::uint64_t count, const D3D12_RESOURCE_DESC* descs) { note_slot(25); const StructReturnCall call = struct_return_call(a0, a1); - *static_cast(call.ret) = call.self->real->GetResourceAllocationInfo( - static_cast(visible_mask), static_cast(count), descs); + ID3D12Device* const real = call.self->real; + D3D12_RESOURCE_ALLOCATION_INFO info = + real->GetResourceAllocationInfo(static_cast(visible_mask), static_cast(count), descs); + // A render target takes whole console tiles, which the PC device's size does not (d3d12_xs_alloc_size.h). The + // total grows by what each render target lacks on its own, so the placement of the others stays as the PC lays it. + if (info.SizeInBytes != UINT64_MAX) { + const UINT64 extra = console_render_target_extra(descs, static_cast(count), [&](UINT i) { + return real->GetResourceAllocationInfo(static_cast(visible_mask), 1, &descs[i]).SizeInBytes; + }); + if (extra) { + static std::atomic logged{false}; + if (!logged.exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, + "[rt] d3d12_xs: slot 25: render target sizes padded to console tiles, +%llu B on " + "%llu B for %u description(s)\n", + static_cast(extra), + static_cast(info.SizeInBytes), static_cast(count)); + info.SizeInBytes = extra > kSizeSaturated - info.SizeInBytes ? kSizeSaturated : info.SizeInBytes + extra; + } + } + *static_cast(call.ret) = info; return call.ret; } diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 8991a2114b..b291e4beda 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -77,7 +77,6 @@ constexpr unsigned kMockSlots = 128; constexpr std::uint64_t kFenceHandle = 0x1000, kResourceHandle = 0x2000; // the handles the mock device opens constexpr std::uint64_t kCompletedValue = 7; // what a mock fence's slot 8 returns constexpr UINT kHeapMarker = 0x26262626; // the VisibleNodeMask a mock device's slot 26 answers -constexpr UINT64 kAllocationMarker = 0x2525252500000000ull; // in the SizeInBytes a mock device's slot 25 answers constexpr SIZE_T kMockHeapCpuStart = 0x55550000ull; constexpr UINT64 kMockHeapGpuStart = 0x66660000ull; constexpr UINT kMockDescriptorInc = 32; @@ -201,6 +200,27 @@ void copy_array(Mock* m, unsigned slot, std::uint64_t objects, std::uint64_t cou for (std::uint32_t i = 0; in && i < static_cast(count) && i < 4; ++i) m->array[slot][i] = in[i]; } +// The PC device's GetResourceAllocationInfo, as a driver that packs a surface with no tile padding answers it: a buffer +// its width, a texture width x height x slices x element bytes (4 for RGBA8, 8 for RGBA16F), each rounded up to +// 64 KiB, summed over the descriptions; a texture with no width is refused. The struct is written to the hidden return +// pointer (RDX of a C++ method call), which comes back in RAX. +std::uint64_t mock_allocation_info(std::uint64_t ret, std::uint64_t count, std::uint64_t descs_word) { + const auto* descs = reinterpret_cast(descs_word); + std::uint64_t total = 0; + bool refused = false; + for (std::uint32_t i = 0; descs && i < static_cast(count); ++i) { + const D3D12_RESOURCE_DESC& d = descs[i]; + std::uint64_t bytes = d.Width; + if (d.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) + bytes = d.Width * d.Height * d.DepthOrArraySize * (d.Format == DXGI_FORMAT_R16G16B16A16_FLOAT ? 8 : 4); + refused = refused || d.Width == 0; + total += (bytes + 65535) / 65536 * 65536; + } + auto* out = reinterpret_cast(ret); + *out = {refused ? UINT64_MAX : total, 65536}; + return ret; +} + // `words` are the call's first five words (a1..a5), copied into the thunk's own frame. std::uint64_t mock_call(Mock* m, unsigned slot, const std::uint64_t* words) { const std::uint64_t a1 = words[0], a2 = words[1], a3 = words[2], a4 = words[3]; @@ -222,15 +242,9 @@ std::uint64_t mock_call(Mock* m, unsigned slot, const std::uint64_t* words) { if (a1 == kFenceHandle) return static_cast(mock_create(m, Kind::fence, a2, a3)); if (a1 == kResourceHandle) return static_cast(mock_create(m, Kind::resource, a2, a3)); return static_cast(E_INVALIDARG); + case 25: return mock_allocation_info(a1, a3, a4); // GetResourceAllocationInfo (mask a2 is unused) case 34: case 35: case 46: copy_array(m, slot, a2, a1); break; // (count, objects, ...) case 45: copy_array(m, slot, a1, a3); break; // (fences, values, count, ...) - case 25: { // GetResourceAllocationInfo, the PC method: (return buffer, visible mask, count, descs) - auto* out = reinterpret_cast(a1); - if (!out) break; - out->SizeInBytes = kAllocationMarker + a3; // the count, so the test sees the arguments arrive - out->Alignment = static_cast(a2); // the visible mask - return a1; - } case 26: { // GetCustomHeapProperties, the PC method: (return buffer, node mask, heap type) auto* out = reinterpret_cast(a1); if (!out) break; @@ -1100,7 +1114,14 @@ int check_resource_allocation_info() { void* device = make_device(mock, 0, true); EXPECT(device && xs::device_slot_overridden(25)); void* const* vtable = *reinterpret_cast(device); - const D3D12_RESOURCE_DESC descs[2] = {}; + D3D12_RESOURCE_DESC descs[2] = {}; // two one-byte buffers: the mock sizes each as one 64 KiB unit + for (D3D12_RESOURCE_DESC& d : descs) { + d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + d.Width = 1; + d.Height = d.DepthOrArraySize = d.MipLevels = 1; + d.SampleDesc.Count = 1; + d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + } // The console form: the buffer for the struct in RCX, the device in RDX, then the mask, the count and the // descriptions. The buffer sits inside a pattern that must stay. @@ -1115,8 +1136,8 @@ int check_resource_allocation_info() { reinterpret_cast(vtable[25])(&padded.value, device, 1, 2, word(descs)); EXPECT(returned == word(&padded.value)); // The PC method got (a return buffer, mask, count, descriptions) once, on the device behind the proxy. - EXPECT(mock->calls[25] == 1 && mock->args[25][1] == 1 && mock->args[25][2] == 2 && mock->args[25][3] == word(descs)); - EXPECT(padded.value.SizeInBytes == kAllocationMarker + 2 && padded.value.Alignment == 1); + EXPECT(mock->calls[25] == 1 && mock->args[25][1] == 1 && mock->args[25][2] == 2); + EXPECT(padded.value.SizeInBytes == 2 * 65536 && padded.value.Alignment == 65536); for (const std::uint8_t byte : padded.before) EXPECT(byte == 0xA5); for (const std::uint8_t byte : padded.after) EXPECT(byte == 0xA5); EXPECT(xs::is_device_proxy(device) && word(xs::device_proxy_real_device(device)) == word(mock)); @@ -1124,8 +1145,8 @@ int check_resource_allocation_info() { // A PC C++ caller: the proxy in RCX and its buffer in RDX. D3D12_RESOURCE_ALLOCATION_INFO pc{}; EXPECT(raw(device, 25, word(&pc), 1, 1, word(descs)) == word(&pc)); - EXPECT(mock->calls[25] == 2 && mock->args[25][2] == 1 && mock->args[25][3] == word(descs)); - EXPECT(pc.SizeInBytes == kAllocationMarker + 1 && pc.Alignment == 1); + EXPECT(mock->calls[25] == 2 && mock->args[25][2] == 1); + EXPECT(pc.SizeInBytes == 65536 && pc.Alignment == 65536); EXPECT(release(device) == 0 && mock->refs == 0); std::printf("%s: device slot 25 with the buffer in RCX and the device in RDX reaches the PC method and writes " @@ -1159,6 +1180,97 @@ int check_slot70() { return 0; } +// ---- 7. Device slot 25, GetResourceAllocationInfo: a render target takes whole console tiles ---- + +D3D12_RESOURCE_DESC target_desc(std::uint64_t width, UINT height, DXGI_FORMAT format, UINT slices = 1) { + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + d.Width = width; + d.Height = height; + d.DepthOrArraySize = static_cast(slices); + d.MipLevels = 1; + d.Format = format; + d.SampleDesc.Count = 1; + d.Layout = static_cast(0x101); // the Xbox tiled layout word + d.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + return d; +} + +int check_render_target_sizes() { + Mock* mock = nullptr; + void* device = make_device(mock, 0, true); + EXPECT(device); + void* const* vtable = *reinterpret_cast(device); + // The retail executable's call: the buffer for the struct in RCX, the device in RDX. + using ConsoleFn = D3D12_RESOURCE_ALLOCATION_INFO*(WINAPI*)(D3D12_RESOURCE_ALLOCATION_INFO*, void*, UINT, UINT, + const D3D12_RESOURCE_DESC*); + const auto get_info = reinterpret_cast(vtable[25]); + auto ask = [&](const D3D12_RESOURCE_DESC* descs, UINT count) { + D3D12_RESOURCE_ALLOCATION_INFO info{0xDEAD, 0xBEEF}; + const bool same_buffer = get_info(&info, device, 0, count, descs) == &info; + if (!same_buffer) info.SizeInBytes = 0; + return info; + }; + + // A 1920 x 1080 RGBA8 target. A 4-byte element tile is 128 x 128 pixels: 15 tiles across, 9 down (1080 / 128 is + // 8.4), 135 x 64 KiB = 8,847,360 B. The PC device packs it as 8,294,400 B, 8,323,072 B rounded to 64 KiB. + const D3D12_RESOURCE_DESC hd = target_desc(1920, 1080, DXGI_FORMAT_R8G8B8A8_UNORM); + D3D12_RESOURCE_ALLOCATION_INFO info = ask(&hd, 1); + EXPECT(info.SizeInBytes == 8847360 && info.Alignment == 65536); + // A 3840 x 2160 RGBA16F target: an 8-byte element tile is 128 x 64, 30 across and 34 down (2160 / 64 is 33.75), + // 1020 tiles = 66,846,720 B, where the PC device says 66,387,968 B. + const D3D12_RESOURCE_DESC uhd = target_desc(3840, 2160, DXGI_FORMAT_R16G16B16A16_FLOAT); + EXPECT(ask(&uhd, 1).SizeInBytes == 66846720); + // Both in one call: the sum of the two console sizes. + const D3D12_RESOURCE_DESC both[] = {hd, uhd}; + EXPECT(ask(both, 2).SizeInBytes == 8847360 + 66846720); + // Two slices take two surfaces. + const D3D12_RESOURCE_DESC two = target_desc(1920, 1080, DXGI_FORMAT_R8G8B8A8_UNORM, 2); + EXPECT(ask(&two, 1).SizeInBytes == 2 * 8847360); + + // What is left alone: a texture that is not a render target, a buffer, a render target of a format the rule does + // not list, one the PC device refuses, and a surface that is already whole tiles (1024 x 1024 RGBA8). + D3D12_RESOURCE_DESC sampled = hd; + sampled.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + EXPECT(ask(&sampled, 1).SizeInBytes == 8323072); + D3D12_RESOURCE_DESC buffer{}; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Width = 100000; + buffer.Height = 1; + buffer.DepthOrArraySize = 1; + buffer.MipLevels = 1; + buffer.SampleDesc.Count = 1; + buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + buffer.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + EXPECT(ask(&buffer, 1).SizeInBytes == 131072); + D3D12_RESOURCE_DESC odd_format = hd; + odd_format.Format = DXGI_FORMAT_BC1_UNORM; + EXPECT(ask(&odd_format, 1).SizeInBytes == 8323072); + D3D12_RESOURCE_DESC empty = hd; + empty.Width = 0; + EXPECT(ask(&empty, 1).SizeInBytes == UINT64_MAX); + const D3D12_RESOURCE_DESC exact = target_desc(1024, 1024, DXGI_FORMAT_R8G8B8A8_UNORM); + EXPECT(ask(&exact, 1).SizeInBytes == 4194304); + // A refused description in a list refuses the list, as before. + const D3D12_RESOURCE_DESC refused[] = {hd, empty}; + EXPECT(ask(refused, 2).SizeInBytes == UINT64_MAX); + // A mip chain: 1920 x 1080 with 3 mips is mip 0 in 135 tiles, mip 1 (960 x 540) in 8 x 5 = 40 tiles and mip 2 + // (480 x 270) in 4 x 3 = 12 tiles. + D3D12_RESOURCE_DESC mips = hd; + mips.MipLevels = 3; + EXPECT(ask(&mips, 1).SizeInBytes == (135 + 40 + 12) * 65536ull); + + // The PC form (this in RCX, the buffer in RDX) answers the same sizes. + D3D12_RESOURCE_ALLOCATION_INFO pc{}; + EXPECT(raw(device, 25, word(&pc), 0, 1, word(&hd)) == word(&pc)); + EXPECT(pc.SizeInBytes == 8847360); + + EXPECT(release(device) == 0 && mock->refs == 0); + std::printf("%s: device slot 25 pads render targets to whole console tiles and leaves the other sizes as the PC " + "device gives them\n", g_label); + return 0; +} + // ---- 9. The refused tail and the guard region ---- int check_tail(bool want_guarded) { @@ -1682,7 +1794,8 @@ int main(int argc, char** argv) { check_alloc_failures() || check_allocators() || check_xbox_slots() || check_console_command_list() || check_custom_heap_properties() || check_resource_allocation_info() || check_slot70() || check_committed_resource3_x() || - check_descriptor_heap_hooks()) + check_descriptor_heap_hooks() || + check_render_target_sizes()) return 1; std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news); return 0; From 584ef36fa82ca00e19a4a03104b1b0d6ce295bd4 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Mon, 23 Nov 2026 16:56:52 +0100 Subject: [PATCH 038/110] d3d12_xs: device slot 25 gives the PC device clean resource descriptions (RT-5 stop 16) The title's descriptions carry the Xbox layout word and flag bits above the PC ones. Slot 25 now passes a copy with PC flags and a PC layout; the title's array is not written. Depends on #7078. (cherry picked from commit c7ca0f2d1c3d1aaa1dca7c01740dac076c523154) --- docs/d3d12_vulkan.md | 3 ++ runtime/shims/d3d12_xs_desc_clean.h | 34 ++++++++++++++ runtime/shims/d3d12_xs_device.cpp | 16 ++++++- runtime/test/xs_proxy_mock_test.cpp | 70 ++++++++++++++++++++++++++++- 4 files changed, 121 insertions(+), 2 deletions(-) create mode 100644 runtime/shims/d3d12_xs_desc_clean.h diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 6f378aebb8..b8c519a210 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2255,6 +2255,9 @@ The trace will enumerate them. size is larger and never lowers a size (`d3d12_xs_alloc_size.h`; `xs_proxy_mock_test`). **Assumption**: the retail title's own sizes are not measured (#6982, stop 17), so that its allocation is these shapes and no DCC or CMask memory is open until they are. + The descriptions the title passes to slot 25 carry console values (layout word `0x101`/`0x1`, flag bits above the PC + ones). The proxy gives the PC device a copy with the PC flags only and ROW_MAJOR (buffer) or UNKNOWN (texture); the + title's array is never written (`d3d12_xs_desc_clean.h`, the same cleaning as slot 76; #6982 section 3.7). - `GetAdapterLuid` (implemented): `VkPhysicalDeviceIDProperties::deviceLUID`, which on Windows is the DXGI adapter's LUID; `d3d12_fence_timing_test` finds it with `IDXGIFactory4::EnumAdapterByLuid` (RTX 4090, driver 621.14). A driver that reports `deviceLUIDValid = VK_FALSE` gets a zero LUID, logged. diff --git a/runtime/shims/d3d12_xs_desc_clean.h b/runtime/shims/d3d12_xs_desc_clean.h new file mode 100644 index 0000000000..61f49eb8b2 --- /dev/null +++ b/runtime/shims/d3d12_xs_desc_clean.h @@ -0,0 +1,34 @@ +// The PC form of a resource description the retail title builds for the console, for the Xbox-ABI device proxy. +// +// The title's D3D12_RESOURCE_DESC carries console values the PC device cannot take: the layout word is 0x101 (tiled) +// or 0x1 (row-major buffer), and the flags have bits above the PC ones set (docs/retail_boot_chain.md, #6982). Slot 76 +// replaces the layout word the same way before it forwards to CreateCommittedResource; slot 25 and the slot 127 +// stand-in need the same cleaning. The title's own description is never written: a caller gets a copy. +#pragma once + +#include +#include + +#include + +namespace rt::d3d12_xs { + +// The D3D12_RESOURCE_FLAGS bits the PC runtime defines; every other bit is a console one. +constexpr std::uint32_t kPcResourceFlagsMask = + D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE | + D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER | D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS | + D3D12_RESOURCE_FLAG_VIDEO_DECODE_REFERENCE_ONLY | D3D12_RESOURCE_FLAG_VIDEO_ENCODE_REFERENCE_ONLY | + D3D12_RESOURCE_FLAG_RAYTRACING_ACCELERATION_STRUCTURE; + +// A copy of the title's description with the PC flags only and a PC layout: ROW_MAJOR for a buffer, UNKNOWN for a +// texture (the layout the PC device picks itself). +inline D3D12_RESOURCE_DESC pc_resource_desc(const D3D12_RESOURCE_DESC& xbox) { + D3D12_RESOURCE_DESC pc = xbox; + pc.Layout = xbox.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER ? D3D12_TEXTURE_LAYOUT_ROW_MAJOR + : D3D12_TEXTURE_LAYOUT_UNKNOWN; + pc.Flags = static_cast(static_cast(xbox.Flags) & kPcResourceFlagsMask); + return pc; +} + +} // namespace rt::d3d12_xs diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index b6263491cc..43cbaf7b13 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -26,6 +26,7 @@ #include "d3d12_xs_device.h" #include "d3d12_trace.h" #include "d3d12_xs_alloc_size.h" +#include "d3d12_xs_desc_clean.h" #include "../src/shader_library.h" // leonida::fspx_payload_from_parts for slot 67 #include @@ -2380,8 +2381,21 @@ void* WINAPI proxy_get_resource_allocation_info(std::uint64_t a0, std::uint64_t note_slot(25); const StructReturnCall call = struct_return_call(a0, a1); ID3D12Device* const real = call.self->real; + // The descriptions are the console's. The PC device gets a copy with PC flags and layout; the title's array is + // read only. A copy that cannot be made answers as an invalid description. + const UINT desc_count = static_cast(count); + std::unique_ptr clean; + if (descs && desc_count) { + clean.reset(new (std::nothrow) D3D12_RESOURCE_DESC[desc_count]); + if (!clean) { + *static_cast(call.ret) = {UINT64_MAX, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT}; + return call.ret; + } + for (UINT i = 0; i < desc_count; ++i) clean[i] = pc_resource_desc(descs[i]); + descs = clean.get(); + } D3D12_RESOURCE_ALLOCATION_INFO info = - real->GetResourceAllocationInfo(static_cast(visible_mask), static_cast(count), descs); + real->GetResourceAllocationInfo(static_cast(visible_mask), desc_count, descs); // A render target takes whole console tiles, which the PC device's size does not (d3d12_xs_alloc_size.h). The // total grows by what each render target lacks on its own, so the placement of the others stays as the PC lays it. if (info.SizeInBytes != UINT64_MAX) { diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index b291e4beda..d0e837ef07 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -204,8 +204,17 @@ void copy_array(Mock* m, unsigned slot, std::uint64_t objects, std::uint64_t cou // its width, a texture width x height x slices x element bytes (4 for RGBA8, 8 for RGBA16F), each rounded up to // 64 KiB, summed over the descriptions; a texture with no width is refused. The struct is written to the hidden return // pointer (RDX of a C++ method call), which comes back in RAX. +D3D12_RESOURCE_DESC g_seen_descs[4]; // the first descriptions the mock device's slot 25 was given +std::uint32_t g_seen_desc_count = 0; +std::uint32_t g_seen_calls = 0; // slot 25 calls since the test cleared it; only the first is recorded + std::uint64_t mock_allocation_info(std::uint64_t ret, std::uint64_t count, std::uint64_t descs_word) { const auto* descs = reinterpret_cast(descs_word); + if (g_seen_calls++ == 0) { + g_seen_desc_count = static_cast(count); + for (std::uint32_t i = 0; descs && i < g_seen_desc_count && i < std::size(g_seen_descs); ++i) + g_seen_descs[i] = descs[i]; + } std::uint64_t total = 0; bool refused = false; for (std::uint32_t i = 0; descs && i < static_cast(count); ++i) { @@ -1271,6 +1280,64 @@ int check_render_target_sizes() { return 0; } + +// ---- 7b. Device slot 25 hands the PC device clean descriptions and leaves the title's array alone ---- + +int check_allocation_descriptions_cleaned() { + constexpr std::uint32_t kXboxTiledLayout = 0x101, kXboxRowMajorLayout = 0x1, kXboxFlagBits = 0x40000 | 0x20000; + constexpr D3D12_RESOURCE_FLAGS kPcFlags = + D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + Mock* mock = nullptr; + void* device = make_device(mock, 0, true); + EXPECT(device); + void* const* vtable = *reinterpret_cast(device); + using ConsoleFn = D3D12_RESOURCE_ALLOCATION_INFO*(WINAPI*)(D3D12_RESOURCE_ALLOCATION_INFO*, void*, UINT, UINT, + const D3D12_RESOURCE_DESC*); + const auto get_info = reinterpret_cast(vtable[25]); + + // A texture with the Xbox tiled layout word and Xbox bits above the PC flags, and a buffer with the row-major word. + D3D12_RESOURCE_DESC titles[2] = {target_desc(1920, 1080, DXGI_FORMAT_R8G8B8A8_UNORM), {}}; + titles[0].Flags = static_cast(kPcFlags | kXboxFlagBits); + titles[0].Layout = static_cast(kXboxTiledLayout); + titles[1].Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + titles[1].Width = 100000; + titles[1].Height = 1; + titles[1].DepthOrArraySize = 1; + titles[1].MipLevels = 1; + titles[1].SampleDesc.Count = 1; + titles[1].Layout = static_cast(kXboxRowMajorLayout); + titles[1].Flags = static_cast(kXboxFlagBits); + D3D12_RESOURCE_DESC kept[2]; + std::memcpy(kept, titles, sizeof(kept)); + + D3D12_RESOURCE_ALLOCATION_INFO info{}; + g_seen_desc_count = 0; + g_seen_calls = 0; + std::memset(g_seen_descs, 0xCC, sizeof(g_seen_descs)); + EXPECT(get_info(&info, device, 0, 2, titles) == &info); + // The PC device saw both descriptions with PC flags and a PC layout, the rest of each as the title wrote it. + EXPECT(g_seen_desc_count == 2); + EXPECT(g_seen_descs[0].Layout == D3D12_TEXTURE_LAYOUT_UNKNOWN && g_seen_descs[0].Flags == kPcFlags); + EXPECT(g_seen_descs[0].Width == 1920 && g_seen_descs[0].Height == 1080 && + g_seen_descs[0].Format == DXGI_FORMAT_R8G8B8A8_UNORM); + EXPECT(g_seen_descs[1].Layout == D3D12_TEXTURE_LAYOUT_ROW_MAJOR && g_seen_descs[1].Flags == D3D12_RESOURCE_FLAG_NONE); + EXPECT(g_seen_descs[1].Width == 100000); + // The title's array is as it was, and the size still follows the render-target flag it kept (the proxy's later + // per-target questions to the PC device are not recorded). + EXPECT(std::memcmp(kept, titles, sizeof(kept)) == 0); + EXPECT(info.SizeInBytes == 8847360 + 131072); + + // A null array with a zero count reaches the PC device as it came. + g_seen_desc_count = 99; + g_seen_calls = 0; + EXPECT(get_info(&info, device, 0, 0, nullptr) == &info && g_seen_calls == 1 && g_seen_desc_count == 0); + + EXPECT(release(device) == 0 && mock->refs == 0); + std::printf("%s: device slot 25 gives the PC device descriptions with PC flags and layout, and the title's own " + "array is not written\n", g_label); + return 0; +} + // ---- 9. The refused tail and the guard region ---- int check_tail(bool want_guarded) { @@ -1795,7 +1862,8 @@ int main(int argc, char** argv) { check_custom_heap_properties() || check_resource_allocation_info() || check_slot70() || check_committed_resource3_x() || check_descriptor_heap_hooks() || - check_render_target_sizes()) + check_render_target_sizes() || + check_allocation_descriptions_cleaned()) return 1; std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news); return 0; From f1a68eeffbf280b2e2c86f439ebd674da026d82e Mon Sep 17 00:00:00 2001 From: tedin7 Date: Mon, 23 Nov 2026 17:26:57 +0100 Subject: [PATCH 039/110] d3d12_xs: console render target sizes follow each resource's alignment, slot 56 offsets, full mip chains, rounded-up mip extents, B5G5R5A1, saturating sums (cherry picked from commit 359390833f62378a5d1d2c0f9a6cea48fccbcb53) --- docs/d3d12_vulkan.md | 22 ++-- runtime/shims/d3d12_xs_alloc_size.h | 81 +++++++++++---- runtime/shims/d3d12_xs_device.cpp | 73 +++++++++---- runtime/test/xs_proxy_mock_test.cpp | 155 +++++++++++++++++++++++++--- 4 files changed, 266 insertions(+), 65 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index b8c519a210..0e8e947aac 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2247,12 +2247,17 @@ The trace will enumerate them. Intel Raptor Lake-S (101.7092) and RTX 5060 Laptop (621.24) hosts wrap, two 2^63 buffers to 0, and WARP on that PC still saturates. A wrapped total could make a caller allocate less than one of its resources, so the layer keeps saturating, and the test accepts a host that wraps. - Behind the Xbox-ABI proxy (device slot 25) a 2D render target of a listed colour format with one sample is padded to - whole console tiles: the size is the sum over its mips, each mip rounded up to the RDNA2 SW_64KB_D tile shape - (`runtime/src/gfx10_tiling.h`: 128 x 128 pixels for 4-byte elements, 128 x 64 for 8-byte ones), with the mips that - fit in one tile sharing one tail tile, times the array size. A 1920 x 1080 RGBA8 target is 135 tiles, 8,847,360 bytes, - where the PC answer is 8,323,072. The proxy adds the difference per description to the PC total when the console - size is larger and never lowers a size (`d3d12_xs_alloc_size.h`; `xs_proxy_mock_test`). **Assumption**: the + Behind the Xbox-ABI proxy (device slots 25 and 56) a 2D render target of a listed colour format with one sample is + padded to whole console tiles: the size is the sum over its mips (MipLevels 0 is the full chain, an odd extent + rounds up), each mip rounded up to the RDNA2 SW_64KB_D tile shape (`runtime/src/gfx10_tiling.h`: 256 x 128 pixels + for 2-byte elements, 128 x 128 for 4-byte, 128 x 64 for 8-byte, 64 x 64 for 16-byte), with the first mip that fits + in half a tile's width and a whole tile's height, and the mips after it, sharing one tail tile, times the array + size. A 1920 x 1080 RGBA8 target is 135 tiles, 8,847,360 bytes, where the PC answer is 8,323,072. The proxy lays + the descriptions out as the PC device does (each at its own alignment, the total rounded up to the largest + alignment, sums saturating) with each render target at the larger of its console size and its PC size; a 4 MiB + aligned multisampled neighbour therefore keeps its place (a 1 x 1 four-sample target and a 1080p target need 16 MiB, + not 12.5). Slot 56 reports the same offsets. The PC layout stands when no description grows + (`d3d12_xs_alloc_size.h`; `xs_proxy_mock_test`). **Assumption**: the retail title's own sizes are not measured (#6982, stop 17), so that its allocation is these shapes and no DCC or CMask memory is open until they are. The descriptions the title passes to slot 25 carry console values (layout word `0x101`/`0x1`, flag bits above the PC @@ -2274,8 +2279,9 @@ The trace will enumerate them. RDX, node mask in R8 and heap type in R9: three calls right after device creation, node mask 1 and types 1, 2 and 3 (measured under `gta6rt --run` with a register probe in the slot's thunk). A PC C++ method has the device in RCX and the buffer in RDX, so the Xbox-ABI proxy takes the console form when RDX holds the proxy - (`d3d12_xs_device.cpp`; `xs_proxy_mock_test`, `device_proxy_test`). Slots 25 and 43 return structs too; the - executable has not been seen calling them yet, so the proxy still forwards them in the PC form. + (`d3d12_xs_device.cpp`; `xs_proxy_mock_test`, `device_proxy_test`). Slot 43 returns a struct too and the + proxy still forwards it in the PC form: no call of slot 43 has been seen. Slots 25 and 56 take the same form by the + same rule (reported later in the boot, #6982; not measured), as #6973 first did for slot 25. - Residency and power (D3D-33) are no-ops that still check their arguments (`d3d12_vulkan_device.cpp`, tested in `d3d12_vulkan_device_test`). Vulkan has no residency API: memory from `vkAllocateMemory` stays usable until `vkFreeMemory`, and paging under pressure is the kernel driver's job, so every pageable object is always resident. diff --git a/runtime/shims/d3d12_xs_alloc_size.h b/runtime/shims/d3d12_xs_alloc_size.h index 8caead8d70..3321c4ec88 100644 --- a/runtime/shims/d3d12_xs_alloc_size.h +++ b/runtime/shims/d3d12_xs_alloc_size.h @@ -1,4 +1,4 @@ -// Console allocation sizes for render targets, for the Xbox-ABI device proxy's slot 25 (GetResourceAllocationInfo). +// Console allocation sizes for render targets, for the Xbox-ABI device proxy's slots 25 and 56 (GetResourceAllocationInfo and GetResourceAllocationInfo1). // // Why: the retail title checks a fixed memory budget against what its first full-screen render targets used and asserts // when more than 2 MiB is left over (docs/retail_boot_chain.md, stop 17, #6982). The PC device sizes a 2D render target @@ -10,7 +10,9 @@ // What this is: the tile shapes are the RDNA2 SW_64KB_D shapes of runtime/src/gfx10_tiling.h (Mesa addrlib patterns, // validated against real textures in docs/textures.md). That a console render target uses these shapes and no extra // (DCC, CMask) memory in its allocation size is an assumption: the title's own sizes are not measured. The rule only -// ever makes a size larger than the PC device's own answer, never smaller. +// ever makes a size larger than the PC device's own answer, never smaller. The mip tail follows AMD's addrlib +// (gfx10, 2D): a mip extent is rounded up (ShiftCeil), and the tail starts at the first mip that fits in half a tile's +// width and a whole tile's height; the tail is one tile. #pragma once #include "../src/gfx10_tiling.h" @@ -19,6 +21,7 @@ #include #include +#include #include #include @@ -36,6 +39,7 @@ inline std::size_t render_target_element_bytes(DXGI_FORMAT format) { case DXGI_FORMAT_R8G8_SNORM: case DXGI_FORMAT_R8G8_SINT: case DXGI_FORMAT_R16_TYPELESS: case DXGI_FORMAT_R16_FLOAT: case DXGI_FORMAT_R16_UNORM: case DXGI_FORMAT_R16_UINT: case DXGI_FORMAT_R16_SNORM: case DXGI_FORMAT_R16_SINT: case DXGI_FORMAT_B5G6R5_UNORM: + case DXGI_FORMAT_B5G5R5A1_UNORM: return 2; case DXGI_FORMAT_R10G10B10A2_TYPELESS: case DXGI_FORMAT_R10G10B10A2_UNORM: case DXGI_FORMAT_R10G10B10A2_UINT: case DXGI_FORMAT_R11G11B10_FLOAT: @@ -66,7 +70,9 @@ inline std::size_t render_target_element_bytes(DXGI_FORMAT format) { // The console's allocation size for a single-sampled 2D render target, or 0 when the rule does not apply (not a 2D // texture, not a render target, more than one sample, an unlisted format, an empty extent, or a size that overflows). -// Mips whose extent fits in one tile share the tail tile; every other mip is padded to whole tiles. Slices add up. +// MipLevels 0 is the full chain, as on the PC device. A mip extent is rounded up. Mips before the tail are padded to +// whole tiles; the first mip that fits in half a tile's width and the whole tile height, and every mip after it, share +// one tail tile. Slices add up. inline UINT64 console_render_target_size(const D3D12_RESOURCE_DESC& desc) { if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return 0; if (!(desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)) return 0; @@ -74,19 +80,20 @@ inline UINT64 console_render_target_size(const D3D12_RESOURCE_DESC& desc) { const std::size_t element_bytes = render_target_element_bytes(desc.Format); if (!element_bytes || !desc.Width || !desc.Height || !desc.DepthOrArraySize) return 0; - const UINT mips = desc.MipLevels ? desc.MipLevels : 1; + const UINT full_chain = static_cast(std::bit_width(std::max(desc.Width, desc.Height))); + const UINT mips = desc.MipLevels ? std::min(desc.MipLevels, full_chain) : full_chain; UINT64 slice = 0; bool tail = false; - for (UINT mip = 0; mip < mips && mip < 32; ++mip) { - const UINT64 width = std::max(desc.Width >> mip, 1); - const UINT64 height = std::max(desc.Height >> mip, 1); + for (UINT mip = 0; mip < mips; ++mip) { + const UINT64 width = std::max((desc.Width + (UINT64{1} << mip) - 1) >> mip, 1); + const UINT64 height = std::max((UINT64{desc.Height} + (UINT64{1} << mip) - 1) >> mip, 1); leonida::gfx10::TiledSurface2D surface; if (width > UINT32_MAX || !leonida::gfx10::TiledSurface2D::make(leonida::gfx10::TileMode::sw_64kb_d, element_bytes, static_cast(width), static_cast(height), surface)) return 0; - if (width <= surface.tile_width() && height <= surface.tile_height()) { + if (width <= surface.tile_width() / 2 && height <= surface.tile_height()) { tail = true; break; } @@ -98,20 +105,52 @@ inline UINT64 console_render_target_size(const D3D12_RESOURCE_DESC& desc) { return slice * slices; } -// What GetResourceAllocationInfo adds to the PC device's answer: for every description with a console size larger than -// the PC device's size for it alone, the difference. pc_size_of(i) is the PC device's size for description i alone. -// A description the PC device refuses (UINT64_MAX) or the rule does not cover adds nothing. -template -UINT64 console_render_target_extra(const D3D12_RESOURCE_DESC* descs, UINT count, PcSizeOf pc_size_of) { - UINT64 extra = 0; - for (UINT i = 0; descs && i < count; ++i) { - const UINT64 console = console_render_target_size(descs[i]); - if (!console) continue; - const UINT64 pc = pc_size_of(i); - if (pc == UINT64_MAX || pc >= console) continue; - extra += console - pc; +// Rounds up to a multiple of `to`, stopping at the last multiple below 2^64 instead of wrapping (as the PC device's +// totals do). +inline UINT64 align_up_saturating(UINT64 value, UINT64 to) { + return value > UINT64_MAX - (to - 1) ? UINT64_MAX / to * to : (value + to - 1) / to * to; +} + +// Lays the descriptions out as the PC device does (one after another, each at its own alignment, the total rounded up +// to the largest alignment), with a render target's size taken as its console size when that is larger than the PC +// size. pc_one(i) is the PC device's answer for description i alone. Sizes are rounded to each description's own +// alignment, so a multisampled neighbour at 4 MiB keeps its place, and sums saturate instead of wrapping. When +// `each` is given it receives every description's offset, alignment and size. +// +// Returns false, and writes nothing, when no description is a console render target that grows, or when the PC +// device refuses one: the PC answer then stands. A true answer is never below what the PC device gave for the same +// descriptions laid out in that way. +template +bool console_placement(const D3D12_RESOURCE_DESC* descs, UINT count, PcOne pc_one, + D3D12_RESOURCE_ALLOCATION_INFO& total, D3D12_RESOURCE_ALLOCATION_INFO1* each) { + if (!descs) return false; + bool any_target = false; + for (UINT i = 0; i < count && !any_target; ++i) any_target = console_render_target_size(descs[i]) != 0; + if (!any_target) return false; + // Two passes when `each` is wanted: the first decides, the second writes, so a refusal or a list that does not + // grow leaves the array as the PC device filled it. + for (const bool write : {false, true}) { + if (write && !each) break; + bool grows = false; + UINT64 end = 0, alignment = 1; + for (UINT i = 0; i < count; ++i) { + const D3D12_RESOURCE_ALLOCATION_INFO one = pc_one(i); + if (one.SizeInBytes == UINT64_MAX || !one.Alignment) return false; + UINT64 size = one.SizeInBytes; + const UINT64 console = console_render_target_size(descs[i]); + if (console > size) { + size = align_up_saturating(console, one.Alignment); + grows = true; + } + const UINT64 offset = align_up_saturating(end, one.Alignment); + if (write) each[i] = {offset, one.Alignment, size}; + end = size > UINT64_MAX - offset ? UINT64_MAX : offset + size; + alignment = std::max(alignment, one.Alignment); + } + if (!grows) return false; + total = {align_up_saturating(end, alignment), alignment}; } - return extra; + return true; } } // namespace rt::d3d12_xs diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 43cbaf7b13..cd3953fa61 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -33,6 +33,7 @@ #include #include +#include #include #include #include @@ -237,6 +238,7 @@ const char* slot_name(unsigned slot) { case 46: return "SetResidencyPriority (proxies unwrapped)"; case 48: return "Xbox CreateCommandQueueX -> queue proxy"; case 50: return "EnqueueMakeResident (proxies unwrapped)"; + case 56: return "GetResourceAllocationInfo1 (C or PC form)"; case 62: return "Xbox CreateComputePipelineState"; case 67: return "Xbox DeserializeComputePipelineStateX"; case 70: return "Xbox shader-resource view from raw words"; @@ -2373,8 +2375,24 @@ StructReturnCall struct_return_call(std::uint64_t a0, std::uint64_t a1) { return {reinterpret_cast(a1), reinterpret_cast(a0)}; // C form: return buffer, this } -// The size the PC device saturates a total at (docs/d3d12_vulkan.md, GetResourceAllocationInfo). -constexpr UINT64 kSizeSaturated = 0xFFFFFFFFFFFF0000ull; +// The console size of a list of descriptions (d3d12_xs_alloc_size.h): the PC device's answer with every console render +// target laid out at its console size, each at its own alignment. `info` is the PC answer and is replaced only when +// the console layout is larger. `each` is the per-description array of slot 56, or null. +void apply_console_placement(const D3D12_RESOURCE_DESC* descs, UINT count, D3D12_RESOURCE_ALLOCATION_INFO& info, + D3D12_RESOURCE_ALLOCATION_INFO1* each, + const std::function& pc_one, unsigned slot) { + if (info.SizeInBytes == UINT64_MAX) return; + D3D12_RESOURCE_ALLOCATION_INFO console{}; + if (!console_placement(descs, count, pc_one, console, each)) return; + static std::atomic logged{false}; + if (!logged.exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, + "[rt] d3d12_xs: slot %u: render targets sized as console tiles, %llu B for %llu B on %u " + "description(s)\n", + slot, static_cast(console.SizeInBytes), + static_cast(info.SizeInBytes), static_cast(count)); + if (console.SizeInBytes >= info.SizeInBytes) info = console; +} void* WINAPI proxy_get_resource_allocation_info(std::uint64_t a0, std::uint64_t a1, std::uint64_t visible_mask, std::uint64_t count, const D3D12_RESOURCE_DESC* descs) { @@ -2394,34 +2412,45 @@ void* WINAPI proxy_get_resource_allocation_info(std::uint64_t a0, std::uint64_t for (UINT i = 0; i < desc_count; ++i) clean[i] = pc_resource_desc(descs[i]); descs = clean.get(); } - D3D12_RESOURCE_ALLOCATION_INFO info = - real->GetResourceAllocationInfo(static_cast(visible_mask), desc_count, descs); - // A render target takes whole console tiles, which the PC device's size does not (d3d12_xs_alloc_size.h). The - // total grows by what each render target lacks on its own, so the placement of the others stays as the PC lays it. - if (info.SizeInBytes != UINT64_MAX) { - const UINT64 extra = console_render_target_extra(descs, static_cast(count), [&](UINT i) { - return real->GetResourceAllocationInfo(static_cast(visible_mask), 1, &descs[i]).SizeInBytes; - }); - if (extra) { - static std::atomic logged{false}; - if (!logged.exchange(true, std::memory_order_relaxed)) - std::fprintf(stderr, - "[rt] d3d12_xs: slot 25: render target sizes padded to console tiles, +%llu B on " - "%llu B for %u description(s)\n", - static_cast(extra), - static_cast(info.SizeInBytes), static_cast(count)); - info.SizeInBytes = extra > kSizeSaturated - info.SizeInBytes ? kSizeSaturated : info.SizeInBytes + extra; - } - } + const UINT mask = static_cast(visible_mask); + D3D12_RESOURCE_ALLOCATION_INFO info = real->GetResourceAllocationInfo(mask, desc_count, descs); + apply_console_placement(descs, desc_count, info, nullptr, + [&](UINT i) { return real->GetResourceAllocationInfo(mask, 1, &descs[i]); }, 25); *static_cast(call.ret) = info; return call.ret; } +// Slot 56, ID3D12Device4::GetResourceAllocationInfo1: the same answer, and the per-description offsets follow the +// padded sizes, so a title that places its resources at those offsets does not overlap them. The call is forwarded +// as it came; the console layout then replaces the total and the offsets. +void* WINAPI proxy_get_resource_allocation_info1(std::uint64_t a0, std::uint64_t a1, std::uint64_t visible_mask, + std::uint64_t count, const D3D12_RESOURCE_DESC* descs, + D3D12_RESOURCE_ALLOCATION_INFO1* each) { + const StructReturnCall call = struct_return_call(a0, a1); + DeviceProxy* const self = call.self; + note_slot(56); + if (56 >= self->slot_count) { + return reinterpret_cast(hr_to_u64(refuse_beyond_device(56, self->slot_count))); + } + using Fn = void*(WINAPI*)(void*, void*, UINT, UINT, const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_ALLOCATION_INFO1*); + const UINT n = static_cast(count); + void* const returned = reinterpret_cast(self->real_vtable[56])( + self->real, call.ret, static_cast(visible_mask), n, descs, each); + if (each) { + auto& info = *static_cast(call.ret); + apply_console_placement(descs, n, info, each, [&](UINT i) { + return D3D12_RESOURCE_ALLOCATION_INFO{each[i].SizeInBytes, each[i].Alignment}; + }, 56); + } + return returned; +} + void** get_vtable() { static void** vtable = [] { static void* storage[kMaxSlots]; fill_vtable(storage, std::make_index_sequence{}); storage[25] = reinterpret_cast(&proxy_get_resource_allocation_info); + storage[56] = reinterpret_cast(&proxy_get_resource_allocation_info1); return storage; }(); return vtable; @@ -2578,7 +2607,7 @@ ID3D12Device* device_proxy_real_device(const void* device) { bool device_slot_overridden(unsigned slot) { if (slot <= 2 || slot == 8 || slot == 9 || slot == 14 || (slot >= 17 && slot <= 24) || slot == 25 || slot == 26 || slot == 31 || slot == 32 || slot == 34 || slot == 35 || - slot == 36 || slot == 45 || slot == 46 || slot == 50 || slot == 62 || slot == 67 || + slot == 36 || slot == 45 || slot == 46 || slot == 50 || slot == 56 || slot == 62 || slot == 67 || slot == 70 || slot == 75 || slot == 76 || slot == 133 || slot == kCreateCommittedResource3X) return true; const XboxDeviceSlotRoutes& routes = xbox_device_slot_routes(); diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index d0e837ef07..6bae19ac75 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -16,6 +16,8 @@ #include #include +#include + #include #include @@ -200,33 +202,55 @@ void copy_array(Mock* m, unsigned slot, std::uint64_t objects, std::uint64_t cou for (std::uint32_t i = 0; in && i < static_cast(count) && i < 4; ++i) m->array[slot][i] = in[i]; } -// The PC device's GetResourceAllocationInfo, as a driver that packs a surface with no tile padding answers it: a buffer -// its width, a texture width x height x slices x element bytes (4 for RGBA8, 8 for RGBA16F), each rounded up to -// 64 KiB, summed over the descriptions; a texture with no width is refused. The struct is written to the hidden return -// pointer (RDX of a C++ method call), which comes back in RAX. +// GetResourceAllocationInfo as a PC driver without console tile padding answers it. A buffer is its width, a texture +// width x height x slices x element bytes (2 for B5G5R5A1, 4 for RGBA8, 8 for RGBA16F, 16 for RGBA32F; mips are not +// counted, and one resource is at most 4 GiB, the way a driver caps an allocation), each rounded up to the +// resource's alignment: 64 KiB, or 4 MiB with more than one sample. A texture with no width is refused. Resources are +// laid out one after another, each at its own alignment, and the total is rounded up to the largest alignment, as the +// Vulkan layer's place() does. The struct is written to the hidden return pointer (RDX of a C++ method call), which +// comes back in RAX. `each` (slot 56) gets every resource's offset, alignment and size. +std::uint64_t mock_align(std::uint64_t value, std::uint64_t to) { + return value > UINT64_MAX - (to - 1) ? UINT64_MAX / to * to : (value + to - 1) / to * to; +} + +D3D12_RESOURCE_ALLOCATION_INFO mock_one_allocation(const D3D12_RESOURCE_DESC& d) { + if (d.Width == 0) return {UINT64_MAX, 65536}; + if (d.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) return {mock_align(d.Width, 65536), 65536}; + std::uint64_t element = 4; + if (d.Format == DXGI_FORMAT_B5G5R5A1_UNORM) element = 2; + if (d.Format == DXGI_FORMAT_R16G16B16A16_FLOAT) element = 8; + if (d.Format == DXGI_FORMAT_R32G32B32A32_FLOAT) element = 16; + const std::uint64_t samples = d.SampleDesc.Count ? d.SampleDesc.Count : 1; + const std::uint64_t alignment = samples > 1 ? 4194304 : 65536; + const std::uint64_t bytes = std::min( + d.Width * d.Height * d.DepthOrArraySize * element * samples, std::uint64_t{4} << 30); + return {mock_align(bytes, alignment), alignment}; +} + D3D12_RESOURCE_DESC g_seen_descs[4]; // the first descriptions the mock device's slot 25 was given std::uint32_t g_seen_desc_count = 0; std::uint32_t g_seen_calls = 0; // slot 25 calls since the test cleared it; only the first is recorded -std::uint64_t mock_allocation_info(std::uint64_t ret, std::uint64_t count, std::uint64_t descs_word) { +std::uint64_t mock_allocation_info(std::uint64_t ret, std::uint64_t count, std::uint64_t descs_word, + D3D12_RESOURCE_ALLOCATION_INFO1* each = nullptr) { const auto* descs = reinterpret_cast(descs_word); if (g_seen_calls++ == 0) { g_seen_desc_count = static_cast(count); for (std::uint32_t i = 0; descs && i < g_seen_desc_count && i < std::size(g_seen_descs); ++i) g_seen_descs[i] = descs[i]; } - std::uint64_t total = 0; + D3D12_RESOURCE_ALLOCATION_INFO total{0, 1}; bool refused = false; for (std::uint32_t i = 0; descs && i < static_cast(count); ++i) { - const D3D12_RESOURCE_DESC& d = descs[i]; - std::uint64_t bytes = d.Width; - if (d.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) - bytes = d.Width * d.Height * d.DepthOrArraySize * (d.Format == DXGI_FORMAT_R16G16B16A16_FLOAT ? 8 : 4); - refused = refused || d.Width == 0; - total += (bytes + 65535) / 65536 * 65536; + const D3D12_RESOURCE_ALLOCATION_INFO one = mock_one_allocation(descs[i]); + refused = refused || one.SizeInBytes == UINT64_MAX; + const std::uint64_t offset = mock_align(total.SizeInBytes, one.Alignment); + if (each) each[i] = {offset, one.Alignment, one.SizeInBytes}; + total.SizeInBytes = one.SizeInBytes > UINT64_MAX - offset ? UINT64_MAX : offset + one.SizeInBytes; + total.Alignment = std::max(total.Alignment, one.Alignment); } auto* out = reinterpret_cast(ret); - *out = {refused ? UINT64_MAX : total, 65536}; + *out = {refused ? UINT64_MAX : mock_align(total.SizeInBytes, total.Alignment), total.Alignment}; return ret; } @@ -252,6 +276,8 @@ std::uint64_t mock_call(Mock* m, unsigned slot, const std::uint64_t* words) { if (a1 == kResourceHandle) return static_cast(mock_create(m, Kind::resource, a2, a3)); return static_cast(E_INVALIDARG); case 25: return mock_allocation_info(a1, a3, a4); // GetResourceAllocationInfo (mask a2 is unused) + case 56: // GetResourceAllocationInfo1: (return buffer, mask, count, descs, per-description array) + return mock_allocation_info(a1, a3, a4, reinterpret_cast(words[4])); case 34: case 35: case 46: copy_array(m, slot, a2, a1); break; // (count, objects, ...) case 45: copy_array(m, slot, a1, a3); break; // (fences, values, count, ...) case 26: { // GetCustomHeapProperties, the PC method: (return buffer, node mask, heap type) @@ -1280,6 +1306,106 @@ int check_render_target_sizes() { return 0; } +// ---- 11. Console render target layout: alignment, per-description offsets, mips, formats, overflow ---- + +int check_render_target_layout() { + Mock* mock = nullptr; + void* device = make_device(mock, 9, true); + EXPECT(device); + void* const* vtable = *reinterpret_cast(device); + // The retail executable's calls: the buffer for the struct in RCX, the device in RDX. + using InfoFn = D3D12_RESOURCE_ALLOCATION_INFO*(WINAPI*)(D3D12_RESOURCE_ALLOCATION_INFO*, void*, UINT, UINT, + const D3D12_RESOURCE_DESC*); + using Info1Fn = D3D12_RESOURCE_ALLOCATION_INFO*(WINAPI*)(D3D12_RESOURCE_ALLOCATION_INFO*, void*, UINT, UINT, + const D3D12_RESOURCE_DESC*, + D3D12_RESOURCE_ALLOCATION_INFO1*); + const auto get_info = reinterpret_cast(vtable[25]); + const auto get_info1 = reinterpret_cast(vtable[56]); + auto ask = [&](const D3D12_RESOURCE_DESC* descs, UINT count) { + D3D12_RESOURCE_ALLOCATION_INFO info{0xDEAD, 0xBEEF}; + if (get_info(&info, device, 0, count, descs) != &info) info = {0, 0}; + return info; + }; + auto ask_one = [&](const D3D12_RESOURCE_DESC& d) { return ask(&d, 1); }; + auto target = [](std::uint64_t w, UINT h, DXGI_FORMAT f, UINT slices, UINT mips) { + D3D12_RESOURCE_DESC d = target_desc(w, h, f, slices); + d.MipLevels = static_cast(mips); + return d; + }; + + // A four-sample 1 x 1 target is 4 MiB at 4 MiB alignment. Next to a 1080p target that grows to 8,847,360 B, the + // two need 4 MiB + 8,847,360 B = 13,041,664 B placed, and the total is a whole number of 4 MiB: 16 MiB, in + // either order. (The PC device says 12 MiB for them; adding the 512 KiB the padding takes would say 12.5 MiB.) + const D3D12_RESOURCE_DESC hd = target_desc(1920, 1080, DXGI_FORMAT_R8G8B8A8_UNORM); + D3D12_RESOURCE_DESC msaa = target_desc(1, 1, DXGI_FORMAT_R8G8B8A8_UNORM); + msaa.SampleDesc.Count = 4; + const D3D12_RESOURCE_DESC msaa_first[] = {msaa, hd}; + const D3D12_RESOURCE_DESC msaa_last[] = {hd, msaa}; + D3D12_RESOURCE_ALLOCATION_INFO info = ask(msaa_first, 2); + EXPECT(info.SizeInBytes == 16777216 && info.Alignment == 4194304); + info = ask(msaa_last, 2); + EXPECT(info.SizeInBytes == 16777216 && info.Alignment == 4194304); + EXPECT(ask(&msaa, 1).SizeInBytes == 4194304); // multisampled targets are left as the PC device sizes them + + // GetResourceAllocationInfo1: the offsets follow the padded sizes, in the console form and the PC form. + const D3D12_RESOURCE_DESC two[] = {hd, hd}; + D3D12_RESOURCE_ALLOCATION_INFO1 each[2]{}; + D3D12_RESOURCE_ALLOCATION_INFO total{}; + EXPECT(get_info1(&total, device, 0, 2, two, each) == &total); + EXPECT(total.SizeInBytes == 17694720 && total.Alignment == 65536); + EXPECT(each[0].Offset == 0 && each[0].SizeInBytes == 8847360 && each[0].Alignment == 65536); + EXPECT(each[1].Offset == 8847360 && each[1].SizeInBytes == 8847360 && each[1].Alignment == 65536); + D3D12_RESOURCE_ALLOCATION_INFO1 mixed[2]{}; + D3D12_RESOURCE_ALLOCATION_INFO pc{}; + EXPECT(raw(device, 56, word(&pc), 0, 2, word(msaa_first), word(mixed)) == word(&pc)); + EXPECT(pc.SizeInBytes == 16777216 && pc.Alignment == 4194304); + EXPECT(mixed[0].Offset == 0 && mixed[0].SizeInBytes == 4194304 && mixed[0].Alignment == 4194304); + EXPECT(mixed[1].Offset == 4194304 && mixed[1].SizeInBytes == 8847360 && mixed[1].Alignment == 65536); + // Nothing to pad: the PC device's answer stands, per-description array included. + D3D12_RESOURCE_DESC buffer{}; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Width = 100000; + buffer.Height = 1; + buffer.DepthOrArraySize = 1; + buffer.MipLevels = 1; + buffer.SampleDesc.Count = 1; + buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + const D3D12_RESOURCE_DESC buffers[] = {buffer, buffer}; + D3D12_RESOURCE_ALLOCATION_INFO1 plain[2]{}; + EXPECT(get_info1(&total, device, 0, 2, buffers, plain) == &total); + EXPECT(total.SizeInBytes == 262144 && plain[1].Offset == 131072 && plain[1].SizeInBytes == 131072); + + // Mips: 0 is the full chain. 256 x 128 RGBA8 takes two tiles for mip 0, one for mip 1 (128 x 64 is wider than half a + // tile) and one tail tile for the rest. + EXPECT(ask_one(target(256, 128, DXGI_FORMAT_R8G8B8A8_UNORM, 1, 0)).SizeInBytes == + 4 * 65536ull); + // 128 x 32 with two mips and two slices: mip 0 is a whole tile, mip 1 (64 x 16) is the tail tile, per slice. + EXPECT(ask_one(target(128, 32, DXGI_FORMAT_R8G8B8A8_UNORM, 2, 2)).SizeInBytes == + 4 * 65536ull); + // 257 x 32 with two mips: mip 0 is 3 tiles across, mip 1 is 129 x 16 (an odd extent rounds up): 2 tiles. + EXPECT(ask_one(target(257, 32, DXGI_FORMAT_R8G8B8A8_UNORM, 1, 2)).SizeInBytes == + 5 * 65536ull); + // 2-byte B5G5R5A1 is a 256 x 128 tile: 257 x 64 takes two. + EXPECT(ask_one(target(257, 64, DXGI_FORMAT_B5G5R5A1_UNORM, 1, 1)).SizeInBytes == + 2 * 65536ull); + // 16-byte RGBA32F is a 64 x 64 tile: 65 x 32 takes two. + EXPECT(ask_one(target(65, 32, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 1)).SizeInBytes == + 2 * 65536ull); + + // Sums saturate where the PC device's do. A 2^26 x 2^26 RGBA32F target of 200 slices is 200 x 2^56 B (the PC mock + // caps it at 4 GiB); two of them are past 2^64. + const D3D12_RESOURCE_DESC huge = target(1ull << 26, 1u << 26, DXGI_FORMAT_R32G32B32A32_FLOAT, 200, 1); + EXPECT(ask(&huge, 1).SizeInBytes == 200ull << 56); + const D3D12_RESOURCE_DESC huge_two[] = {huge, huge}; + info = ask(huge_two, 2); + EXPECT(info.SizeInBytes == 0xFFFFFFFFFFFF0000ull && info.Alignment == 65536); + + EXPECT(release(device) == 0 && mock->refs == 0); + std::printf("%s: render targets are laid out at their own alignments, with per-description offsets, mip chains " + "and saturating sums\n", g_label); + return 0; +} + // ---- 7b. Device slot 25 hands the PC device clean descriptions and leaves the title's array alone ---- @@ -1863,7 +1989,8 @@ int main(int argc, char** argv) { check_resource_allocation_info() || check_slot70() || check_committed_resource3_x() || check_descriptor_heap_hooks() || check_render_target_sizes() || - check_allocation_descriptions_cleaned()) + check_allocation_descriptions_cleaned() || + check_render_target_layout()) return 1; std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news); return 0; From 35e687f2ac1eeca764deffc307c6a076c9a44230 Mon Sep 17 00:00:00 2001 From: Jackson <37029272+NinJackson@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:16:28 -0500 Subject: [PATCH 040/110] d3d12_xs: committed resources lease their size through the title's XMem hooks (RT-5 stop 17) On the console a committed resource's memory is allocated with XMemAlloc, so it goes through the title's __XMemAllocationHooks__. The retail title budgets its first full-screen render targets with a per-thread hook that bump-allocates out of a range it reserved and asserts that less than 2 MiB is left; PC resources never allocated through the hooks, so the assert always fired. Slots 76 and 127 now allocate the slot-25 size of each resource through the hooks, held by the resource with SetPrivateDataInterface and freed when it is destroyed. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit ae322dafc560f07f839be457e3ba6b68bcbf83c8) Adapted to main by Mumogg: the lease size is the later form of this series (d61755d4d, a render target's console tile size, else the PC size), since console_render_target_extra is gone after 359390833. --- docs/d3d12_vulkan.md | 7 ++ runtime/shims/d3d12_xs_device.cpp | 135 ++++++++++++++++++++++++++-- runtime/test/xs_proxy_mock_test.cpp | 104 ++++++++++++++++++++- 3 files changed, 235 insertions(+), 11 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 0e8e947aac..b39a558923 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2263,6 +2263,13 @@ The trace will enumerate them. The descriptions the title passes to slot 25 carry console values (layout word `0x101`/`0x1`, flag bits above the PC ones). The proxy gives the PC device a copy with the PC flags only and ROW_MAJOR (buffer) or UNKNOWN (texture); the title's array is never written (`d3d12_xs_desc_clean.h`, the same cleaning as slot 76; #6982 section 3.7). + A committed resource made through slots 76 and 127 also allocates that size through the title's + `__XMemAllocationHooks__`, as the console runtime's `XMemAlloc` for the resource does, and frees it when the + resource is destroyed (a lease kept with `SetPrivateDataInterface`; the bytes are not used). The retail title + budgets its first full-screen render targets with such a hook: it bump-allocates the allocations whose XALLOC + page-size field is 2 out of a range it reserved and asserts that less than 2 MiB is left (RT-5 stop 17). The + lease's attribute word (allocator ID 0x80, page-size field 2, object type 0) is an **assumption**; the measured + hook reads only the page-size field. - `GetAdapterLuid` (implemented): `VkPhysicalDeviceIDProperties::deviceLUID`, which on Windows is the DXGI adapter's LUID; `d3d12_fence_timing_test` finds it with `IDXGIFactory4::EnumAdapterByLuid` (RTX 4090, driver 621.14). A driver that reports `deviceLUIDValid = VK_FALSE` gets a zero LUID, logged. diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index cd3953fa61..4662577459 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -2013,6 +2013,97 @@ HRESULT proxy_create_compute_pipeline_from_native_code(DeviceProxy* self, const return hr; } +// ---- Committed resources take their memory through the title's XMem hooks (RT-5 stop 17) ---- +// On the console the D3D runtime allocates a committed resource's memory with XMemAlloc, so the allocation goes +// through the title's __XMemAllocationHooks__. Around its first full-screen render targets (slot 127) the retail title +// registers a per-thread matcher that bump-allocates out of a range it reserved, taking any allocation whose XALLOC +// page-size field (bits 14..15) is 2, and afterwards asserts that less than 2 MiB of the range is left. Resources +// created on the PC never allocated through the hooks, so the whole range was left and the assert fired. Each committed +// resource made by slots 76 and 127 therefore allocates its size through the hooks as a lease: the resource holds it +// (SetPrivateDataInterface) and the hooks' free runs when the resource is destroyed. The bytes are not used for the +// resource; the PC device owns its memory. The size is the one slot 25 answers for the same description +// (lease_size), the figure the title budgets with. +// HYPOTHESIS: the attribute word, allocator ID 0x80 (eXALLOCAllocatorId_D3D) with page-size field 2 and object type 0. +// Of it the measured matcher reads only the page-size field; a title hook that matches on other fields may not take +// these leases for the console's allocations. +inline constexpr std::uint64_t kXmemCommittedResourceAttributes = (0x80ULL << 16) | (2ULL << 14); + +// {6c1f3a52-8d47-4e0b-9b1e-2f7a5c3d9e61}: the private-data entry a committed resource keeps its lease under. +constexpr GUID kTitleMemoryLeaseGuid{0x6c1f3a52, 0x8d47, 0x4e0b, {0x9b, 0x1e, 0x2f, 0x7a, 0x5c, 0x3d, 0x9e, 0x61}}; + +// The console allocation for one clean description: a listed render-target shape's whole tiles, else the PC size. +UINT64 lease_size(ID3D12Device* real, const D3D12_RESOURCE_DESC& clean_desc) { + if (const UINT64 tiles = console_render_target_size(clean_desc)) return tiles; + return real->GetResourceAllocationInfo(0, 1, &clean_desc).SizeInBytes; +} + +// One reference is held by the resource; the last Release gives the memory back through the hooks' free. +class TitleMemoryLease final : public IUnknown { +public: + TitleMemoryLease(void* memory, DescriptorHeapBackingFree free_fn) : memory_(memory), free_(free_fn) {} + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { + if (!out) return E_POINTER; + if (!IsEqualIID(riid, __uuidof(IUnknown))) { + *out = nullptr; + return E_NOINTERFACE; + } + AddRef(); + *out = this; + return S_OK; + } + ULONG STDMETHODCALLTYPE AddRef() override { return refs_.fetch_add(1, std::memory_order_relaxed) + 1; } + ULONG STDMETHODCALLTYPE Release() override { + const ULONG left = refs_.fetch_sub(1, std::memory_order_acq_rel) - 1; + if (left == 0) { + if (free_) free_(memory_, kXmemCommittedResourceAttributes); + delete this; + } + return left; + } + +private: + std::atomic refs_{1}; + void* memory_; + DescriptorHeapBackingFree free_; +}; + +// `created` is the object a slot 76/127 creation returned (any interface of the resource). Nothing happens without +// installed hooks, for a size the PC device refuses, or when the hooks return null; creation never fails here. +void lease_title_resource_memory(DeviceProxy* self, void* created, const D3D12_RESOURCE_DESC& clean_desc) { + if (!created) return; + DescriptorHeapBackingAlloc alloc_fn = nullptr; + DescriptorHeapBackingFree free_fn = nullptr; + { + std::lock_guard lock(heap_alloc_mutex()); + alloc_fn = g_heap_alloc; + free_fn = g_heap_free; + } + if (!alloc_fn) return; + const UINT64 size = lease_size(self->real, clean_desc); + if (size == 0 || size == UINT64_MAX || size > (std::numeric_limits::max)()) return; + void* const memory = alloc_fn(static_cast(size), kXmemCommittedResourceAttributes); + if (!memory) return; + ID3D12Object* object = nullptr; + auto* const lease = new (std::nothrow) TitleMemoryLease(memory, free_fn); + if (!lease || FAILED(static_cast(created)->QueryInterface(__uuidof(ID3D12Object), + reinterpret_cast(&object)))) { + if (lease) + lease->Release(); // frees the memory + else if (free_fn) + free_fn(memory, kXmemCommittedResourceAttributes); + return; + } + object->SetPrivateDataInterface(kTitleMemoryLeaseGuid, lease); // the resource's reference + object->Release(); + lease->Release(); // ours; from here the resource's reference is the only one + static std::atomic logged{false}; + if (!logged.exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, + "[rt] d3d12_xs: committed resources lease their size through the title's XMem hooks (first: " + "%llu B)\n", + static_cast(size)); +} + HRESULT proxy_create_resource(DeviceProxy* self, const D3D12_HEAP_PROPERTIES* heap_properties, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC* xbox_desc, D3D12_RESOURCE_STATES initial_state, const D3D12_CLEAR_VALUE* clear_value, @@ -2037,8 +2128,10 @@ HRESULT proxy_create_resource(DeviceProxy* self, const D3D12_HEAP_PROPERTIES* he "[rt] d3d12_xs: slot 76 resource: dimension=%d xbox layout=0x%x -> PC layout=0x%x\n", static_cast(pc_desc.Dimension), xbox_layout, static_cast(pc_desc.Layout)); } - return self->real->CreateCommittedResource(heap_properties, heap_flags, &pc_desc, initial_state, clear_value, - *riid, out); + const HRESULT hr = self->real->CreateCommittedResource(heap_properties, heap_flags, &pc_desc, initial_state, + clear_value, *riid, out); + if (SUCCEEDED(hr)) lease_title_resource_memory(self, *out, pc_desc); + return hr; } // Device slot 133 is the console's CreatePlacedResourceX: (va, desc, state, clear, riid, out), measured on the retail @@ -2164,13 +2257,37 @@ HRESULT proxy_create_committed_resource3_x(DeviceProxy* self, std::uint64_t heap const D3D12_RESOURCE_DESC1*, std::uint32_t, const D3D12_CLEAR_VALUE*, ID3D12ProtectedResourceSession*, std::uint32_t, const DXGI_FORMAT*, const IID*, void**); - const auto create = reinterpret_cast(self->real_vtable[kPcCreateCommittedResource3]); - return create(self->real, reinterpret_cast(heap_word), - static_cast(static_cast(heap_flags)), &pc_desc, - static_cast(layout_word), reinterpret_cast(clear_word), - reinterpret_cast(session_word), - static_cast(castable_count), reinterpret_cast(castable_formats), - riid, out); + // The ID3D12Device10 interface pointer, not the base device's: COM only promises that QueryInterface on the + // original pointer yields that interface, and a different pointer has its own vtable. Released after the call. + void* device10 = nullptr; +#ifdef __ID3D12Device10_INTERFACE_DEFINED__ + if (FAILED(self->real->QueryInterface(__uuidof(ID3D12Device10), &device10))) device10 = nullptr; +#endif + if (!device10) return E_NOTIMPL; + const auto create = reinterpret_cast((*reinterpret_cast(device10))[kPcCreateCommittedResource3]); + const HRESULT hr = + create(static_cast(device10), reinterpret_cast(heap_word), + static_cast(static_cast(heap_flags)), &pc_desc, + static_cast(layout_word), reinterpret_cast(clear_word), + reinterpret_cast(session_word), + static_cast(castable_count), reinterpret_cast(castable_formats), riid, + out); + static_cast(device10)->Release(); + if (SUCCEEDED(hr)) { + D3D12_RESOURCE_DESC plain{}; // D3D12_RESOURCE_DESC1 without SamplerFeedbackMipRegion + plain.Dimension = pc_desc.Dimension; + plain.Alignment = pc_desc.Alignment; + plain.Width = pc_desc.Width; + plain.Height = pc_desc.Height; + plain.DepthOrArraySize = pc_desc.DepthOrArraySize; + plain.MipLevels = pc_desc.MipLevels; + plain.Format = pc_desc.Format; + plain.SampleDesc = pc_desc.SampleDesc; + plain.Layout = pc_desc.Layout; + plain.Flags = pc_desc.Flags; + lease_title_resource_memory(self, *out, plain); + } + return hr; } template diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 6bae19ac75..45055b888b 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -100,6 +100,7 @@ struct Mock { std::uint64_t args[kMockSlots][5]; std::uint64_t array[kMockSlots][4]; // device: the first entries of the array argument, as received D3D12_COMMAND_QUEUE_DESC queue_desc; // device: the description of its last CreateCommandQueue (slot 8) + IUnknown* held; // ID3D12Object::SetPrivateDataInterface (slot 5): one reference, until destroyed }; Mock g_pool[256]; @@ -317,7 +318,20 @@ std::uint64_t WINAPI mock_slot(Mock* self, std::uint64_t a1, std::uint64_t a2, s } else if constexpr (Slot == 1) { return static_cast(++self->refs); } else if constexpr (Slot == 2) { - return static_cast(--self->refs); + const long left = --self->refs; + if (left == 0 && self->held) { // destroyed: private data goes with it + IUnknown* const held = self->held; + self->held = nullptr; + held->Release(); + } + return static_cast(left); + } else if constexpr (Slot == 5) { // SetPrivateDataInterface(guid, object): keeps one reference + ++self->calls[5]; + auto* const object = reinterpret_cast(a2); + if (object) object->AddRef(); + if (self->held) self->held->Release(); + self->held = object; + return S_OK; } else { // A caller may pass fewer words than this thunk declares (OpenSharedHandle passes three), so its frame // has no room past the four register homes. The words are copied into this frame and passed by pointer: @@ -384,11 +398,23 @@ void fill_mock_vtable(void** vtable, std::index_sequence) { ((vtable[I] = reinterpret_cast(&mock_slot(I)>)), ...); } +// PC ID3D12Device::CreateCommittedResource(heap, flags, desc, state, clear, riid, out) takes seven words after `this`, +// so a device answers it from its own entry; other kinds keep the generic path for slot 27. +HRESULT WINAPI mock_create_committed_resource(Mock* self, std::uint64_t heap, std::uint64_t flags, std::uint64_t desc, + std::uint64_t state, std::uint64_t clear, const IID* riid, void** out) { + ++self->calls[27]; + const std::uint64_t words[] = {heap, flags, desc, state, clear}; + std::memcpy(self->args[27], words, sizeof(words)); + if (self->kind != Kind::device) return mock_call(self, 27, words); + return mock_create(self, Kind::resource, reinterpret_cast(riid), reinterpret_cast(out)); +} + void** mock_vtable() { static void* table[kMockSlots]; static const bool filled = [] { fill_mock_vtable(table, std::make_index_sequence{}); table[12] = reinterpret_cast(&mock_create_command_list); + table[27] = reinterpret_cast(&mock_create_committed_resource); #ifdef __ID3D12Device10_INTERFACE_DEFINED__ table[76] = reinterpret_cast(&mock_create_committed_resource3); #endif @@ -1605,6 +1631,79 @@ int check_descriptor_heap_hooks() { return 0; } +// ---- Committed resources lease their size through the title's XMem hooks (RT-5 stop 17) ---- +// Slots 76 and 127 allocate the slot-25 size of the resource through the installed hooks with page-size field 2, the +// resource holds the lease, and the hooks' free runs once, when the resource is destroyed. +int check_committed_resource_leases() { + g_heap_hook = {}; + xs::set_descriptor_heap_allocator(&mock_heap_alloc, &mock_heap_free); + Mock* mock = nullptr; + void* device = make_device(mock, 10, true); + EXPECT(device); + constexpr std::uint64_t kLeaseAttributes = (0x80ULL << 16) | (2ULL << 14); + static std::uint8_t lease_memory[64]; + g_heap_hook.next_ptr = lease_memory; + + D3D12_HEAP_PROPERTIES heap{}; + heap.Type = D3D12_HEAP_TYPE_DEFAULT; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = 1920; + desc.Height = 1080; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + desc.SampleDesc.Count = 1; + desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + + // Slot 76: the lease is the console-tiled size slot 25 answers (135 tiles), not the PC one. + void* resource = nullptr; + std::uint64_t words76[10] = {word(&heap), 0, word(&desc), 0, 0, word(&kResourceIid), word(&resource), 0, 0, 0}; + EXPECT(hr_of(raw10(device, 76, words76)) == S_OK && resource); + EXPECT(g_heap_hook.alloc_calls == 1 && g_heap_hook.last_alloc_size == 8847360); + EXPECT(g_heap_hook.last_alloc_attr == kLeaseAttributes); + EXPECT(g_heap_hook.free_calls == 0 && reinterpret_cast(resource)->held); + EXPECT(release(resource) == 0); + EXPECT(g_heap_hook.free_calls == 1 && g_heap_hook.last_free_ptr == lease_memory && + g_heap_hook.last_free_attr == kLeaseAttributes); + +#ifdef __ID3D12Device10_INTERFACE_DEFINED__ + // Slot 127, a buffer: its PC size, leased the same way. + D3D12_RESOURCE_DESC1 buffer{}; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Width = 3 * 65536; + buffer.Height = 1; + buffer.DepthOrArraySize = 1; + buffer.MipLevels = 1; + buffer.SampleDesc.Count = 1; + buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + resource = nullptr; + std::uint64_t words127[10] = {word(&heap), 0, word(&buffer), 0xFFFFFFFFu, 0, 0, 0, 0, word(&kResourceIid), + word(&resource)}; + EXPECT(hr_of(raw10(device, 127, words127)) == S_OK && resource); + EXPECT(g_heap_hook.alloc_calls == 2 && g_heap_hook.last_alloc_size == 3 * 65536); + EXPECT(release(resource) == 0 && g_heap_hook.free_calls == 2); +#endif + + // Hooks that return null: the resource is still created, and nothing is freed later. + g_heap_hook.next_ptr = nullptr; + resource = nullptr; + EXPECT(hr_of(raw10(device, 76, words76)) == S_OK && resource && !reinterpret_cast(resource)->held); + const unsigned frees = g_heap_hook.free_calls; + EXPECT(release(resource) == 0 && g_heap_hook.free_calls == frees); + + // No hooks: no lease. + xs::set_descriptor_heap_allocator(nullptr, nullptr); + const unsigned allocs = g_heap_hook.alloc_calls; + resource = nullptr; + EXPECT(hr_of(raw10(device, 76, words76)) == S_OK && resource && g_heap_hook.alloc_calls == allocs); + EXPECT(release(resource) == 0); + EXPECT(release(device) == 0 && mock->refs == 0); + std::printf("%s: committed resources lease their slot-25 size through the title's XMem hooks until destroyed\n", + g_label); + return 0; +} + // ---- Guard-region setup failures: this executable's import table, patched before the first proxy table ---- std::atomic g_injected{0}; @@ -1990,7 +2089,8 @@ int main(int argc, char** argv) { check_descriptor_heap_hooks() || check_render_target_sizes() || check_allocation_descriptions_cleaned() || - check_render_target_layout()) + check_render_target_layout() || + check_committed_resource_leases()) return 1; std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news); return 0; From 20936e84537a25441aa7d8e84fd7fd7073afba82 Mon Sep 17 00:00:00 2001 From: mrp1no <137657338+mrp1no@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:05:11 +0100 Subject: [PATCH 041/110] d3d12_xs: a console indirect argument of type 105 is created as DISPATCH (slot 41) The retail title creates five one-argument command signatures with no root signature at startup (device slot 41, CreateCommandSignature at its PC position). One has the console argument type 105 and a 12-byte stride, next to a DISPATCH and a DISPATCH_MESH of 12 bytes. The PC layer refuses the unknown type, which is stop 19 of the RT-5 boot measurements. Read statically from the title's call sites (shapes only): the two ExecuteIndirect sites of that signature pass MaxCommandCount 1 and an offset into the same argument buffer as the DISPATCH sites. Right before, they set the same compute state as the DISPATCH path (pipeline, compute root signature, tables, constants, SRV and UAV); they record on a second command list of the title's context. So the argument is taken as a D3D12_DISPATCH_ARGUMENTS. Slot 41 now has its own handler. A description that holds type 105 is copied with that type replaced by DISPATCH (logged once). Any other description is forwarded as the same pointer. What the console does differently for type 105 is left open in docs/d3d12_vulkan.md (section 4.9). xs_proxy_mock_test: a two-argument description (a root constant, then type 105) reaches the PC slot 41 as a copy with DISPATCH, the same stride, count, root signature, IID and output, and the caller's description is untouched; a PC description is passed through unchanged. With main's d3d12_xs_device.cpp the new check fails. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 4c04c0f4e36476a6bbf309e2f0f4d6cfcbe9f045) --- docs/d3d12_vulkan.md | 1 + runtime/shims/d3d12_xs_device.cpp | 49 ++++++++++++++++++++++++++++- runtime/shims/d3d12_xs_device.h | 2 ++ runtime/test/xs_proxy_mock_test.cpp | 40 ++++++++++++++++++++--- 4 files changed, 87 insertions(+), 5 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index b39a558923..379a2724d4 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -3530,6 +3530,7 @@ to be recovered from call sites (or the NDA GDK headers, if a developer has acce | DCC / texture compatibility | Public release note for `D3D12XBOX_RESOURCE_FLAG_FORCE_TEXTURE_COMPATIBILITY` | Let Vulkan choose compression; fail if the game aliases/reads raw compressed data. | | PresentX / present planes / frame events | Public GDK samples (MIT/zlib), §4.5 | Likely the only present path of a GDKX title. Presenter + vblank-timed frame events; 1-2 planes composed into the Vulkan swapchain (placement, filter, alpha overlay, HDR10 conversions). Call shapes known; slots/layouts **Open**. | | Device slots 48/73/78/79/80 | Public HLE `Freminet`/`ScarlettX` (third-party, not Microsoft documentation) | `d3d12_xs_device.cpp` routes `CreateCommandQueueX` (48), `CreateCommandListX` (73), `SetFrameIntervalX` (78), `ScheduleFrameEventX` (79) and `WaitFrameEventX` (80) before it indexes the PC vtable. Queue and list creation use the existing create paths. The frame-event calls are a per-device token counter: `WaitFrameEventX` returns at once with a fresh non-zero token, because there is no vblank source before a presenter exists. The five indices can be moved with `LEONIDA_XS_QUEUE_X_SLOT`, `LEONIDA_XS_LIST_X_SLOT`, `LEONIDA_XS_FRAME_INTERVAL_SLOT`, `LEONIDA_XS_SCHEDULE_EVENT_SLOT` and `LEONIDA_XS_WAIT_EVENT_SLOT` (3..127; a value that names a slot the proxy already handles keeps that slot's handler); a trace that disagrees wins. | +| Indirect argument type 105 | The retail title's startup creates five one-argument command signatures (device slot 41) with no root signature; one has type 105 and a 12-byte stride. Its two `ExecuteIndirect` sites, read statically, set the compute state first, as the `DISPATCH` sites do, and pass one command from the same argument buffer, on a second command list | `d3d12_xs_device.cpp` creates it as `DISPATCH` (`D3D12_DISPATCH_ARGUMENTS`). What the console does differently for it is **Open**. | | VRS | Public `D3D12_SHADING_RATE` / `D3D12_AXIS_SHADING_RATE` | `VK_KHR_fragment_shading_rate`; `RSSetShadingRate`/image-based rate map to `vkCmdSetFragmentShadingRateKHR`. | | Mesh shader tier | Public `D3D12_MESH_SHADER_TIER` | `VK_EXT_mesh_shader`; the 9,282 translated mesh shaders make this a hard requirement for any content that uses them. | | Wave MMA | Public `D3D12_WAVE_MMA_TIER` | Not used: no shader sets `WAVE_MMA` in SFI0 and none contains `v_mfma`/`v_wmma` (all 26,503, `tools/feature_scan.py`). Answer the tier query truthfully; no cooperative-matrix mapping is needed. | diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 4662577459..9cdb9439d7 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -233,6 +233,7 @@ const char* slot_name(unsigned slot) { case 34: return "MakeResident (proxies unwrapped)"; case 35: return "Evict (proxies unwrapped)"; case 36: return "CreateFence -> fence proxy"; + case 41: return "CreateCommandSignature (Xbox argument type 105 as DISPATCH)"; case 43: return "GetAdapterLuid"; case 45: return "SetEventOnMultipleFenceCompletion (fence proxies unwrapped)"; case 46: return "SetResidencyPriority (proxies unwrapped)"; @@ -1931,6 +1932,48 @@ HRESULT proxy_create_compute_pipeline_state(DeviceProxy* self, const D3D12_COMPU return self->real->CreateComputePipelineState(desc, *riid, out); } +// The Xbox slot 41 is CreateCommandSignature at its PC position, (desc, root signature, riid, out), but a console +// description can hold an argument type the PC does not have. The retail title creates five one-argument signatures +// with no root signature at startup; one has type 105 (0x69) and a 12-byte stride, next to a DISPATCH and a +// DISPATCH_MESH of 12 bytes. Read statically from its call sites (counts and shapes only): its two ExecuteIndirect +// sites pass MaxCommandCount 1 and an argument offset into the same upload buffer as the DISPATCH ones, and set the +// compute state (pipeline, compute root signature, tables, constants, SRV/UAV) right before, as the DISPATCH path +// does; they record on a second command list of the title's context. So type 105 is taken as a dispatch whose +// arguments are a D3D12_DISPATCH_ARGUMENTS. HYPOTHESIS: what the console does differently for it (which command +// stream it feeds) is not known; the PC layer has one compute path. Other descriptions are forwarded unchanged. +constexpr D3D12_INDIRECT_ARGUMENT_TYPE kXboxIndirectArgumentDispatch105 = static_cast(105); + +HRESULT proxy_create_command_signature(DeviceProxy* self, const D3D12_COMMAND_SIGNATURE_DESC* desc, + std::uint64_t root_signature, const IID* riid, void** out) { + note_slot(41); + using Fn = HRESULT(STDMETHODCALLTYPE*)(ID3D12Device*, const D3D12_COMMAND_SIGNATURE_DESC*, std::uint64_t, + const IID*, void**); + const auto forward = reinterpret_cast(self->real_vtable[41]); + bool console = false; + if (desc && desc->pArgumentDescs) + for (UINT i = 0; i < desc->NumArgumentDescs && !console; ++i) + console = desc->pArgumentDescs[i].Type == kXboxIndirectArgumentDispatch105; + if (!console) return forward(self->real, desc, root_signature, riid, out); + + std::unique_ptr args(new (std::nothrow) + D3D12_INDIRECT_ARGUMENT_DESC[desc->NumArgumentDescs]); + if (!args) { + if (out) *out = nullptr; + return E_OUTOFMEMORY; + } + for (UINT i = 0; i < desc->NumArgumentDescs; ++i) { + args[i] = desc->pArgumentDescs[i]; + if (args[i].Type == kXboxIndirectArgumentDispatch105) args[i].Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH; + } + static std::atomic logged{false}; + if (!logged.exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, "[rt] d3d12_xs: slot 41 argument type 105 (stride %u) created as DISPATCH\n", + desc->ByteStride); + D3D12_COMMAND_SIGNATURE_DESC pc = *desc; + pc.pArgumentDescs = args.get(); + return forward(self->real, &pc, root_signature, riid, out); +} + // The Xbox slot 67 creates a compute pipeline from native GPU code: (desc, riid, out), named // DeserializeComputePipelineStateX in amd_fidelityfx_upscaler_xbox.dll's messages (call at RVA 0x56d9). The desc // passes the root signature at +0x00, followed by pointer/size pairs for the shader's FSPX entries (docs/fspx.md): @@ -2380,6 +2423,10 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64 return hr_to_u64(proxy_create_compute_pipeline_state( self, reinterpret_cast(a1), a2, a3, reinterpret_cast(a4), reinterpret_cast(a5))); + } else if constexpr (Slot == 41) { + return hr_to_u64(proxy_create_command_signature( + self, reinterpret_cast(a1), a2, reinterpret_cast(a3), + reinterpret_cast(a4))); } else if constexpr (Slot == 67) { return hr_to_u64(proxy_create_compute_pipeline_from_native_code( self, reinterpret_cast(a1), reinterpret_cast(a2), @@ -2724,7 +2771,7 @@ ID3D12Device* device_proxy_real_device(const void* device) { bool device_slot_overridden(unsigned slot) { if (slot <= 2 || slot == 8 || slot == 9 || slot == 14 || (slot >= 17 && slot <= 24) || slot == 25 || slot == 26 || slot == 31 || slot == 32 || slot == 34 || slot == 35 || - slot == 36 || slot == 45 || slot == 46 || slot == 50 || slot == 56 || slot == 62 || slot == 67 || + slot == 36 || slot == 41 || slot == 45 || slot == 46 || slot == 50 || slot == 56 || slot == 62 || slot == 67 || slot == 70 || slot == 75 || slot == 76 || slot == 133 || slot == kCreateCommittedResource3X) return true; const XboxDeviceSlotRoutes& routes = xbox_device_slot_routes(); diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index 8d474dd1d5..5841656967 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -6,6 +6,8 @@ // the device in RCX and the buffer in RDX. The thunk takes the console form when RDX holds a device // proxy, and forwards the PC form otherwise. Slots 25 and 43 return structs too; no call of them by // the executable has been seen yet, so they are forwarded in the PC form. +// slot 41 CreateCommandSignature at its PC position; a console argument of type 105 (a 12-byte dispatch, read +// from the retail title's call sites) is created as D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH. // slot 62 CreateComputePipelineState(desc, w2, w3, iid, out): two words (0 from XboxBvhBuilder, meaning unknown) // before the IID. The PC slot 62 is CreateStateObject. // slot 67 CreateComputePipelineState from native code (desc, iid, out): converts the Xbox native-code desc diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 45055b888b..36eb07a15b 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -290,6 +290,13 @@ std::uint64_t mock_call(Mock* m, unsigned slot, const std::uint64_t* words) { out->VisibleNodeMask = kHeapMarker; return a1; // a struct-returning method hands the buffer's address back in RAX } + case 41: // CreateCommandSignature(desc, ...) + if (const auto* desc = reinterpret_cast(a1)) { + m->array[41][0] = desc->ByteStride | std::uint64_t{desc->NumArgumentDescs} << 32; + for (UINT i = 0; desc->pArgumentDescs && i < desc->NumArgumentDescs && i < 3; ++i) + m->array[41][i + 1] = static_cast(desc->pArgumentDescs[i].Type); + } + break; case 50: copy_array(m, slot, a3, a2); break; // (flags, count, objects, fence, value) default: break; } @@ -987,7 +994,7 @@ int check_allocators() { return 0; } -// ---- 7. Xbox device slots from the public HLE (48, 73, 78, 79, 80) ---- +// ---- 7. Xbox device slots from the public HLE (48, 73, 78, 79, 80) and the retail title (41) ---- // // A device that answers ID3D12Device11 (80 PC slots) is the Vulkan layer's shape: slots 78/79 are inside its table // (CreateReservedResource2/CreateSampler2 there) and 80 is just past it. None of the five may reach the mock's own @@ -1055,14 +1062,39 @@ int check_xbox_slots() { EXPECT(hr_of(raw(device, 73, word(&desc), 0, 0, word(&list_iid), word(&list))) == E_INVALIDARG); EXPECT(hr_of(raw(device, 73, word(&desc), word(allocator), 0, word(&list_iid), 0)) == E_POINTER); - EXPECT(xs::device_slot_overridden(48) && xs::device_slot_overridden(73) && xs::device_slot_overridden(78) && - xs::device_slot_overridden(79) && xs::device_slot_overridden(80)); + // 41 CreateCommandSignature: a console argument of type 105 reaches the PC slot 41 as DISPATCH, in a copy of the + // description (stride, count, the root argument before it and the root signature kept). A PC description is + // passed as the same pointer. + D3D12_INDIRECT_ARGUMENT_DESC console_args[2]{}; + console_args[0].Type = D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT; + console_args[0].Constant.Num32BitValuesToSet = 1; + console_args[1].Type = static_cast(105); + const D3D12_COMMAND_SIGNATURE_DESC console_sig{16, 2, console_args, 0}; + const IID sig_iid = __uuidof(ID3D12CommandSignature); + void* sig = nullptr; + EXPECT(hr_of(raw(device, 41, word(&console_sig), 0x5150, word(&sig_iid), word(&sig))) == S_OK); + EXPECT(mock->calls[41] == 1 && xs::device_slot_hits(41) == 1); + EXPECT(mock->args[41][0] != word(&console_sig) && mock->args[41][1] == 0x5150); + EXPECT(mock->args[41][2] == word(&sig_iid) && mock->args[41][3] == word(&sig)); + EXPECT(mock->array[41][0] == (16 | std::uint64_t{2} << 32)); + EXPECT(mock->array[41][1] == D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT && + mock->array[41][2] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH); + EXPECT(console_args[1].Type == static_cast(105)); // the caller's copy is untouched + D3D12_INDIRECT_ARGUMENT_DESC pc_arg{}; + pc_arg.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH; + const D3D12_COMMAND_SIGNATURE_DESC pc_sig{12, 1, &pc_arg, 0}; + EXPECT(hr_of(raw(device, 41, word(&pc_sig), 0, word(&sig_iid), word(&sig))) == S_OK); + EXPECT(mock->calls[41] == 2 && mock->args[41][0] == word(&pc_sig)); + EXPECT(mock->array[41][1] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH); + + EXPECT(xs::device_slot_overridden(41) && xs::device_slot_overridden(48) && xs::device_slot_overridden(73) && + xs::device_slot_overridden(78) && xs::device_slot_overridden(79) && xs::device_slot_overridden(80)); EXPECT(release(allocator) == 0 && real_allocator->refs == 0); EXPECT(release(queue) == 0); EXPECT(release(device) == 0 && mock->refs == 0); std::printf("%s: device slots 48/73/78/79/80 route to a queue, a list and frame-event tokens without reaching " - "the mock's own PC slots\n", g_label); + "the mock's own PC slots; slot 41 creates argument type 105 as DISPATCH\n", g_label); return 0; #else std::printf("%s: ID3D12Device11 is not in this SDK; Xbox slot 80's beyond-table case is not built\n", g_label); From 58ce13c12d541c32dfbcbb199112d31bf712cb0a Mon Sep 17 00:00:00 2001 From: mrp1no <137657338+mrp1no@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:17:22 +0100 Subject: [PATCH 042/110] d3d12_xs: read the console argument type as its 32 bits (clang-cl) 105 is outside D3D12_INDIRECT_ARGUMENT_TYPE's range [0, 15], so clang-cl rejects a constant expression that casts it to the enum (reported by umnitus on #7163). The handler now reads each argument's Type field as a uint32_t through memcpy and compares it with 105; the test writes and reads the raw value the same way, and the mock records it the same way. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 084c8c60e7e839d0caefaaeccf41a6348b062cf1) --- runtime/shims/d3d12_xs_device.cpp | 15 ++++++++++++--- runtime/test/xs_proxy_mock_test.cpp | 14 ++++++++++---- 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 9cdb9439d7..ea8bed3ca4 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -1941,7 +1941,15 @@ HRESULT proxy_create_compute_pipeline_state(DeviceProxy* self, const D3D12_COMPU // does; they record on a second command list of the title's context. So type 105 is taken as a dispatch whose // arguments are a D3D12_DISPATCH_ARGUMENTS. HYPOTHESIS: what the console does differently for it (which command // stream it feeds) is not known; the PC layer has one compute path. Other descriptions are forwarded unchanged. -constexpr D3D12_INDIRECT_ARGUMENT_TYPE kXboxIndirectArgumentDispatch105 = static_cast(105); +// 105 is outside D3D12_INDIRECT_ARGUMENT_TYPE's range, so the field is read as its 32 bits (a constant expression that +// casts 105 to the enum does not compile with clang-cl). +constexpr std::uint32_t kXboxIndirectArgumentDispatch105 = 105; + +std::uint32_t argument_type(const D3D12_INDIRECT_ARGUMENT_DESC& arg) { + std::uint32_t type = 0; + std::memcpy(&type, &arg.Type, sizeof(type)); + return type; +} HRESULT proxy_create_command_signature(DeviceProxy* self, const D3D12_COMMAND_SIGNATURE_DESC* desc, std::uint64_t root_signature, const IID* riid, void** out) { @@ -1952,7 +1960,7 @@ HRESULT proxy_create_command_signature(DeviceProxy* self, const D3D12_COMMAND_SI bool console = false; if (desc && desc->pArgumentDescs) for (UINT i = 0; i < desc->NumArgumentDescs && !console; ++i) - console = desc->pArgumentDescs[i].Type == kXboxIndirectArgumentDispatch105; + console = argument_type(desc->pArgumentDescs[i]) == kXboxIndirectArgumentDispatch105; if (!console) return forward(self->real, desc, root_signature, riid, out); std::unique_ptr args(new (std::nothrow) @@ -1963,7 +1971,8 @@ HRESULT proxy_create_command_signature(DeviceProxy* self, const D3D12_COMMAND_SI } for (UINT i = 0; i < desc->NumArgumentDescs; ++i) { args[i] = desc->pArgumentDescs[i]; - if (args[i].Type == kXboxIndirectArgumentDispatch105) args[i].Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH; + if (argument_type(args[i]) == kXboxIndirectArgumentDispatch105) + args[i].Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH; } static std::atomic logged{false}; if (!logged.exchange(true, std::memory_order_relaxed)) diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 36eb07a15b..ac2bf2ed7d 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -293,8 +293,11 @@ std::uint64_t mock_call(Mock* m, unsigned slot, const std::uint64_t* words) { case 41: // CreateCommandSignature(desc, ...) if (const auto* desc = reinterpret_cast(a1)) { m->array[41][0] = desc->ByteStride | std::uint64_t{desc->NumArgumentDescs} << 32; - for (UINT i = 0; desc->pArgumentDescs && i < desc->NumArgumentDescs && i < 3; ++i) - m->array[41][i + 1] = static_cast(desc->pArgumentDescs[i].Type); + for (UINT i = 0; desc->pArgumentDescs && i < desc->NumArgumentDescs && i < 3; ++i) { + std::uint32_t type = 0; // read as its 32 bits: a console type is outside the enum's range + std::memcpy(&type, &desc->pArgumentDescs[i].Type, sizeof(type)); + m->array[41][i + 1] = type; + } } break; case 50: copy_array(m, slot, a3, a2); break; // (flags, count, objects, fence, value) @@ -1068,7 +1071,8 @@ int check_xbox_slots() { D3D12_INDIRECT_ARGUMENT_DESC console_args[2]{}; console_args[0].Type = D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT; console_args[0].Constant.Num32BitValuesToSet = 1; - console_args[1].Type = static_cast(105); + constexpr std::uint32_t kType105 = 105; // outside the enum's range: written and read as its 32 bits + std::memcpy(&console_args[1].Type, &kType105, sizeof(kType105)); const D3D12_COMMAND_SIGNATURE_DESC console_sig{16, 2, console_args, 0}; const IID sig_iid = __uuidof(ID3D12CommandSignature); void* sig = nullptr; @@ -1079,7 +1083,9 @@ int check_xbox_slots() { EXPECT(mock->array[41][0] == (16 | std::uint64_t{2} << 32)); EXPECT(mock->array[41][1] == D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT && mock->array[41][2] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH); - EXPECT(console_args[1].Type == static_cast(105)); // the caller's copy is untouched + std::uint32_t caller_type = 0; + std::memcpy(&caller_type, &console_args[1].Type, sizeof(caller_type)); + EXPECT(caller_type == kType105); // the caller's description is untouched D3D12_INDIRECT_ARGUMENT_DESC pc_arg{}; pc_arg.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH; const D3D12_COMMAND_SIGNATURE_DESC pc_sig{12, 1, &pc_arg, 0}; From 3b86f5fb3cfa97d2aa8b500768ac72cad7a4dbfa Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Mon, 23 Nov 2026 17:29:49 +0100 Subject: [PATCH 043/110] d3d12: CreateCommandSignature creates a DISPATCH_MESH signature on a device with mesh shaders The Vulkan layer created signatures for draw, draw-indexed and dispatch only and answered E_NOTIMPL for DISPATCH_MESH, which the PC runtime creates on any mesh-shader tier 1 device. A title that creates such a signature at startup and asserts on the result stopped there. The signature is created when the device has VK_EXT_mesh_shader (MeshShaderTier 1), as a new IndirectKind::dispatch_mesh (the name and value #3777 uses, so the two merge). ExecuteIndirect with it records nothing yet and says so once; #3777 replays it as vkCmdDrawMeshTasksIndirectEXT. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit efc347830b9ccf1461baf9a764ac9e5e911de8f6) --- runtime/shims/d3d12_com.cpp | 22 +++++++++------------- runtime/shims/d3d12_vulkan_device.cpp | 5 +++++ runtime/src/command_list.h | 3 +++ runtime/test/d3d12_mesh_test.cpp | 22 ++++++++++++++++++++++ 4 files changed, 39 insertions(+), 13 deletions(-) diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 4f4904e965..55fea20c91 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -834,19 +834,15 @@ class GraphicsCommandList final } else if (count_buffer_offset != 0) { return check(false); } - // The record size is checked for every call: D3D12 rejects a signature whose stride cannot hold a record - // even when no command runs. The argument span is what the signature can walk, max_command_count * stride: - // the host refuses a range that ends past the buffer (`240` with stride `20` in a `256`-byte buffer), and - // it checks the offset itself when max_command_count is 0, where the required bytes are none. - const UINT64 record_size = - kind == leonida::IndirectKind::draw ? sizeof(D3D12_DRAW_ARGUMENTS) - : kind == leonida::IndirectKind::draw_indexed ? sizeof(D3D12_DRAW_INDEXED_ARGUMENTS) - : kind == leonida::IndirectKind::dispatch ? sizeof(D3D12_DISPATCH_ARGUMENTS) - : 0; - if (!record_size || stride < record_size || stride % 4 != 0) return check(false); - if (argument_buffer_offset > arg_desc.Width || - UINT64(max_command_count) > (arg_desc.Width - argument_buffer_offset) / stride) - return check(false); + if (kind == leonida::IndirectKind::dispatch_mesh) { + // Not replayed yet (#3777 replays it as vkCmdDrawMeshTasksIndirectEXT): nothing is recorded, and the + // first such call says so. The list stays valid. + static std::atomic logged{false}; + if (!logged.exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, "[rt] d3d12: ExecuteIndirect with a DISPATCH_MESH signature is not replayed yet; " + "nothing was recorded\n"); + return; + } leonida::ExecuteIndirect cmd{}; cmd.kind = kind; cmd.stride = stride; diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 0273f9339b..6cc357c87e 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -5833,6 +5833,11 @@ class Device final case D3D12_INDIRECT_ARGUMENT_TYPE_DRAW: kind = leonida::IndirectKind::draw; break; case D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED: kind = leonida::IndirectKind::draw_indexed; break; case D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH: kind = leonida::IndirectKind::dispatch; break; + case D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH: + // As DispatchMesh: only a device with mesh shaders (MeshShaderTier 1) takes it. + if (!state_.info.mesh_shader) return E_NOTIMPL; + kind = leonida::IndirectKind::dispatch_mesh; + break; default: return E_NOTIMPL; } return create_command_signature(kind, desc->ByteStride, riid, out, identity()); diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index 7c5c09e0ac..595110f360 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h @@ -587,6 +587,9 @@ enum class IndirectKind : std::uint8_t { draw = 0, draw_indexed = 1, dispatch = 2, + // D3D12_DISPATCH_MESH_ARGUMENTS. Created on a device with mesh shaders; ExecuteIndirect with it records nothing + // yet (the replay is #3777's), so a title that only creates such a signature at startup goes on. + dispatch_mesh = 3, }; struct ExecuteIndirect { diff --git a/runtime/test/d3d12_mesh_test.cpp b/runtime/test/d3d12_mesh_test.cpp index df430c11a6..590d3507b9 100644 --- a/runtime/test/d3d12_mesh_test.cpp +++ b/runtime/test/d3d12_mesh_test.cpp @@ -12,6 +12,8 @@ // bottom-left quadrant (yellow). Each pixel is read back and compared. // - A vertex draw with the mesh PSO, and DispatchMesh with the VS one, fail at execution (ReplayResult:: // invalid_draw); a mesh grid beyond D3D12's limits fails at Close; an empty grid records nothing. +// - A DISPATCH_MESH command signature is created only with the extension; ExecuteIndirect with it records nothing +// yet, so its list closes. // The shaders are GLSL written to the translator's contract (test/glsl/ms_draw.mesh, ps_draw.frag, vs_fullscreen.vert). // No game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. #include "vk_test_device.h" @@ -180,6 +182,11 @@ int main() { stream.add(TargetsSubobject{.inner = one_target()}); Ref pso; EXPECT(create(device.p, stream, pso) == E_NOTIMPL && !pso.p); + // A DISPATCH_MESH command signature is refused the same way. + const D3D12_INDIRECT_ARGUMENT_DESC mesh_arg{D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH}; + const D3D12_COMMAND_SIGNATURE_DESC mesh_sig{12, 1, &mesh_arg, 0}; + Ref sig; + EXPECT(device->CreateCommandSignature(&mesh_sig, nullptr, IID_PPV_ARGS(&sig.p)) == E_NOTIMPL && !sig.p); root.reset(); EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); } @@ -398,6 +405,21 @@ int main() { list->RSSetViewports(1, &viewport); list6->DispatchMesh(4096, 1025, 1); EXPECT(list->Close() == E_INVALIDARG); + // A DISPATCH_MESH command signature (D3D12_DISPATCH_MESH_ARGUMENTS, 12 bytes) is created; a stride below its + // 12 bytes is refused as the PC runtime refuses it. ExecuteIndirect with it records nothing yet (#3777 replays + // it), so the list still closes. + { + const D3D12_INDIRECT_ARGUMENT_DESC mesh_arg{D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH}; + const D3D12_COMMAND_SIGNATURE_DESC mesh_sig{12, 1, &mesh_arg, 0}; + const D3D12_COMMAND_SIGNATURE_DESC short_sig{8, 1, &mesh_arg, 0}; + Ref sig, short_one; + EXPECT(SUCCEEDED(device->CreateCommandSignature(&mesh_sig, nullptr, IID_PPV_ARGS(&sig.p))) && sig.p); + EXPECT(device->CreateCommandSignature(&short_sig, nullptr, IID_PPV_ARGS(&short_one.p)) == E_INVALIDARG); + EXPECT(SUCCEEDED(list->Reset(allocator.p, mesh_pso.p))); + list->SetGraphicsRootSignature(root.p); + list->ExecuteIndirect(sig.p, 1, upload.p, 0, nullptr, 0); + EXPECT(list->Close() == S_OK); + } EXPECT(SUCCEEDED(queue->Signal(fence.p, 2)) && SUCCEEDED(fence->SetEventOnCompletion(2, nullptr))); // D3D-291: pipeline statistics around mesh draws. Query 0 holds a vertex draw, two mesh draws and another From f54cf315b434cc5980c0bc30499e1837291c5b8f Mon Sep 17 00:00:00 2001 From: mrp1no <137657338+mrp1no@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:57:30 +0100 Subject: [PATCH 044/110] d3d12_xs: Xbox device slot 61 is CreateSamplerX, routed to the PC CreateSampler The retail title calls device slot 61 as CreateSamplerX(desc, dest handle), once per sampler, after its descriptor heaps exist (stop 20 of the RT-5 boot measurements in the coordination issue). The generic thunk forwarded it to the PC slot 61, which is CreateMetaCommand, so the sampler was never written. Slot 61 now has its own handler, like 62 and 67. It passes the description's PC D3D12_SAMPLER_DESC prefix and the handle to the PC CreateSampler (slot 22). That was enough to get the title past this call under Wine. Whatever follows the prefix in the console description is not known and is not read. A null description is skipped and logged once. A handle in the title's own heap range is #7021's translation. xs_proxy_mock_test: slot 61 reaches the mock's slot 22 with the same two words and never its slot 61; a null description reaches nothing. With main's d3d12_xs_device.cpp the new check fails. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit e22994464b17517624c898ed34b3e03c06ce2261) --- docs/d3d12_vulkan.md | 1 + runtime/shims/d3d12_xs_device.cpp | 27 ++++++++++++++++++++++++++- runtime/shims/d3d12_xs_device.h | 2 ++ runtime/test/xs_proxy_mock_test.cpp | 23 ++++++++++++++++++++--- 4 files changed, 49 insertions(+), 4 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 379a2724d4..48e2990554 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -3531,6 +3531,7 @@ to be recovered from call sites (or the NDA GDK headers, if a developer has acce | PresentX / present planes / frame events | Public GDK samples (MIT/zlib), §4.5 | Likely the only present path of a GDKX title. Presenter + vblank-timed frame events; 1-2 planes composed into the Vulkan swapchain (placement, filter, alpha overlay, HDR10 conversions). Call shapes known; slots/layouts **Open**. | | Device slots 48/73/78/79/80 | Public HLE `Freminet`/`ScarlettX` (third-party, not Microsoft documentation) | `d3d12_xs_device.cpp` routes `CreateCommandQueueX` (48), `CreateCommandListX` (73), `SetFrameIntervalX` (78), `ScheduleFrameEventX` (79) and `WaitFrameEventX` (80) before it indexes the PC vtable. Queue and list creation use the existing create paths. The frame-event calls are a per-device token counter: `WaitFrameEventX` returns at once with a fresh non-zero token, because there is no vblank source before a presenter exists. The five indices can be moved with `LEONIDA_XS_QUEUE_X_SLOT`, `LEONIDA_XS_LIST_X_SLOT`, `LEONIDA_XS_FRAME_INTERVAL_SLOT`, `LEONIDA_XS_SCHEDULE_EVENT_SLOT` and `LEONIDA_XS_WAIT_EVENT_SLOT` (3..127; a value that names a slot the proxy already handles keeps that slot's handler); a trace that disagrees wins. | | Indirect argument type 105 | The retail title's startup creates five one-argument command signatures (device slot 41) with no root signature; one has type 105 and a 12-byte stride. Its two `ExecuteIndirect` sites, read statically, set the compute state first, as the `DISPATCH` sites do, and pass one command from the same argument buffer, on a second command list | `d3d12_xs_device.cpp` creates it as `DISPATCH` (`D3D12_DISPATCH_ARGUMENTS`). What the console does differently for it is **Open**. | +| Device slot 61 | The retail title's boot under `gta6rt --run` (stop 20 of the RT-5 measurements in #6910): called as `(desc, dest handle)` once per sampler | `d3d12_xs_device.cpp` routes it to the PC `CreateSampler` (slot 22) with the description's PC `D3D12_SAMPLER_DESC` prefix; the PC slot 61 is `CreateMetaCommand`. The layout of the description beyond the PC fields is **Open**. | | VRS | Public `D3D12_SHADING_RATE` / `D3D12_AXIS_SHADING_RATE` | `VK_KHR_fragment_shading_rate`; `RSSetShadingRate`/image-based rate map to `vkCmdSetFragmentShadingRateKHR`. | | Mesh shader tier | Public `D3D12_MESH_SHADER_TIER` | `VK_EXT_mesh_shader`; the 9,282 translated mesh shaders make this a hard requirement for any content that uses them. | | Wave MMA | Public `D3D12_WAVE_MMA_TIER` | Not used: no shader sets `WAVE_MMA` in SFI0 and none contains `v_mfma`/`v_wmma` (all 26,503, `tools/feature_scan.py`). Answer the tier query truthfully; no cooperative-matrix mapping is needed. | diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index ea8bed3ca4..d8c92bd0f5 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -240,6 +240,7 @@ const char* slot_name(unsigned slot) { case 48: return "Xbox CreateCommandQueueX -> queue proxy"; case 50: return "EnqueueMakeResident (proxies unwrapped)"; case 56: return "GetResourceAllocationInfo1 (C or PC form)"; + case 61: return "Xbox CreateSamplerX -> PC CreateSampler"; case 62: return "Xbox CreateComputePipelineState"; case 67: return "Xbox DeserializeComputePipelineStateX"; case 70: return "Xbox shader-resource view from raw words"; @@ -1983,6 +1984,27 @@ HRESULT proxy_create_command_signature(DeviceProxy* self, const D3D12_COMMAND_SI return forward(self->real, &pc, root_signature, riid, out); } +// The Xbox slot 61 is CreateSamplerX(desc, dest): a sampler written to a CPU descriptor handle, with the PC +// CreateSampler's two arguments. Measured on the retail title's boot (stop 20 in #6910's RT-5 measurements): the +// title calls it once per sampler after its descriptor heaps exist, and it goes on when the call is served by the PC +// CreateSampler. The PC slot 61 is CreateMetaCommand, which would take these words as (CommandId, NodeMask, ...). +// HYPOTHESIS: the console description begins with the PC D3D12_SAMPLER_DESC (52 bytes), which is what got the title +// past this call; whatever follows it is not known and not read. The title was not seen testing a result, so a null +// description is skipped rather than reported. The handle is passed as given: a handle in the title's own heap range +// is #7021's translation. +void proxy_create_sampler_x(DeviceProxy* self, const D3D12_SAMPLER_DESC* desc, std::uint64_t dest) { + note_slot(61); + if (!desc) { + static std::atomic logged{false}; + if (!logged.exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, "[rt] d3d12_xs: slot 61 CreateSamplerX without a description (skipped)\n"); + return; + } + D3D12_CPU_DESCRIPTOR_HANDLE handle{}; + handle.ptr = static_cast(dest); + self->real->CreateSampler(desc, handle); +} + // The Xbox slot 67 creates a compute pipeline from native GPU code: (desc, riid, out), named // DeserializeComputePipelineStateX in amd_fidelityfx_upscaler_xbox.dll's messages (call at RVA 0x56d9). The desc // passes the root signature at +0x00, followed by pointer/size pairs for the shader's FSPX entries (docs/fspx.md): @@ -2436,6 +2458,9 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64 return hr_to_u64(proxy_create_command_signature( self, reinterpret_cast(a1), a2, reinterpret_cast(a3), reinterpret_cast(a4))); + } else if constexpr (Slot == 61) { + proxy_create_sampler_x(self, reinterpret_cast(a1), a2); + return 0; } else if constexpr (Slot == 67) { return hr_to_u64(proxy_create_compute_pipeline_from_native_code( self, reinterpret_cast(a1), reinterpret_cast(a2), @@ -2780,7 +2805,7 @@ ID3D12Device* device_proxy_real_device(const void* device) { bool device_slot_overridden(unsigned slot) { if (slot <= 2 || slot == 8 || slot == 9 || slot == 14 || (slot >= 17 && slot <= 24) || slot == 25 || slot == 26 || slot == 31 || slot == 32 || slot == 34 || slot == 35 || - slot == 36 || slot == 41 || slot == 45 || slot == 46 || slot == 50 || slot == 56 || slot == 62 || slot == 67 || + slot == 36 || slot == 41 || slot == 45 || slot == 46 || slot == 50 || slot == 56 || slot == 61 || slot == 62 || slot == 67 || slot == 70 || slot == 75 || slot == 76 || slot == 133 || slot == kCreateCommittedResource3X) return true; const XboxDeviceSlotRoutes& routes = xbox_device_slot_routes(); diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index 5841656967..3b2c576d17 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -8,6 +8,8 @@ // the executable has been seen yet, so they are forwarded in the PC form. // slot 41 CreateCommandSignature at its PC position; a console argument of type 105 (a 12-byte dispatch, read // from the retail title's call sites) is created as D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH. +// slot 61 CreateSamplerX(desc, dest) -> PC CreateSampler (slot 22); the description's PC +// D3D12_SAMPLER_DESC prefix is passed. The PC slot 61 is CreateMetaCommand. Measured on the retail title's boot. // slot 62 CreateComputePipelineState(desc, w2, w3, iid, out): two words (0 from XboxBvhBuilder, meaning unknown) // before the IID. The PC slot 62 is CreateStateObject. // slot 67 CreateComputePipelineState from native code (desc, iid, out): converts the Xbox native-code desc diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index ac2bf2ed7d..b26a860692 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -997,6 +997,8 @@ int check_allocators() { return 0; } + + // ---- 7. Xbox device slots from the public HLE (48, 73, 78, 79, 80) and the retail title (41) ---- // // A device that answers ID3D12Device11 (80 PC slots) is the Vulkan layer's shape: slots 78/79 are inside its table @@ -1093,14 +1095,29 @@ int check_xbox_slots() { EXPECT(mock->calls[41] == 2 && mock->args[41][0] == word(&pc_sig)); EXPECT(mock->array[41][1] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH); - EXPECT(xs::device_slot_overridden(41) && xs::device_slot_overridden(48) && xs::device_slot_overridden(73) && + // 61 CreateSamplerX(desc, dest): the PC CreateSampler (slot 22) gets the same two words, not the PC slot 61 + // (CreateMetaCommand). A null description is skipped without reaching the device. + D3D12_SAMPLER_DESC sampler{}; + sampler.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR; + sampler.AddressU = sampler.AddressV = sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP; + sampler.MaxLOD = D3D12_FLOAT32_MAX; + const std::uint64_t sampler_handle = 0x7ff012340040ull; + raw(device, 61, word(&sampler), sampler_handle); + EXPECT(mock->calls[61] == 0 && mock->calls[22] == 1 && xs::device_slot_hits(61) == 1); + EXPECT(mock->args[22][0] == word(&sampler) && mock->args[22][1] == sampler_handle); + raw(device, 61, 0, sampler_handle); + EXPECT(mock->calls[61] == 0 && mock->calls[22] == 1 && xs::device_slot_hits(61) == 2); + + EXPECT(xs::device_slot_overridden(41) && xs::device_slot_overridden(48) && xs::device_slot_overridden(61) && + xs::device_slot_overridden(73) && xs::device_slot_overridden(78) && xs::device_slot_overridden(79) && xs::device_slot_overridden(80)); EXPECT(release(allocator) == 0 && real_allocator->refs == 0); EXPECT(release(queue) == 0); EXPECT(release(device) == 0 && mock->refs == 0); - std::printf("%s: device slots 48/73/78/79/80 route to a queue, a list and frame-event tokens without reaching " - "the mock's own PC slots; slot 41 creates argument type 105 as DISPATCH\n", g_label); + std::printf("%s: device slots 48/73/78/79/80 route to a queue, a list and frame-event tokens, and slot 61 to " + "CreateSampler, without reaching the mock's own PC slots; slot 41 creates argument type 105 as DISPATCH\n", + g_label); return 0; #else std::printf("%s: ID3D12Device11 is not in this SDK; Xbox slot 80's beyond-table case is not built\n", g_label); From 6d4cf2ceb705b4d1bf2fdc0611e6431d91718320 Mon Sep 17 00:00:00 2001 From: mrp1no <137657338+mrp1no@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:44:08 +0100 Subject: [PATCH 045/110] d3d12_xs: slot 61 is CreateSamplerX only for the title's calls; a host caller gets PC CreateMetaCommand The proxy also serves host callers: d3d12_vulkan_device_test drives the Vulkan device through it, and its ID3D12Device5::CreateMetaCommand call (PC slot 61) landed in proxy_create_sampler_x (found by nullmarsh on #7115: the test stopped at line 5763 instead of main's known line 6574). Slot 61 now checks the caller's return address with a classifier the runtime installs (set_console_caller, the name #7490 uses): D3D12XboxCreateDevice installs rt::shims::mapped_image_base, so only a caller in an image the guest loader mapped gets CreateSamplerX. Any other caller, and every caller when no classifier is installed, is forwarded to the PC slot 61. xs_proxy_mock_test checks all three cases: no classifier (PC slot 61), a guest caller (PC CreateSampler with the same words; a null description skipped) and a host caller under an installed classifier (PC slot 61). d3d12_vulkan_device_test again stops at line 6574, as on main. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 8f756ebe048af042638ce51a61490f35f4f44ee3) (cherry picked from commit c915e1da45e17d46c90c32be9809e4f043a77fd3) --- docs/d3d12_vulkan.md | 2 +- runtime/shims/d3d12_xs.cpp | 6 ++++++ runtime/shims/d3d12_xs_device.cpp | 33 ++++++++++++++++++++++++++--- runtime/shims/d3d12_xs_device.h | 6 ++++++ runtime/test/xs_proxy_mock_test.cpp | 18 ++++++++++++---- 5 files changed, 57 insertions(+), 8 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 48e2990554..77f60c3ebd 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -3531,7 +3531,7 @@ to be recovered from call sites (or the NDA GDK headers, if a developer has acce | PresentX / present planes / frame events | Public GDK samples (MIT/zlib), §4.5 | Likely the only present path of a GDKX title. Presenter + vblank-timed frame events; 1-2 planes composed into the Vulkan swapchain (placement, filter, alpha overlay, HDR10 conversions). Call shapes known; slots/layouts **Open**. | | Device slots 48/73/78/79/80 | Public HLE `Freminet`/`ScarlettX` (third-party, not Microsoft documentation) | `d3d12_xs_device.cpp` routes `CreateCommandQueueX` (48), `CreateCommandListX` (73), `SetFrameIntervalX` (78), `ScheduleFrameEventX` (79) and `WaitFrameEventX` (80) before it indexes the PC vtable. Queue and list creation use the existing create paths. The frame-event calls are a per-device token counter: `WaitFrameEventX` returns at once with a fresh non-zero token, because there is no vblank source before a presenter exists. The five indices can be moved with `LEONIDA_XS_QUEUE_X_SLOT`, `LEONIDA_XS_LIST_X_SLOT`, `LEONIDA_XS_FRAME_INTERVAL_SLOT`, `LEONIDA_XS_SCHEDULE_EVENT_SLOT` and `LEONIDA_XS_WAIT_EVENT_SLOT` (3..127; a value that names a slot the proxy already handles keeps that slot's handler); a trace that disagrees wins. | | Indirect argument type 105 | The retail title's startup creates five one-argument command signatures (device slot 41) with no root signature; one has type 105 and a 12-byte stride. Its two `ExecuteIndirect` sites, read statically, set the compute state first, as the `DISPATCH` sites do, and pass one command from the same argument buffer, on a second command list | `d3d12_xs_device.cpp` creates it as `DISPATCH` (`D3D12_DISPATCH_ARGUMENTS`). What the console does differently for it is **Open**. | -| Device slot 61 | The retail title's boot under `gta6rt --run` (stop 20 of the RT-5 measurements in #6910): called as `(desc, dest handle)` once per sampler | `d3d12_xs_device.cpp` routes it to the PC `CreateSampler` (slot 22) with the description's PC `D3D12_SAMPLER_DESC` prefix; the PC slot 61 is `CreateMetaCommand`. The layout of the description beyond the PC fields is **Open**. | +| Device slot 61 | The retail title's boot under `gta6rt --run` (stop 20 of the RT-5 measurements in #6910): called as `(desc, dest handle)` once per sampler | `d3d12_xs_device.cpp` routes it to the PC `CreateSampler` (slot 22) with the description's PC `D3D12_SAMPLER_DESC` prefix, for a caller in an image the guest loader mapped; the PC slot 61 is `CreateMetaCommand`, which any other caller (a host test driving the device through the proxy) still gets. The layout of the description beyond the PC fields is **Open**. | | VRS | Public `D3D12_SHADING_RATE` / `D3D12_AXIS_SHADING_RATE` | `VK_KHR_fragment_shading_rate`; `RSSetShadingRate`/image-based rate map to `vkCmdSetFragmentShadingRateKHR`. | | Mesh shader tier | Public `D3D12_MESH_SHADER_TIER` | `VK_EXT_mesh_shader`; the 9,282 translated mesh shaders make this a hard requirement for any content that uses them. | | Wave MMA | Public `D3D12_WAVE_MMA_TIER` | Not used: no shader sets `WAVE_MMA` in SFI0 and none contains `v_mfma`/`v_wmma` (all 26,503, `tools/feature_scan.py`). Answer the tier query truthfully; no cooperative-matrix mapping is needed. | diff --git a/runtime/shims/d3d12_xs.cpp b/runtime/shims/d3d12_xs.cpp index 67ac93dd0d..173106f1cd 100644 --- a/runtime/shims/d3d12_xs.cpp +++ b/runtime/shims/d3d12_xs.cpp @@ -166,6 +166,12 @@ HRESULT WINAPI D3D12XboxCreateDevice(IUnknown* adapter, const void* params, cons std::fprintf(stderr, "[rt] d3d12_xs: D3D12XboxCreateDevice: wrapping the PC ID3D12Device in the Xbox-ABI proxy " "(slot 62 -> CreateComputePipelineState, slot 76 -> CreateCommittedResource).\n"); + // A console method whose slot is another PC method (61) is served only to the title: a caller in an image + // this loader mapped. + rt::d3d12_xs::set_console_caller([](std::uint64_t address) { + std::uint64_t base = 0; + return rt::shims::mapped_image_base(address, base); + }); } #ifdef LEONIDA_VULKAN_DEVICE diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index d8c92bd0f5..45fdf3e2e6 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -31,6 +31,7 @@ #include #include +#include // _ReturnAddress: slot 61 serves a console caller differently from a host one #include #include @@ -240,7 +241,7 @@ const char* slot_name(unsigned slot) { case 48: return "Xbox CreateCommandQueueX -> queue proxy"; case 50: return "EnqueueMakeResident (proxies unwrapped)"; case 56: return "GetResourceAllocationInfo1 (C or PC form)"; - case 61: return "Xbox CreateSamplerX -> PC CreateSampler"; + case 61: return "Xbox CreateSamplerX -> PC CreateSampler (a host caller gets PC CreateMetaCommand)"; case 62: return "Xbox CreateComputePipelineState"; case 67: return "Xbox DeserializeComputePipelineStateX"; case 70: return "Xbox shader-resource view from raw words"; @@ -1992,6 +1993,17 @@ HRESULT proxy_create_command_signature(DeviceProxy* self, const D3D12_COMMAND_SI // past this call; whatever follows it is not known and not read. The title was not seen testing a result, so a null // description is skipped rather than reported. The handle is passed as given: a handle in the title's own heap range // is #7021's translation. +// The same proxy also serves host callers (the runtime's own tests drive the Vulkan device through it), for whom slot +// 61 is the PC ID3D12Device5::CreateMetaCommand. So the slot is CreateSamplerX only for a caller in an image the +// guest loader mapped (set_console_caller); any other caller, or every caller when no check is installed, gets the PC +// method. Without the check d3d12_vulkan_device_test's CreateMetaCommand call reached this handler (#7115). +std::atomic g_console_caller{nullptr}; + +bool is_console_caller(const void* address) { + const ConsoleCaller classify = g_console_caller.load(std::memory_order_acquire); + return classify && classify(reinterpret_cast(address)); +} + void proxy_create_sampler_x(DeviceProxy* self, const D3D12_SAMPLER_DESC* desc, std::uint64_t dest) { note_slot(61); if (!desc) { @@ -2459,8 +2471,19 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64 self, reinterpret_cast(a1), a2, reinterpret_cast(a3), reinterpret_cast(a4))); } else if constexpr (Slot == 61) { - proxy_create_sampler_x(self, reinterpret_cast(a1), a2); - return 0; + if (is_console_caller(_ReturnAddress())) { + proxy_create_sampler_x(self, reinterpret_cast(a1), a2); + return 0; + } + // A host caller: the PC slot 61 (ID3D12Device5::CreateMetaCommand), forwarded like any other PC method. + note_slot(Slot); + if (Slot >= self->slot_count) return hr_to_u64(refuse_beyond_device(Slot, self->slot_count)); + using ForwardFn = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std::uint64_t, + std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, + std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, + std::uint64_t, std::uint64_t, std::uint64_t); + auto fn = reinterpret_cast(self->real_vtable[Slot]); + return fn(self->real, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14); } else if constexpr (Slot == 67) { return hr_to_u64(proxy_create_compute_pipeline_from_native_code( self, reinterpret_cast(a1), reinterpret_cast(a2), @@ -2910,6 +2933,10 @@ bool heap_slot_overridden(unsigned slot) { return slot <= 2 || slot == 7 || slot == 9 || slot == 10; } +void set_console_caller(ConsoleCaller classify) { + g_console_caller.store(classify, std::memory_order_release); +} + std::uint64_t device_slot_hits(unsigned slot) { start_hit_counts(); return slot < kMaxSlots ? g_hits[slot].load(std::memory_order_relaxed) : 0; diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index 3b2c576d17..da7990cb4e 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -159,6 +159,12 @@ void set_console_descriptor_heap_handler(ConsoleDescriptorHeapHandler handler); // handles for the allocator proxy. bool device_slot_overridden(unsigned slot); +// Whether a return address is in an image the guest loader mapped, i.e. the call comes from the title. Device slot 61 +// is CreateSamplerX for such a caller and the PC ID3D12Device5::CreateMetaCommand for any other; with no check +// installed every caller is a host one. D3D12XboxCreateDevice installs rt::shims::mapped_image_base. +using ConsoleCaller = bool (*)(std::uint64_t address); +void set_console_caller(ConsoleCaller classify); + // Queue and fence proxies created by device slots 8/75 and 36. The real_* accessors return the wrapped object // (no reference added), or null when the pointer is not such a proxy. bool is_queue_proxy(const void* queue); diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index b26a860692..9aa1b1614d 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -1095,18 +1095,28 @@ int check_xbox_slots() { EXPECT(mock->calls[41] == 2 && mock->args[41][0] == word(&pc_sig)); EXPECT(mock->array[41][1] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH); - // 61 CreateSamplerX(desc, dest): the PC CreateSampler (slot 22) gets the same two words, not the PC slot 61 - // (CreateMetaCommand). A null description is skipped without reaching the device. + // 61 is CreateSamplerX(desc, dest) for the title and the PC CreateMetaCommand for a host caller. With no + // console-caller check installed (a host program like this one), the call is the PC slot 61. D3D12_SAMPLER_DESC sampler{}; sampler.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR; sampler.AddressU = sampler.AddressV = sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP; sampler.MaxLOD = D3D12_FLOAT32_MAX; const std::uint64_t sampler_handle = 0x7ff012340040ull; raw(device, 61, word(&sampler), sampler_handle); - EXPECT(mock->calls[61] == 0 && mock->calls[22] == 1 && xs::device_slot_hits(61) == 1); + EXPECT(mock->calls[61] == 1 && mock->calls[22] == 0 && xs::device_slot_hits(61) == 1); + // A caller the check calls the title's (here every one): the PC CreateSampler (slot 22) gets the same two words, + // not the PC slot 61. A null description is skipped without reaching the device. + xs::set_console_caller([](std::uint64_t) { return true; }); + raw(device, 61, word(&sampler), sampler_handle); + EXPECT(mock->calls[61] == 1 && mock->calls[22] == 1 && xs::device_slot_hits(61) == 2); EXPECT(mock->args[22][0] == word(&sampler) && mock->args[22][1] == sampler_handle); raw(device, 61, 0, sampler_handle); - EXPECT(mock->calls[61] == 0 && mock->calls[22] == 1 && xs::device_slot_hits(61) == 2); + EXPECT(mock->calls[61] == 1 && mock->calls[22] == 1 && xs::device_slot_hits(61) == 3); + // A caller outside the title's images is a host one again. + xs::set_console_caller([](std::uint64_t) { return false; }); + raw(device, 61, word(&sampler), sampler_handle); + EXPECT(mock->calls[61] == 2 && mock->calls[22] == 1); + xs::set_console_caller(nullptr); EXPECT(xs::device_slot_overridden(41) && xs::device_slot_overridden(48) && xs::device_slot_overridden(61) && xs::device_slot_overridden(73) && From 25826cddddd1cc590f0a321d356de6fe2dfcdbc1 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Mon, 23 Nov 2026 17:28:57 +0100 Subject: [PATCH 046/110] d3d12_xs: device slot 74 (pointer, u32, pointer) returns S_OK instead of reaching PC ShaderCacheControl (#7231) The retail title calls slot 74 once; the PC slot 74 reads the first pointer as kinds and returns E_INVALIDARG, so the title hits an int3. The proxy handler does not call the PC device, writes nothing, logs the three words once, and yields to an env slot override that moves a route onto 74. (cherry picked from commit cdeee35aa80471ab2e1b7f946da1f1cdbf395451) Adapted to main by Mumogg: the queue route inside route_xbox_device_slot calls proxy_create_command_queue_xbox (the 32-byte description of 0cde63d61), as the inline route did before this commit moved the routes into a function. --- runtime/CMakeLists.txt | 1 + runtime/shims/d3d12_xs_device.cpp | 77 +++++++++++++++++++---------- runtime/shims/d3d12_xs_device.h | 4 +- runtime/test/xs_proxy_mock_test.cpp | 36 ++++++++++++-- 4 files changed, 88 insertions(+), 30 deletions(-) diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 64e346f40a..e922f067c9 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -1025,6 +1025,7 @@ if(BUILD_TESTING) # The routes are read once per process, so each override case is its own test. add_test(NAME xs_proxy_mock_env_slots COMMAND xs_proxy_mock_test --env-slots) add_test(NAME xs_proxy_mock_env_slots_invalid COMMAND xs_proxy_mock_test --env-slots-invalid) + add_test(NAME xs_proxy_mock_env_slots_74 COMMAND xs_proxy_mock_test --env-slots-74) endif() if(TARGET root_sig_test) add_test(NAME root_sig COMMAND root_sig_test) diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 45fdf3e2e6..42f23b1d07 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -246,6 +246,7 @@ const char* slot_name(unsigned slot) { case 67: return "Xbox DeserializeComputePipelineStateX"; case 70: return "Xbox shader-resource view from raw words"; case 73: return "Xbox CreateCommandListX -> PC CreateCommandList"; + case 74: return "Xbox (pointer, u32, pointer) stand-in"; case 75: return "CreateCommandQueue1 -> queue proxy"; case 76: return "Xbox resource creation"; case 127: return "Xbox CreateCommittedResource3"; @@ -2376,6 +2377,49 @@ HRESULT proxy_create_committed_resource3_x(DeviceProxy* self, std::uint64_t heap return hr; } +// The Xbox routes at their configured indices. Returns false when `slot` is none of them. Built-in handlers (slot 74) ask +// too, because an override that moves a route onto their slot must win over the built-in handler. +bool route_xbox_device_slot(DeviceProxy* self, unsigned slot, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, + std::uint64_t a4, std::uint64_t a5, std::uint64_t& result) { + const XboxDeviceSlotRoutes& routes = xbox_device_slot_routes(); + if (slot == routes.frame_interval) { + log_xbox_route_once(slot, "SetFrameIntervalX", a1, a2, a3, a4, a5); + result = hr_to_u64(proxy_set_frame_interval_x(self, a1, a2, a3, a4)); + } else if (slot == routes.schedule_event) { + log_xbox_route_once(slot, "ScheduleFrameEventX", a1, a2, a3, a4, a5); + result = hr_to_u64(proxy_schedule_frame_event_x(self, a1, a2, a4)); + } else if (slot == routes.wait_event) { + log_xbox_route_once(slot, "WaitFrameEventX", a1, a2, a3, a4, a5); + result = hr_to_u64(proxy_wait_frame_event_x(self, a1, a2, a4, a5)); + } else if (slot == routes.queue_x) { + log_xbox_route_once(slot, "CreateCommandQueueX", a1, a2, a3, a4, a5); + result = hr_to_u64(proxy_create_command_queue_xbox(self, reinterpret_cast(a1), + reinterpret_cast(a2), + reinterpret_cast(a3))); + } else if (slot == routes.list_x) { + log_xbox_route_once(slot, "CreateCommandListX", a1, a2, a3, a4, a5); + result = hr_to_u64(proxy_create_command_list_x(self, a1, a2, a3, reinterpret_cast(a4), + reinterpret_cast(a5))); + } else { + return false; + } + return true; +} + +// Slot 74: the retail title calls it once with (pointer, u32, pointer) (kapitche, issue 7231). The PC slot 74 is +// ID3D12Device9::ShaderCacheControl(kinds, control), which reads the first word as a flags value and returns +// E_INVALIDARG, and the title then stops on an int3. The words are not measured: nothing is written through the +// pointers, the PC device is not called, and the call succeeds. +std::uint64_t proxy_slot74(std::uint64_t a1, std::uint64_t a2, std::uint64_t a3) { + static std::atomic logged{false}; + bool expected = false; + if (logged.compare_exchange_strong(expected, true, std::memory_order_relaxed)) + std::fprintf(stderr, "[rt] d3d12_xs: slot 74 (pointer, u32, pointer) returns S_OK; words 0x%llx 0x%llx 0x%llx\n", + static_cast(a1), static_cast(a2), + static_cast(a3)); + return hr_to_u64(S_OK); +} + template std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7, @@ -2414,6 +2458,11 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64 reinterpret_cast(a3))); } else if constexpr (Slot == 31 || Slot == 34 || Slot == 35 || Slot == 45 || Slot == 46 || Slot == 50) { return hr_to_u64(proxy_unwrapping_call(self, a1, a2, a3, a4, a5)); + } else if constexpr (Slot == 74) { + std::uint64_t routed = 0; + if (route_xbox_device_slot(self, Slot, a1, a2, a3, a4, a5, routed)) return routed; // an override moved a route here + note_slot(Slot); + return proxy_slot74(a1, a2, a3); } else if constexpr (Slot == 75) { return hr_to_u64(proxy_create_command_queue1(self, a1, a2, reinterpret_cast(a3), reinterpret_cast(a4))); @@ -2519,30 +2568,8 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64 // Xbox device slots, before the PC vtable is indexed: the public HLE's 78/79/80 would otherwise reach // CreateReservedResource2/CreateSampler2 or fall past an 80-slot table, and 48/73 would reach unrelated PC // methods. The check is before the slot-count refusal because slot 80 is outside a PC ID3D12Device11 table. - const XboxDeviceSlotRoutes& routes = xbox_device_slot_routes(); - if (Slot == routes.frame_interval) { - log_xbox_route_once(Slot, "SetFrameIntervalX", a1, a2, a3, a4, a5); - return hr_to_u64(proxy_set_frame_interval_x(self, a1, a2, a3, a4)); - } - if (Slot == routes.schedule_event) { - log_xbox_route_once(Slot, "ScheduleFrameEventX", a1, a2, a3, a4, a5); - return hr_to_u64(proxy_schedule_frame_event_x(self, a1, a2, a4)); - } - if (Slot == routes.wait_event) { - log_xbox_route_once(Slot, "WaitFrameEventX", a1, a2, a3, a4, a5); - return hr_to_u64(proxy_wait_frame_event_x(self, a1, a2, a4, a5)); - } - if (Slot == routes.queue_x) { - log_xbox_route_once(Slot, "CreateCommandQueueX", a1, a2, a3, a4, a5); - return hr_to_u64(proxy_create_command_queue_xbox(self, reinterpret_cast(a1), - reinterpret_cast(a2), - reinterpret_cast(a3))); - } - if (Slot == routes.list_x) { - log_xbox_route_once(Slot, "CreateCommandListX", a1, a2, a3, a4, a5); - return hr_to_u64(proxy_create_command_list_x(self, a1, a2, a3, reinterpret_cast(a4), - reinterpret_cast(a5))); - } + std::uint64_t routed = 0; + if (route_xbox_device_slot(self, Slot, a1, a2, a3, a4, a5, routed)) return routed; if (Slot >= self->slot_count) return hr_to_u64(refuse_beyond_device(Slot, self->slot_count)); // The PC vtable entry, called with the PC device as `this`. Integer/pointer arguments, the hidden @@ -2828,7 +2855,7 @@ ID3D12Device* device_proxy_real_device(const void* device) { bool device_slot_overridden(unsigned slot) { if (slot <= 2 || slot == 8 || slot == 9 || slot == 14 || (slot >= 17 && slot <= 24) || slot == 25 || slot == 26 || slot == 31 || slot == 32 || slot == 34 || slot == 35 || - slot == 36 || slot == 41 || slot == 45 || slot == 46 || slot == 50 || slot == 56 || slot == 61 || slot == 62 || slot == 67 || + slot == 36 || slot == 41 || slot == 45 || slot == 46 || slot == 50 || slot == 56 || slot == 61 || slot == 74 || slot == 62 || slot == 67 || slot == 70 || slot == 75 || slot == 76 || slot == 133 || slot == kCreateCommittedResource3X) return true; const XboxDeviceSlotRoutes& routes = xbox_device_slot_routes(); diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index da7990cb4e..ecd39db7bf 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -19,6 +19,8 @@ // and a GPU address, with no resource (retail boot chain stop 14). The PC slot 70 is CreatePlacedResource1. // The words are not measured, so the destination gets the PC null view (PC CreateShaderResourceView // with no resource) and the call returns. +// slot 74 (pointer, u32, pointer): not measured, returns S_OK. The PC slot 74 is ShaderCacheControl(kinds, control), +// which reads the first word as flags and returns E_INVALIDARG. Nothing is written, the PC device is not called. // slot 76 resource creation -> PC CreateCommittedResource (PC slot 27), with the Xbox layout word ignored. // slot 127 CreateCommittedResource3 (heap, flags, desc1, layout, clear, session, castable count/list, riid, out) -> // PC ID3D12Device10::CreateCommittedResource3 (PC slot 76), with the Xbox layout word replaced and the @@ -154,7 +156,7 @@ void set_console_descriptor_heap_handler(ConsoleDescriptorHeapHandler handler); // proxies), 9 (allocator proxies), 14 (descriptor heap proxy), 17-24 (CPU descriptor handle translation), 26 (the // console's struct-return form), // 31/34/35/45/46/50 (proxies unwrapped), 32 and 36 (fence proxies), 48/73 and -// 78/79/80 (the Xbox slots above, at their configured indices), 62, 67, 70, 76 and 127. Slot 10 is intentionally false: the +// 78/79/80 (the Xbox slots above, at their configured indices), 62, 67, 70, 74, 76 and 127. Slot 10 is intentionally false: the // measured 9/10 handle conversion is on the heap proxy, and device slot 9 is CreateCommandAllocator, which the proxy // handles for the allocator proxy. bool device_slot_overridden(unsigned slot); diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 9aa1b1614d..9eca96c9d6 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -1137,8 +1137,8 @@ int check_xbox_slots() { // ---- 8. Environment overrides for the Xbox device slots (one process each, read once) ---- -int run_env_slots(bool valid) { - const char* frame_interval = valid ? "96" : "2"; +int run_env_slots(bool valid, bool on_slot74 = false) { + const char* frame_interval = on_slot74 ? "74" : valid ? "96" : "2"; const char* schedule_event = valid ? "97" : "2"; const char* wait_event = valid ? "98" : "2"; const char* queue_x = valid ? "99" : "2"; @@ -1154,7 +1154,12 @@ int run_env_slots(bool valid) { EXPECT(device); xs::reset_device_proxy_stats(); std::uint64_t token = 0; - if (valid) { + if (on_slot74) { + // SetFrameIntervalX moved onto 74, which also has a built-in handler: the override wins, so (output, interval, + // latency, flags) is a frame-interval call that reaches no PC slot, not the stand-in that ignores its words. + EXPECT(hr_of(raw(device, 74, 0, 16667, 1, 0)) == S_OK && mock->calls[74] == 0); + EXPECT(hr_of(raw(device, 78, 0, 16667, 1, 0)) == S_OK && mock->calls[78] == 1); // the old default is a PC slot now + } else if (valid) { // Every route moved: the new slot is handled, the default slot is forwarded to the mock. EXPECT(hr_of(raw(device, 96, 0, 16667, 1, 0)) == S_OK && mock->calls[96] == 0); EXPECT(hr_of(raw(device, 97, 0, 0, 0, 0)) == S_OK && mock->calls[97] == 0); @@ -1306,6 +1311,27 @@ int check_slot70() { return 0; } +// ---- 8b. Device slot 74: (pointer, u32, pointer) succeeds and touches nothing, never the PC ShaderCacheControl ---- + +int check_slot74() { + // Level 9 has the PC slot 74 (ShaderCacheControl); level 0 does not (44 PC slots). Neither may reach it. + for (const int level : {9, 0}) { + Mock* mock = nullptr; + void* device = make_device(mock, level, true); + EXPECT(device && xs::device_slot_overridden(74)); + xs::reset_device_proxy_stats(); + std::uint32_t first[4] = {0x11111111, 0x22222222, 0x33333333, 0x44444444}; + std::uint32_t second[4] = {0x55555555, 0x66666666, 0x77777777, 0x88888888}; + const std::uint32_t first_before[4] = {first[0], first[1], first[2], first[3]}; + const std::uint32_t second_before[4] = {second[0], second[1], second[2], second[3]}; + EXPECT(hr_of(raw(device, 74, word(first), 7, word(second))) == S_OK); + EXPECT(mock->calls[74] == 0 && xs::device_slot_hits(74) == 1); + EXPECT(std::memcmp(first, first_before, sizeof(first)) == 0 && std::memcmp(second, second_before, sizeof(second)) == 0); + EXPECT(release(device) == 0 && mock->refs == 0); + } + return 0; +} + // ---- 7. Device slot 25, GetResourceAllocationInfo: a render target takes whole console tiles ---- D3D12_RESOURCE_DESC target_desc(std::uint64_t width, UINT height, DXGI_FORMAT format, UINT slices = 1) { @@ -2144,6 +2170,7 @@ int main(int argc, char** argv) { if (argc == 2) { if (std::strcmp(argv[1], "--env-slots") == 0) return run_env_slots(true); if (std::strcmp(argv[1], "--env-slots-invalid") == 0) return run_env_slots(false); + if (std::strcmp(argv[1], "--env-slots-74") == 0) return run_env_slots(true, true); return run_fault_mode(argv[1]); } if (argc != 1) return 2; @@ -2155,7 +2182,8 @@ int main(int argc, char** argv) { check_render_target_sizes() || check_allocation_descriptions_cleaned() || check_render_target_layout() || - check_committed_resource_leases()) + check_committed_resource_leases() || + check_slot74()) return 1; std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news); return 0; From 6a9edfe37f6d44a114e07d599aa875381f681d0a Mon Sep 17 00:00:00 2001 From: Mumogg <104529023+Mumogg@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:36:22 -0600 Subject: [PATCH 047/110] d3d12_xs: slot 74's stand-in is for the title's calls; a host caller gets PC ShaderCacheControl The stand-in also took a host's ID3D12Device9::ShaderCacheControl call through the proxy and answered S_OK without reaching the device (found on native Windows by BadgersMC in the review of this change). Slot 74 now asks the caller classifier slot 61 uses (set_console_caller): a caller in an image the guest loader mapped gets the stand-in, any other caller, and every caller when no classifier is installed, is forwarded to the PC slot 74 or refused past the PC device's table. xs_proxy_mock_test: the guest case under a classifier, and the host case with a classifier and with none, on a device that has ShaderCacheControl and on one that does not. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01HxBQf4pXH8PWpC5oZsM4bt --- runtime/shims/d3d12_xs_device.cpp | 14 ++++++++++++-- runtime/test/xs_proxy_mock_test.cpp | 20 ++++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 42f23b1d07..da6f392c19 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -2409,7 +2409,8 @@ bool route_xbox_device_slot(DeviceProxy* self, unsigned slot, std::uint64_t a1, // Slot 74: the retail title calls it once with (pointer, u32, pointer) (kapitche, issue 7231). The PC slot 74 is // ID3D12Device9::ShaderCacheControl(kinds, control), which reads the first word as a flags value and returns // E_INVALIDARG, and the title then stops on an int3. The words are not measured: nothing is written through the -// pointers, the PC device is not called, and the call succeeds. +// pointers, the PC device is not called, and the call succeeds. Only for the title's calls (set_console_caller, as +// slot 61): a host caller of ID3D12Device9::ShaderCacheControl through the proxy gets the PC method. std::uint64_t proxy_slot74(std::uint64_t a1, std::uint64_t a2, std::uint64_t a3) { static std::atomic logged{false}; bool expected = false; @@ -2462,7 +2463,16 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64 std::uint64_t routed = 0; if (route_xbox_device_slot(self, Slot, a1, a2, a3, a4, a5, routed)) return routed; // an override moved a route here note_slot(Slot); - return proxy_slot74(a1, a2, a3); + if (is_console_caller(_ReturnAddress())) return proxy_slot74(a1, a2, a3); + // A host caller: the PC slot 74 (ID3D12Device9::ShaderCacheControl), forwarded like any other PC method, as + // slot 61 does. With no classifier installed every caller is a host one. + if (Slot >= self->slot_count) return hr_to_u64(refuse_beyond_device(Slot, self->slot_count)); + using ForwardFn = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std::uint64_t, + std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, + std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, + std::uint64_t, std::uint64_t, std::uint64_t); + auto fn = reinterpret_cast(self->real_vtable[Slot]); + return fn(self->real, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14); } else if constexpr (Slot == 75) { return hr_to_u64(proxy_create_command_queue1(self, a1, a2, reinterpret_cast(a3), reinterpret_cast(a4))); diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 9eca96c9d6..7e0d2da479 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -1324,9 +1324,29 @@ int check_slot74() { std::uint32_t second[4] = {0x55555555, 0x66666666, 0x77777777, 0x88888888}; const std::uint32_t first_before[4] = {first[0], first[1], first[2], first[3]}; const std::uint32_t second_before[4] = {second[0], second[1], second[2], second[3]}; + // The title's call (a caller the classifier takes for a guest image): the stand-in. + xs::set_console_caller([](std::uint64_t) { return true; }); EXPECT(hr_of(raw(device, 74, word(first), 7, word(second))) == S_OK); EXPECT(mock->calls[74] == 0 && xs::device_slot_hits(74) == 1); EXPECT(std::memcmp(first, first_before, sizeof(first)) == 0 && std::memcmp(second, second_before, sizeof(second)) == 0); + // A host caller, under a classifier and with none installed: the PC slot 74 (ShaderCacheControl) with the + // same words where the PC device has it, and the refusal past its table where it does not (found on Windows + // in the review of this change: the stand-in used to take a host's ShaderCacheControl too). + for (const bool installed : {true, false}) { + if (installed) + xs::set_console_caller([](std::uint64_t) { return false; }); + else + xs::set_console_caller(nullptr); + const std::uint64_t before = mock->calls[74]; + const HRESULT hr = hr_of(raw(device, 74, 0x1, 0x2)); + if (level >= 9) { + EXPECT(hr == S_OK && mock->calls[74] == before + 1); + EXPECT(mock->args[74][0] == 0x1 && mock->args[74][1] == 0x2); + } else { + EXPECT(hr == E_NOTIMPL && mock->calls[74] == before); + } + } + xs::set_console_caller(nullptr); EXPECT(release(device) == 0 && mock->refs == 0); } return 0; From 5d5afdeb4c02962f0bf33d2ccb69998ecebe93d6 Mon Sep 17 00:00:00 2001 From: Vadson159 Date: Mon, 23 Nov 2026 17:24:09 +0100 Subject: [PATCH 048/110] d3d12_xs: route command queue slot 35 to ExecuteCommandLists (cherry picked from commit e925b634551ed96d1ed097dfe17d7dfca0cdbe4d) Adapted to main by Mumogg: main has command-list proxies, so the shared execute function replaces them by their real lists in a copy of the array (UnwrappedArray), for the console slot 35 as for the PC slot 10, whose test failed otherwise. The slot 35 mock case passes two mock lists instead of two numbers and checks that they arrive and that the caller's array is not written. --- runtime/shims/d3d12_xs_device.cpp | 31 +++++++++++++ runtime/shims/d3d12_xs_device.h | 14 ++++-- runtime/test/queue_proxy_test.cpp | 72 +++++++++++++++++++++++------ runtime/test/xs_proxy_mock_test.cpp | 43 ++++++++++++++++- 4 files changed, 140 insertions(+), 20 deletions(-) diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index da6f392c19..ef0ae77815 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -803,7 +803,11 @@ static_assert(kQueueSlots * sizeof(void*) <= 4096 && kFenceSlots * sizeof(void*) kAllocatorSlots * sizeof(void*) <= 4096, "a table must fit in the first page of its reservation"); +constexpr unsigned kQueueExecuteCommandLists = 10; // (UINT, ID3D12CommandList* const*) constexpr unsigned kQueueSignal = 14, kQueueWait = 15; // (ID3D12Fence*, UINT64) +constexpr unsigned kQueueExecuteCommandListsX = 35; // console ExecuteCommandLists(count, lists) variant +static_assert(kQueueExecuteCommandLists < kQueuePublicSlots && kQueueExecuteCommandListsX < kQueueSlots, + "queue execution slots must stay within their respective tables"); struct ChildProxy { void** vtable; // offset 0: the caller's ID3D12CommandQueue* / ID3D12Fence* points here @@ -844,6 +848,7 @@ const char* child_public_name(unsigned slot) { if (slot < 8) return object[slot]; if constexpr (K == ChildKind::queue) { if (slot < kQueuePublicSlots) return queue[slot - 8]; + if (slot == kQueueExecuteCommandListsX) return "ExecuteCommandListsX"; } else if constexpr (K == ChildKind::fence) { if (slot < kFence1PublicSlots) return fence[slot - 8]; } else { @@ -1312,6 +1317,20 @@ LONG CALLBACK table_overrun_handler(EXCEPTION_POINTERS* info) { return EXCEPTION_CONTINUE_SEARCH; // diagnostics only: the fault goes on to the title's handlers or the crash } +std::uint64_t queue_execute_command_lists(ChildProxy* self, std::uint64_t count_word, std::uint64_t lists_word) { + // The array holds what the title got from the proxy: list proxies are replaced by the real lists in a copy, as + // for every other array of objects the real device or queue reads. + UnwrappedArray unwrapped_lists; + if (!unwrapped_lists.fill(lists_word, static_cast(count_word))) return hr_to_u64(E_OUTOFMEMORY); + if (unwrapped_lists.data()) lists_word = unwrapped_lists.data(); + // Pass zero-extended UINT in 64-bit RDX so both 32-bit PC implementations and 64-bit mock thunks see clean count. + using ExecuteFn = void(WINAPI*)(void*, std::uint64_t, ID3D12CommandList* const*); + reinterpret_cast(self->real_vtable[kQueueExecuteCommandLists])( + self->real, static_cast(static_cast(count_word)), + reinterpret_cast(lists_word)); + return 0; +} + template std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7, @@ -1331,6 +1350,10 @@ std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_ reinterpret_cast(a2))); } else { note_child_slot(Slot); + if constexpr (K == ChildKind::queue && Slot == kQueueExecuteCommandListsX) { + d3d12_trace::record(child_trace_name(Slot)); + return queue_execute_command_lists(self, a1, a2); + } if (Slot >= self->slot_count) { bool expected = false; if (ChildStats::beyond_warned[Slot].compare_exchange_strong(expected, true, @@ -1346,6 +1369,9 @@ std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_ return hr_to_u64(E_NOTIMPL); } d3d12_trace::record(child_trace_name(Slot)); // "called": the real object's result is not inspected + if constexpr (K == ChildKind::queue && Slot == kQueueExecuteCommandLists) { + return queue_execute_command_lists(self, a1, a2); + } if constexpr (K == ChildKind::queue && (Slot == kQueueSignal || Slot == kQueueWait)) a1 = unwrap_object(a1); UnwrappedArray unwrapped_lists; if constexpr (K == ChildKind::queue && Slot == 10) { @@ -2902,6 +2928,11 @@ unsigned fence_proxy_slot_count(const void* fence) { unsigned queue_proxy_table_size() { return kQueueSlots; } unsigned fence_proxy_table_size() { return kFenceSlots; } + +bool queue_slot_overridden(unsigned slot) { + return slot <= 2 || slot == 7 || slot == kQueueSignal || slot == kQueueWait || + slot == kQueueExecuteCommandListsX; +} unsigned allocator_proxy_table_size() { return kAllocatorSlots; } unsigned allocator_proxy_slot_count(const void* allocator) { return is_allocator_proxy(allocator) ? static_cast(allocator)->slot_count : 0; diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index ecd39db7bf..9f72820258 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -56,11 +56,12 @@ // // Command queues and fences (device slots 8, 75, 36, and 32 for a shared fence) come back wrapped in queue and fence // proxies of the same kind: the public chain (19 queue slots, 11 or 12 fence slots in SDK 10.0.26100) is forwarded -// in PC order, and a slot past it, up to the end of the proxy's table (128 queue, 64 fence slots), is logged with its -// first four argument words and refused with E_NOTIMPL. A slot past the table faults on the vtable read inside a -// reserved, never-committed region, and the fault is logged with the slot. That is where the console's queue methods -// (PresentX, SuspendX, ResumeX) will show up; their slots are not known and are not guessed, and that the console -// keeps the public slots is an assumption (docs/d3d12_command_objects.md §5.2). Heap, queue and fence proxies are +// in PC order. Queue slot 35 is the console ExecuteCommandLists(count, lists) variant and forwards to PC slot 10; +// every other slot past the public chain, up to the end of the proxy's table (128 queue, 64 fence slots), is logged +// with its first four argument words and refused with E_NOTIMPL. A slot past the table faults on the vtable read inside a +// reserved, never-committed region, and the fault is logged with the slot. PresentX, SuspendX and ResumeX slots past +// the public chain remain refused until measured and implemented, and that the console keeps the public slots is an +// assumption (docs/d3d12_command_objects.md §5.2). Heap, queue and fence proxies are // unwrapped wherever a device or queue method hands them to the real runtime: queue Signal/Wait (14/15), device // CreateSharedHandle (31), MakeResident/Evict (34/35), SetEventOnMultipleFenceCompletion (45), SetResidencyPriority // (46) and EnqueueMakeResident (50). Command lists are not wrapped, so ExecuteCommandLists passes them through and a @@ -178,6 +179,9 @@ unsigned queue_proxy_slot_count(const void* queue); unsigned fence_proxy_slot_count(const void* fence); unsigned queue_proxy_table_size(); unsigned fence_proxy_table_size(); +// True for queue slots handled by the proxy instead of forwarded verbatim past IUnknown: 0-2 (IUnknown), +// 7 (GetDevice), 14/15 (Signal/Wait unwrap fences), and 35 (Xbox ExecuteCommandLists variant -> PC slot 10). +bool queue_slot_overridden(unsigned slot); // Live references on a queue, fence or allocator proxy (0 for anything else). Test helper. unsigned long command_object_proxy_ref_count(const void* object); // Per-slot call counters and first-call flags, shared by all queue proxies and all fence proxies. diff --git a/runtime/test/queue_proxy_test.cpp b/runtime/test/queue_proxy_test.cpp index 3f46567f85..967313d53a 100644 --- a/runtime/test/queue_proxy_test.cpp +++ b/runtime/test/queue_proxy_test.cpp @@ -257,7 +257,9 @@ int check_slots(const Backend& b) { } } - // 10: ExecuteCommandLists passes the (real, not wrapped) command lists through. + // 10 and console slot 35: ExecuteCommandLists passes the (real, not wrapped) command lists through. + EXPECT(xs::queue_slot_overridden(35) && xs::queue_slot_overridden(14) && xs::queue_slot_overridden(15)); + EXPECT(!xs::queue_slot_overridden(10) && !xs::queue_slot_overridden(34)); { Ref allocator; EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, @@ -272,6 +274,11 @@ int check_slots(const Backend& b) { EXPECT(qhits(10) == before + 1); EXPECT(SUCCEEDED(queue->Signal(fence.p, 6))); if (wait_for(label, fence.p, 6)) return 1; + const std::uint64_t before35 = qhits(35); + EXPECT(raw_call(queue.p, 35, 1, reinterpret_cast(lists)) == 0); + EXPECT(qhits(35) == before35 + 1 && xs::queue_slot_first_call_seen(35)); + EXPECT(SUCCEEDED(queue->Signal(fence.p, 7))); + if (wait_for(label, fence.p, 7)) return 1; if (b.vulkan) { // The layer's own helpers find their queue behind the proxy. EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); @@ -293,17 +300,17 @@ int check_slots(const Backend& b) { // 14/15: Signal and Wait take fence proxies; the real queue gets the real fences. before = qhits(14); - EXPECT(SUCCEEDED(queue->Signal(fence.p, 7))); + EXPECT(SUCCEEDED(queue->Signal(fence.p, 8))); EXPECT(qhits(14) == before + 1); - if (wait_for(label, fence.p, 7)) return 1; + if (wait_for(label, fence.p, 8)) return 1; before = qhits(15); - EXPECT(SUCCEEDED(queue->Wait(fence.p, 8))); // the queue waits until the CPU signals 8 + EXPECT(SUCCEEDED(queue->Wait(fence.p, 9))); // the queue waits until the CPU signals 9 EXPECT(qhits(15) == before + 1); EXPECT(SUCCEEDED(queue->Signal(second.p, 1))); Sleep(50); EXPECT(second->GetCompletedValue() == 0); // still held by the Wait before = fhits(10); - EXPECT(SUCCEEDED(fence->Signal(8))); // fence 10, from the CPU + EXPECT(SUCCEEDED(fence->Signal(9))); // fence 10, from the CPU EXPECT(fhits(10) == before + 1); if (wait_for(label, second.p, 1)) return 1; @@ -359,12 +366,12 @@ int check_slots(const Backend& b) { EXPECT(fhits(7) == before + 1); } before = fhits(8); - EXPECT(fence->GetCompletedValue() == 8); + EXPECT(fence->GetCompletedValue() == 9); EXPECT(fhits(8) == before + 1); { Event done; before = fhits(9); - EXPECT(SUCCEEDED(fence->SetEventOnCompletion(8, done.h)) && done.set_within(5000)); + EXPECT(SUCCEEDED(fence->SetEventOnCompletion(9, done.h)) && done.set_within(5000)); EXPECT(fhits(9) == before + 1); } if (fence_slots == 12) { @@ -389,8 +396,9 @@ int check_slots(const Backend& b) { } } - // The refused tail: every slot from the end of the public chain to the end of the table. + // The refused tail: every unmodelled slot from the end of the public chain to the end of the table. for (unsigned slot = 19; slot < xs::queue_proxy_table_size(); ++slot) { + if (xs::queue_slot_overridden(slot)) continue; before = qhits(slot); EXPECT(as_hr(call_slot(queue.p, slot)) == E_NOTIMPL); EXPECT(qhits(slot) == before + 1 && xs::queue_slot_first_call_seen(slot)); @@ -1460,18 +1468,56 @@ int check_xbox_client(const Backend& b) { EXPECT(same); // the GPU really ran the list the queue proxy submitted } - // Device slot 50: EnqueueMakeResident with the objects and a fence proxy to signal. - EXPECT(SUCCEEDED(as_hr(raw(device, 50, D3D12_RESIDENCY_FLAG_NONE, 4, word(pageables), word(fence.p), 2)))); + // Second copy with fresh bytes, submitted through console ExecuteCommandLists slot 35. + { + std::uint8_t* bytes = nullptr; + EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast(&bytes)))); + for (UINT64 i = 0; i < kBytes; ++i) bytes[i] = static_cast(i * 11 + 5); + upload->Unmap(0, nullptr); + } + EXPECT(SUCCEEDED(allocator->Reset())); + EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr))); + D3D12_RESOURCE_BARRIER to_dest{}; + to_dest.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + to_dest.Transition.pResource = gpu.p; + to_dest.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + to_dest.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_SOURCE; + to_dest.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST; + list->ResourceBarrier(1, &to_dest); + list->CopyBufferRegion(gpu.p, 0, upload.p, 0, kBytes); + D3D12_RESOURCE_BARRIER to_source = to_dest; + to_source.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST; + to_source.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; + list->ResourceBarrier(1, &to_source); + list->CopyBufferRegion(readback.p, 0, gpu.p, 0, kBytes); + EXPECT(SUCCEEDED(list->Close())); + EXPECT(raw(queue.p, 35, 1, word(lists)) == 0); + EXPECT(SUCCEEDED(as_hr(raw(queue.p, 14, word(fence.p), 2)))); EXPECT(SUCCEEDED(as_hr(raw(fence.p, 9, 2, word(done.h)))) && done.set_within(5000)); + EXPECT(raw(fence.p, 8) >= 2); + { + std::uint8_t* bytes = nullptr; + const D3D12_RANGE read_range{0, kBytes}; + EXPECT(SUCCEEDED(readback->Map(0, &read_range, reinterpret_cast(&bytes)))); + bool same = true; + for (UINT64 i = 0; i < kBytes; ++i) same = same && bytes[i] == static_cast(i * 11 + 5); + const D3D12_RANGE nothing{0, 0}; + readback->Unmap(0, ¬hing); + EXPECT(same); // the GPU really ran the list submitted via queue slot 35 + } + + // Device slot 50: EnqueueMakeResident with the objects and a fence proxy to signal. + EXPECT(SUCCEEDED(as_hr(raw(device, 50, D3D12_RESIDENCY_FLAG_NONE, 4, word(pageables), word(fence.p), 3)))); + EXPECT(SUCCEEDED(as_hr(raw(fence.p, 9, 3, word(done.h)))) && done.set_within(5000)); // Queue slot 15 holds the queue until the CPU (fence slot 10) signals; device slot 45 then sees both fences. - EXPECT(SUCCEEDED(as_hr(raw(queue.p, 15, word(fence.p), 3)))); + EXPECT(SUCCEEDED(as_hr(raw(queue.p, 15, word(fence.p), 4)))); EXPECT(SUCCEEDED(as_hr(raw(queue.p, 14, word(second.p), 1)))); Sleep(50); EXPECT(raw(second.p, 8) == 0); - EXPECT(SUCCEEDED(as_hr(raw(fence.p, 10, 3)))); + EXPECT(SUCCEEDED(as_hr(raw(fence.p, 10, 4)))); ID3D12Fence* both[] = {fence.p, second.p}; - const UINT64 values[] = {3, 1}; + const UINT64 values[] = {4, 1}; EXPECT(SUCCEEDED(as_hr(raw(device, 45, word(both), word(values), 2, D3D12_MULTIPLE_FENCE_WAIT_FLAG_ALL, word(done.h)))) && done.set_within(5000)); diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 7e0d2da479..b4bdc97a01 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -1135,6 +1135,42 @@ int check_xbox_slots() { #endif } +// ---- 7b. Xbox queue ExecuteCommandLists variant (queue slot 35 -> PC slot 10) ---- + +int check_xbox_queue_slots() { + Mock* mock = nullptr; + void* device = make_device(mock, 9, true); + EXPECT(device); + void* queue = make_queue(device); + EXPECT(queue); + Mock* const queue_mock = reinterpret_cast(xs::queue_proxy_real_queue(queue)); + xs::reset_device_proxy_stats(); + + EXPECT(xs::queue_slot_overridden(35) && xs::queue_slot_overridden(14) && xs::queue_slot_overridden(15)); + EXPECT(!xs::queue_slot_overridden(10) && !xs::queue_slot_overridden(34) && !xs::queue_slot_overridden(36)); + + // Real objects, not numbers: the array is read to replace list proxies by their real lists, as slot 10's is. + Mock* const list_a = new_mock(Kind::command_list); + Mock* const list_b = new_mock(Kind::command_list); + void* lists[2] = {list_a, list_b}; + EXPECT(raw(queue, 35, (0xdeadbeefull << 32) | 2ull, word(lists)) == 0); + EXPECT(xs::queue_slot_hits(35) == 1 && xs::queue_slot_first_call_seen(35)); + EXPECT(xs::queue_slot_hits(10) == 0); + EXPECT(queue_mock->calls[35] == 0 && queue_mock->calls[10] == 1); + EXPECT(queue_mock->args[10][0] == 2); + EXPECT(queue_mock->array[10][0] == word(list_a) && queue_mock->array[10][1] == word(list_b)); + EXPECT(lists[0] == list_a && lists[1] == list_b); // the caller's array is not written + + EXPECT(raw(queue, 35, 0, 0) == 0); + EXPECT(xs::queue_slot_hits(35) == 2 && queue_mock->calls[35] == 0 && queue_mock->calls[10] == 2); + EXPECT(queue_mock->args[10][0] == 0 && queue_mock->args[10][1] == 0); + + EXPECT(release(queue) == 0 && release(device) == 0 && mock->refs == 0); + std::printf("%s: queue slot 35 routes ExecuteCommandLists(count, lists) to PC slot 10 with UINT count masking\n", + g_label); + return 0; +} + // ---- 8. Environment overrides for the Xbox device slots (one process each, read once) ---- int run_env_slots(bool valid, bool on_slot74 = false) { @@ -1615,8 +1651,10 @@ int check_tail(bool want_guarded) { // Signal (14) still reaches the real queue, with the real fence. EXPECT(hr_of(raw(queue, 14, word(fence), 5)) == S_OK && queue_mock->calls[14] == 1 && queue_mock->args[14][0] == word(xs::fence_proxy_real_fence(fence)) && queue_mock->args[14][1] == 5); - for (unsigned slot = 19; slot < xs::queue_proxy_table_size(); ++slot) + for (unsigned slot = 19; slot < xs::queue_proxy_table_size(); ++slot) { + if (xs::queue_slot_overridden(slot)) continue; EXPECT(hr_of(raw(queue, slot)) == E_NOTIMPL && queue_mock->calls[slot] == 0); + } for (unsigned slot = 12; slot < xs::fence_proxy_table_size(); ++slot) EXPECT(hr_of(raw(fence, slot)) == E_NOTIMPL); EXPECT(xs::queue_table_overruns() == 0 && xs::fence_table_overruns() == 0); EXPECT(release(queue) == 0 && release(fence) == 0 && release(device) == 0 && mock->refs == 0); @@ -2203,7 +2241,8 @@ int main(int argc, char** argv) { check_allocation_descriptions_cleaned() || check_render_target_layout() || check_committed_resource_leases() || - check_slot74()) + check_slot74() || + check_xbox_queue_slots()) return 1; std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news); return 0; From 6d5b2d4c2f0782e583b2094719b5292218de6594 Mon Sep 17 00:00:00 2001 From: DevilNine <102010568+DevilNine@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:46:12 -0300 Subject: [PATCH 049/110] d3d12_xs: handle ID3D12CommandAllocator slot 9 (SetAllocatorCallbackX) on allocator proxy (cherry picked from commit e29e9899809347a730fd57a14532a22fe0ee7231) --- runtime/shims/d3d12_xs_device.cpp | 34 +++++++++++++++++++++++++++ runtime/shims/d3d12_xs_device.h | 12 ++++++---- runtime/test/allocator_proxy_test.cpp | 31 ++++++++++++++++++------ runtime/test/xs_proxy_mock_test.cpp | 16 +++++++++++-- 4 files changed, 80 insertions(+), 13 deletions(-) diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index ef0ae77815..2665dd4aff 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -816,6 +816,9 @@ struct ChildProxy { void** real_vtable; unsigned slot_count; // public slots the real object implements; the rest of the table is refused std::atomic refs; + // Allocators only: callback and context recorded by console slot 9 (SetAllocatorCallbackX). + std::atomic allocator_callback{0}; + std::atomic allocator_callback_context{0}; }; template @@ -853,6 +856,7 @@ const char* child_public_name(unsigned slot) { if (slot < kFence1PublicSlots) return fence[slot - 8]; } else { if (slot == 8) return "Reset"; + if (slot == 9) return "SetAllocatorCallbackX"; } return nullptr; } @@ -1354,6 +1358,24 @@ std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_ d3d12_trace::record(child_trace_name(Slot)); return queue_execute_command_lists(self, a1, a2); } + if constexpr (K == ChildKind::allocator && Slot == 9) { + // Console-only ID3D12CommandAllocator::SetAllocatorCallbackX(callback, context, ...), observed past the + // 9-slot PC chain on the retail executable (call shape: function pointer, context, plus trailing words). + // The PC/Vulkan layer manages command-buffer backing directly without invoking a title allocator callback, + // so record the callback and context on the proxy and return S_OK while leaving slots 10+ refused. + self->allocator_callback.store(static_cast(a1), std::memory_order_relaxed); + self->allocator_callback_context.store(static_cast(a2), std::memory_order_relaxed); + static std::atomic logged{false}; + if (!logged.exchange(true, std::memory_order_relaxed)) { + std::fprintf(stderr, + "[rt] d3d12_xs: allocator slot 9 (SetAllocatorCallbackX) recorded " + "(callback=0x%llx context=0x%llx a3=0x%llx a4=0x%llx)\n", + static_cast(a1), static_cast(a2), + static_cast(a3), static_cast(a4)); + } + d3d12_trace::record(child_trace_name(Slot)); + return hr_to_u64(S_OK); + } if (Slot >= self->slot_count) { bool expected = false; if (ChildStats::beyond_warned[Slot].compare_exchange_strong(expected, true, @@ -2938,6 +2960,18 @@ unsigned allocator_proxy_slot_count(const void* allocator) { return is_allocator_proxy(allocator) ? static_cast(allocator)->slot_count : 0; } +std::uintptr_t allocator_proxy_callback(const void* allocator) { + return is_allocator_proxy(allocator) + ? static_cast(allocator)->allocator_callback.load(std::memory_order_relaxed) + : 0; +} + +std::uintptr_t allocator_proxy_callback_context(const void* allocator) { + return is_allocator_proxy(allocator) + ? static_cast(allocator)->allocator_callback_context.load(std::memory_order_relaxed) + : 0; +} + unsigned long command_object_proxy_ref_count(const void* object) { if (!is_queue_proxy(object) && !is_fence_proxy(object) && !is_allocator_proxy(object)) return 0; return static_cast(object)->refs.load(std::memory_order_relaxed); diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index 9f72820258..652b6047c3 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -196,10 +196,11 @@ std::uint64_t fence_table_overruns(); // or the fault logger failed). bool command_object_tables_guarded(); -// Command allocator proxies (device slot 9): the public chain (9 slots: the base chain and Reset) is forwarded, a -// slot past it up to the end of the table (64 slots) is logged and refused with E_NOTIMPL, and a read past the -// table faults in a guard region, as for queues and fences. The console allocator's extra methods are not -// measured and not guessed. Slot 9 wraps only an allocator that answers kLeonidaCommandAllocatorTag, Leonida's +// Command allocator proxies (device slot 9): the public chain (9 slots: the base chain and Reset) is forwarded, +// slot 9 (console SetAllocatorCallbackX(callback, context, ...)) records the callback and context on the proxy and +// returns S_OK without invoking the callback on the PC/Vulkan path, slots 10..63 are logged and refused with +// E_NOTIMPL, and a read past the table faults in a guard region, as for queues and fences. Slot 9 wraps only an +// allocator that answers kLeonidaCommandAllocatorTag, Leonida's // own Vulkan-layer allocator: its command lists resolve the proxy (CreateCommandList, Reset). A PC runtime // allocator goes back unchanged, because the PC runtime's lists would take a proxy for their own allocator; a // command-list proxy that unwraps at Reset is what lets the host backend wrap allocators too. @@ -211,6 +212,9 @@ bool is_allocator_proxy(const void* allocator); ID3D12CommandAllocator* allocator_proxy_real_allocator(const void* allocator); unsigned allocator_proxy_slot_count(const void* allocator); unsigned allocator_proxy_table_size(); +// Callback and context recorded by console allocator slot 9 (SetAllocatorCallbackX), or 0 if unset / not a proxy. +std::uintptr_t allocator_proxy_callback(const void* allocator); +std::uintptr_t allocator_proxy_callback_context(const void* allocator); std::uint64_t allocator_slot_hits(unsigned slot); bool allocator_slot_first_call_seen(unsigned slot); std::uint64_t allocator_table_overruns(); diff --git a/runtime/test/allocator_proxy_test.cpp b/runtime/test/allocator_proxy_test.cpp index 5f89366f54..b48b224b72 100644 --- a/runtime/test/allocator_proxy_test.cpp +++ b/runtime/test/allocator_proxy_test.cpp @@ -58,11 +58,13 @@ using SlotFn = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std:: std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t); -// A call through slot `slot` with all words zero, the way a title calls a console method the PC interface lacks. -HRESULT call_slot(void* object, unsigned slot) { +// A call through slot `slot` with up to four explicit words (rest zero), the way a title calls a console method the PC +// interface lacks. +HRESULT call_slot(void* object, unsigned slot, std::uint64_t a1 = 0, std::uint64_t a2 = 0, std::uint64_t a3 = 0, + std::uint64_t a4 = 0) { void** vtable = *reinterpret_cast(object); return static_cast(static_cast( - reinterpret_cast(vtable[slot])(object, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))); + reinterpret_cast(vtable[slot])(object, a1, a2, a3, a4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))); } ULONG_PTR g_fault_address = 0; @@ -182,10 +184,24 @@ int check_proxy(const Backend& b, ID3D12CommandAllocator* allocator) { back->Release(); EXPECT(SUCCEEDED(allocator->SetPrivateDataInterface(key, nullptr))); - // The refused tail: every slot past the public chain, up to the table end, is E_NOTIMPL and counted. + // Console slot 9 (SetAllocatorCallbackX): records callback/context on the proxy and returns S_OK. const unsigned table = xs::allocator_proxy_table_size(); EXPECT(table == 64); - for (unsigned slot = 9; slot < table; ++slot) { + { + EXPECT(xs::allocator_proxy_callback(allocator) == 0 && xs::allocator_proxy_callback_context(allocator) == 0); + constexpr std::uintptr_t fake_cb = 0x11223344u; + constexpr std::uintptr_t fake_ctx = 0x55667788u; + const std::uint64_t before = xs::allocator_slot_hits(9); + EXPECT(call_slot(allocator, 9, fake_cb, fake_ctx, 0, 0x99aabbccu) == S_OK); + EXPECT(xs::allocator_slot_hits(9) == before + 1 && xs::allocator_slot_first_call_seen(9)); + EXPECT(xs::allocator_proxy_callback(allocator) == fake_cb && + xs::allocator_proxy_callback_context(allocator) == fake_ctx); + EXPECT(call_slot(allocator, 9, 0, 0) == S_OK); + EXPECT(xs::allocator_proxy_callback(allocator) == 0 && xs::allocator_proxy_callback_context(allocator) == 0); + } + + // The refused tail: every slot past slot 9, up to the table end, is E_NOTIMPL and counted. + for (unsigned slot = 10; slot < table; ++slot) { const std::uint64_t before = xs::allocator_slot_hits(slot); EXPECT(call_slot(allocator, slot) == E_NOTIMPL); EXPECT(xs::allocator_slot_hits(slot) == before + 1 && xs::allocator_slot_first_call_seen(slot)); @@ -201,8 +217,9 @@ int check_proxy(const Backend& b, ID3D12CommandAllocator* allocator) { EXPECT(g_fault_address == reinterpret_cast(&vtable[slot])); EXPECT(xs::allocator_table_overruns() == before + 1); } - std::printf("%s: allocator proxy: 9 public slots forwarded, slots 9-%u refused, the guard region names a read " - "past the table; QueryInterface/GetDevice/private data keep the proxy identity\n", label, table - 1); + std::printf("%s: allocator proxy: 9 public slots forwarded, slot 9 SetAllocatorCallbackX handled, slots 10-%u " + "refused, the guard region names a read past the table; QueryInterface/GetDevice/private data keep " + "the proxy identity\n", label, table - 1); return 0; } diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index b4bdc97a01..469796cd46 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -935,9 +935,21 @@ int check_allocators() { EXPECT(xs::is_allocator_proxy(allocator) && word(xs::allocator_proxy_real_allocator(allocator)) == word(real)); EXPECT(mock->args[9][0] == D3D12_COMMAND_LIST_TYPE_DIRECT && real->refs == 1); EXPECT(xs::allocator_proxy_slot_count(allocator) == 9 && xs::device_proxy_ref_count(device) == device_refs + 1); - // Reset (slot 8) reaches the real allocator; every slot past it up to the table end is refused. + // Reset (slot 8) reaches the real allocator; slot 9 (SetAllocatorCallbackX) records callback/context and + // succeeds without touching the real vtable; every slot past 9 up to the table end is refused. EXPECT(hr_of(raw(allocator, 8)) == S_OK && real->calls[8] == 1); - for (unsigned slot = 9; slot < xs::allocator_proxy_table_size(); ++slot) + EXPECT(xs::allocator_proxy_callback(allocator) == 0 && xs::allocator_proxy_callback_context(allocator) == 0); + EXPECT(xs::allocator_proxy_callback(nullptr) == 0 && xs::allocator_proxy_callback_context(device) == 0); + constexpr std::uintptr_t fake_cb = 0x12345678u; + constexpr std::uintptr_t fake_ctx = 0x9abcdef0u; + const std::uint64_t slot9_hits_before = xs::allocator_slot_hits(9); + EXPECT(hr_of(raw(allocator, 9, fake_cb, fake_ctx, 0, 0xfeedfaceu)) == S_OK && real->calls[9] == 0); + EXPECT(xs::allocator_slot_hits(9) == slot9_hits_before + 1 && xs::allocator_slot_first_call_seen(9)); + EXPECT(xs::allocator_proxy_callback(allocator) == fake_cb && + xs::allocator_proxy_callback_context(allocator) == fake_ctx); + EXPECT(hr_of(raw(allocator, 9, 0, 0)) == S_OK && real->calls[9] == 0); + EXPECT(xs::allocator_proxy_callback(allocator) == 0 && xs::allocator_proxy_callback_context(allocator) == 0); + for (unsigned slot = 10; slot < xs::allocator_proxy_table_size(); ++slot) EXPECT(hr_of(raw(allocator, slot)) == E_NOTIMPL && real->calls[slot] == 0); // The tag and the real object stay hidden: QueryInterface answers only the modelled interfaces. void* found = reinterpret_cast(1); From 7d58fa5790ed1764cad6258e9730080437ab5f7e Mon Sep 17 00:00:00 2001 From: Mumogg <104529023+Mumogg@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:30:28 -0600 Subject: [PATCH 050/110] d3d12_xs: console list slot 139 is Reset, routed to the PC slot 10 The retail title resets its command lists through list slot 139, with (allocator proxy, pipeline state). main's slot map had no entry for it, so the call was recorded and dropped and the list stayed closed. The map sends it to the PC slot 10, and the unwrap keys on the PC slot, so console slot 10 and console slot 139 both hand the real list its real allocator (and a wrapped pipeline state the same way) and re-pin the inline cursor. The mapping and the unwrap rule are those of ef9d0759d (Nolan Cotter; measured by Pipodi), written again for main's list proxy, where that commit does not apply. xs_proxy_mock_test checks the map entry and a slot 139 call. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01HxBQf4pXH8PWpC5oZsM4bt --- runtime/shims/d3d12_xs_device.cpp | 5 ++++- runtime/shims/d3d12_xs_device.h | 1 + runtime/test/xs_proxy_mock_test.cpp | 10 ++++++++++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 2665dd4aff..1d3350a7ac 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -1221,8 +1221,11 @@ std::uint64_t WINAPI list_slot(ListProxy* self, std::uint64_t a1, std::uint64_t std::uint64_t, std::uint64_t); auto** const real_vtable = *reinterpret_cast(self->real); UnwrappedArray heaps; - if constexpr (Slot == 10) { + if constexpr (pc == 10) { + // Reset(allocator, pso): console slot 10, and slot 139 as the retail title calls it. The title hands + // its allocator proxy; the real list takes the real one (and a wrapped pipeline state the same way). a1 = unwrap_object(a1); + a2 = unwrap_object(a2); self->pin_cursor_at_limit(); } else if constexpr (Slot == kConsoleExecuteBundle) { a1 = unwrap_object(a1); diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index 652b6047c3..b9062ff202 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -237,6 +237,7 @@ inline constexpr unsigned console_to_pc_list_slot(unsigned slot) { if (slot == 60) return 58; // EndEvent (no console SetMarker/BeginEvent) if (slot == 61) return 59; // ExecuteIndirect (Package) if (slot == 85) return 16; // CopyTextureRegionX -> CopyTextureRegion + if (slot == 139) return 10; // Reset(allocator, pso), as the retail title calls it (measured, Pipodi) if (slot == 146) return 80; // D3D12_BARRIER_GROUP (Package; PC GCL7) return kListNotForwarded; } diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 469796cd46..1ea064c559 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -2068,6 +2068,7 @@ int check_console_command_list() { EXPECT(xs::console_to_pc_list_slot(60) == 58); // EndEvent EXPECT(xs::console_to_pc_list_slot(61) == 59); // ExecuteIndirect EXPECT(xs::console_to_pc_list_slot(85) == 16); // CopyTextureRegion + EXPECT(xs::console_to_pc_list_slot(139) == 10); // Reset, as the retail title calls it EXPECT(xs::console_to_pc_list_slot(146) == 80); // GCL7 Barrier EXPECT(xs::console_to_pc_list_slot(148) == xs::kListNotForwarded); // AllocateUploadMemory @@ -2173,6 +2174,15 @@ int check_console_command_list() { std::memcpy(&c18, reinterpret_cast(base + 0x18), sizeof(c18)); EXPECT(c18 == expected_limit); + // Console slot 139 is Reset as the retail title calls it: the same PC slot 10, allocator unwrapped, cursor + // re-pinned, and the list's own slot 139 never reached. + std::memcpy(reinterpret_cast(base + 0x18), &zero, sizeof(zero)); + EXPECT(hr_of(raw(list_proxy, 139, word(allocator), 0, 0, 0)) == S_OK); + EXPECT(real_list->calls[10] == 2 && real_list->calls[139] == 0); + EXPECT(real_list->args[10][0] == word(real_allocator) && real_list->args[10][1] == 0); + std::memcpy(&c18, reinterpret_cast(base + 0x18), sizeof(c18)); + EXPECT(c18 == expected_limit); + // Console slot 7 (GetDevice) returns device proxy void* list_dev = nullptr; const IID dev_iid = __uuidof(ID3D12Device); From e7044cb9bb1c0a5a1d075405ad916a48a8ec5e0b Mon Sep 17 00:00:00 2001 From: Mumogg <104529023+Mumogg@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:42:00 -0600 Subject: [PATCH 051/110] d3d12_xs: the title's queue slot 18 is the frequency getter, not PC GetDesc Queue slot 18 is ID3D12CommandQueue::GetDesc on the PC: a struct return that writes a 16-byte description through the hidden pointer. The retail title calls slot 18 with one pointer to 8 bytes, the shape of GetTimestampFrequency(UINT64*), which the console queue has there (two methods are inserted at 14/15, so the PC slots 16 to 18 sit two later). Forwarded as GetDesc, the call wrote a description over the title's 8 bytes and what follows them; the title then went wrong a little later, after its first submission. The title's call (set_console_caller, as device slots 61 and 74) now goes to the PC slot 16. A host caller, and every caller when no classifier is installed, keeps the PC GetDesc. The reading of slot 18 is that of the console queue work in old PR 2490 (Nolan Cotter), which answers an undetected slot 18 as the frequency getter because it is the only reading that cannot overrun its argument. That work's layout detection does not apply to main's queue proxy; this is the one rule the boot needs, written for it. xs_proxy_mock_test: the guest call reaches the mock queue's slot 16 with its pointer and leaves the words around it; a host call, with a classifier and with none, reaches slot 18. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01HxBQf4pXH8PWpC5oZsM4bt --- runtime/shims/d3d12_xs_device.cpp | 15 +++++++++++++++ runtime/test/xs_proxy_mock_test.cpp | 16 ++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 1d3350a7ac..0acfa0d752 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -805,6 +805,8 @@ static_assert(kQueueSlots * sizeof(void*) <= 4096 && kFenceSlots * sizeof(void*) constexpr unsigned kQueueExecuteCommandLists = 10; // (UINT, ID3D12CommandList* const*) constexpr unsigned kQueueSignal = 14, kQueueWait = 15; // (ID3D12Fence*, UINT64) +constexpr unsigned kQueueGetTimestampFrequency = 16, kQueueGetDesc = 18; // the PC slots +bool is_console_caller(const void* address); // defined with the device proxy constexpr unsigned kQueueExecuteCommandListsX = 35; // console ExecuteCommandLists(count, lists) variant static_assert(kQueueExecuteCommandLists < kQueuePublicSlots && kQueueExecuteCommandListsX < kQueueSlots, "queue execution slots must stay within their respective tables"); @@ -1397,6 +1399,19 @@ std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_ if constexpr (K == ChildKind::queue && Slot == kQueueExecuteCommandLists) { return queue_execute_command_lists(self, a1, a2); } + if constexpr (K == ChildKind::queue && Slot == kQueueGetDesc) { + // Queue slot 18 is GetDesc on the PC: a struct return, 16 bytes written through the hidden pointer. The + // retail title calls slot 18 with one pointer to 8 bytes, the shape of GetTimestampFrequency(UINT64*), + // which the console layout with two methods inserted at 14/15 has there (PC slot 16). Forwarded as + // GetDesc it wrote a whole description over the title's 8 bytes and what follows them. The title's call + // therefore goes to the frequency getter, the only reading that cannot overrun its argument; a host + // caller (set_console_caller, as device slots 61 and 74) keeps the PC GetDesc. + if (is_console_caller(_ReturnAddress())) { + using Fn = HRESULT(WINAPI*)(void*, UINT64*); + return hr_to_u64(reinterpret_cast(self->real_vtable[kQueueGetTimestampFrequency])( + self->real, reinterpret_cast(a1))); + } + } if constexpr (K == ChildKind::queue && (Slot == kQueueSignal || Slot == kQueueWait)) a1 = unwrap_object(a1); UnwrappedArray unwrapped_lists; if constexpr (K == ChildKind::queue && Slot == 10) { diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 1ea064c559..9f6dd50461 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -1177,6 +1177,22 @@ int check_xbox_queue_slots() { EXPECT(xs::queue_slot_hits(35) == 2 && queue_mock->calls[35] == 0 && queue_mock->calls[10] == 2); EXPECT(queue_mock->args[10][0] == 0 && queue_mock->args[10][1] == 0); + // Queue slot 18. The title's call (one pointer to 8 bytes) is the frequency getter, PC slot 16, and never the + // PC slot 18 (GetDesc), which would write a 16-byte description through that pointer. A host caller, under a + // classifier and with none installed, keeps the PC slot 18. + std::uint64_t frequency[3] = {0xA5A5A5A5A5A5A5A5ull, 0xA5A5A5A5A5A5A5A5ull, 0xA5A5A5A5A5A5A5A5ull}; + xs::set_console_caller([](std::uint64_t) { return true; }); + raw(queue, 18, word(&frequency[1])); + EXPECT(queue_mock->calls[16] == 1 && queue_mock->calls[18] == 0 && queue_mock->args[16][0] == word(&frequency[1])); + EXPECT(frequency[0] == 0xA5A5A5A5A5A5A5A5ull && frequency[2] == 0xA5A5A5A5A5A5A5A5ull); + xs::set_console_caller([](std::uint64_t) { return false; }); + D3D12_COMMAND_QUEUE_DESC host_desc{}; + raw(queue, 18, word(&host_desc)); + EXPECT(queue_mock->calls[16] == 1 && queue_mock->calls[18] == 1 && queue_mock->args[18][0] == word(&host_desc)); + xs::set_console_caller(nullptr); + raw(queue, 18, word(&host_desc)); + EXPECT(queue_mock->calls[16] == 1 && queue_mock->calls[18] == 2); + EXPECT(release(queue) == 0 && release(device) == 0 && mock->refs == 0); std::printf("%s: queue slot 35 routes ExecuteCommandLists(count, lists) to PC slot 10 with UINT count masking\n", g_label); From 06196160febe3416020a1899da1c4381b56097ae Mon Sep 17 00:00:00 2001 From: Mumogg <104529023+Mumogg@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:45:09 -0600 Subject: [PATCH 052/110] d3d12_xs: the queue's console slot 32 is PresentX, wired to the presentation core The retail title presents through command-queue slot 32, past the PC queue's 19 slots, so main refused it with E_NOTIMPL and nothing could be shown. The slot now calls XboxPresentation::PresentX (xbox_present.h) with the title's plane count, planes and parameters. The first call on a device builds a window and the Vulkan layer's presenter for it, once; a device that cannot present answers S_OK and shows nothing, so the title's frame loop runs either way. The mock and COM builds of this file have no presenter and answer S_OK. The wiring follows old PR 2490's (Nolan Cotter, 2be25cee2), written again for main's queue proxy, where that commit does not apply. Not carried over: the queue layout detection (the older layout has PresentX at slot 30) and presenting into the title's own window (old PR 8591); the window here is one this layer creates. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01HxBQf4pXH8PWpC5oZsM4bt --- runtime/shims/d3d12_xs_device.cpp | 96 ++++++++++++++++++++++++++++++- 1 file changed, 95 insertions(+), 1 deletion(-) diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 0acfa0d752..63e834beea 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -29,6 +29,12 @@ #include "d3d12_xs_desc_clean.h" #include "../src/shader_library.h" // leonida::fspx_payload_from_parts for slot 67 +#ifdef LEONIDA_VULKAN_DEVICE +// PresentX wiring: the queue's console slot lands on the Xbox presentation core, which needs the Vulkan layer's +// WindowPresenter. Other builds of this file (the mock and COM tests) have no presenter and answer S_OK. +#include "xbox_present.h" +#endif + #include #include #include // _ReturnAddress: slot 61 serves a console caller differently from a host one @@ -83,8 +89,13 @@ struct DeviceProxy { std::atomic frame_latency{1}; std::atomic frame_event_scheduled{false}; std::atomic frame_next_token{1}; + // The PresentX state (window, presenter, XboxPresentation) the first queue PresentX builds on this device, + // destroyed with the proxy. Opaque here: PresentState is defined with the queue proxy. + void* present_state = nullptr; }; +void destroy_present_state(void* present_state); + constexpr unsigned kHeapSlots = 11; // IUnknown + ID3D12Object + DeviceChild + Pageable + GetDesc + 2 handles struct HeapProxy { @@ -379,6 +390,7 @@ unsigned long proxy_release(DeviceProxy* self) { const unsigned long refs = self->refs.fetch_sub(1, std::memory_order_acq_rel) - 1; if (refs == 0) { ID3D12Device* real = self->real; + destroy_present_state(self->present_state); // the presenter goes before the device it draws with delete self; if (real) real->Release(); } @@ -1326,6 +1338,85 @@ LONG CALLBACK table_overrun_handler(EXCEPTION_POINTERS* info) { return EXCEPTION_CONTINUE_SEARCH; // diagnostics only: the fault goes on to the title's handlers or the crash } +// ---- PresentX (console queue slot 32) ---- +// +// The retail title presents through command-queue slot 32, past the PC queue's 19 slots: PresentX(plane count, +// planes, parameters), the call the Xbox presentation core (xbox_present.h) implements. The first call on a device +// builds a window and the Vulkan layer's presenter for it, once; a device that cannot present (no presenter, no +// window) answers S_OK and shows nothing, so the title's frame loop keeps running either way. +// ASSUMPTION: the window is one this layer creates. The title has a window of its own; presenting into that one is +// a separate piece of work (old PR 8591). +constexpr unsigned kQueuePresentX = 32; + +#ifdef LEONIDA_VULKAN_DEVICE + +struct PresentState { + ~PresentState() { + xbox.reset(); + if (window) DestroyWindow(window); + } + HWND window = nullptr; + std::unique_ptr xbox; +}; + +void destroy_present_state(void* present_state) { delete static_cast(present_state); } + +LRESULT CALLBACK present_window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { + return DefWindowProcW(window, message, wparam, lparam); +} + +// Builds the window, presenter and XboxPresentation once per device. Returns the state even when `xbox` stays null: +// the failure is logged once and not retried. +PresentState* present_state_for(DeviceProxy* device) { + static std::mutex mutex; + const std::lock_guard lock(mutex); + if (auto* state = static_cast(device->present_state)) return state; + auto* state = new (std::nothrow) PresentState; + if (!state) return nullptr; + device->present_state = state; + WNDCLASSW window_class{}; + window_class.lpfnWndProc = present_window_proc; + window_class.hInstance = GetModuleHandleW(nullptr); + window_class.lpszClassName = L"LeonidaPresentX"; + if (!RegisterClassW(&window_class) && GetLastError() != ERROR_CLASS_ALREADY_EXISTS) { + std::fprintf(stderr, "[rt] d3d12_xs: PresentX window class failed (error %lu)\n", GetLastError()); + return state; + } + state->window = CreateWindowExW(0, window_class.lpszClassName, L"Leonida", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, + CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, nullptr, nullptr, + window_class.hInstance, nullptr); + if (!state->window) { + std::fprintf(stderr, "[rt] d3d12_xs: PresentX window failed (error %lu)\n", GetLastError()); + return state; + } + ShowWindow(state->window, SW_SHOWNOACTIVATE); + auto presenter = rt::d3d12::create_window_presenter(device->real, state->window); + if (!presenter) { + std::fprintf(stderr, "[rt] d3d12_xs: no window presenter on this device; PresentX shows nothing\n"); + return state; + } + state->xbox = std::make_unique(std::move(presenter)); + std::fprintf(stderr, "[rt] d3d12_xs: PresentX ready (window %p)\n", static_cast(state->window)); + return state; +} + +std::uint64_t queue_present_x(ChildProxy* self, std::uint64_t plane_count, std::uint64_t planes, + std::uint64_t params) { + PresentState* state = self->device ? present_state_for(self->device) : nullptr; + if (!state || !state->xbox) return hr_to_u64(S_OK); // the title still runs with nothing presented + return hr_to_u64(state->xbox->PresentX( + static_cast(plane_count), reinterpret_cast(planes), + reinterpret_cast(params))); +} + +#else // !LEONIDA_VULKAN_DEVICE: this translation unit stands alone (the mock and COM tests) + +void destroy_present_state(void*) {} + +std::uint64_t queue_present_x(ChildProxy*, std::uint64_t, std::uint64_t, std::uint64_t) { return hr_to_u64(S_OK); } + +#endif + std::uint64_t queue_execute_command_lists(ChildProxy* self, std::uint64_t count_word, std::uint64_t lists_word) { // The array holds what the title got from the proxy: list proxies are replaced by the real lists in a copy, as // for every other array of objects the real device or queue reads. @@ -1363,6 +1454,9 @@ std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_ d3d12_trace::record(child_trace_name(Slot)); return queue_execute_command_lists(self, a1, a2); } + if constexpr (K == ChildKind::queue && Slot == kQueuePresentX) { + return queue_present_x(self, a1, a2, a3); // XboxPresentation::PresentX writes the trace line + } if constexpr (K == ChildKind::allocator && Slot == 9) { // Console-only ID3D12CommandAllocator::SetAllocatorCallbackX(callback, context, ...), observed past the // 9-slot PC chain on the retail executable (call shape: function pointer, context, plus trailing words). @@ -2971,7 +3065,7 @@ unsigned fence_proxy_table_size() { return kFenceSlots; } bool queue_slot_overridden(unsigned slot) { return slot <= 2 || slot == 7 || slot == kQueueSignal || slot == kQueueWait || - slot == kQueueExecuteCommandListsX; + slot == kQueueExecuteCommandListsX || slot == kQueuePresentX; } unsigned allocator_proxy_table_size() { return kAllocatorSlots; } unsigned allocator_proxy_slot_count(const void* allocator) { From 21a6c617bc6e5706debde9a6320c9f785e55cf2b Mon Sep 17 00:00:00 2001 From: Logan Date: Mon, 23 Nov 2026 12:16:11 -0500 Subject: [PATCH 053/110] PresentX: device-side WaitFrameEventX and the frame pacer share one token source Device slot 80 (WaitFrameEventX, from #6935) numbered its tokens with a counter of its own, while XboxPresentation's pacer refuses any token above the ones it issued itself. A title that waits through the device and presents through the device's XboxPresentation therefore had every PresentX refused with E_INVALIDARG once its tokens ran ahead of the pacer's. leonida::FrameTokenSource is now the counter both use: a pacer takes an optional shared source (a standalone pacer still owns its own and numbers as before), the device proxy owns one and exposes it through rt::d3d12_xs::device_frame_tokens, and XboxPresentation passes a given source to its pacer. A token that was never issued is still refused. Reported by rafaelpssz in #7496. (cherry picked from commit afb14d56c6a1683fae4345702c874a62d9234e71) Adapted to main by Mumogg: main's uncapped pacer path issues its token from the shared source too, the device proxy keeps the PresentX state next to the token source, and the queue's PresentX hands the device's source to its XboxPresentation, which is what makes the title's tokens valid there. --- runtime/shims/d3d12_xs_device.cpp | 15 ++++++++++----- runtime/shims/d3d12_xs_device.h | 7 +++++++ runtime/shims/xbox_present.cpp | 5 +++-- runtime/shims/xbox_present.h | 3 ++- runtime/src/frame_pacer.h | 25 +++++++++++++++++++------ runtime/test/device_proxy_test.cpp | 5 +++++ runtime/test/frame_pacer_test.cpp | 19 +++++++++++++++++++ runtime/test/xbox_present_test.cpp | 20 +++++++++++++++++++- 8 files changed, 84 insertions(+), 15 deletions(-) diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 63e834beea..e53d96d564 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -27,6 +27,7 @@ #include "d3d12_trace.h" #include "d3d12_xs_alloc_size.h" #include "d3d12_xs_desc_clean.h" +#include "../src/frame_pacer.h" #include "../src/shader_library.h" // leonida::fspx_payload_from_parts for slot 67 #ifdef LEONIDA_VULKAN_DEVICE @@ -88,7 +89,7 @@ struct DeviceProxy { std::atomic frame_interval_us{0}; std::atomic frame_latency{1}; std::atomic frame_event_scheduled{false}; - std::atomic frame_next_token{1}; + std::shared_ptr frame_tokens = std::make_shared(); // The PresentX state (window, presenter, XboxPresentation) the first queue PresentX builds on this device, // destroyed with the proxy. Opaque here: PresentState is defined with the queue proxy. void* present_state = nullptr; @@ -1395,7 +1396,8 @@ PresentState* present_state_for(DeviceProxy* device) { std::fprintf(stderr, "[rt] d3d12_xs: no window presenter on this device; PresentX shows nothing\n"); return state; } - state->xbox = std::make_unique(std::move(presenter)); + state->xbox = std::make_unique(std::move(presenter), nullptr, device->frame_tokens); + // The device's token source: the title takes its frame tokens from device slot 80 and presents them here. std::fprintf(stderr, "[rt] d3d12_xs: PresentX ready (window %p)\n", static_cast(state->window)); return state; } @@ -1685,9 +1687,7 @@ HRESULT proxy_wait_frame_event_x(DeviceProxy* self, std::uint64_t event, std::ui (void)flags; auto* token = reinterpret_cast(token_word); if (!token) return E_POINTER; - std::uint64_t value = self->frame_next_token.fetch_add(1, std::memory_order_relaxed); - if (value == 0) value = self->frame_next_token.fetch_add(1, std::memory_order_relaxed); // skip the null token - *token = value; + *token = self->frame_tokens->issue(); return S_OK; } @@ -3023,6 +3023,11 @@ ID3D12Device* device_proxy_real_device(const void* device) { return static_cast(device)->real; } +std::shared_ptr device_frame_tokens(const void* device) { + if (!is_device_proxy(device)) return nullptr; + return static_cast(device)->frame_tokens; +} + bool device_slot_overridden(unsigned slot) { if (slot <= 2 || slot == 8 || slot == 9 || slot == 14 || (slot >= 17 && slot <= 24) || slot == 25 || slot == 26 || slot == 31 || slot == 32 || slot == 34 || slot == 35 || slot == 36 || slot == 41 || slot == 45 || slot == 46 || slot == 50 || slot == 56 || slot == 61 || slot == 74 || slot == 62 || slot == 67 || diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index b9062ff202..6ae5200341 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -73,6 +73,11 @@ #include #include +#include + +namespace leonida { +class FrameTokenSource; +} namespace rt::d3d12_xs { @@ -153,6 +158,8 @@ using ConsoleDescriptorHeapHandler = HRESULT (*)(ID3D12Device* real, const D3D12 REFIID riid, void** out); void set_console_descriptor_heap_handler(ConsoleDescriptorHeapHandler handler); +std::shared_ptr device_frame_tokens(const void* device); + // True for slots the proxy handles itself rather than forwarding verbatim: IUnknown (0-2), 8 and 75 (queue // proxies), 9 (allocator proxies), 14 (descriptor heap proxy), 17-24 (CPU descriptor handle translation), 26 (the // console's struct-return form), diff --git a/runtime/shims/xbox_present.cpp b/runtime/shims/xbox_present.cpp index dd5f810cf7..f41f2c4680 100644 --- a/runtime/shims/xbox_present.cpp +++ b/runtime/shims/xbox_present.cpp @@ -28,10 +28,11 @@ void log_once(bool& done, const char* text) { } // namespace -XboxPresentation::XboxPresentation(std::unique_ptr presenter, leonida::FrameClock* clock) +XboxPresentation::XboxPresentation(std::unique_ptr presenter, leonida::FrameClock* clock, + std::shared_ptr tokens) : presenter_(std::move(presenter)), own_clock_(clock ? nullptr : std::make_unique()), - pacer_(clock ? *clock : *own_clock_) { + pacer_(clock ? *clock : *own_clock_, std::move(tokens)) { // A present waiting for a swapchain image gives up once SuspendX has been called. presenter_->set_abort([this] { return pacer_.suspended(); }); // LEONIDA_SDR_EOTF=gamma22 (or 2.2, any case) decodes SDR with a pure power of 2.2 instead of piecewise sRGB; "srgb" or diff --git a/runtime/shims/xbox_present.h b/runtime/shims/xbox_present.h index 60a317beec..914d707a3d 100644 --- a/runtime/shims/xbox_present.h +++ b/runtime/shims/xbox_present.h @@ -100,7 +100,8 @@ class XboxPresentation { public: // `clock` null: real time (a steady high-resolution timer). Tests pass a leonida::ManualFrameClock, which must // outlive this object. `presenter` is what create_window_presenter returned. - explicit XboxPresentation(std::unique_ptr presenter, leonida::FrameClock* clock = nullptr); + explicit XboxPresentation(std::unique_ptr presenter, leonida::FrameClock* clock = nullptr, + std::shared_ptr tokens = nullptr); ~XboxPresentation(); XboxPresentation(const XboxPresentation&) = delete; XboxPresentation& operator=(const XboxPresentation&) = delete; diff --git a/runtime/src/frame_pacer.h b/runtime/src/frame_pacer.h index fa9c20df1d..5de8e9b79d 100644 --- a/runtime/src/frame_pacer.h +++ b/runtime/src/frame_pacer.h @@ -37,7 +37,9 @@ #include #include #include +#include #include +#include namespace leonida { @@ -143,9 +145,19 @@ struct FrameStatistic { float percent_scanned = 0.0f; // display entries: where the scan was when the frame came up (0 at a vblank) }; +class FrameTokenSource { +public: + std::uint64_t issue() { return last_.fetch_add(1, std::memory_order_acq_rel) + 1; } + std::uint64_t issued() const { return last_.load(std::memory_order_acquire); } + +private: + std::atomic last_{0}; +}; + class FramePacer { public: - explicit FramePacer(FrameClock& clock) : clock_(clock) { + explicit FramePacer(FrameClock& clock, std::shared_ptr tokens = nullptr) + : clock_(clock), tokens_(tokens ? std::move(tokens) : std::make_shared()) { clock_.set_wake([this] { { std::lock_guard guard(mutex_); } cv_.notify_all(); @@ -263,7 +275,7 @@ class FramePacer { std::lock_guard guard(mutex_); if (issue) *issue = TokenIssue::none; if (suspended_) return pacer_hr::invalid_state; - if (token > issued_) return pacer_hr::invalid_arg; + if (token > tokens_->issued()) return pacer_hr::invalid_arg; if (issue) { if (token == 0) *issue = TokenIssue::null_token; else if (token == last_presented_) *issue = TokenIssue::repeated; @@ -357,7 +369,8 @@ class FramePacer { } bool suspended() const { std::lock_guard guard(mutex_); return suspended_; } - std::uint64_t tokens_issued() const { std::lock_guard guard(mutex_); return issued_; } + std::uint64_t tokens_issued() const { return tokens_->issued(); } + const std::shared_ptr& token_source() const { return tokens_; } std::uint32_t frames_in_flight() { std::lock_guard guard(mutex_); retire_locked(clock_.now_us()); @@ -408,7 +421,7 @@ class FramePacer { const std::uint64_t now = clock_.now_us(); retire_locked(now); if (uncapped_) { // no vblank grid and no latency throttle: a token at once, due now - *token = ++issued_; + *token = tokens_->issue(); Record record; record.token = *token; record.origin_us = now; @@ -426,7 +439,7 @@ class FramePacer { const std::int64_t newest = std::int64_t((now - first) / period_us_); const std::int64_t origin = std::max(next, newest); last_origin_ = origin; - *token = ++issued_; + *token = tokens_->issue(); Record record; record.token = *token; record.origin_us = first + std::uint64_t(origin) * period_us_; @@ -457,7 +470,7 @@ class FramePacer { std::uint32_t offset_us_ = 0; std::uint64_t epoch_us_ = 0; std::int64_t last_origin_ = 0; // origin 0 is the epoch itself, which has passed - std::uint64_t issued_ = 0; + std::shared_ptr tokens_; std::uint64_t last_presented_ = 0; std::uint64_t immediate_presents_ = 0; std::deque pending_; diff --git a/runtime/test/device_proxy_test.cpp b/runtime/test/device_proxy_test.cpp index 6b91a7a1f8..3653556f3f 100644 --- a/runtime/test/device_proxy_test.cpp +++ b/runtime/test/device_proxy_test.cpp @@ -25,6 +25,7 @@ #include "d3d12_trace.h" #include "d3d12_xs_device.h" #include "shims.h" +#include "../src/frame_pacer.h" namespace { @@ -428,6 +429,10 @@ int main(int argc, char** argv) { check(hr == S_OK && token2 != 0 && token2 != token, "slot 80 returns a fresh token on the next wait"); hr = reinterpret_cast(proxy_vtbl[80])(device.Get(), 0, 0, nullptr, 0, nullptr); check(hr == E_POINTER, "slot 80 refuses a null token with E_POINTER"); + const auto tokens = rt::d3d12_xs::device_frame_tokens(device.Get()); + check(tokens && tokens->issued() == token2 && token2 == token + 1, + "slot 80 tokens come from the device's frame token source"); + check(!rt::d3d12_xs::device_frame_tokens(nullptr), "a non-proxy has no frame token source"); check(rt::d3d12_xs::device_slot_hits(78) == 1 && rt::d3d12_xs::device_slot_hits(79) == 1 && rt::d3d12_xs::device_slot_hits(80) == 3, "slots 78/79/80 hit counters are 1/1/3"); diff --git a/runtime/test/frame_pacer_test.cpp b/runtime/test/frame_pacer_test.cpp index 8d089acdaf..e86c6f560a 100644 --- a/runtime/test/frame_pacer_test.cpp +++ b/runtime/test/frame_pacer_test.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include using namespace leonida; @@ -86,6 +87,24 @@ int main() { EXPECT(pacer.tokens_issued() == 2); } + { + ManualFrameClock clock; + auto tokens = std::make_shared(); + FramePacer pacer(clock, tokens); + EXPECT(pacer.token_source() == tokens); + const std::uint64_t outside = tokens->issue(); + EXPECT(outside == 1 && pacer.tokens_issued() == 1); + EXPECT(pacer.check_present_token(outside) == pacer_hr::ok); + EXPECT(pacer.check_present_token(outside + 1) == pacer_hr::invalid_arg); + EXPECT(setup(pacer, 1)); + clock.advance_us(period); + std::uint64_t token = 0; + EXPECT(pacer.wait_frame_event(frame_event_origin, 0, 0, &token) == pacer_hr::ok && token == outside + 1); + EXPECT(tokens->issue() == outside + 2); + EXPECT(pacer.check_present_token(outside + 2) == pacer_hr::ok); + EXPECT(pacer.check_present_token(outside + 3) == pacer_hr::invalid_arg); + } + // An offset delays the event inside the period: origin n comes at n * period + offset. { ManualFrameClock clock; diff --git a/runtime/test/xbox_present_test.cpp b/runtime/test/xbox_present_test.cpp index 1526f87a7a..adbb75e6a5 100644 --- a/runtime/test/xbox_present_test.cpp +++ b/runtime/test/xbox_present_test.cpp @@ -375,8 +375,10 @@ int main() { EXPECT(presenter->enable_capture()); leonida::ManualFrameClock clock; - auto owner = std::make_unique(std::move(presenter), &clock); + auto owner = std::make_unique(std::move(presenter), &clock, + rt::d3d12_xs::device_frame_tokens(device.p)); rt::d3d12::XboxPresentation& xbox = *owner; + EXPECT(xbox.pacer().token_source() == rt::d3d12_xs::device_frame_tokens(device.p)); D3D12_COMMAND_QUEUE_DESC queue_desc{}; Ref queue; @@ -665,6 +667,22 @@ int main() { EXPECT(region_is(frame, 0, 0, width, height, {51, 153, 230})); EXPECT(xbox.presents() == presented_before + 3); + using DeviceWaitFrameEventFn = HRESULT(WINAPI*)(void*, UINT, UINT, void*, UINT, std::uint64_t*); + const auto device_wait = + reinterpret_cast((*reinterpret_cast(device.p))[80]); + std::uint64_t device_token = 0; + EXPECT(device_wait(device.p, rt::d3d12::xbox_frame_event_origin, 0, nullptr, 0, &device_token) == S_OK); + EXPECT(device_token != 0 && device_token == xbox.pacer().tokens_issued()); + plane = plane_of(second, device_token + 1); + EXPECT(xbox.PresentX(1, &plane, nullptr) == E_INVALIDARG); + EXPECT(xbox.presents() == presented_before + 3); + plane = plane_of(rgba, device_token); + EXPECT(xbox.PresentX(1, &plane, nullptr) == S_OK); + EXPECT(xbox.presents() == presented_before + 4); + EXPECT(grab(frame)); + EXPECT(region_is(frame, 0, 0, width, height, {51, 153, 230})); + std::printf("a token from device slot 80 (WaitFrameEventX) presents: ok\n"); + // Sources the GPU cannot blit are refused with DXGI_ERROR_UNSUPPORTED and present nothing: multisampled, // integer and block-compressed. The last frame stays on screen and the token is still usable afterwards. { From 11d44eee9f00c2c1273240ad2220ddf14c5a8a1d Mon Sep 17 00:00:00 2001 From: Mumogg <104529023+Mumogg@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:03:47 -0600 Subject: [PATCH 054/110] queue_proxy_test: the PresentX slot is called and counted The coverage gate asks for every queue slot to have been called, and skips the overridden ones in its sweep of the refused tail. Slot 32 is overridden since the PresentX wiring, so nothing called it and the gate failed ("queue slot 32 never called"). The test now calls it where it calls the console ExecuteCommandLists slot: this build of the proxy has no presenter, so the answer is S_OK. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01HxBQf4pXH8PWpC5oZsM4bt --- runtime/test/queue_proxy_test.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/runtime/test/queue_proxy_test.cpp b/runtime/test/queue_proxy_test.cpp index 967313d53a..674a8cf2ed 100644 --- a/runtime/test/queue_proxy_test.cpp +++ b/runtime/test/queue_proxy_test.cpp @@ -277,6 +277,12 @@ int check_slots(const Backend& b) { const std::uint64_t before35 = qhits(35); EXPECT(raw_call(queue.p, 35, 1, reinterpret_cast(lists)) == 0); EXPECT(qhits(35) == before35 + 1 && xs::queue_slot_first_call_seen(35)); + // Console slot 32, PresentX. This test's build of the proxy has no presenter (the wiring is in gta6rt's, + // LEONIDA_VULKAN_DEVICE), so the slot answers S_OK and reaches no PC slot; it is counted like any other. + EXPECT(xs::queue_slot_overridden(32)); + const std::uint64_t before32 = qhits(32); + EXPECT(static_cast(raw_call(queue.p, 32, 0, 0, 0)) == static_cast(S_OK)); + EXPECT(qhits(32) == before32 + 1); EXPECT(SUCCEEDED(queue->Signal(fence.p, 7))); if (wait_for(label, fence.p, 7)) return 1; if (b.vulkan) { From 77f44fbe3bd477727a1f5ab6d20c6dd5f40e25e8 Mon Sep 17 00:00:00 2001 From: oscarlosu-lab <251827664+oscarlosu-lab@users.noreply.github.com> Date: Tue, 24 Nov 2026 06:32:30 +0100 Subject: [PATCH 055/110] xg_xs: lay out console textures and serve the texture computer (RT-XG-TEXTURE-COMPUTER) XGSuggestSwizzleMode and every texture-computer slot returned E_NOTIMPL, so the title's texture layout and copy calls did nothing. They now run on a model of the GFX10 texture layouts (runtime/src/console_texture_layout.h, AMD addrlib's rules for the linear, 256 B, 4 KiB and 64 KiB modes): the suggested mode, the layout structure (slot 2), element offsets (slot 6), copies into and out of a subresource (slots 8 and 9) and the 64 KiB tiling (slot 10). A description the model cannot lay out still gets a computer in *out (with E_INVALIDARG), as before, because two measured callers use *out without checking the HRESULT. Not modelled: compression metadata planes and the XOR and MSAA modes' addressing (E_NOTIMPL). The layout model, the computer's method table and the layout structure are ported from Marvisak/VIctory (GPL-3.0), crates/victory-formats/src/texture.rs and crates/victory-hle/src/modules/xg.rs at d2a4bae1f, credited in the files; the addrlib notice is kept. xg_xs_test now checks the model (hand-checked addresses, mip tails, a two-plane depth-stencil, a bijection and round trip over every element of ten layouts) and the shim's slots: 106 checks, MSVC /W4. Co-Authored-By: Claude Opus 5.5 --- docs/runtime_imports.md | 20 +- runtime/shims/xg_xs.cpp | 490 +++++++++++++++++++-- runtime/src/console_texture_layout.h | 610 +++++++++++++++++++++++++++ runtime/test/xg_xs_test.cpp | 391 ++++++++++++++--- 4 files changed, 1418 insertions(+), 93 deletions(-) create mode 100644 runtime/src/console_texture_layout.h diff --git a/docs/runtime_imports.md b/docs/runtime_imports.md index 7b9f62d5a1..74be4533a9 100644 --- a/docs/runtime_imports.md +++ b/docs/runtime_imports.md @@ -165,13 +165,19 @@ policy "other" (none is counted as returning an `HRESULT`), and they come from s The game executable imports two functions from `xg_xs.dll`, the console's texture layout library: `XGSuggestSwizzleMode` (2 call sites, in the helper that fills a texture description) and `XGCreateTextureComputer` -(4 call sites, which use slots 1, 2, 8 and 10 of the returned object's vtable). The runtime has no model of the console -resource layout, so `runtime/shims/xg_xs.cpp` computes none: both return `E_NOTIMPL` and write no layout. Two of the -four `XGCreateTextureComputer` callers ignore the HRESULT and call through the object at once, so the shim still stores -a static object in the out pointer; its slot 1 (read as `Release`) does nothing, and every other slot up to 31 logs its -index and caller once and returns `E_NOTIMPL` without writing its arguments. The call shapes and the reasoning are at -the top of the file; `xg_xs_test` covers them. Textures whose layout the game asks for are therefore not laid out yet. -The table above was measured before this shim and still lists these two as unimplemented; they are served now. +(4 call sites, which use slots 1, 2, 8 and 10 of the returned object's vtable). `runtime/shims/xg_xs.cpp` answers them +from a model of the console's texture layouts, `runtime/src/console_texture_layout.h` (AMD addrlib's GFX10 rules for +the linear, 256 B, 4 KiB and 64 KiB modes: block shapes, mip tails, the micro tile patterns, a separate stencil plane), +ported with the computer's method table and layout structure from Marvisak/VIctory (GPL-3.0, `xg.rs` and `texture.rs` +at `d2a4bae1f`). `XGSuggestSwizzleMode` writes `0x100 | mode` (linear for 1D, `64KB_Z_X` for depth, `64KB_R_X` for +render targets, else `4KB_S`); the computer fills the layout (slot 2), gives an element's offset (slot 6), copies a +subresource into (slot 8) and out of (slot 9) tiled memory, and reports the 64 KiB tiling (slot 10). Not modelled: +compression metadata planes, and addressing or copies for the pipe/bank XOR modes and MSAA (`E_NOTIMPL`). A description +it cannot lay out still gets a computer in the out pointer with `E_INVALIDARG`, because two of the four callers ignore +the HRESULT and call through the object at once; that object answers every slot with `E_NOTIMPL` and writes nothing. +`xg_xs_test` covers the model (hand-checked addresses, mip tails, a bijection and round trip over every element) and the +shim's slots. The table above was measured before this shim and still lists these two as unimplemented; they are served +now. Only two of these DLLs have a shim in the repository (`xmem.dll` and `d3d12_xs.dll`), and they are not complete: they hold 8 of the 30 unimplemented imports. The other 22 are in five DLLs (`xg_xs.dll`, `XCRDAPI.dll`, `chad.dll`, diff --git a/runtime/shims/xg_xs.cpp b/runtime/shims/xg_xs.cpp index b45fbf689a..751305c85b 100644 --- a/runtime/shims/xg_xs.cpp +++ b/runtime/shims/xg_xs.cpp @@ -1,4 +1,6 @@ -// xg_xs.dll: the console's texture layout library. The game executable (1.0.2.1) imports two functions from it. +// xg_xs.dll: the console's texture layout library. Titles ask it which swizzle mode a texture should use, how large it +// is, where each mip and slice lies, and to copy linear data into tiled memory and back. The game executable +// (1.0.2.1) imports two functions from it. // // Measured from the call sites in the executable, read statically (shapes and checks only): // HRESULT XGSuggestSwizzleMode(const desc*, 0, uint32_t* mode) @@ -7,86 +9,498 @@ // known, writes itself as 0x100 | mode. The HRESULT is only passed back up; no caller branches on it. // HRESULT XGCreateTextureComputer(const desc*, computer** out) // 4 call sites. Two test the HRESULT and take their failure path when it is negative; two ignore it and call -// through *out at once. On the computer the callers use vtable slot 1 after they are done (3 sites, read as -// Release; no site calls slot 0, read as AddRef, nor QueryInterface), slot 2 with one out pointer to a large -// stack structure (2 sites), slot 8 with six arguments in a loop over subresources (1 site) and slot 10 with -// seven arguments (1 site). No site reads the return value of slots 2, 8 or 10. +// through *out at once. On the computer the callers use vtable slot 1 after they are done (3 sites), slot 2 with +// one out pointer to a large stack structure (2 sites), slot 8 with six arguments in a loop over subresources +// (1 site) and slot 10 with seven arguments (1 site). // -// The runtime has no model of the console's resource layout (runtime/src/gfx10_tiling.h covers two swizzle modes of -// one 2D level, without mips or the layout structure slot 2 fills), so nothing here computes a layout: -// - XGSuggestSwizzleMode returns E_NOTIMPL and writes nothing, so the field keeps the 0 the caller put there. -// - XGCreateTextureComputer returns E_NOTIMPL, but still stores a computer in *out. The two checking callers then -// fail cleanly; the two that do not check would otherwise call through a null pointer. COM says *out is null on -// failure; this breaks that on purpose, because the measured callers need it. -// - Slot 0 and slot 1 count nothing (the computer is one static object). Every other slot, up to kSlots, prints its -// index and caller once and returns E_NOTIMPL without writing its arguments, so a caller's own zero-filled outputs -// stay zero and a stack structure the caller did not fill stays as it was. -// Hypothesis, not measured: slots 0 and 1 being AddRef and Release; the meaning of slots 2, 8 and 10; that callers -// reach no slot above kSlots - 1 (the computer is also stored in an object at one site and may be called later). +// The computer's methods, their arguments and the layout structure slot 2 fills are taken from Marvisak/VIctory +// (GPL-3.0), crates/victory-hle/src/modules/xg.rs at commit d2a4bae1f, which serves the same title: 0 AddRef, +// 1 Release, 2 the layout, 6 an element's byte offset, 8 a copy into and 9 a copy out of a subresource, 10 the 64 KiB +// tiling. They match the slots measured above. The layouts come from runtime/src/console_texture_layout.h, ported +// from the same project. +// +// Kept from the measured callers: a description this shim cannot lay out still gets a computer in *out (with a +// negative HRESULT), because two callers use *out without checking the HRESULT. That computer answers every slot +// with E_NOTIMPL and writes nothing. COM says *out is null on failure; this breaks that on purpose. +// +// Not modelled: compression metadata planes (HTILE, CMASK, FMASK, DCC), addressing and copies for the pipe/bank XOR +// modes (_X, _T) and MSAA (they need the GPU's pipe configuration; the host renders those targets), and the slots no +// caller reaches (size, alignment, mip offset, element coordinate, view descriptor), which log once and return +// E_NOTIMPL. #include #include +#include #include #include +#include #include #include +#include +#include +#include +#include #include +#include "../src/console_texture_layout.h" #include "shims.h" namespace { +namespace ct = leonida::console_texture; + constexpr HRESULT kNotImpl = static_cast(rt::shims::kENotImpl); +constexpr HRESULT kInvalidArg = static_cast(0x80070057u); +constexpr HRESULT kFail = static_cast(0x80004005u); constexpr size_t kSlots = 32; -// Prints once per entry point; `slot` is the vtable index for a computer method, or -1 for an export. -void warn_once(std::atomic& warned, const char* what, int slot, const void* caller) { +// D3D12_RESOURCE_DESC, whose layout field carries 0x100 | swizzle mode on the console (1 row major, 0 "pick one"). +struct ResourceDesc { + uint32_t dimension; + uint64_t alignment; + uint64_t width; + uint32_t height; + uint16_t depth_or_array; + uint16_t mips; + uint32_t format; + uint32_t samples; + uint32_t quality; + uint32_t layout; + uint32_t flags; +}; +static_assert(sizeof(ResourceDesc) == 0x38); + +constexpr uint32_t kSwizzled = 0x100; +constexpr uint32_t kRowMajor = 1; +constexpr uint32_t kAllowRenderTarget = 1; +constexpr uint32_t kAllowDepthStencil = 2; +constexpr uint32_t kTexture1d = 2, kTexture2d = 3, kTexture3d = 4; + +// The layout structure slot 2 fills. Offsets 0x00, 0x08, 0x10 and 0x1c of a mip are the ones the title reads; the +// rest follow the library's older public shape (VIctory's reading). +constexpr size_t kMips = 15; +struct MipOut { + uint64_t size; + uint64_t offset; + uint64_t slice_size; + uint32_t pitch_texels; + uint32_t pitch_bytes; + uint32_t alignment; + uint32_t padded[3]; // width, height in elements, depth or array size + uint32_t elements[2]; + uint32_t texels[2]; + uint32_t depth_or_array; + uint32_t samples; + uint32_t swizzle; + uint64_t bank_rotation[2]; + uint32_t slice_depth; + uint32_t in_tail; + uint32_t tail_position; // where a tail mip starts in elements: x bits 0-10, y 11-21 +}; +struct PlaneOut { + uint32_t usage; // 1 data, 7 depth, 8 stencil (metadata planes are not made) + uint64_t size; + uint64_t slice_size; + uint64_t offset; + uint64_t alignment; + uint32_t element_bytes; + uint32_t standard_mips; + uint32_t tail_mips; + MipOut mips[kMips]; +}; +struct LayoutOut { + uint64_t size; + uint64_t alignment; + uint32_t mips; + uint32_t planes; + PlaneOut plane[4]; + uint32_t dimension; +}; +static_assert(sizeof(MipOut) == 0x70); +static_assert(sizeof(PlaneOut) == 0x6c8); +static_assert(sizeof(LayoutOut) == 0x1b40); + +struct PackedMips { + uint8_t standard; + uint8_t packed; + uint32_t tiles; + uint32_t start; +}; +struct SubresourceTiling { + uint32_t width; + uint16_t height; + uint16_t depth; + uint32_t start; +}; +constexpr uint64_t kTile = 64u << 10; + +// Prints once per call site kind; `slot` is the vtable index for a computer method, or -1 for an export. +void warn_once(std::atomic& warned, const char* what, int slot, const void* caller, const char* why) { if (warned.exchange(true, std::memory_order_relaxed)) return; char name[64]; if (slot < 0) std::snprintf(name, sizeof(name), "%s", what); else std::snprintf(name, sizeof(name), "%s%d", what, slot); - std::fprintf(stderr, "[rt] xg_xs: %s: no console texture layout on the PC; E_NOTIMPL (caller %s, logged once)\n", - name, rt::shims::module_offset(reinterpret_cast(caller)).c_str()); + std::fprintf(stderr, "[rt] xg_xs: %s: %s (caller %s, logged once)\n", name, why, + rt::shims::module_offset(reinterpret_cast(caller)).c_str()); +} + +// The mode the console's library picks for a description: linear for 1D, the XOR render and depth modes for targets, +// else 4 KiB standard. VIctory's reading of the library's older optimal-mode function (any size, 2D, 3D and cubes +// alike); revisit if streamed textures come out scrambled. +uint32_t suggested(const ResourceDesc& d) { + if (d.dimension == kTexture1d) return ct::kLinear; + if (d.flags & kAllowDepthStencil) return ct::kSw64kbZX; + if (d.flags & kAllowRenderTarget) return ct::kSw64kbRX; + return ct::kSw4kbS; } -ULONG __stdcall computer_add_ref(void*) { return 1; } -ULONG __stdcall computer_release(void*) { return 1; } +std::optional texture_of(const ResourceDesc& d) { + ct::TextureDesc t; + switch (d.dimension) { + case kTexture1d: t.dimension = ct::Dimension::tex1d; break; + case kTexture2d: t.dimension = ct::Dimension::tex2d; break; + case kTexture3d: t.dimension = ct::Dimension::tex3d; break; + default: return std::nullopt; + } + if (d.layout == 0) t.swizzle = suggested(d); + else if (d.layout == kRowMajor) t.swizzle = ct::kLinear; + else if ((d.layout & ~0xffu) == kSwizzled) t.swizzle = d.layout & 0xffu; + else return std::nullopt; + if (d.width > std::numeric_limits::max()) return std::nullopt; + t.width = static_cast(d.width); + t.height = d.height; + t.depth_or_array = d.depth_or_array; + t.mips = d.mips; + t.format = d.format; + t.samples = d.samples ? d.samples : 1; + auto texture = ct::Texture::make(t); + // The layout structure has room for 15 mips. + if (!texture || texture->planes[0].layout.mips.size() > kMips) return std::nullopt; + return texture; +} + +// ---- The computer that cannot lay its description out: every slot E_NOTIMPL, nothing written. ---- + +ULONG __stdcall stub_add_ref(void*) { return 1; } +ULONG __stdcall stub_release(void*) { return 1; } template -HRESULT __stdcall computer_slot(void*) { +HRESULT __stdcall stub_slot(void*) { static std::atomic warned{false}; - warn_once(warned, "texture computer slot ", static_cast(Slot), _ReturnAddress()); + warn_once(warned, "texture computer slot ", static_cast(Slot), _ReturnAddress(), + "no layout for this description; E_NOTIMPL"); return kNotImpl; } template -constexpr auto make_vtable(std::index_sequence) { +constexpr auto make_stub_vtable(std::index_sequence) { return std::array{ - (Slot == 0 ? reinterpret_cast(&computer_add_ref) - : Slot == 1 ? reinterpret_cast(&computer_release) - : reinterpret_cast(&computer_slot))...}; + (Slot == 0 ? reinterpret_cast(&stub_add_ref) + : Slot == 1 ? reinterpret_cast(&stub_release) + : reinterpret_cast(&stub_slot))...}; } +const auto kStubVtable = make_stub_vtable(std::make_index_sequence{}); +struct StubComputer { + const void* const* vtable; +}; +StubComputer g_stub{kStubVtable.data()}; + +// ---- The computer with a layout. ---- -const auto kVtable = make_vtable(std::make_index_sequence{}); struct Computer { const void* const* vtable; + std::atomic refs{1}; + ResourceDesc desc{}; + uint32_t mips = 0; + ct::Texture texture; }; -Computer g_computer{kVtable.data()}; -HRESULT __stdcall XGCreateTextureComputer(const void* /*desc*/, void** out) { - static std::atomic warned{false}; - warn_once(warned, "XGCreateTextureComputer", -1, _ReturnAddress()); - if (!out) return E_POINTER; - *out = &g_computer; // see the top of the file: two measured callers use *out without checking the HRESULT - return kNotImpl; +ULONG __stdcall add_ref(Computer* c) { return c->refs.fetch_add(1, std::memory_order_relaxed) + 1; } + +ULONG __stdcall release(Computer* c) { + const ULONG left = c->refs.fetch_sub(1, std::memory_order_acq_rel) - 1; + if (left == 0) delete c; + return left; +} + +// The mode a tail mip is reported in: the 256-byte one of its kind (3 for the render kind, which GFX10 lacks), the +// depth mode itself. +uint32_t tail_swizzle(uint32_t s) { + switch (s) { + case 2: case 6: case 10: case 18: case 22: case 26: return ct::kSw256bD; + case 23: case 27: return 3; + case 24: return s; + default: return ct::kSw256bS; + } +} + +MipOut mip_out(const ResourceDesc& desc, const ct::Layout& l, size_t i) { + const ct::Mip& m = l.mips[i]; + const uint64_t bpe = l.desc.element_bytes; + const uint32_t block = l.desc.block; + const bool three_d = desc.dimension == kTexture3d; + const uint32_t array = desc.depth_or_array ? desc.depth_or_array : 1u; + MipOut out{}; + out.pitch_texels = m.pitch * block; + out.pitch_bytes = m.pitch * l.desc.element_bytes; + out.padded[0] = m.pitch; + out.padded[1] = m.rows; + out.padded[2] = three_d ? m.depth_pitch : array; + out.elements[0] = m.width; + out.elements[1] = m.height; + const uint64_t w = desc.width >> i; + out.texels[0] = w ? static_cast(w) : 1u; + out.texels[1] = (desc.height >> i) ? (desc.height >> i) : 1u; + out.depth_or_array = three_d ? m.depth : array; + out.samples = l.desc.samples; + out.slice_depth = l.block[2]; + const uint64_t slice = uint64_t{m.pitch} * m.rows * bpe; + const uint64_t depth = three_d ? m.depth_pitch : 1u; + if (!m.tail) { + out.offset = m.offset; + out.slice_size = slice * l.desc.samples; + out.size = out.slice_size * depth; + out.alignment = static_cast(l.alignment); + out.swizzle = l.desc.swizzle; + } else { + out.in_tail = 1; + out.alignment = 256; + out.swizzle = tail_swizzle(l.desc.swizzle); + if (l.thick) { // a 3D tail mip is placed by position, not by offset + out.slice_size = l.alignment / l.block[2]; + out.tail_position = m.tail->x | (m.tail->y << 11); + } else { + out.offset = m.tail->offset; + out.slice_size = slice; + } + out.size = out.slice_size * depth; + } + return out; } -HRESULT __stdcall XGSuggestSwizzleMode(const void* /*desc*/, uint32_t /*flags*/, uint32_t* /*mode*/) { +HRESULT __stdcall layout(Computer* c, LayoutOut* out) { + if (!out) return kInvalidArg; + std::memset(out, 0, sizeof(*out)); + out->size = c->texture.size; + out->alignment = c->texture.alignment; + out->mips = c->mips; + out->planes = static_cast(c->texture.planes.size()); + out->dimension = c->desc.dimension; + // The library calls a depth plane "depth" only beside stencil or without mips. + const bool depth = (c->desc.flags & kAllowDepthStencil) && (c->texture.planes.size() > 1 || c->mips == 1); + for (size_t p = 0; p < c->texture.planes.size() && p < 4; ++p) { + const ct::Plane& src = c->texture.planes[p]; + const ct::Layout& l = src.layout; + PlaneOut& plane = out->plane[p]; + plane.usage = src.stencil ? 8u : depth ? 7u : 1u; + plane.size = l.size; + plane.slice_size = l.slice_size; + plane.offset = src.offset; + plane.alignment = l.alignment; + plane.element_bytes = l.desc.element_bytes; + plane.standard_mips = l.first_tail_mip; + plane.tail_mips = c->mips - l.first_tail_mip; + for (size_t i = 0; i < l.mips.size() && i < kMips; ++i) plane.mips[i] = mip_out(c->desc, l, i); + } + return S_OK; +} + +// The plane, its mip and array slice for a subresource index, and the tiled bytes and the linear bytes a copy touches. +struct CopyArgs { + const ct::Plane* plane; + uint32_t mip, slice; + size_t tiled, linear; +}; + +std::optional copy_args(const Computer* c, uint32_t plane, uint32_t subresource, uint32_t row, + uint32_t depth) { + if (plane >= c->texture.planes.size() || c->mips == 0) return std::nullopt; + const ct::Plane& p = c->texture.planes[plane]; + const ct::Layout& l = p.layout; + const uint32_t mip = subresource % c->mips, slice = subresource / c->mips; + if (mip >= l.mips.size()) return std::nullopt; + const ct::Mip& m = l.mips[mip]; + const uint64_t bytes = uint64_t{m.width} * l.desc.element_bytes; + const uint64_t depths = l.subresource_depth(mip); + // Every factor is at most 2^32, so each product fits in 64 bits; the sum is checked against size_t below. + const uint64_t linear = (depths - 1) * depth + uint64_t{m.height - 1} * row + bytes; + const uint64_t tiled = p.offset + l.size; + if (linear > std::numeric_limits::max() || tiled > std::numeric_limits::max()) + return std::nullopt; + return CopyArgs{&p, mip, slice, static_cast(tiled), static_cast(linear)}; +} + +HRESULT result(ct::Error e) { + switch (e) { + case ct::Error::ok: return S_OK; + case ct::Error::unsupported: return kNotImpl; + default: return kInvalidArg; + } +} + +void warn_copy(const Computer* c, const char* what, uint32_t subresource, ct::Error e) { + static std::atomic warned{0}; + if (warned.fetch_add(1, std::memory_order_relaxed) >= 8) return; + std::fprintf(stderr, + "[rt] xg_xs: %s subresource %u failed (%s): dim=%u %llux%u depth/array=%u mips=%u format=%u " + "layout=0x%x\n", + what, subresource, + e == ct::Error::unsupported ? "addressing not modelled" : e == ct::Error::too_small ? "too small" + : "invalid", + c->desc.dimension, static_cast(c->desc.width), c->desc.height, + c->desc.depth_or_array, c->desc.mips, c->desc.format, c->desc.layout); +} + +// (tiled base, plane, subresource, linear, row pitch, depth pitch). +HRESULT __stdcall copy_into(Computer* c, uint8_t* tiled, uint32_t plane, uint32_t subresource, const uint8_t* linear, + uint32_t row, uint32_t depth) { + const auto a = copy_args(c, plane, subresource, row, depth); + if (!a || !tiled || !linear) return kInvalidArg; + const size_t offset = static_cast(a->plane->offset); + const ct::Error e = a->plane->layout.tile(tiled + offset, a->tiled - offset, a->mip, a->slice, linear, a->linear, + row, depth); + if (e != ct::Error::ok) warn_copy(c, "copy into", subresource, e); + return result(e); +} + +// (linear, plane, subresource, sample, tiled base, row pitch, depth pitch). +HRESULT __stdcall copy_from(Computer* c, uint8_t* linear, uint32_t plane, uint32_t subresource, uint32_t /*sample*/, + const uint8_t* tiled, uint32_t row, uint32_t depth) { + const auto a = copy_args(c, plane, subresource, row, depth); + if (!a || !tiled || !linear) return kInvalidArg; + const size_t offset = static_cast(a->plane->offset); + const ct::Error e = a->plane->layout.detile(tiled + offset, a->tiled - offset, a->mip, a->slice, linear, a->linear, + row, depth); + if (e != ct::Error::ok) warn_copy(c, "copy out of", subresource, e); + return result(e); +} + +// (total tiles, packed mips, tile shape in texels, in: room / out: count, first, subresource tilings), in 64 KiB +// tiles of plane 0, for 2D 64 KiB modes only (others fail, as on the console). The mip tail is the packed part, tile 0 +// of each slice; tilings list the standard mips of every slice in turn. With a tail the console's library lists two +// slices at most and zeroes all but the first (VIctory's reading; the title reads slice 0 only). +HRESULT __stdcall tiling(Computer* c, uint32_t* tiles, PackedMips* packed, uint32_t* shape, uint32_t* count, + uint32_t first, SubresourceTiling* out) { + const ct::Layout& l = c->texture.planes[0].layout; + if (l.alignment != kTile) return kFail; + if (l.thick) return kNotImpl; + const uint32_t standard = l.first_tail_mip; + const bool tail = standard < c->mips; + const uint64_t tail_tiles = standard == 0 ? l.slice_size / kTile + : tail ? l.mips[standard - 1].offset / kTile + : 0; + const uint32_t block = l.desc.block; + if (tiles) *tiles = static_cast(l.size / kTile); + if (packed) { + packed->standard = static_cast(standard); + packed->packed = static_cast(c->mips - standard); + packed->tiles = static_cast(tail_tiles); + packed->start = 0; + } + if (shape) { + shape[0] = l.block[0] * block; + shape[1] = l.block[1] * block; + shape[2] = l.block[2]; + } + if (count) { + const uint32_t slices = tail ? std::min(l.slices, 2u) : l.slices; + const uint64_t total = uint64_t{standard} * slices; + const uint32_t wanted = + static_cast(std::min(total > first ? total - first : 0, *count)); + for (uint32_t i = 0; i < wanted && out; ++i) { + const uint32_t slice = (first + i) / standard, mip = (first + i) % standard; + const ct::Mip& m = l.mips[mip]; + SubresourceTiling entry{}; + if (!(tail && slice > 0)) { + entry.width = m.pitch / l.block[0]; + entry.height = static_cast(m.rows / l.block[1]); + entry.depth = 1; + entry.start = static_cast((uint64_t{slice} * l.slice_size + m.offset) / kTile); + } + out[i] = entry; + } + *count = out ? wanted : 0; + } + return S_OK; +} + +// (plane, mip, x, y, z or slice, sample, bit position): an element's byte offset from the texture's start, 0 if +// outside. VIctory measured the title reading texels of a 128x4 4KB_S texture on the CPU through it. +uint64_t __stdcall element_offset(Computer* c, uint32_t plane, uint32_t mip, uint64_t x, uint32_t y, uint32_t z, + uint32_t /*sample*/, uint32_t* bit) { + if (bit) *bit = 0; + if (plane >= c->texture.planes.size()) return 0; + const ct::Plane& p = c->texture.planes[plane]; + const uint32_t x32 = x > std::numeric_limits::max() ? std::numeric_limits::max() + : static_cast(x); + uint64_t at = 0; + if (p.layout.offset(mip, x32, y, z, at) != ct::Error::ok) return 0; + return p.offset + at; +} + +template +HRESULT __stdcall unused_slot(Computer*) { static std::atomic warned{false}; - warn_once(warned, "XGSuggestSwizzleMode", -1, _ReturnAddress()); + warn_once(warned, "texture computer slot ", static_cast(Slot), _ReturnAddress(), + "method not implemented; E_NOTIMPL"); return kNotImpl; } +template +constexpr auto make_vtable(std::index_sequence) { + return std::array{ + (Slot == 0 ? reinterpret_cast(&add_ref) + : Slot == 1 ? reinterpret_cast(&release) + : Slot == 2 ? reinterpret_cast(&layout) + : Slot == 6 ? reinterpret_cast(&element_offset) + : Slot == 8 ? reinterpret_cast(©_into) + : Slot == 9 ? reinterpret_cast(©_from) + : Slot == 10 ? reinterpret_cast(&tiling) + : reinterpret_cast(&unused_slot))...}; +} +const auto kVtable = make_vtable(std::make_index_sequence{}); + +HRESULT __stdcall XGCreateTextureComputer(const ResourceDesc* desc, void** out) { + if (!out) return E_POINTER; + std::optional texture; + if (desc) texture = texture_of(*desc); + if (!texture) { + static std::atomic warned{0}; + if (warned.fetch_add(1, std::memory_order_relaxed) < 8) { + if (desc) + std::fprintf(stderr, + "[rt] xg_xs: XGCreateTextureComputer: no layout for dim=%u %llux%u depth/array=%u " + "mips=%u format=%u samples=%u layout=0x%x flags=0x%x (caller %s)\n", + desc->dimension, static_cast(desc->width), desc->height, + desc->depth_or_array, desc->mips, desc->format, desc->samples, desc->layout, + desc->flags, + rt::shims::module_offset(reinterpret_cast(_ReturnAddress())).c_str()); + else + std::fprintf(stderr, "[rt] xg_xs: XGCreateTextureComputer: null description\n"); + } + *out = &g_stub; // see the top of the file: two measured callers use *out without checking the HRESULT + return kInvalidArg; + } + auto* c = new (std::nothrow) Computer; + if (!c) { + *out = &g_stub; + return E_OUTOFMEMORY; + } + c->vtable = kVtable.data(); + c->desc = *desc; + c->mips = static_cast(texture->planes[0].layout.mips.size()); + c->texture = std::move(*texture); + *out = c; + return S_OK; +} + +// (desc, flags, out layout); the title passes flags 0 and puts the result in the description's layout field. +HRESULT __stdcall XGSuggestSwizzleMode(const ResourceDesc* desc, uint32_t /*flags*/, uint32_t* mode) { + if (!desc || !mode) return kInvalidArg; + *mode = kSwizzled | suggested(*desc); + return S_OK; +} + } // namespace SHIM_TABLE(xg_xs, diff --git a/runtime/src/console_texture_layout.h b/runtime/src/console_texture_layout.h new file mode 100644 index 0000000000..782d8584ad --- /dev/null +++ b/runtime/src/console_texture_layout.h @@ -0,0 +1,610 @@ +// Texture layouts of the console GPU (RDNA2, GFX10.3): a texture's size and alignment, where each mip and array slice +// starts, the address of each element, and copies between tiled memory and linear rows. Used by the xg_xs.dll shim +// (runtime/shims/xg_xs.cpp), whose texture computer answers the title's layout and copy calls from it. +// +// Ported from Marvisak/VIctory (GPL-3.0), crates/victory-formats/src/texture.rs at commit d2a4bae1f, which follows +// AMD's address library (addrlib) as shipped in Mesa under src/amd/addrlib: block dimensions, mip placement and mip +// tails from gfx10addrlib.cpp and addrlib2.cpp (ComputeSurfaceInfoMacroTiled, ComputeThinBlockDimension, +// GetMipTailDim, GetMaxNumMipsInTail, HwlComputeSurfaceInfoLinear, ComputeSurfaceAddrFromCoordMacroTiled), and the +// 256-byte micro tile patterns in kMicro from gfx10SwizzlePattern.h (the RB+ tables, as on RDNA2). addrlib carries +// this notice: +// +// Copyright (C) 2007-2026 Advanced Micro Devices, Inc. All rights reserved. +// SPDX-License-Identifier: MIT +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated +// documentation files (the "Software"), to deal in the Software without restriction, including without limitation +// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and +// to permit persons to whom the Software is furnished to do so, subject to the following conditions: the above +// copyright notice and this permission notice shall be included in all copies or substantial portions of the +// Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. +// +// Units: an element is a texel, or a 4x4 block of a block-compressed format. Mips of one array slice (or one depth +// slab of a thick 3D texture) are stored together, smallest first: the mip tail (the small mips sharing one block) +// at offset 0, mip 0 last. +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace leonida::console_texture { + +// A swizzle mode, by its hardware number (addrlib's ADDR_SW_* order). +enum : uint32_t { + kLinear = 0, + kSw256bS = 1, + kSw256bD = 2, + kSw4kbS = 5, + kSw4kbD = 6, + kSw64kbS = 9, + kSw64kbD = 10, + kSw64kbST = 17, + kSw64kbDT = 18, + kSw4kbSX = 21, + kSw4kbDX = 22, + kSw4kbRX = 23, + kSw64kbZX = 24, + kSw64kbSX = 25, + kSw64kbDX = 26, + kSw64kbRX = 27, +}; + +// log2 of the block size in bytes (0 for linear); nullopt for modes GFX10 does not have. +inline std::optional block_log2(uint32_t swizzle) { + switch (swizzle) { + case 0: return 0; + case 1: case 2: return 8; + case 5: case 6: case 21: case 22: case 23: return 12; + case 9: case 10: case 17: case 18: case 24: case 25: case 26: case 27: return 16; + default: return std::nullopt; + } +} +inline bool is_standard(uint32_t s) { return s == 1 || s == 5 || s == 9 || s == 17 || s == 21 || s == 25; } +inline bool is_display(uint32_t s) { return s == 2 || s == 6 || s == 10 || s == 18 || s == 22 || s == 26; } +inline bool is_z_order(uint32_t s) { return s == 24; } +// Pipe and bank XOR modes (_T, _X): their addresses depend on the GPU's pipe configuration. +inline bool is_xor(uint32_t s) { return s >= 16; } + +enum class Dimension { tex1d, tex2d, tex3d }; + +enum class Error { + ok, + invalid, // the description makes no texture, or a coordinate or subresource lies outside it + unsupported, // a valid layout whose addressing is not implemented here + too_small, // a buffer is smaller than the layout or the rows need +}; + +// One plane of a texture. +struct Desc { + Dimension dimension = Dimension::tex2d; + uint32_t width = 1, height = 1; // in texels + uint32_t depth = 1; // depth of a 3D texture, else the array size + uint32_t mips = 1; + uint32_t element_bytes = 4; // 1, 2, 4, 8 or 16 + uint32_t block = 1; // texels per element side: 1, or 4 for block compression + uint32_t samples = 1; + uint32_t swizzle = kLinear; +}; + +struct Tail { + uint32_t offset = 0; // byte offset inside the tail block + uint32_t x = 0, y = 0; // element position the mip starts at +}; + +// Where one mip lives inside a slice. +struct Mip { + uint32_t width = 0, height = 0, depth = 0; // size in elements (depth 1 unless the texture is 3D) + uint32_t pitch = 0, rows = 0, depth_pitch = 0; // padded size in elements: whole blocks, or the tail's share + uint64_t offset = 0; // byte offset of its first block in the slice (0 in the tail) + std::optional tail; +}; + +namespace detail { + +constexpr uint32_t div_ceil(uint32_t a, uint32_t b) { return (a + b - 1) / b; } +constexpr uint32_t round_up(uint32_t a, uint32_t b) { return div_ceil(a, b) * b; } + +// Elements along one side of mip `mip`, as data and copies see it: texels halve rounding down (to at least 1), then +// round up to whole elements. +constexpr uint32_t dim(uint32_t texels, uint32_t mip, uint32_t block) { + return div_ceil(std::max(texels >> mip, 1u), block); +} +// Elements along one side of mip `mip` for placement (padding, tail, offsets): addrlib halves mip 0's elements +// rounding up, which can be one more than dim() for odd sizes. +constexpr uint32_t padded_dim(uint32_t texels, uint32_t mip, uint32_t block) { + return div_ceil(div_ceil(std::max(texels, 1u), block), 1u << mip); +} + +// Micro tile (256 bytes) patterns by log2 of the element size: for each address bit, the element coordinate bit it +// takes (x0, y1, z0...), "--" for the bits inside an element. Thin S, thin D, thick S (also the D 3D modes). From +// addrlib's GFX10_SW_256_S_RBPLUS, GFX10_SW_256_D_RBPLUS and GFX10_SW_4K_S3_RBPLUS patterns; the larger blocks add +// bits Y, X (thin) or Y, X, Z (thick) in turn. +inline constexpr const char* kMicro[3][5] = { + {"x0x1x2x3y0y1y2y3", "--x0x1x2y0y1y2x3", "----x0x1y0y1y2x2", "------x0y0y1x1x2", "--------y0y1x0x1"}, + {"x0x1x2y1y0y2x3y3", "--x0x1x2y0y1y2x3", "----x0x1y0y1x2y2", "------x0y0x1x2y1", "--------x0y0x1y1"}, + {"x0x1z0y0z1y1x2z2", "--x0z0y0z1y1x1z2", "----x0y0z0y1x1z1", "------x0z0y0x1z1", "--------z0y0x0z1"}, +}; + +// For each axis, the address bit each coordinate bit lands on. +inline std::array, 3> pattern(int kind, uint32_t element_log2, uint32_t block_log2) { + std::array, 3> axes; + const char* micro = kMicro[kind][element_log2]; + for (uint32_t bit = 0; bit < 8; ++bit) { + const char a = micro[2 * bit]; + const int axis = a == 'x' ? 0 : a == 'y' ? 1 : a == 'z' ? 2 : -1; + if (axis < 0) continue; + const size_t index = static_cast(micro[2 * bit + 1] - '0'); + auto& to = axes[static_cast(axis)]; + if (to.size() <= index) to.resize(index + 1, 0); + to[index] = bit; + } + static constexpr int kThin[2] = {1, 0}; + static constexpr int kThick[3] = {1, 0, 2}; + const int* order = kind == 2 ? kThick : kThin; + const uint32_t n = kind == 2 ? 3u : 2u; + for (uint32_t bit = 8, i = 0; bit < block_log2; ++bit, ++i) axes[static_cast(order[i % n])].push_back(bit); + return axes; +} + +// Byte offsets inside a block for coordinates 0..2^bits of one axis. +inline std::vector spread(const std::vector& bits) { + std::vector out(size_t{1} << bits.size()); + for (uint32_t c = 0; c < out.size(); ++c) { + uint32_t v = 0; + for (size_t i = 0; i < bits.size(); ++i) v |= ((c >> i) & 1u) << bits[i]; + out[c] = v; + } + return out; +} + +} // namespace detail + +constexpr uint32_t kMaxMips = 16; +// The largest width, height and depth (or array size) accepted, in texels. GFX10's image descriptors hold at most +// 16384 texels per side, so no texture the GPU can use is refused. The bound also keeps every size computed below +// within uint64_t (and its uint32_t steps), which unchecked values from a title would otherwise overflow. +constexpr uint32_t kMaxExtent = 1u << 14; + +// 256-byte micro tile dimensions by log2 element size, 2D and 3D. +inline constexpr uint32_t kBlock256_2d[5][2] = {{16, 16}, {16, 8}, {8, 8}, {8, 4}, {4, 4}}; +inline constexpr uint32_t kBlock256_3d[5][3] = {{8, 4, 8}, {4, 4, 8}, {4, 4, 4}, {4, 2, 4}, {2, 2, 4}}; +inline constexpr uint32_t kBlock1k_3d[5][3] = {{16, 8, 8}, {8, 8, 8}, {8, 8, 4}, {8, 4, 4}, {4, 4, 4}}; + +class Layout { +public: + Desc desc; + std::array block{}; // block dimensions in elements (linear: the pitch alignment, 1, 1) + bool thick = false; // 3D blocks span block[2] depth slices (GFX10 3D S and D modes) + // Array slices, depth slabs of block[2] slices (thick), or depth slices (thin and linear 3D). + uint32_t slices = 0; + uint64_t slice_size = 0; // bytes of one slice: its whole mip chain + uint64_t size = 0; + uint64_t alignment = 0; + uint32_t first_tail_mip = 0; // the first mip in the tail; mips.size() without one + std::vector mips; + + static std::optional make(const Desc& d) { + const auto log2 = block_log2(d.swizzle); + if (!log2) return std::nullopt; + const auto in = [](uint32_t v, uint32_t lo, uint32_t hi) { return v >= lo && v <= hi; }; + const bool valid = + in(d.width, 1, kMaxExtent) && in(d.height, 1, kMaxExtent) && in(d.depth, 1, kMaxExtent) && + in(d.mips, 1, kMaxMips) && std::has_single_bit(d.element_bytes) && d.element_bytes <= 16 && + (d.block == 1 || d.block == 4) && std::has_single_bit(d.samples) && d.samples <= 8 && + (d.samples == 1 || (d.dimension == Dimension::tex2d && d.mips == 1)) && + (d.dimension != Dimension::tex1d || d.height == 1) && + (d.dimension != Dimension::tex3d || d.swizzle == 0 || d.swizzle == 5 || d.swizzle == 9 || + d.swizzle == 17 || d.swizzle == 21 || (d.swizzle >= 24 && d.swizzle <= 27)); + if (!valid) return std::nullopt; + return *log2 == 0 ? linear(d) : tiled(d, *log2); + } + + // Whether offset() and the copies work for this layout: linear and the modes without pipe or bank XOR, + // single-sampled. The XOR modes (_X, _T) and MSAA need the GPU's pipe and bank configuration (Series X and S + // differ); titles use them for render targets and depth, which the host renders. + bool addressable() const { return desc.swizzle == kLinear || !pattern_[0].empty(); } + + // Depth slices a subresource of mip `mip` covers: the mip's depth for 3D textures, else 1 (one array slice). + uint32_t subresource_depth(uint32_t mip) const { return mip < mips.size() ? mips[mip].depth : 0; } + + // Byte offset of element (x, y) of mip `mip` in array slice or depth slice `z`. Coordinates must lie inside. + Error offset(uint32_t mip, uint32_t x, uint32_t y, uint32_t z, uint64_t& out) const { + if (mip >= mips.size()) return Error::invalid; + const Mip& m = mips[mip]; + const uint32_t depth = desc.dimension == Dimension::tex3d ? m.depth : slices; + const bool inside = x < m.width && y < m.height && z < depth; + if (!inside) return Error::invalid; + if (!addressable()) return Error::unsupported; + const auto [slice, inner] = split(z); + const uint64_t base = uint64_t{slice} * slice_size + m.offset; + if (desc.swizzle == kLinear) { + out = base + (uint64_t{y} * m.pitch + x) * desc.element_bytes; + return Error::ok; + } + out = base + row(m, y, inner) + column(m, x); + return Error::ok; + } + + // Copies one subresource out of tiled memory (the whole texture, `size` bytes) into linear rows: mip `mip` of + // array slice `slice` (3D: every depth slice of the mip, slice 0). Rows are row_pitch bytes apart, depth slices + // depth_pitch. + Error detile(const uint8_t* tiled, size_t tiled_len, uint32_t mip, uint32_t slice, uint8_t* linear, + size_t linear_len, size_t row_pitch, size_t depth_pitch) const { + return walk(tiled_len, mip, slice, linear_len, row_pitch, depth_pitch, [&](size_t t, size_t l, size_t n) { + std::memcpy(linear + l, tiled + t, n); + }); + } + // The reverse of detile(): linear rows into tiled memory. + Error tile(uint8_t* tiled, size_t tiled_len, uint32_t mip, uint32_t slice, const uint8_t* linear, + size_t linear_len, size_t row_pitch, size_t depth_pitch) const { + return walk(tiled_len, mip, slice, linear_len, row_pitch, depth_pitch, [&](size_t t, size_t l, size_t n) { + std::memcpy(tiled + t, linear + l, n); + }); + } + + // Byte offsets inside a block of each element coordinate bit, per axis; empty for linear and XOR/MSAA modes. + const std::array, 3>& pattern() const { return pattern_; } + +private: + std::array, 3> pattern_; + + // HwlComputeSurfaceInfoLinear: rows aligned to 256 bytes, mips packed smallest first, a 3D texture's depth slices + // each hold the chain. + static Layout linear(const Desc& d) { + using namespace detail; + Layout l; + l.desc = d; + const uint64_t bpe = d.element_bytes; + const uint32_t align = 256 / d.element_bytes; + const bool three_d = d.dimension == Dimension::tex3d; + uint64_t offset = 0; + for (uint32_t i = d.mips; i-- > 0;) { + const uint32_t h = padded_dim(d.height, i, d.block); + const uint32_t pitch = round_up(padded_dim(d.width, i, d.block), align); + Mip m; + m.width = dim(d.width, i, d.block); + m.height = dim(d.height, i, d.block); + m.depth = three_d ? dim(d.depth, i, 1) : 1; + m.pitch = pitch; + m.rows = h; + m.depth_pitch = three_d ? d.depth : 1; + m.offset = offset; + l.mips.push_back(m); + offset += uint64_t{pitch} * h * bpe; + } + std::reverse(l.mips.begin(), l.mips.end()); + l.block = {align, 1, 1}; + l.slices = d.depth; + l.slice_size = offset; + l.size = offset * d.depth; + l.alignment = 256; + l.first_tail_mip = d.mips; + return l; + } + + static Layout tiled(const Desc& d, uint32_t block_log2) { + using namespace detail; + Layout l; + l.desc = d; + const uint32_t element_log2 = static_cast(std::countr_zero(d.element_bytes)); + const uint64_t bpe = d.element_bytes; + const uint64_t block_bytes = uint64_t{1} << block_log2; + const bool thick = d.dimension == Dimension::tex3d && (is_standard(d.swizzle) || is_display(d.swizzle)); + std::array block{}; + if (thick) { // ComputeThickBlockDimension + const uint32_t amp = (block_log2 - 10) / 3, rest = (block_log2 - 10) % 3; + const auto* b = kBlock1k_3d[element_log2]; + block = {b[0] << amp, b[1] << (amp + rest / 2), b[2] << (amp + (rest != 0 ? 1u : 0u))}; + } else { // ComputeThinBlockDimension + const uint32_t samples_log2 = static_cast(std::countr_zero(d.samples)); + const uint32_t elements_log2 = block_log2 - element_log2 - samples_log2; + const bool wide = (samples_log2 & 1) == 0 || (block_log2 & 1) != 0; + const uint32_t w = (elements_log2 + (wide ? 1u : 0u)) / 2; + block = {1u << w, 1u << (elements_log2 - w), 1}; + } + uint32_t slices = round_up(d.depth, block[2]); + const bool three_d = d.dimension == Dimension::tex3d; + // Mip depths placed by a thick layout (thin ones store depth as slices). + const auto mip_depth = [&](uint32_t i) { return thick ? padded_dim(d.depth, i, 1) : 1u; }; + const auto depth_of = [&](uint32_t i) { return three_d ? dim(d.depth, i, 1) : 1u; }; + const auto width = [&](uint32_t i) { return dim(d.width, i, d.block); }; + const auto height = [&](uint32_t i) { return dim(d.height, i, d.block); }; + uint32_t first_tail_mip = d.mips; + uint64_t slice_size = 0; + if (d.mips == 1) { + Mip m; + m.width = width(0); + m.height = height(0); + m.depth = depth_of(0); + m.pitch = round_up(width(0), block[0]); + m.rows = round_up(height(0), block[1]); + m.depth_pitch = three_d ? slices : 1; + l.mips.push_back(m); + slice_size = uint64_t{m.pitch} * m.rows * bpe * d.samples; + } else { + // GetMipTailDim: the largest mip the tail takes. + std::array tail_max = block; + if (thick) { + switch (block_log2 % 3) { + case 0: tail_max[1] >>= 1; break; + case 1: tail_max[0] >>= 1; break; + default: tail_max[2] >>= 1; break; + } + } else { + tail_max[0] >>= 1; + } + // GetMaxNumMipsInTail; 256-byte blocks have no tail (ComputeSurfaceInfoMicroTiled). + const uint32_t effective = thick ? block_log2 - (block_log2 - 8) / 3 : block_log2; + const uint32_t max_in_tail = effective == 8 ? 0 + : (effective >= 9 && effective <= 11) ? 1 + (1u << (effective - 9)) + : effective - 4; + // dsMipmapHtileFix: 8- and 16-bit depth enter the tail as 32-bit. + std::array fixed = tail_max; + if (is_z_order(d.swizzle) && element_log2 <= 1) { + const auto* b = kBlock256_2d[element_log2]; + fixed[0] /= b[0] / kBlock256_2d[2][0]; + fixed[1] /= b[1] / kBlock256_2d[2][1]; + } + std::vector sizes; + for (uint32_t i = 0; i < d.mips; ++i) { + const uint32_t w = padded_dim(d.width, i, d.block), h = padded_dim(d.height, i, d.block); + if (w <= fixed[0] && h <= fixed[1] && d.mips - i <= max_in_tail) { + first_tail_mip = i; + slice_size += block_bytes / block[2]; + break; + } + const uint32_t pitch = round_up(w, block[0]), rows = round_up(h, block[1]); + const uint32_t depth = round_up(mip_depth(i), block[2]); + const uint64_t one = uint64_t{pitch} * rows * bpe; + slice_size += one; + sizes.push_back(one * block[2]); + Mip m; + m.width = width(i); + m.height = height(i); + m.depth = depth_of(i); + m.pitch = pitch; + m.rows = rows; + m.depth_pitch = three_d ? depth : 1; + l.mips.push_back(m); + } + // Standard mips from the smallest up, after the tail block. + uint64_t offset = first_tail_mip < d.mips ? block_bytes : 0; + for (uint32_t i = first_tail_mip; i-- > 0;) { + l.mips[i].offset = offset; + offset += sizes[i]; + } + uint32_t micro[2]; + if (thick) { + micro[0] = kBlock256_3d[element_log2][0]; + micro[1] = kBlock256_3d[element_log2][1]; + } else { + micro[0] = kBlock256_2d[element_log2][0]; + micro[1] = kBlock256_2d[element_log2][1]; + } + uint32_t pitch = tail_max[0], rows = tail_max[1]; + for (uint32_t i = first_tail_mip; i < d.mips; ++i) { + const uint32_t m = max_in_tail - 1 - (i - first_tail_mip); + const uint32_t offset_in_tail = m > 6 ? 16u << m : m << 8; + // Address bits 8.. of the offset, odd ones x, even ones y. + const auto bits = [&](uint32_t from) { + uint32_t v = 0; + for (uint32_t b = 0; b < 6; ++b) v |= ((offset_in_tail >> (from + 2 * b)) & 1u) << b; + return v; + }; + uint32_t x = bits(9), y = bits(8); + if ((block_log2 & 1) != 0) { + std::swap(x, y); + if ((element_log2 & 1) != 0) { + y = (y << 1) | (x & 1); + x >>= 1; + } + } + Mip t; + t.width = width(i); + t.height = height(i); + t.depth = depth_of(i); + t.pitch = pitch; + t.rows = rows; + t.depth_pitch = thick ? round_up(mip_depth(i), kBlock256_3d[element_log2][2]) : 1; + t.offset = 0; + t.tail = Tail{offset_in_tail, x * micro[0], y * micro[1]}; + l.mips.push_back(t); + pitch = std::max(pitch >> 1, micro[0]); + rows = std::max(rows >> 1, micro[1]); + } + } + // Thick layouts store each depth slab's chain together. + const uint64_t slab = thick ? block[2] : 1; + slice_size *= slab; + slices /= block[2]; + if (!is_xor(d.swizzle) && d.samples == 1) { + const int kind = thick ? 2 : (is_display(d.swizzle) ? 1 : 0); + const auto bits = detail::pattern(kind, element_log2, block_log2); + for (size_t a = 0; a < 3; ++a) l.pattern_[a] = detail::spread(bits[a]); + } + l.block = block; + l.thick = thick; + l.slices = slices; + l.slice_size = slice_size; + l.size = slice_size * slices; + l.alignment = block_bytes; + l.first_tail_mip = first_tail_mip; + return l; + } + + // The slice and the depth inside it for z (an array slice or a 3D depth slice). + std::pair split(uint32_t z) const { + return thick ? std::pair{z / block[2], z % block[2]} : std::pair{z, 0u}; + } + + // The part of an address that depends on the row (and depth in a thick block). + uint64_t row(const Mip& m, uint32_t y, uint32_t z) const { + const uint32_t bw = block[0], bh = block[1]; + const int log2 = std::countr_zero(alignment); + // In the tail the pattern of the shifted position gives the mip's offset inside the tail block. + y += m.tail ? m.tail->y : 0; + const uint64_t blocks = uint64_t{y / bh} * (m.pitch / bw); + return (blocks << log2) + (pattern_[1][y % bh] | pattern_[2][z]); + } + + // The part of an address that depends on the column. + uint64_t column(const Mip& m, uint32_t x) const { + const uint32_t bw = block[0]; + x += m.tail ? m.tail->x : 0; + return (uint64_t{x / bw} << std::countr_zero(alignment)) + pattern_[0][x % bw]; + } + + // Visits contiguous runs as (tiled byte offset, linear byte offset, length). + template + Error walk(size_t tiled_len, uint32_t mip, uint32_t slice, size_t linear_len, size_t row_pitch, + size_t depth_pitch, Copy&& copy) const { + if (mip >= mips.size()) return Error::invalid; + const Mip& m = mips[mip]; + const uint32_t depth = m.depth; + uint32_t first = slice; + if (desc.dimension == Dimension::tex3d) { + if (slice != 0) return Error::invalid; + first = 0; + } + if (first >= slices) return Error::invalid; + if (!addressable()) return Error::unsupported; + const size_t n = desc.element_bytes; + const size_t bytes = size_t{m.width} * n; + // need = (depth - 1) * depth_pitch + (height - 1) * row_pitch + bytes, refused on overflow. + const size_t dz = depth - 1u, dy = m.height - 1u; + if ((dz && depth_pitch > SIZE_MAX / dz) || (dy && row_pitch > SIZE_MAX / dy)) return Error::too_small; + const size_t depth_offset = dz * depth_pitch, row_offset = dy * row_pitch; + if (depth_offset > SIZE_MAX - row_offset || depth_offset + row_offset > SIZE_MAX - bytes) + return Error::too_small; + const size_t need = depth_offset + row_offset + bytes; + if (tiled_len < size || linear_len < need || row_pitch < bytes) return Error::too_small; + const bool is_linear = desc.swizzle == kLinear; + // The row and depth contribute one common base to every column, so the same contiguous runs repeat on + // every row, including mip tails. + struct Run { + size_t tiled, linear, len; + }; + std::vector runs; + if (!is_linear) { + size_t first_linear = 0, first_tiled = static_cast(column(m, 0)); + for (uint32_t x = 1; x < m.width; ++x) { + const size_t off = static_cast(column(m, x)); + const size_t at = x * n; + if (off != first_tiled + (at - first_linear)) { + runs.push_back({first_tiled, first_linear, at - first_linear}); + first_tiled = off; + first_linear = at; + } + } + runs.push_back({first_tiled, first_linear, bytes - first_linear}); + } + for (uint32_t z = 0; z < depth; ++z) { + const auto [s, inner] = split(first + z); + const uint64_t base = uint64_t{s} * slice_size + m.offset; + for (uint32_t y = 0; y < m.height; ++y) { + const size_t linear_row = z * depth_pitch + y * row_pitch; + if (is_linear) { + copy(static_cast(base + uint64_t{y} * m.pitch * n), linear_row, bytes); + } else { + const size_t tiled_row = static_cast(base + row(m, y, inner)); + for (const Run& r : runs) copy(tiled_row + r.tiled, linear_row + r.linear, r.len); + } + } + } + return Error::ok; + } +}; + +// What a DXGI format stores per element: bytes, texels per element side (4 for block compression), and whether its +// stencil is a second plane (the GPU keeps depth and stencil apart). nullopt for 96-bit, 1-bit, packed 4:2:2 and +// video formats, which have no layout here. +struct Format { + uint32_t bytes, block; + bool stencil; +}; +inline std::optional format(uint32_t dxgi) { + const auto in = [&](uint32_t lo, uint32_t hi) { return dxgi >= lo && dxgi <= hi; }; + if (in(1, 4)) return Format{16, 1, false}; + if (in(9, 18)) return Format{8, 1, false}; + if (in(19, 22) || in(44, 47)) return Format{4, 1, true}; + if (in(23, 43) || dxgi == 67 || in(87, 93) || dxgi == 116 || dxgi == 117) return Format{4, 1, false}; + if (in(48, 59) || dxgi == 85 || dxgi == 86 || dxgi == 115) return Format{2, 1, false}; + if (in(118, 120)) return Format{2, 1, true}; + if (in(60, 65)) return Format{1, 1, false}; + if (in(70, 72) || in(79, 81)) return Format{8, 4, false}; + if (in(73, 78) || in(82, 84) || in(94, 99)) return Format{16, 4, false}; + return std::nullopt; +} + +// A texture as the console allocates it: a D3D12-style description with a swizzle mode. +struct TextureDesc { + Dimension dimension = Dimension::tex2d; + uint32_t width = 1, height = 1; // in texels + uint32_t depth_or_array = 1; // depth of a 3D texture, else the array size + uint32_t mips = 1; // 0: the full chain + uint32_t format = 0; // DXGI format number + uint32_t samples = 1; + uint32_t swizzle = kLinear; +}; + +struct Plane { + uint64_t offset = 0; // from the start of the texture + bool stencil = false; + Layout layout; +}; + +// Every data plane of a texture (depth, then stencil), placed one after the other. No compression metadata planes +// (HTILE, CMASK, FMASK, DCC): the console adds them to render targets and depth buffers unless the description +// denies them, so those are smaller here than on the console; the host GPU renders them, so nothing reads that +// memory. +struct Texture { + std::vector planes; + uint64_t size = 0; + uint64_t alignment = 0; + + static std::optional make(const TextureDesc& desc) { + const auto f = format(desc.format); + if (!f) return std::nullopt; + const uint32_t depth3d = desc.dimension == Dimension::tex3d ? desc.depth_or_array : 1; + const uint32_t mips = + desc.mips ? desc.mips + : 32u - static_cast(std::countl_zero( + std::max({desc.width, desc.height, depth3d, 1u}))); + const auto plane = [&](uint32_t bytes) { + Desc d; + d.dimension = desc.dimension; + d.width = desc.width; + d.height = desc.height; + d.depth = desc.depth_or_array; + d.mips = mips; + d.element_bytes = bytes; + d.block = f->block; + d.samples = std::max(desc.samples, 1u); + d.swizzle = desc.swizzle; + return d; + }; + Texture t; + auto main = Layout::make(plane(f->bytes)); + if (!main) return std::nullopt; + t.planes.push_back({0, false, std::move(*main)}); + if (f->stencil) { + auto s = Layout::make(plane(1)); + if (!s) return std::nullopt; + const uint64_t a = s->alignment; + const uint64_t offset = (t.planes[0].layout.size + a - 1) / a * a; + t.planes.push_back({offset, true, std::move(*s)}); + } + const Plane& last = t.planes.back(); + t.size = last.offset + last.layout.size; + for (const Plane& p : t.planes) t.alignment = std::max(t.alignment, p.layout.alignment); + return t; + } +}; + +} // namespace leonida::console_texture diff --git a/runtime/test/xg_xs_test.cpp b/runtime/test/xg_xs_test.cpp index 7db9b60962..46e16788be 100644 --- a/runtime/test/xg_xs_test.cpp +++ b/runtime/test/xg_xs_test.cpp @@ -1,34 +1,45 @@ -// Checks the registered xg_xs.dll shim against the call shapes measured in the game executable (runtime/shims/xg_xs.cpp). +// Checks the registered xg_xs.dll shim (runtime/shims/xg_xs.cpp) and the console texture layout model behind it +// (runtime/src/console_texture_layout.h). Synthetic textures only; no game files. // -// Both exports are resolved through rt::shims::find, so this is the table the runtime installs. The checks: both -// return E_NOTIMPL, XGSuggestSwizzleMode leaves the caller's field alone, XGCreateTextureComputer still hands out a -// computer (two measured callers use it without checking the HRESULT), and the computer's slots called at the -// measured sites (1, 2, 8, 10) return without writing what their arguments point to. +// Both exports are resolved through rt::shims::find, so this is the table the runtime installs. The layout cases and +// their expected numbers are those of the project the model is ported from (Marvisak/VIctory, GPL-3.0, +// crates/victory-formats/src/texture.rs and crates/victory-hle/src/modules/xg.rs tests at d2a4bae1f): hand-checked +// addresses, mip tail placement, a two-plane depth-stencil, and a bijection plus round trip over every element. #include #include #include #include +#include +#include "../src/console_texture_layout.h" #include "shims.h" namespace { +namespace ct = leonida::console_texture; + using CreateFn = HRESULT(__stdcall*)(const void*, void**); using SuggestFn = HRESULT(__stdcall*)(const void*, uint32_t, uint32_t*); using ReleaseFn = ULONG(__stdcall*)(void*); -using Slot2Fn = HRESULT(__stdcall*)(void*, void*); -using Slot8Fn = HRESULT(__stdcall*)(void*, void*, uint32_t, uint32_t, const void*, uint32_t, uint32_t); -using Slot10Fn = HRESULT(__stdcall*)(void*, uint32_t*, void*, void*, uint32_t*, uint32_t, void*); +using LayoutFn = HRESULT(__stdcall*)(void*, void*); +using OffsetFn = uint64_t(__stdcall*)(void*, uint32_t, uint32_t, uint64_t, uint32_t, uint32_t, uint32_t, uint32_t*); +using IntoFn = HRESULT(__stdcall*)(void*, uint8_t*, uint32_t, uint32_t, const uint8_t*, uint32_t, uint32_t); +using FromFn = HRESULT(__stdcall*)(void*, uint8_t*, uint32_t, uint32_t, uint32_t, const uint8_t*, uint32_t, uint32_t); +using TilingFn = HRESULT(__stdcall*)(void*, uint32_t*, void*, uint32_t*, uint32_t*, uint32_t, void*); constexpr HRESULT kNotImpl = static_cast(rt::shims::kENotImpl); +constexpr HRESULT kInvalidArg = static_cast(0x80070057u); +constexpr HRESULT kFail = static_cast(0x80004005u); int g_checks = 0; int g_failures = 0; void check(bool condition, const char* what) { ++g_checks; - std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); - if (!condition) ++g_failures; + if (!condition) { + std::printf("FAIL %s\n", what); + ++g_failures; + } } bool all_bytes(const uint8_t* p, size_t n, uint8_t value) { @@ -37,6 +48,325 @@ bool all_bytes(const uint8_t* p, size_t n, uint8_t value) { return true; } +ct::Desc desc2d(uint32_t w, uint32_t h, uint32_t mips, uint32_t bpe, uint32_t swizzle) { + ct::Desc d; + d.width = w; + d.height = h; + d.mips = mips; + d.element_bytes = bpe; + d.swizzle = swizzle; + return d; +} + +uint64_t offset_of(const ct::Layout& l, uint32_t mip, uint32_t x, uint32_t y, uint32_t z) { + uint64_t at = ~uint64_t{0}; + return l.offset(mip, x, y, z, at) == ct::Error::ok ? at : ~uint64_t{0}; +} + +// The D3D12-style description the title passes (0x38 bytes). +struct ResourceDesc { + uint32_t dimension; + uint64_t alignment; + uint64_t width; + uint32_t height; + uint16_t depth_or_array; + uint16_t mips; + uint32_t format; + uint32_t samples; + uint32_t quality; + uint32_t layout; + uint32_t flags; +}; +static_assert(sizeof(ResourceDesc) == 0x38); + +ResourceDesc rdesc(uint64_t w, uint32_t h, uint16_t mips, uint32_t format, uint32_t layout) { + ResourceDesc d{}; + d.dimension = 3; + d.width = w; + d.height = h; + d.depth_or_array = 1; + d.mips = mips; + d.format = format; + d.samples = 1; + d.layout = layout; + return d; +} + +void test_layout_model() { + // Sizes past the hardware's 16384 texels per side are refused instead of overflowing. + for (uint32_t s : {ct::kLinear, ct::kSw64kbDX}) { + const auto largest = ct::Layout::make(desc2d(ct::kMaxExtent, ct::kMaxExtent, 15, 16, s)); + check(largest && largest->size >= uint64_t{ct::kMaxExtent} * ct::kMaxExtent * 16, "largest texture lays out"); + check(!ct::Layout::make(desc2d(ct::kMaxExtent + 1, 1, 1, 16, s)), "width past 16384 is refused"); + check(!ct::Layout::make(desc2d(1, 0xffffffffu, 1, 16, s)), "height past 16384 is refused"); + auto deep = desc2d(1, 1, 1, 16, s); + deep.depth = 0xffffffffu; + check(!ct::Layout::make(deep), "depth past 16384 is refused"); + } + // Blocks hold their size in elements, and the pattern covers exactly the block's coordinates. + for (uint32_t log2 : {8u, 12u, 16u}) { + const uint32_t s = log2 == 8 ? ct::kSw256bS : log2 == 12 ? ct::kSw4kbS : ct::kSw64kbD; + for (uint32_t e = 0; e < 5; ++e) { + const auto l = ct::Layout::make(desc2d(1, 1, 1, 1u << e, s)); + check(l && (uint64_t{l->block[0]} * l->block[1] * l->block[2] << e) == (uint64_t{1} << log2), + "block holds its size in elements"); + check(l && l->pattern()[0].size() == l->block[0] && l->pattern()[1].size() == l->block[1], + "pattern covers the block"); + } + } + { + const auto l = ct::Layout::make(desc2d(64, 64, 1, 16, ct::kSw64kbD)); + check(l && l->block[0] == 64 && l->block[1] == 64 && l->block[2] == 1, "64 KiB, 16-byte elements: 64x64"); + check(l && l->size == 65536 && l->alignment == 65536, "64 KiB, 16-byte elements: one block"); + } + // Hand-checked: in a 64 KiB D block of 4-byte elements, x bits go to address bits 2, 3, 6, 9, 11, 13, 15 and y + // bits to 4, 5, 7, 8, 10, 12, 14; a 4 KiB S block of 16-byte elements is 16x16 with y first. + { + const auto l = ct::Layout::make(desc2d(128, 128, 1, 4, ct::kSw64kbD)); + check(l && offset_of(*l, 0, 1, 0, 0) == (1u << 2), "64KB_D x=1"); + check(l && offset_of(*l, 0, 4, 0, 0) == (1u << 6), "64KB_D x=4"); + check(l && offset_of(*l, 0, 0, 4, 0) == (1u << 7), "64KB_D y=4"); + check(l && offset_of(*l, 0, 0, 8, 0) == (1u << 8), "64KB_D y=8"); + check(l && offset_of(*l, 0, 64, 64, 0) == ((1u << 15) | (1u << 14)), "64KB_D (64,64)"); + const auto s = ct::Layout::make(desc2d(32, 32, 1, 16, ct::kSw4kbS)); + check(s && s->block[0] == 16 && s->block[1] == 16, "4KB_S 16-byte block is 16x16"); + check(s && offset_of(*s, 0, 0, 1, 0) == (1u << 4), "4KB_S y=1"); + check(s && offset_of(*s, 0, 1, 0, 0) == (1u << 6), "4KB_S x=1"); + check(s && offset_of(*s, 0, 16, 0, 0) == 4096, "4KB_S second block"); + check(s && offset_of(*s, 0, 0, 16, 0) == 8192, "4KB_S third block"); + } + // A 256x256 BC7 chain in 64 KiB D: one tail block holding mips 1-8, then mip 0; mip 1 sits at x = 32 elements, + // 32 KiB into the tail. 4 KiB blocks hold fewer tail mips. + { + const auto l = ct::Layout::make(desc2d(64, 64, 9, 16, ct::kSw64kbD)); + check(l && l->first_tail_mip == 1 && l->size == 2 * 65536 && l->mips[0].offset == 65536, "tail comes first"); + check(l && l->mips[1].tail && l->mips[1].tail->offset == 32768 && l->mips[1].tail->x == 32 && + l->mips[1].tail->y == 0, + "mip 1 tail position"); + check(l && offset_of(*l, 1, 0, 0, 0) == 32768, "mip 1 element 0 address"); + const auto s = ct::Layout::make(desc2d(64, 64, 9, 16, ct::kSw4kbS)); + check(s && s->first_tail_mip == 3 && s->mips[2].offset == 4096 && s->mips[1].offset == 8192 && + s->mips[0].offset == 8192 + 16384, + "4 KiB tail holds fewer mips"); + } + // Depth-stencil is two planes: 4-byte depth in 128x128 blocks, 1-byte stencil in 256x256 blocks. + { + ct::TextureDesc t; + t.width = 1920; + t.height = 1080; + t.format = 20; + t.swizzle = ct::kSw64kbZX; + const auto tex = ct::Texture::make(t); + check(tex && tex->planes.size() == 2, "D32_FLOAT_S8X24 has two planes"); + check(tex && tex->planes[0].layout.size == 1920ull * 1152 * 4, "depth plane size"); + check(tex && tex->planes[1].offset == tex->planes[0].layout.size, "stencil follows depth"); + check(tex && tex->planes[1].layout.size == 2048ull * 1280, "stencil plane size"); + check(tex && !tex->planes[0].layout.addressable(), "XOR modes are not addressed"); + } + // Bad descriptions and buffers are refused. + { + check(!ct::Layout::make(desc2d(0, 4, 1, 4, ct::kSw4kbS)), "zero width is refused"); + check(!ct::Layout::make(desc2d(4, 4, 1, 12, ct::kSw4kbS)), "12-byte elements are refused"); + check(!ct::Layout::make(desc2d(4, 4, 1, 4, 3)), "mode 3 is refused"); + const auto l = ct::Layout::make(desc2d(64, 64, 1, 4, ct::kSw4kbS)); + std::vector out(64 * 64 * 4), small(100); + check(l && l->detile(small.data(), small.size(), 0, 0, out.data(), out.size(), 256, 0) == ct::Error::too_small, + "a short tiled buffer is too small"); + uint64_t at = 0; + check(l && l->offset(0, 64, 0, 0, at) == ct::Error::invalid, "an element outside is invalid"); + const auto lin = ct::Layout::make(desc2d(4, 2, 1, 4, ct::kLinear)); + std::vector tiled(lin ? lin->size : 0), linear(32); + check(lin && lin->detile(tiled.data(), tiled.size(), 0, 0, linear.data(), linear.size(), SIZE_MAX, 0) == + ct::Error::too_small, + "an overflowing row pitch is refused"); + auto vol = desc2d(4, 2, 1, 4, ct::kLinear); + vol.dimension = ct::Dimension::tex3d; + vol.depth = 3; + const auto v = ct::Layout::make(vol); + std::vector vt(v ? v->size : 0), vl(96); + check(v && v->detile(vt.data(), vt.size(), 0, 0, vl.data(), vl.size(), 16, SIZE_MAX) == ct::Error::too_small, + "an overflowing depth pitch is refused"); + } +} + +// Every element of every mip and slice lands on its own address inside the texture, and tiling then detiling gives +// the rows back without touching the padding around them. +void test_bijection_and_round_trip() { + std::vector cases = { + desc2d(64, 64, 7, 16, ct::kSw64kbD), desc2d(100, 60, 7, 4, ct::kSw64kbD), desc2d(250, 175, 8, 8, ct::kSw4kbS), + desc2d(33, 17, 6, 1, ct::kSw4kbD), desc2d(40, 9, 3, 2, ct::kSw64kbS), desc2d(30, 20, 5, 4, ct::kLinear), + desc2d(83, 31, 6, 1, ct::kSw256bS), + }; + auto bc = desc2d(109, 71, 6, 16, ct::kSw256bD); + bc.block = 4; + cases.push_back(bc); + auto array = desc2d(70, 70, 4, 16, ct::kSw4kbS); + array.depth = 3; + cases.push_back(array); + auto volume = desc2d(64, 32, 7, 4, ct::kSw4kbS); + volume.dimension = ct::Dimension::tex3d; + volume.depth = 16; + cases.push_back(volume); + for (const ct::Desc& d : cases) { + const auto l = ct::Layout::make(d); + if (!l) { + check(false, "round-trip case lays out"); + continue; + } + std::vector seen(static_cast(l->size)); + std::vector tiled(static_cast(l->size)); + const size_t n = d.element_bytes; + const uint32_t slices = d.dimension == ct::Dimension::tex3d ? 1 : d.depth; + bool ok = true; + for (uint32_t slice = 0; slice < slices; ++slice) { + for (uint32_t mip = 0; mip < d.mips; ++mip) { + const ct::Mip& m = l->mips[mip]; + const size_t active = size_t{m.width} * n, row = active + 13, plane = row * m.height + 11; + std::vector linear(plane * m.depth); + for (size_t i = 0; i < linear.size(); ++i) linear[i] = static_cast(i * 7 + mip * 13 + slice); + ok &= l->tile(tiled.data(), tiled.size(), mip, slice, linear.data(), linear.size(), row, plane) == + ct::Error::ok; + std::vector back(linear.size(), 0xcc); + ok &= l->detile(tiled.data(), tiled.size(), mip, slice, back.data(), back.size(), row, plane) == + ct::Error::ok; + for (uint32_t z = 0; z < m.depth; ++z) { + const size_t base = z * plane; + for (uint32_t y = 0; y < m.height; ++y) { + const size_t start = base + y * row; + ok &= std::memcmp(&back[start], &linear[start], active) == 0; + ok &= all_bytes(&back[start + active], row - active, 0xcc); + for (uint32_t x = 0; x < m.width; ++x) { + uint64_t at64 = 0; + if (l->offset(mip, x, y, slice + z, at64) != ct::Error::ok) { + ok = false; + continue; + } + const size_t at = static_cast(at64); + const size_t source = start + x * n; + if (at + n > seen.size() || at % n != 0 || seen[at]) { + ok = false; + continue; + } + ok &= std::memcmp(&tiled[at], &linear[source], n) == 0; + seen[at] = true; + } + } + ok &= all_bytes(&back[base + plane - 11], 11, 0xcc); + } + } + } + char what[96]; + std::snprintf(what, sizeof(what), "bijection and round trip: %ux%ux%u mips %u bpe %u mode %u", d.width, + d.height, d.depth, d.mips, d.element_bytes, d.swizzle); + check(ok, what); + } +} + +void test_shim(CreateFn create, SuggestFn suggest) { + // XGSuggestSwizzleMode follows the use: 4KB_S, then the XOR render and depth modes. + uint32_t mode = 0; + ResourceDesc d = rdesc(256, 256, 1, 98, 0); + check(suggest(&d, 0, &mode) == S_OK && mode == 0x105, "suggest: a sampled texture gets 4KB_S"); + d.flags = 1; + check(suggest(&d, 0, &mode) == S_OK && mode == 0x11b, "suggest: a render target gets 64KB_R_X"); + d.flags = 2; + check(suggest(&d, 0, &mode) == S_OK && mode == 0x118, "suggest: a depth target gets 64KB_Z_X"); + check(suggest(nullptr, 0, &mode) == kInvalidArg, "suggest: a null description is E_INVALIDARG"); + + check(create(&d, nullptr) == E_POINTER, "XGCreateTextureComputer(desc, nullptr) is E_POINTER"); + + // A description with no layout still hands out a computer (two measured callers use *out without checking). + void* stub = nullptr; + const ResourceDesc bad = rdesc(256, 256, 1, 0, 0x10a); + check(create(&bad, &stub) == kInvalidArg, "an unknown format is E_INVALIDARG"); + check(stub != nullptr, "and still stores a computer for the callers that do not check"); + if (stub) { + void* const* vt = *static_cast(stub); + std::vector out(0x1b40, 0xcd); + check(reinterpret_cast(vt[2])(stub, out.data()) == kNotImpl && + all_bytes(out.data(), out.size(), 0xcd), + "that computer's slot 2 is E_NOTIMPL and writes nothing"); + reinterpret_cast(vt[1])(stub); + reinterpret_cast(vt[1])(stub); + check(reinterpret_cast(vt[2])(stub, out.data()) == kNotImpl, + "that computer stays usable after more Releases than it was handed out"); + } + + // Element offsets (slot 6): linear rows of 1 KiB (128 8-byte elements), 0 outside. + { + void* c = nullptr; + const ResourceDesc lin = rdesc(128, 4, 1, 11, 0x100); + check(create(&lin, &c) == S_OK && c, "a 128x4 R16G16B16A16 linear texture gets a computer"); + if (c) { + void* const* vt = *static_cast(c); + uint32_t bit = 7; + check(reinterpret_cast(vt[6])(c, 0, 0, 3, 1, 0, 0, &bit) == (128 + 3) * 8 && bit == 0, + "slot 6: element (3, 1) of linear rows"); + check(reinterpret_cast(vt[6])(c, 0, 0, 128, 0, 0, 0, nullptr) == 0, "slot 6: 0 outside"); + check(reinterpret_cast(vt[1])(c) == 0, "Release frees the computer"); + } + } + + // The title's calls: the layout, then a copy in and out of each mip. 256x256 BC7, full chain, 64 KiB display. + void* c = nullptr; + const ResourceDesc bc7 = rdesc(256, 256, 0, 98, 0x10a); + check(create(&bc7, &c) == S_OK && c, "a 256x256 BC7 chain gets a computer"); + if (!c) return; + void* const* vt = *static_cast(c); + std::vector buf(0x1b40); + check(reinterpret_cast(vt[2])(c, buf.data()) == S_OK, "slot 2 fills the layout"); + const auto u64 = [&](size_t at) { uint64_t v; std::memcpy(&v, &buf[at], 8); return v; }; + const auto u32 = [&](size_t at) { uint32_t v; std::memcpy(&v, &buf[at], 4); return v; }; + // LayoutOut: size 0x00, alignment 0x08, mips 0x10, planes 0x14, plane[0] at 0x18 (PlaneOut: element_bytes 0x28, + // standard 0x2c, tail 0x30, mips at 0x38, MipOut 0x70 bytes: offset 0x08, pitch_bytes 0x1c, elements 0x30, in_tail + // 0x64). + check(u64(0x00) == 131072 && u64(0x08) == 65536 && u32(0x10) == 9 && u32(0x14) == 1, "layout totals"); + const size_t plane = 0x18; + check(u32(plane + 0x2c) == 1 && u32(plane + 0x30) == 8 && u32(plane + 0x28) == 16, "plane 0 mips and elements"); + const size_t mip0 = plane + 0x38, mip1 = mip0 + 0x70; + check(u64(mip0 + 0x08) == 65536 && u32(mip0 + 0x1c) == 1024, "mip 0 offset and pitch"); + check(u64(mip1 + 0x08) == 32768 && u32(mip1 + 0x64) == 1, "mip 1 sits in the tail"); + + std::vector tiled(131072); + bool copies = true; + for (uint32_t mip = 0; mip < 9; ++mip) { + const size_t m = mip0 + mip * 0x70; + const uint32_t w = u32(m + 0x30), h = u32(m + 0x34), row = w * 16; + std::vector rows(size_t{row} * h); + for (size_t i = 0; i < rows.size(); ++i) rows[i] = static_cast(i ^ mip); + copies &= reinterpret_cast(vt[8])(c, tiled.data(), 0, mip, rows.data(), row, 0) == S_OK; + std::vector back(rows.size()); + copies &= reinterpret_cast(vt[9])(c, back.data(), 0, mip, 0, tiled.data(), row, 0) == S_OK; + copies &= back == rows; + } + check(copies, "slots 8 and 9 copy every mip in and out"); + + // Slot 10: one tile for the tail, one for mip 0. + uint32_t tiles = 0, shape[3] = {}, count = 4; + uint8_t packed[12] = {}; + uint8_t subs[4 * 12] = {}; + check(reinterpret_cast(vt[10])(c, &tiles, packed, shape, &count, 0, subs) == S_OK, "slot 10 succeeds"); + uint32_t packed_tiles = 0, first_start = 0; + std::memcpy(&packed_tiles, packed + 4, 4); + std::memcpy(&first_start, subs + 8, 4); + check(tiles == 2 && packed[0] == 1 && packed[1] == 8 && packed_tiles == 1, "slot 10 tiles and packed mips"); + check(shape[0] == 256 && shape[1] == 256 && shape[2] == 1 && count == 1 && first_start == 1, + "slot 10 shape and mip 0's tiling"); + check(reinterpret_cast(vt[1])(c) == 0, "Release frees the BC7 computer"); + + // 4 KiB modes have no 64 KiB tiling. + void* c4 = nullptr; + const ResourceDesc four = rdesc(256, 256, 0, 98, 0x105); + check(create(&four, &c4) == S_OK && c4, "a 4KB_S chain gets a computer"); + if (c4) { + void* const* v4 = *static_cast(c4); + check(reinterpret_cast(v4[10])(c4, &tiles, nullptr, nullptr, nullptr, 0, nullptr) == kFail, + "slot 10 of a 4 KiB mode is E_FAIL"); + check(reinterpret_cast(v4[31])(c4, buf.data()) == kNotImpl, "the last slot (31) is E_NOTIMPL"); + reinterpret_cast(v4[1])(c4); + } +} + } // namespace int main() { @@ -47,44 +377,9 @@ int main() { check(rt::shims::owns_dll("xg_xs.dll"), "the registry owns xg_xs.dll"); if (!create || !suggest) return 1; - uint8_t desc[0x38] = {}; - uint32_t mode = 0x1234; - check(suggest(desc, 0, &mode) == kNotImpl, "XGSuggestSwizzleMode returns E_NOTIMPL"); - check(mode == 0x1234, "XGSuggestSwizzleMode leaves the mode field as the caller set it"); - - check(create(desc, nullptr) == E_POINTER, "XGCreateTextureComputer(desc, nullptr) is E_POINTER"); - void* computer = nullptr; - check(create(desc, &computer) == kNotImpl, "XGCreateTextureComputer returns E_NOTIMPL"); - check(computer != nullptr, "XGCreateTextureComputer still stores a computer for the callers that do not check"); - if (!computer) return 1; - - void* const* vtable = *static_cast(computer); - uint8_t layout[0x800]; - std::memset(layout, 0xcd, sizeof(layout)); - check(reinterpret_cast(vtable[2])(computer, layout) == kNotImpl, "slot 2 returns E_NOTIMPL"); - check(all_bytes(layout, sizeof(layout), 0xcd), "slot 2 writes nothing to its output"); - - uint8_t dst[64]; - std::memset(dst, 0xcd, sizeof(dst)); - const uint8_t src[64] = {}; - check(reinterpret_cast(vtable[8])(computer, dst, 0, 0, src, 16, 64) == kNotImpl, - "slot 8 returns E_NOTIMPL"); - check(all_bytes(dst, sizeof(dst), 0xcd), "slot 8 writes nothing to its destination"); - - uint32_t count = 0, inout = 0x10; - uint8_t a[12] = {}, b[12] = {}, list[0xc0] = {}; - check(reinterpret_cast(vtable[10])(computer, &count, a, b, &inout, 0, list) == kNotImpl, - "slot 10 returns E_NOTIMPL"); - check(count == 0 && inout == 0x10 && all_bytes(a, 12, 0) && all_bytes(b, 12, 0) && - all_bytes(list, sizeof(list), 0), - "slot 10 leaves the caller's zero-filled outputs as they were"); - check(reinterpret_cast(vtable[31])(computer, layout) == kNotImpl, "the last slot (31) is traced too"); - - auto release = reinterpret_cast(vtable[1]); - release(computer); - release(computer); - check(reinterpret_cast(vtable[2])(computer, layout) == kNotImpl, - "the computer stays usable after more Releases than it was handed out"); + test_layout_model(); + test_bijection_and_round_trip(); + test_shim(create, suggest); std::printf("%d checks, %d failures\n", g_checks, g_failures); return g_failures ? 1 : 0; From ce3e5153f1150f90b9291eff5aa133941d06124e Mon Sep 17 00:00:00 2001 From: Rain156 <1954786975@qq.com> Date: Tue, 24 Nov 2026 14:53:10 +0800 Subject: [PATCH 056/110] d3d12_xs: keep the fallback PresentX window responsive during rendering Create and dispatch the Win32 window on its own thread. Shut that thread down after the presenter has released the surface and test window messages and closure independently of the submitting thread. --- runtime/CMakeLists.txt | 7 +++ runtime/shims/d3d12_xs_device.cpp | 33 ++++--------- runtime/shims/present_window.h | 72 ++++++++++++++++++++++++++++ runtime/test/present_window_test.cpp | 35 ++++++++++++++ 4 files changed, 123 insertions(+), 24 deletions(-) create mode 100644 runtime/shims/present_window.h create mode 100644 runtime/test/present_window_test.cpp diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index e922f067c9..e1b3aee816 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -1006,6 +1006,13 @@ if(BUILD_TESTING) add_test(NAME startup_trace COMMAND startup_trace_test) endif() + if(WIN32) + add_executable(present_window_test test/present_window_test.cpp) + target_link_libraries(present_window_test PRIVATE user32) + add_test(NAME present_window COMMAND present_window_test) + set_tests_properties(present_window PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 15) + endif() + if(TARGET device_proxy_test) add_test(NAME device_proxy COMMAND device_proxy_test) set_tests_properties(device_proxy PROPERTIES SKIP_RETURN_CODE 77) # no WARP adapter (Wine) diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index e53d96d564..7a47e76a2f 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -24,6 +24,9 @@ // for a trace that disagrees. The frame-event calls answer from a per-device token counter: there is no vblank source // behind the device before a presenter exists, so WaitFrameEventX returns at once with a fresh non-zero token. #include "d3d12_xs_device.h" +#ifdef LEONIDA_VULKAN_DEVICE +#include "present_window.h" +#endif #include "d3d12_trace.h" #include "d3d12_xs_alloc_size.h" #include "d3d12_xs_desc_clean.h" @@ -1352,20 +1355,12 @@ constexpr unsigned kQueuePresentX = 32; #ifdef LEONIDA_VULKAN_DEVICE struct PresentState { - ~PresentState() { - xbox.reset(); - if (window) DestroyWindow(window); - } - HWND window = nullptr; + PresentWindow window; // The presenter is destroyed before its surface window. std::unique_ptr xbox; }; void destroy_present_state(void* present_state) { delete static_cast(present_state); } -LRESULT CALLBACK present_window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { - return DefWindowProcW(window, message, wparam, lparam); -} - // Builds the window, presenter and XboxPresentation once per device. Returns the state even when `xbox` stays null: // the failure is logged once and not retried. PresentState* present_state_for(DeviceProxy* device) { @@ -1375,30 +1370,20 @@ PresentState* present_state_for(DeviceProxy* device) { auto* state = new (std::nothrow) PresentState; if (!state) return nullptr; device->present_state = state; - WNDCLASSW window_class{}; - window_class.lpfnWndProc = present_window_proc; - window_class.hInstance = GetModuleHandleW(nullptr); - window_class.lpszClassName = L"LeonidaPresentX"; - if (!RegisterClassW(&window_class) && GetLastError() != ERROR_CLASS_ALREADY_EXISTS) { - std::fprintf(stderr, "[rt] d3d12_xs: PresentX window class failed (error %lu)\n", GetLastError()); - return state; - } - state->window = CreateWindowExW(0, window_class.lpszClassName, L"Leonida", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, - CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, nullptr, nullptr, - window_class.hInstance, nullptr); - if (!state->window) { + HWND window = state->window.create(); + if (!window) { std::fprintf(stderr, "[rt] d3d12_xs: PresentX window failed (error %lu)\n", GetLastError()); return state; } - ShowWindow(state->window, SW_SHOWNOACTIVATE); - auto presenter = rt::d3d12::create_window_presenter(device->real, state->window); + ShowWindowAsync(window, SW_SHOWNOACTIVATE); + auto presenter = rt::d3d12::create_window_presenter(device->real, window); if (!presenter) { std::fprintf(stderr, "[rt] d3d12_xs: no window presenter on this device; PresentX shows nothing\n"); return state; } state->xbox = std::make_unique(std::move(presenter), nullptr, device->frame_tokens); // The device's token source: the title takes its frame tokens from device slot 80 and presents them here. - std::fprintf(stderr, "[rt] d3d12_xs: PresentX ready (window %p)\n", static_cast(state->window)); + std::fprintf(stderr, "[rt] d3d12_xs: PresentX ready (window %p)\n", static_cast(window)); return state; } diff --git a/runtime/shims/present_window.h b/runtime/shims/present_window.h new file mode 100644 index 0000000000..1f03f58fcc --- /dev/null +++ b/runtime/shims/present_window.h @@ -0,0 +1,72 @@ +#pragma once + +#include +#include +#include +#include + +// The thread that owns an HWND must continue dispatching window messages while another +// thread creates pipelines or waits for the GPU. A stop event also wakes an idle window. +namespace rt::d3d12_xs { +class PresentWindow { +public: + PresentWindow() = default; + PresentWindow(const PresentWindow&) = delete; + PresentWindow& operator=(const PresentWindow&) = delete; + ~PresentWindow() { + if (stop_) SetEvent(stop_); + if (owner_.joinable()) owner_.join(); + if (stop_) CloseHandle(stop_); + } + + HWND create() { + if (stop_) return nullptr; + stop_ = CreateEventW(nullptr, TRUE, FALSE, nullptr); + if (!stop_) return nullptr; + try { + std::promise> ready; + auto result = ready.get_future(); + owner_ = std::thread([stop = stop_, ready = std::move(ready)]() mutable { + WNDCLASSW cls{}; + cls.lpfnWndProc = &procedure; + cls.hInstance = GetModuleHandleW(nullptr); + cls.lpszClassName = L"LeonidaPresentX"; + HWND window = nullptr; + if (RegisterClassW(&cls) || GetLastError() == ERROR_CLASS_ALREADY_EXISTS) + window = CreateWindowExW(0, cls.lpszClassName, L"Leonida", WS_OVERLAPPEDWINDOW, + CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, + nullptr, nullptr, cls.hInstance, nullptr); + ready.set_value({window, window ? ERROR_SUCCESS : GetLastError()}); + if (!window) return; + while (MsgWaitForMultipleObjectsEx(1, &stop, INFINITE, QS_ALLINPUT, MWMO_INPUTAVAILABLE) == + WAIT_OBJECT_0 + 1) { + MSG msg; + while (WaitForSingleObject(stop, 0) == WAIT_TIMEOUT && PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) { + if (msg.message == WM_QUIT) return; + TranslateMessage(&msg); + DispatchMessageW(&msg); + } + } + if (IsWindow(window)) DestroyWindow(window); + }); + const auto [window, error] = result.get(); + if (!window) SetLastError(error); + return window; + } catch (const std::exception&) { + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + return nullptr; + } + } + +private: + static LRESULT CALLBACK procedure(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { + if (message == WM_DESTROY) { + PostQuitMessage(0); + return 0; + } + return DefWindowProcW(window, message, wparam, lparam); + } + HANDLE stop_ = nullptr; + std::thread owner_; +}; +} // namespace rt::d3d12_xs diff --git a/runtime/test/present_window_test.cpp b/runtime/test/present_window_test.cpp new file mode 100644 index 0000000000..9488563c95 --- /dev/null +++ b/runtime/test/present_window_test.cpp @@ -0,0 +1,35 @@ +// The submitting thread does no message dispatch. Each hidden presentation window must still +// process messages, close on its owner thread and allow the other window to keep running. +#include "../shims/present_window.h" + +#include +#include + +namespace { +bool send(HWND window, UINT message) { + DWORD_PTR result = 0; + return SendMessageTimeoutW(window, message, 0, 0, SMTO_ABORTIFHUNG | SMTO_BLOCK, 2000, &result) != 0; +} +} + +int main() { + HWND control = CreateWindowExW(0, L"STATIC", L"", WS_POPUP, 0, 0, 1, 1, nullptr, nullptr, + GetModuleHandleW(nullptr), nullptr); + if (!control) { + std::fprintf(stderr, "no Win32 desktop available (error %lu)\n", GetLastError()); + return 77; + } + DestroyWindow(control); + + rt::d3d12_xs::PresentWindow first; + auto second = std::make_unique(); + const HWND a = first.create(), b = second->create(); + if (!a || !b || a == b || GetWindowThreadProcessId(a, nullptr) == GetCurrentThreadId() || + !send(a, WM_NULL) || !send(b, WM_NULL)) return 1; + if (!send(a, WM_CLOSE) || IsWindow(a) || !send(b, WM_NULL)) return 1; + + std::thread release([window = std::move(second)]() mutable { window.reset(); }); + release.join(); + if (IsWindow(b)) return 1; + return 0; +} From 1ea2ffbcadac0ea8cd58fe0794a513ff68661af4 Mon Sep 17 00:00:00 2001 From: Tyrannys <80750971+Tyrannys@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:25:31 -0600 Subject: [PATCH 057/110] rdna2spirv: s_bitreplicate_b64_b32 into VCC, s_flbit_i32_b64 of a lane mask - s_bitreplicate_b64_b32 with a VCC destination: lane L gets S0 bit L // 2, stored as mov64 stores a mask into VCC (EXEC already took this path). - s_flbit_i32_b64 of a lane mask reads the wave's whole mask (wave_mask), as s_ff1_i32_b64 does; s_flbit_i32_i64 of a mask stays Unsupported. Both occur in pipeline-library compute programs that the retail boot creates. Tests: tests/semantic/test_lane_mask_bitreplicate_flbit.py runs both on every lane of a wave64 (run_workgroup); docs/design.md contract rows updated. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5.5 --- docs/design.md | 4 +- .../test_lane_mask_bitreplicate_flbit.py | 65 +++++++++++++++++++ tests/semantic/test_salu_flbit_64.py | 5 +- tools/rdna2spirv.py | 19 ++++-- 4 files changed, 85 insertions(+), 8 deletions(-) create mode 100644 tests/semantic/test_lane_mask_bitreplicate_flbit.py diff --git a/docs/design.md b/docs/design.md index ba4c33fa1c..de55f9283b 100644 --- a/docs/design.md +++ b/docs/design.md @@ -449,9 +449,9 @@ How the generated SPIR-V expects the runtime to work: | `v_bfi_b32` | `(S0 & S1) \| (~S0 & S2)` (RDNA2 ISA, VOP3 opcode 330). A literal or known same-block SGPR mask of zero or all ones selects S2 or S1 directly. A contiguous mask uses `OpBitFieldInsert` with S1 shifted down by the field offset, since RDNA2 reads the bits in place. For sparse constant masks the translator precomputes the complement. Runtime masks use the full bitwise expression. Checked by the hand-written `bfi_known_mask.asm` and `tests/semantic/test_bfi_known_mask.py`. | | `v_bfm_b32` | The low five bits of S0 give the width and those of S1 give the offset. The result is the low 32 bits of `((1 << width) - 1) << offset` (RDNA2 ISA §12.12, VOP3 opcode 867). Literal and same-block SGPR constants are folded in the translator, including zero width and shifts that discard the high bits. Runtime operands keep their low-five-bit masks. Checked by `tests/semantic/test_bfm_known_operands.py` and `test_alu_int_misc.py`. | | `s_bfe_u32` / `s_bfe_i32` past bit 31 | offset = S1[4:0], width = S1[22:16] (7 bits; S1 bits 23 to 31 are ignored). When offset + width > 32 the field stops at bit 31: width = min(width, 32 - offset), and `s_bfe_i32` sign-extends from the top bit that exists. Example: `s_bfe_i32 s4, 0xd2f90159, 0x7f001c` gives `0xfffffffd` (4-bit field `0xd`), not `0xd`. SCC = D ≠ 0. Source: measured on gfx1150 (Radeon 880M) with `tools/salu_diff.py --oracle hw`, 4000 random control words, all bit-exact, on gfx1201 (Radeon RX 9070, RDNA4) with 10,000 `salu_diff --oracle hw` programs, 0 mismatches (seed 500 with `--bfe-any`), and **on RDNA2** (AMD Radeon 680M, `gfx1035`: `tools/salu_diff.py --oracle hw,translator --bfe-any --programs 500 --seed 1`, 500/500 match, plus `tools/int_hw_probe.py --oracle both` wave32 and wave64, SHADER-137; and RDNA2 `gfx1036`, Windows 11, driver 26.10.1, `tools/hw_oracle` HIP launcher: `tools/salu_diff.py --oracle translator,hw --bfe-any --ops s_bfe_u32,s_bfe_i32 --programs 2000` with seeds 1, 2 and 3, 6,000 of 6,000 programs pass on both sides, plus seed 4 over every opcode with `--bfe-any`, 2,000 of 2,000, and `int_hw_probe.py`'s `salu_bfe_past31` cases in wave32 and wave64); the translator (`bfe_width`) already did this. `tools/salu_diff.py --oracle hw,translator --bfe-any --programs 500 --seed 1`, 500/500 match, plus `tools/int_hw_probe.py --oracle both` wave32 and wave64, SHADER-137); the translator (`bfe_width`) already did this. Source: measured on gfx1150 (Radeon 880M) with `tools/salu_diff.py --oracle hw`, 4000 random control words, all bit-exact, and on gfx1201 (Radeon RX 9070, RDNA4) with 10,000 `salu_diff --oracle hw` programs, 0 mismatches (seed 500 with `--bfe-any`); the translator (`bfe_width`) already did this. LLVM's v_bfe fold (`constantFoldBFE`) is analogous but has a 5-bit width. **RDNA2 is not measured**; the ISA pseudocode does not say. | -| 64-bit scalar data ops (`s_brev_b64`, `s_bfe_u64`/`s_bfe_i64`, `s_bitset0_b64`/`s_bitset1_b64`, `s_flbit_i32_b64`/`s_flbit_i32_i64`) | The SGPR pair is 64-bit data, as for `s_lshl_b64`; a pair that `lane_masks.py` marks as a lane mask (or EXEC) stays `Unsupported` (#210). `s_brev_b64`: D.lo = reverse(S0.hi), D.hi = reverse(S0.lo). `s_bfe_*64`: offset = S1[5:0], width = S1[22:16]; width 0 gives 0; a field past bit 63 stops there (the 64-bit form of the `s_bfe_u32` rule, LLVM `constantFoldBFE`); SCC = D ≠ 0. `s_bitset*_b64`: bit S0 & 63 of the pair cleared / set. `s_flbit_i32_b64`: zeros above the top 1 from bit 63, −1 for 0; `s_flbit_i32_i64`: the same of ~S0 when S0 < 0, −1 for 0 and −1. None but `s_bfe` writes SCC. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu_brev_b64.py`, `test_salu_bfe_64.py`, `test_salu_bitset_b64.py`, `test_salu_flbit_64.py` (#723, #726, #729, #733). **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1), one raw wave32 kernel per op through `tools/hw_oracle`: `s_brev_b64` of 0x12345678_0000000F has low word 0x1E6A2C48, `s_bfe_u64(0x00000123_45678000, w16 o28)` = 0x1234, `s_bfe_i64(0x00000001_80000000, w2 o31)` has 0xFFFFFFFF in both words, `s_bitset1_b64(0, 40)` has high word 0x100, `s_flbit_i32_b64(0x00010000)` = 47 and `s_flbit_i32_i64(0xFFFFFFFF_FFFF0000)` = 48. These are the words `runtime/test/shaders/cs_w32_salu64.asm` expects. Also **hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). | +| 64-bit scalar data ops (`s_brev_b64`, `s_bfe_u64`/`s_bfe_i64`, `s_bitset0_b64`/`s_bitset1_b64`, `s_flbit_i32_b64`/`s_flbit_i32_i64`) | The SGPR pair is 64-bit data, as for `s_lshl_b64`; a pair that `lane_masks.py` marks as a lane mask (or EXEC) stays `Unsupported` (#210), except under `s_flbit_i32_b64`, which reads the wave's whole mask as real bits (`wave_mask`, as `s_ff1_i32_b64` does): 63 minus the last active lane (the 1.0.2.1 pipeline library reads EXEC this way; wave64 run of EXEC and VCC masks in `tests/semantic/test_lane_mask_bitreplicate_flbit.py`). `s_brev_b64`: D.lo = reverse(S0.hi), D.hi = reverse(S0.lo). `s_bfe_*64`: offset = S1[5:0], width = S1[22:16]; width 0 gives 0; a field past bit 63 stops there (the 64-bit form of the `s_bfe_u32` rule, LLVM `constantFoldBFE`); SCC = D ≠ 0. `s_bitset*_b64`: bit S0 & 63 of the pair cleared / set. `s_flbit_i32_b64`: zeros above the top 1 from bit 63, −1 for 0; `s_flbit_i32_i64`: the same of ~S0 when S0 < 0, −1 for 0 and −1. None but `s_bfe` writes SCC. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu_brev_b64.py`, `test_salu_bfe_64.py`, `test_salu_bitset_b64.py`, `test_salu_flbit_64.py` (#723, #726, #729, #733). **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1), one raw wave32 kernel per op through `tools/hw_oracle`: `s_brev_b64` of 0x12345678_0000000F has low word 0x1E6A2C48, `s_bfe_u64(0x00000123_45678000, w16 o28)` = 0x1234, `s_bfe_i64(0x00000001_80000000, w2 o31)` has 0xFFFFFFFF in both words, `s_bitset1_b64(0, 40)` has high word 0x100, `s_flbit_i32_b64(0x00010000)` = 47 and `s_flbit_i32_i64(0xFFFFFFFF_FFFF0000)` = 48. These are the words `runtime/test/shaders/cs_w32_salu64.asm` expects. Also **hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). | | `v_bfe_u32` / `v_bfe_i32` past bit 31 | offset = S1[4:0] and width = S2[4:0]: the bits above are ignored, so an offset of 36 reads as 4 and a width of 32 as 0 (a width of 0 gives 0). When offset + width > 32 the field stops at bit 31, as for `s_bfe`: width = min(width, 32 - offset), and `v_bfe_i32` sign-extends from bit 31. Example: `v_bfe_i32` of `0xd2f90159` with offset 28 and width 16 gives `0xfffffffd` (4-bit field `0xd`), not `0xd`, and `0x80000000` with offset 31 and width 4 gives `0xffffffff`. The translator (`bfe_width` for VGPR or SGPR offset and width, the same cut folded at translation time for constants) already did this. Source: **measured on RDNA2**, AMD Radeon 610M (`gfx1036`, Windows 11, AMD driver 32.0.11016.14003), wave32 and wave64 identical, 16 words over VGPR, inline-constant and literal operands: `tools/int_hw_probe.py --oracle both --group valu_bfe_past31`, 4/4 cases match the translator. The words are pinned on the CPU by the unit test `ValuBfeMeasuredOnRdna2.test_translator_gives_the_gfx1036_words` in `tests/test_int_hw_probe.py`. | -| `s_quadmask_b32`/`_b64`, `s_bitreplicate_b64_b32` | On scalar data (RDNA2 ISA SOP1): `s_quadmask_b32` sets D[i] to the OR of S0[4i+3:4i] for the 8 quads, `s_quadmask_b64` does the same for the 16 quads of the 64-bit S0 (D[63:16] = 0), and both set SCC = D != 0. `s_bitreplicate_b64_b32` copies each bit S0[i] to D[2i] and D[2i+1] and leaves SCC. Built from fixed shift/mask steps, with no loop. A lane-mask source (EXEC, VCC or an SGPR that `holds_lane_mask`) or an EXEC/VCC destination raises `Unsupported`: each invocation holds only its own lane's bit, and these ops read the other lanes of a quad or move bits between lanes. Until 2026-11-22 all three were rejected. CPU-checked by `tests/semantic/test_salu_quadmask_bitreplicate.py` (fixed and seeded values, SCC written or kept, immediates, aliasing, lane masks rejected). **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1) through `tools/hw_oracle`, one raw wave32 kernel per op: `s_quadmask_b32(0xF)` = 1 with SCC 1, `(0xF0000000)` = 0x80, `(0x0F0F0F0F)` = 0x55 (the set quads are 0, 2, 4 and 6), `(0)` = 0 with SCC 0; `s_quadmask_b64` of 0xF = 1 and of 0xF0000000_00000000 (quad 15, bits 60..63) = 0x8000 in the low word with D[63:16] = 0; `s_bitreplicate_b64_b32` of 5 = 0x33 and of 0x80000000 = 0xC0000000_00000000, with SCC left as it was. **GPU-checked** by `runtime/test/shaders/cs_w32_new_ops.asm` (`s_quadmask_b32(0x01020408)` = 0x55, `s_quadmask_b64(0x80000000_00000001)` low word 0x8001, `s_bitreplicate_b64_b32(0x80000001)` high word 0xC0000000, with the expected words from the ISA pseudocode), exact on the Radeon iGPU of a Ryzen 9 9950X3D (RDNA2, `gfx1036`, driver 26.10.1) and an RTX 5080 (driver 616.92). **Not GPU-verified.** | +| `s_quadmask_b32`/`_b64`, `s_bitreplicate_b64_b32` | On scalar data (RDNA2 ISA SOP1): `s_quadmask_b32` sets D[i] to the OR of S0[4i+3:4i] for the 8 quads, `s_quadmask_b64` does the same for the 16 quads of the 64-bit S0 (D[63:16] = 0), and both set SCC = D != 0. `s_bitreplicate_b64_b32` copies each bit S0[i] to D[2i] and D[2i+1] and leaves SCC. Built from fixed shift/mask steps, with no loop. An EXEC or VCC destination of `s_bitreplicate_b64_b32` gives lane L bit L // 2 of S0 (EXEC since 6ecd922d9; VCC, which the 1.0.2.1 pipeline library writes from a constant, checked on every lane of a wave64 by `tests/semantic/test_lane_mask_bitreplicate_flbit.py`). Any other lane-mask source (EXEC, VCC or an SGPR that `holds_lane_mask`) or EXEC/VCC destination raises `Unsupported`: each invocation holds only its own lane's bit, and these ops read the other lanes of a quad or move bits between lanes. Until 2026-11-22 all three were rejected. CPU-checked by `tests/semantic/test_salu_quadmask_bitreplicate.py` (fixed and seeded values, SCC written or kept, immediates, aliasing, lane masks rejected). **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1) through `tools/hw_oracle`, one raw wave32 kernel per op: `s_quadmask_b32(0xF)` = 1 with SCC 1, `(0xF0000000)` = 0x80, `(0x0F0F0F0F)` = 0x55 (the set quads are 0, 2, 4 and 6), `(0)` = 0 with SCC 0; `s_quadmask_b64` of 0xF = 1 and of 0xF0000000_00000000 (quad 15, bits 60..63) = 0x8000 in the low word with D[63:16] = 0; `s_bitreplicate_b64_b32` of 5 = 0x33 and of 0x80000000 = 0xC0000000_00000000, with SCC left as it was. **GPU-checked** by `runtime/test/shaders/cs_w32_new_ops.asm` (`s_quadmask_b32(0x01020408)` = 0x55, `s_quadmask_b64(0x80000000_00000001)` low word 0x8001, `s_bitreplicate_b64_b32(0x80000001)` high word 0xC0000000, with the expected words from the ISA pseudocode), exact on the Radeon iGPU of a Ryzen 9 9950X3D (RDNA2, `gfx1036`, driver 26.10.1) and an RTX 5080 (driver 616.92). **Not GPU-verified.** | | 64-bit scalar bitwise ops (`s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64`, `s_orn2_b64`, `s_nand_b64`, `s_nor_b64`, `s_xnor_b64`, `s_not_b64`) | Dispatched like `s_cselect_b64`: when destination is `exec`/`vcc` or any source is a lane mask (`holds_lane_mask` or `exec`/`vcc`), uses the per-lane mask path (`mask_src`/`mask_dst` including `null` dst) and votes SCC across the wave (`scc_from_mask`). Otherwise operates on both 32-bit dwords of non-mask 64-bit scalar data (SGPR pairs, sign-extended inline/literal immediates, `null` = 0), reads all source dwords before storing (preserving destination aliasing), accepts `null` destination, and sets `SCC = ((D.lo \ \| D.hi) != 0)`. Until 2026-11-22 these ops always took the lane-mask path, duplicating D.lo into D.hi and voting SCC on D.lo alone. `s_nand/nor/xnor_b64` compute `~(S0 op S1)` on both paths (a lane's mask value is 0 or ~0, so the NOT is per lane); until 2026-11-22 they were rejected as unsupported. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu64_bitwise_data.py` (all 9 ops, 4-corner SCC, immediates, aliasing, stale mask overwrite, wave32/wave64 lane-mask regression, and `--wave64-emulate`); **Hardware-verified** on the same part through `tools/hw_oracle` for the plain-data path: `s_and_b64(0xFFFFFFFF_00000000, 0x0F0F0F0F_0F0F0F0F)` = 0x0F0F0000_00000000, `s_xnor_b64(0xFFFF0000_00000000, 0_FFFFFFFF)` = 0x0000FFFF_00000000, `s_nand_b64(0xFFFF0000_0, 0)` = 0xFFFFFFFF_FFFFFFFF, `s_not_b64(0x0000FFFF_0)` = 0xFFFF0000_FFFFFFFF and `s_andn2_b64(0xFFFF0000_0, 0)` = 0xFFFF0000_0, all with SCC 1, while `s_or_b64(0, 0)` = 0 with SCC 0: SCC = ((D.lo ≠ 0) or (D.hi ≠ 0)). The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| The measured plain-data words: The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| The measured plain-data words: `s_and_b64(0xFFFFFFFF_00000000, 0x0F0F0F0F_0F0F0F0F)` = 0x0F0F0000_00000000, `s_xnor_b64(0xFFFF0000_00000000, 0_FFFFFFFF)` = 0x0000FFFF_00000000, `s_nand_b64(0xFFFF0000_0, 0)` = 0xFFFFFFFF_FFFFFFFF, `s_not_b64(0x0000FFFF_0)` = 0xFFFF0000_FFFFFFFF and `s_andn2_b64(0xFFFF0000_0, 0)` = 0xFFFF0000_0, all with SCC 1, while `s_or_b64(0, 0)` = 0 with SCC 0. The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way. **Not GPU-verified.** **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| The measured plain-data words: **Not GPU-verified.** **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| D.hi) != 0`, the `andn2`/`orn2` pairs separate negation of the second source from negation of the first, `s_not_b64` inverts both dwords and clears SCC on a zero result, and `s_nand_b64`/`s_nor_b64`/`s_xnor_b64` invert the per-dword result (`and`/`or` of all ones gives `0` with SCC 0, `xnor` of equal pairs gives all ones with SCC 1); the lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. The lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. D.hi) != 0`, the `andn2`/`orn2` pairs separate negation of the second source from negation of the first, `s_not_b64` inverts both dwords and clears SCC on a zero result, and `s_nand_b64`/`s_nor_b64`/`s_xnor_b64` invert the per-dword result (`and`/`or` of all ones gives `0` with SCC 0, `xnor` of equal pairs gives all ones with SCC 1); the lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. **Not GPU-verified.** **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo | The measured plain-data words: `s_and_b64(0xFFFFFFFF_00000000, 0x0F0F0F0F_0F0F0F0F)` = 0x0F0F0000_00000000, `s_xnor_b64(0xFFFF0000_00000000, 0_FFFFFFFF)` = 0x0000FFFF_00000000, `s_nand_b64(0xFFFF0000_0, 0)` = 0xFFFFFFFF_FFFFFFFF, `s_not_b64(0x0000FFFF_0)` = 0xFFFF0000_FFFFFFFF and `s_andn2_b64(0xFFFF0000_0, 0)` = 0xFFFF0000_0, all with SCC 1, while `s_or_b64(0, 0)` = 0 with SCC 0. The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way. The lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. D.hi) != 0`, the `andn2`/`orn2` pairs separate negation of the second source from negation of the first, `s_not_b64` inverts both dwords and clears SCC on a zero result, and `s_nand_b64`/`s_nor_b64`/`s_xnor_b64` invert the per-dword result (`and`/`or` of all ones gives `0` with SCC 0, `xnor` of equal pairs gives all ones with SCC 1); the lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. \| | Constant lane masks (`Gen.mask_src` immediates) | A constant read as a lane mask is one bit per lane: lane L takes bit L. The 64-bit forms (`s_and/or/andn2_saveexec_b64`, `s_andn2_wrexec_b64`, `s_mov_b64`/`s_not_b64` into EXEC or VCC, `s_and/or/xor/andn2/orn2_b64` and `s_cselect_b64` on the lane-mask path) read the 64-bit value, an inline constant sign-extended (`-16` = lanes 4-63) and a literal with a zero high word, as `src64_data` reads 64-bit constants; the b32 forms (`s_*_saveexec_b32`, `s_andn2_wrexec_b32`) read the 32-bit value at bit L mod 32. 0 and -1 still give no lane and every lane, with no per-lane code. `s_bcnt0/1_i32_b64` and `s_ff0/1_i32_b64` of a constant read the constant's 64 bits via `src64_data` (scalar data: inline negative constants sign-extend to 64 bits, so `s_ff0_i32_b64 s0, -1` gives −1 rather than 32, and 32-bit literals zero-extend; CPU-checked in `tests/semantic/test_scalar_bitcmp.py`, **not yet GPU-verified**). `s_bcnt0/1_i32_b64` of a constant counts the constant's 64 bits (scalar data, like `s_ff0/1_i32_b64`). **Before this fix every lane took bit 0 of the constant**: `s_and_saveexec_b32 s7, 0xff00` with all 32 lanes on left none on, `5` left all 32 on, and `s_bcnt1_i32_b64 s0, 0xff00ff` gave 32. llvm-mc rejects a constant as the mask operand of `v_cndmask_b32_e64` / `v_add_co_ci_u32_e64` and decodes one as "Invalid immediate", so those VALU callers never see a constant. **A constant held in an SGPR** (`s_mov_b32 s20, 0x3ffffc00`) is read the same way when it reaches a mask consumer: `mask_src` takes bit L of an SGPR that `holds_lane_mask` doesn't flag (a pair in a wave64 64-bit context: the high SGPR for lanes 32-63). In a wave32 or wave64 program a 32-bit bitwise SALU op (`s_not_b32`, `s_and/or/xor/andn2/orn2/nand/nor/xnor_b32`, `s_cselect_b32`) that writes EXEC/VCC (`exec_lo`/`vcc_lo` in wave32; `exec_lo`/`exec_hi` and mask-holding `vcc_lo`/`vcc_hi` in wave64, including after `s_mov_b64 vcc, 0/-1`) skips scalar constant folding, reads its operands through `Gen._mask_b32_src` / `mask_src` (collecting the opposite half through `wave_mask` if a wave64 op mixes `lo` and `hi` halves), preserves the untouched half of EXEC/VCC in wave64 (`exec_half_write` / `put_mask`), and votes SCC over the wave (wave32) or that 32-lane half (wave64, `scc_any_half`), matching `s_not_b32` and the binary ops on lane-mask SGPRs too; into a plain SGPR with a constant it stays a data read, because `lane_masks.py` classifies that SGPR as data when the other operand is a constant (`s_and_b32 s20, exec_lo, 1` then `s_bcnt1` must count the wave's bits: found by @Pierre-Kookis on #1792, GPU-reproduced), and `s_mov_b32 exec_lo/exec_hi, sN` takes each lane's bit. In a wave32 program a 32-bit bitwise SOP2 (`s_and/or/xor/andn2/orn2/nand/nor/xnor_b32`, `s_cselect_b32`) that writes EXEC/VCC reads both operands through `mask_src` (`Gen.sop2_b32_srcs`); into a plain SGPR it stays a data read, because `lane_masks.py` classifies that SGPR as data when the other operand is a constant (`s_and_b32 s20, exec_lo, 1` then `s_bcnt1` must count the wave's bits: found by @Pierre-Kookis on #1792, GPU-reproduced), and `s_mov_b32 exec_lo/exec_hi, sN` takes each lane's bit. A real mask is unchanged: it holds 0 or ~0 per lane, and bit L of that is the same 0 or 1. Until 2026-11-22 these took the value whole, so `s_and_saveexec_b32 s6, s20` with that constant, or `s_and_b32 exec_lo, exec_lo, 0xff00`, left every lane on (found writing `cs_w32_saveexec_ext`, #1771; CPU-checked by `tests/semantic/test_mask_src_sgpr_const.py`, and `tools/cf_diff.py` / `tools/salu_diff.py` still pass). `s_not_b32` on lane masks, `s_and/or/xor_b32` with two immediates into `vcc_lo`, and wave64 half-mask bitwise ops (destination half preservation, `exec_hi`, and `scc_any_half`) are CPU-checked in `tests/semantic/test_salu_b32_lane_masks.py` (wave32, wave64, and `--wave64-emulate`, validated with `spirv-val`) and GPU-checked on gfx1036, RTX 5080 (`--wave64-emulate`), and RX 9060 XT (RADV). Not covered here: a b32 op on one half of a wave64 mask, masks read as data (#293), and a literal with bit 31 set in a 64-bit position (zero- vs sign-extension not measured). GPU-checked with `runtime/test/shaders/cs_w32_mask_imm.asm` and `cs_w64_mask_imm.asm` on an NVIDIA GeForce RTX 5080 (driver 616.92; wave64 with `LEONIDA_W64_EMULATE=1`) and an AMD Radeon RDNA2 iGPU (driver 26.10.1, native 64-wide subgroup): both failed before on both GPUs. Run across every lane in `tests/semantic/test_value_semantics.py` (`LaneMaskConstants`). **A computed value written to EXEC** (`s_lshl_b32`, `s_add_u32`, `s_bfm_b32`, and every other SALU result that reaches `exec_lo`/`exec_hi` through `Gen.dst`) takes each lane's bit too: until 2026-11-24 the generic path tested the value for non-zero, so `s_lshl_b32 exec_lo, 1, s5` ran all 32 lanes of that half (SHADER-1264; `Gen.exec_bit`). The words are the GPU's, recorded in `runtime/test/shaders/cs_w32_exec_computed.asm` and `cs_w64_exec_computed.asm` (RTX 5070), and `tests/semantic/test_exec_computed.py` replays them through the CPU interpreter. A value that already holds this lane's bit of a mask (0 or ~0) gives the same answer. | | Scalar select and pack (`s_cmov_b32`, `s_cmovk_i32`, `s_pack_ll/lh/hh_b32_b16`) | `s_cmov_b32` / `s_cmovk_i32`: D = SCC ? S0 : D (`s_cmovk_i32`'s S0 is the 16-bit immediate, sign-extended); SCC is read, not written; the destination must be an SGPR (a lane-mask destination, and `s_cmov_b64`, stay `Unsupported`, #210). `s_pack_*`: the low half of D from S0, the high half from S1, the letters naming the half of each (l = 15:0, h = 31:16), S0 first; GFX10 has no `s_pack_hl`; SCC not written. Source: RDNA2 ISA SOP1/SOP2/SOPK. CPU-checked by `tests/semantic/test_salu_cmov.py` and `test_salu_pack.py`; the translated shaders were run on NVIDIA by reviewers (`s_cmov*`: RTX 5090, RTX 4050 and Radeon 740M in #613; `s_pack_*`: RTX 5090 in #449). **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137, SCC kept). | diff --git a/tests/semantic/test_lane_mask_bitreplicate_flbit.py b/tests/semantic/test_lane_mask_bitreplicate_flbit.py new file mode 100644 index 0000000000..66743bd2cc --- /dev/null +++ b/tests/semantic/test_lane_mask_bitreplicate_flbit.py @@ -0,0 +1,65 @@ +"""s_bitreplicate_b64_b32 into VCC and s_flbit_i32_b64 of a lane mask, run on every lane of a wave64 in +spirv_mini_interp.run_workgroup. + +RDNA2 ISA, SOP1: + - s_bitreplicate_b64_b32: D[2i+1] = D[2i] = S0[i], i in 0..31; SCC is not written. Into VCC, lane L's bit is S0 bit + L // 2. + - s_flbit_i32_b64: the zeros above the first 1 from bit 63, -1 when S0 is 0. Of EXEC that is 63 minus the wave's + last active lane. +Synthetic programs only. +""" +import unittest + +import saveexec_run as h +import support +import spirv_mini_interp as si + +OUT_AT = 256 + + +def run(lines): + spv = support.translate_lines("cs_lane_mask_bitreplicate_flbit", lines, fssm=h.fssm()) + return si.run_workgroup(spv, 64, 64, inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, + push_constants=h.VSHARP + [0] * 28, memory={}) + + +def lane_index(): + return ["v_mbcnt_lo_u32_b32 v1, -1, 0", "v_mbcnt_hi_u32_b32 v1, -1, v1", "v_lshlrev_b32_e32 v21, 2, v1"] + + +def flbit_model(mask): + return 63 - (mask.bit_length() - 1) if mask else 0xFFFFFFFF + + +class LaneMaskBitreplicateFlbit(unittest.TestCase): + def test_bitreplicate_into_vcc(self): + for k in (0x0F0F0F0F, 0xFF00FF00, 0, 0xFFFFFFFF, 0x80000001, 0x12345678): + with self.subTest(k=hex(k)): + mem = run(lane_index() + [f"s_bitreplicate_b64_b32 vcc, {k:#x}", "v_cndmask_b32_e64 v2, 0, 1, vcc", + "buffer_store_dword v2, v21, s[0:3], 0 offen", "s_endpgm"]) + got = [mem[4 * lane] for lane in range(64)] + self.assertEqual(got, [(k >> (lane // 2)) & 1 for lane in range(64)]) + + def test_flbit_of_exec(self): + for mask in (h.ALL64, 1, 0x8000000000000000, 0x00000000FFFFFFFF, 0x0000F00000000000, 0x10): + with self.subTest(exec=hex(mask)): + mem = run(lane_index() + [f"s_mov_b32 exec_lo, {mask & 0xFFFFFFFF:#x}", f"s_mov_b32 exec_hi, {mask >> 32:#x}", + "s_flbit_i32_b64 s10, exec", "s_mov_b64 exec, -1", + "v_cmpx_eq_u32_e32 0, v1", "v_mov_b32_e32 v20, s10", + f"v_mov_b32_e32 v21, {OUT_AT}", "buffer_store_dword v20, v21, s[0:3], 0 offen", + "s_endpgm"]) + self.assertEqual(mem[OUT_AT], flbit_model(mask)) + + def test_flbit_of_vcc(self): + # VCC from a compare: the lanes l with l < n. + for n in (0, 1, 31, 33, 64): + with self.subTest(n=n): + mem = run(lane_index() + [f"v_cmp_gt_u32_e32 vcc, {n}, v1", "s_flbit_i32_b64 s10, vcc", + "v_cmpx_eq_u32_e32 0, v1", "v_mov_b32_e32 v20, s10", + f"v_mov_b32_e32 v21, {OUT_AT}", "buffer_store_dword v20, v21, s[0:3], 0 offen", + "s_endpgm"]) + self.assertEqual(mem[OUT_AT], flbit_model((1 << n) - 1)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_salu_flbit_64.py b/tests/semantic/test_salu_flbit_64.py index faf480eb32..743602719f 100644 --- a/tests/semantic/test_salu_flbit_64.py +++ b/tests/semantic/test_salu_flbit_64.py @@ -123,9 +123,10 @@ def test_inline_source(self): self.assertEqual(run_lines(["s_flbit_i32_b64 s0, 1"])[0], 63) self.assertEqual(run_lines(["s_flbit_i32_i64 s0, -1"])[0], M32) - def test_lane_mask_source_is_rejected(self): + # b64 of a lane mask reads the whole wave's mask: tests/semantic/test_lane_mask_bitreplicate_flbit.py. + def test_i64_lane_mask_source_is_rejected(self): with self.assertRaises(rdna2spirv.Unsupported): - run_lines(["s_flbit_i32_b64 s0, exec"]) + run_lines(["s_flbit_i32_i64 s0, exec"]) if __name__ == "__main__": diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index e2acd97dee..35d71ffc39 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -7580,8 +7580,15 @@ def _insn(self, ins): if self.is_mask_op(x): raise Unsupported(op + " on a lane mask") if d["k"] == "special" and d.get("t", "").startswith(("exec", "vcc")): - if op != "s_bitreplicate_b64_b32" or d["t"] != "exec": + if op != "s_bitreplicate_b64_b32" or d["t"] not in ("exec", "vcc"): raise Unsupported(op + " on a lane mask") + if d["t"] == "vcc": + # VCC's bit for lane L is scalar-source bit L // 2 too, stored as mov64 stores a mask into VCC + # (this lane's bit as 0xFFFFFFFF / 0). + half = self.tmp() + self.emit(f"{half} = OpShiftRightLogical %uint {self.wave_lane()} {self.cu(1)}") + self.emit(f"OpStore %vcc {self._scalar_word_lane_bit(self.src_u(x), half)}") + return # EXEC's bit for lane L comes from scalar-source bit L // 2. shift, shifted, bit = (self.tmp() for _ in range(3)) lane = self.wave_lane() @@ -8341,11 +8348,15 @@ def sel(c, t, f): # Leading-bit count of a 64-bit value, from bit 63 down: b64 counts the zeros before the first 1; i64 # counts the bits before the first one that differs from the sign bit (b64 of ~S0 when S0 < 0). -1 when # there is none (0, and for i64 also -1). SCC is not written. The pair is 64-bit data (as for - # s_lshl_b64); a lane-mask source stays Unsupported (#210). + # s_lshl_b64); a lane-mask source of b64 is the wave's mask (wave_mask); of i64 it stays Unsupported. x = a[1] if self.holds_lane_mask(x): - raise Unsupported(op + " of a lane mask") - if x["k"] == "sgpr" and x.get("n") == 2: + if op != "s_flbit_i32_b64": + raise Unsupported(op + " of a lane mask") + # The wave's mask as real bits, as s_ff1_i32_b64 reads one: the result is the zeros above the + # wave's last active lane. + lo, hi = self.wave_mask(x) + elif x["k"] == "sgpr" and x.get("n") == 2: lo, hi = self.load_reg("sgpr", x["r"]), self.load_reg("sgpr", x["r"] + 1) elif x["k"] == "imm": v = x["v"] & 0xFFFFFFFFFFFFFFFF From ce98fbefee2bee293e04835ed30183164be2fd31 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 00:35:11 +0100 Subject: [PATCH 058/110] fix: rdna2spirv decodes scalar, image and buffer tuples that run into vcc from the blob when llvm-mc rejects them llvm-mc skips the first word of s_buffer_load_dwordx8 into s[100:107], an image resource in s[100:107] or a buffer resource in s[104:107] and leaves the second word as junk, so translate() refused those shaders (reachable instruction with normalized encoding) or translated them without the load. restore_vcc_tuples reads the uncovered words of the code range with rdna2_decode and keeps only instructions whose operands hold a VCCTuple list, the form the translator already takes. Other undecodable words are unchanged. --- docs/shader_library.md | 8 +- tests/semantic/test_vcc_tuple_fallback.py | 149 ++++++++++++++++++++++ tools/rdna2spirv.py | 36 ++++++ 3 files changed, 190 insertions(+), 3 deletions(-) create mode 100644 tests/semantic/test_vcc_tuple_fallback.py diff --git a/docs/shader_library.md b/docs/shader_library.md index 09a1997a97..483426225f 100644 --- a/docs/shader_library.md +++ b/docs/shader_library.md @@ -165,9 +165,11 @@ What stops the rest, by the translator's message: run into `vcc` (SGPRs 106 and 107): `s_load_dwordx8`/`x4`/`x16` writing `s[100:107]`, `s[104:107]` or `s[92:107]`, and image instructions whose resource is `s[100:107]`. In the compute programs alone that is 37,952 SMEM, 22,248 MIMG and 2,298 MUBUF words. The same words with the register field one tuple lower decode; with - `gfx1030` they don't either. The FSSM shaders don't use these tuples; the pipeline builds use them often. A decoder - fallback for these encodings would cover most of the remaining programs. The translator already reads - `[s100,...,vcc_lo,vcc_hi]` lists (design.md *Scalar/buffer memory*). + `gfx1030` they don't either. The FSSM shaders don't use these tuples; the pipeline builds use them often. The translator + now decodes these words from the blob with `rdna2_decode` (`restore_vcc_tuples`) and reads them as the + `[s100,...,vcc_lo,vcc_hi]` lists it already takes (design.md *Scalar/buffer memory*); synthetic cases are in + `tests/semantic/test_vcc_tuple_fallback.py`. The count above was measured before this change; it has not been + re-run on the real library. * **443: an instruction llvm-mc prints with another encoding than the blob's** (`v_fma_mix*`, `v_interp_p2_f16`): the existing `check_printed_encodings` refusal. * **90 CS: "CS thread-group-size SGPR"**: RSRC2 `TG_SIZE_EN`, which no FSSM compute shader sets. diff --git a/tests/semantic/test_vcc_tuple_fallback.py b/tests/semantic/test_vcc_tuple_fallback.py new file mode 100644 index 0000000000..dd02b4509a --- /dev/null +++ b/tests/semantic/test_vcc_tuple_fallback.py @@ -0,0 +1,149 @@ +"""A scalar tuple that runs into vcc is translated from the blob when llvm-mc cannot decode it. + +llvm-mc rejects s_buffer_load_dwordx8 into s[100:107], a buffer resource in s[104:107] and an image resource in +s[100:107] (SGPRs 106 and 107 are vcc). It skips the first word as invalid and leaves the second word as junk, so +translate() refused every such shader ("reachable instruction with normalized encoding", or "fall-through into +undecodable words"; docs/shader_library.md section 5), or, when the junk matched the blob, translated a program +with the load missing. The words are now decoded from the blob as the VCCTuple lists the translator takes. + +Hand-built listings and blobs of synthetic instructions (encodings from llvm-mc 19, the three tuple words patched in +their register field), no game data. + + python -I tests/semantic/test_vcc_tuple_fallback.py -v +""" +import os +import struct +import sys +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +from support import rdna2spirv, translate_listing # noqa: E402 +import fssm_header # noqa: E402 +import spirv_mini_interp as si # noqa: E402 + +NAME = "cs_vcc_tuple" +CODE_START = 0x148 +BASE, OUT = 0x1000, 0x3000 +INVALID = "; warning: invalid instruction encoding" + +SET_SGPR_V = [ # s4..s7 = a V# over BASE (32 bytes), as tests/semantic/test_fspx_rules.py builds it + ("s_mov_b32 s4, 0x1000", "ff 03 84 be 00 10 00 00"), + ("s_mov_b32 s5, 0", "80 03 85 be"), + ("s_mov_b32 s6, 32", "a0 03 86 be"), + ("s_mov_b32 s7, 0x30000000", "ff 03 87 be 00 00 00 30"), +] +WAIT = ("s_waitcnt lgkmcnt(0)", "7f c0 8c bf") +WAIT_V = ("s_waitcnt vmcnt(0)", "70 3f 8c bf") +STORE_X4 = [ + ("v_mov_b32_e32 v6, 0x3000", "ff 02 0c 7e 00 30 00 00"), + ("global_store_dwordx4 v6, v[10:13], s[0:1]", "00 80 78 dc 06 0a 00 00"), + ("s_endpgm", "00 00 81 bf"), +] +# the words llvm-mc cannot decode (each is two dwords): the llvm-mc 19 encoding of the same instruction one tuple +# lower, with its register field patched into vcc +LOAD_X8_VCC = "02 19 2c f4 00 00 00 fa" # s_buffer_load_dwordx8 [s100..s105,vcc_lo,vcc_hi], s[4:7], 0x0 +LOAD_X4_VCC = "02 1a 28 f4 00 00 00 fa" # s_buffer_load_dwordx4 [s104,s105,vcc_lo,vcc_hi], s[4:7], 0x0 +LOAD_DW_FROM_VCC = "b4 02 20 f4 00 00 00 fa" # s_buffer_load_dword s10, [s104,s105,vcc_lo,vcc_hi], 0x0 +BUFFER_LOAD_VCC = "00 10 30 e0 01 0b 1a 80" # buffer_load_dword v11, v1, [s104,s105,vcc_lo,vcc_hi], 0 offen +IMAGE_LOAD_VCC = "08 1f 00 f0 01 04 19 00" # image_load v[4:7], v[1:2], [s100..s105,vcc_lo,vcc_hi] 2D unorm +PROGRAM_VARIANTS = ("invalid", "junk", "normalized") + + +def encoding(raw): + return "; encoding: [" + ",".join(f"0x{b:02x}" for b in bytes.fromhex(raw)) + "]" + + +def listing_and_blob(program, variant="invalid"): + """program: (text, hex) pairs; a pair whose text is None is a word llvm-mc rejects, listed as the variant says.""" + code = b"".join(bytes.fromhex(raw) for _, raw in program) + lines = [] + for text, raw in program: + if text is not None: + lines.append(f"\t{text:<40}{encoding(raw)}") + continue + second = bytes.fromhex(raw)[4:8] + lines.append(INVALID) + if variant == "invalid": + lines.append(INVALID) + elif variant == "junk": # the second word decodes as an instruction of its own, bytes as stored + lines.append(f"\ts_nop 0{'':<33}" + encoding(second.hex())) + else: # printed with another encoding than the blob holds + lines.append("\texp mrt0 v0, v0, v0, v0 done vm " + encoding("0f 18 00 f8 00 00 00 00")) + head = f"; {NAME} code 0x{CODE_START:x}..0x{CODE_START + len(code):x} (scan), gfx1013, 2 invalid words" + header = bytearray(CODE_START) + struct.pack_into("<4I", header, 0x138, 0x88, 32, 1, 1) + struct.pack_into(" lo for lo, hi in spans)] + return sorted(kept + restored, key=lambda i: i["pc"]) + + def output_signature(path, name): """OSG1 elements as (register, system value), one per register (first element wins).""" d = shader_container(path, name) @@ -17420,6 +17455,7 @@ def translate(path): ins["normalized"] = True ins["pc"] = at pos = at + len(enc) + insns = restore_vcc_tuples(insns, blob, info["code_start"], info.get("code_end")) insns = fold_far_branches(insns) insns = reachable_code(insns, info.get("code_end")) if any(i.get("normalized") for i in insns): From f7a338b14d5b70b6d183be5f1e7427582d41e3b3 Mon Sep 17 00:00:00 2001 From: JARVIX <273200855+jarvixaiassistant-glitch@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:33:36 +0000 Subject: [PATCH 059/110] rdna2spirv: clamp restore_vcc_tuples decode slice to code_end Clamp blob[at:at + 20] to min(at + 20, stop) and check at + nbytes <= stop so multi-dword NSA MIMG instructions starting near code_end cannot read trailing bytes past code_end. Adds synthetic 12-byte NSA1 regression test. --- tests/semantic/test_vcc_tuple_fallback.py | 8 ++++++++ tools/rdna2spirv.py | 14 ++++++++------ 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/tests/semantic/test_vcc_tuple_fallback.py b/tests/semantic/test_vcc_tuple_fallback.py index dd02b4509a..67e6bc5211 100644 --- a/tests/semantic/test_vcc_tuple_fallback.py +++ b/tests/semantic/test_vcc_tuple_fallback.py @@ -144,6 +144,14 @@ def test_other_undecodable_words_are_still_refused(self): with self.assertRaisesRegex(rdna2spirv.Unsupported, "fall-through into undecodable words"): translate(program) + def test_nsa_mimg_with_vcc_tuple_does_not_read_past_code_end(self): + # A 12-byte NSA1 image_load whose 3rd dword lies past code_end must not be restored across stop. + mimg_nsa1 = bytes.fromhex("0a 1f 00 f0 01 04 19 00 02 00 00 00") + self.assertEqual(rdna2spirv.restore_vcc_tuples([], mimg_nsa1, 0, 8), []) + restored = rdna2spirv.restore_vcc_tuples([], mimg_nsa1, 0, 12) + self.assertEqual(len(restored), 1) + self.assertEqual((restored[0]["pc"], len(restored[0]["enc"]) // 2), (0, 12)) + if __name__ == "__main__": unittest.main() diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index b5ff30b95b..c5135bcd46 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -17165,15 +17165,17 @@ def restore_vcc_tuples(insns, blob, code_start, code_end): stop = min(len(blob), code_end if code_end is not None else len(blob)) restored, at = [], code_start while at + 8 <= stop: - found = None if at in covered else rdna2_decode.decode_bytes(blob[at:at + 20])["insns"][:1] + found = None if at in covered else rdna2_decode.decode_bytes(blob[at:min(at + 20, stop)])["insns"][:1] if found and found[0]["pc"] == 0 and any( a["k"] == "slist" and ("vcc_lo" in a["r"] or "vcc_hi" in a["r"]) for a in found[0]["args"]): ins = found[0] - ins["pc"] = at - restored.append(ins) - at += len(ins["enc"]) // 2 - else: - at += 4 + nbytes = len(ins["enc"]) // 2 + if at + nbytes <= stop: + ins["pc"] = at + restored.append(ins) + at += nbytes + continue + at += 4 if not restored: return insns spans = [(r["pc"], r["pc"] + len(r["enc"]) // 2) for r in restored] From 21f07a063ba0000cfeb8717075d28809056b3561 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Mon, 23 Nov 2026 17:45:10 +0100 Subject: [PATCH 060/110] d3d12: draw the console's rectangle lists (17, PSO type 19) and quad lists (19) as triangles A rectangle list is three corners; the fourth is v2 + v3 - v1 for the position and every interpolant, after the vertex stage. A quad list is four vertices per quad. Vulkan has neither. A PSO with topology type 19 was refused (E_INVALIDARG) and the two list topologies drew as a plain triangle list. Rectangle list: the PSO becomes a triangle-list pipeline with a generated geometry stage (src/rect_list_geometry.h), built from the vertex shader's own SPIR-V outputs, that emits the strip v1 v2 v3 v4. Quad list: one triangle fan per quad (0 1 2, 0 2 3), drawn with the index values 4q..4q+3 so the translated vertex id (VertexIndex - BaseVertex) is right; non-indexed draws read a shared 0, 1, 2, ... buffer reserved in the arena. Facts from xvalkyrie (GPL-3.0, commit 53af7df77c10); no code copied. --- docs/d3d12_vulkan.md | 8 +- runtime/CMakeLists.txt | 9 + runtime/shims/d3d12_vulkan_device.cpp | 45 +++- runtime/src/rect_list_geometry.h | 214 ++++++++++++++++ runtime/src/vulkan_backend.h | 8 + runtime/src/vulkan_replay.h | 29 +++ runtime/test/d3d12_rect_list_test.cpp | 341 ++++++++++++++++++++++++++ 7 files changed, 649 insertions(+), 5 deletions(-) create mode 100644 runtime/src/rect_list_geometry.h create mode 100644 runtime/test/d3d12_rect_list_test.cpp diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 3ae29163e5..51a3a4a9ed 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -169,7 +169,7 @@ The command-list surface maps to the IR as follows: | `SetGraphicsRootSignature` / `SetComputeRootSignature` | state; select the pipeline layout and root map | | `Set*Root32BitConstant(s)` / `Set*Root*View` / `Set*RootDescriptorTable` | update root args; build the push-constant block at the draw/dispatch | | `SetDescriptorHeaps` | state; scan/populate the bindless arrays and hash table at execute | -| `IASetVertexBuffers` / `IASetIndexBuffer` / `IASetPrimitiveTopology` | state; bind arena buffer + offset, dynamic topology | +| `IASetVertexBuffers` / `IASetIndexBuffer` / `IASetPrimitiveTopology` | state; bind arena buffer + offset, dynamic topology. The console's rectangle list (17, PSO topology type 19) and quad list (19) are drawn as triangles, see *Console rectangle and quad lists* below | | `RSSetViewports` / `RSSetScissorRects` | state; dynamic viewport/scissor | | `OMSetRenderTargets` / `OMSetBlendFactor` / `OMSetStencilRef` | state; rendering scope and dynamic state | | `DrawInstanced` / `DrawIndexedInstanced` | command with a state snapshot | @@ -2118,6 +2118,12 @@ The trace will enumerate them. - **What it doesn't cover:** whether the console flattens a 3D `DispatchMesh` grid the same way. That is an open question in `docs/design.md`, "Mesh shaders"; the test shader reads the workgroup ID directly. +### Console rectangle and quad lists + +The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiveTopology(17)`, with a PSO whose topology type is 19) and quad list (`IASetPrimitiveTopology(19)`). The facts are from xvalkyrie (GPL-3.0, commit `53af7df77c10`; no code taken): a rectangle is three corners and the fourth is v2 + v3 - v1 for the position and every interpolant, after the vertex stage; a quad is four vertices. The layer draws both as triangles (`d3d12_rect_list_test`, RTX 4090: 4096 of 4096 pixels, the colour plane exact, quad list bit-exact). +- **Rectangle list**: PSO type 19 builds a triangle-list pipeline plus a generated geometry stage (`src/rect_list_geometry.h`, written from the vertex shader's own outputs) that takes the three corners and emits the strip v1 v2 v3 v4 (same winding). It has to be post-vertex-stage: the translated vertex shaders fetch by V# themselves, and the fourth corner is a function of what they write. A corner value with the same bits at all three corners (a flat attribute) is copied. Needs `geometryShader` (else `E_NOTIMPL`), no application GS, and a vertex shader with no ClipDistance, CullDistance, Layer or ViewportIndex output. +- **Quad list**: one four-vertex triangle fan per quad (the pattern 0 1 2, 0 2 3). The translated vertex id is `VertexIndex - BaseVertex`, so each fan reads the index values 4q..4q+3: from the application's index buffer when the draw is indexed, else from a shared 0, 1, 2, ... buffer in the arena's reserved pages (16384 quads per draw at most), with the draw's first vertex as the vertex offset. The PSO type is the ordinary triangle type. + ## 4. Object model mapping | D3D12 / Xbox object | Vulkan / layer object | Notes | diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 64e346f40a..c422368d05 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2428,6 +2428,15 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_translated_draw COMMAND d3d12_translated_draw_test) set_tests_properties(d3d12_translated_draw PROPERTIES SKIP_RETURN_CODE 77) + # The console's rectangle and quad lists (src/rect_list_geometry.h), through the same translated vs_m15 / ps_m15. + add_executable(d3d12_rect_list_test test/d3d12_rect_list_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_M15_FILES}) + target_link_libraries(d3d12_rect_list_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_rect_list_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_M15_DIR="${LEONIDA_M15_DIR}") + target_compile_options(d3d12_rect_list_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_rect_list COMMAND d3d12_rect_list_test) + set_tests_properties(d3d12_rect_list PROPERTIES SKIP_RETURN_CODE 77) + # vk_bindless_test (the bindless set and its table at the Vulkan level, no D3D12) takes the translated vs_ids, # ps_tex and ps_imgatomic; it was only run by scripts/run_gpu_tests.py and check.py until D3D-314 needed it. set(LEONIDA_BINDLESS_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/bindless_shaders) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 0273f9339b..f6f7b50046 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -18,6 +18,7 @@ #include "../src/arena_size.h" #include "../src/gfx10_descriptors.h" #include "../src/depth24_fragment.h" +#include "../src/rect_list_geometry.h" #include "../src/uav_clear.h" #include "../src/vulkan_bindless.h" #include "../src/vulkan_memory.h" @@ -65,7 +66,9 @@ namespace { constexpr UINT kDescriptorSize = descriptor_size; // The first 64 KiB of the GPU address arena are never handed out: VA 0 stays invalid, and the page is kept zero // for unbound vertex and index buffers to read (D3D12 reads zeros there). -constexpr VkDeviceSize kArenaReserved = 64 * 1024; +constexpr VkDeviceSize kZeroPage = 64 * 1024; // zeroed: what unbound vertex and index buffers read +constexpr std::uint32_t kQuadIndexCount = 64 * 1024; // 0, 1, 2, ... that non-indexed quad lists draw with (16384 quads) +constexpr VkDeviceSize kArenaReserved = kZeroPage + VkDeviceSize(kQuadIndexCount) * sizeof(std::uint32_t); static_assert(sizeof(leonida::TargetView) <= kDescriptorSize); // The shader model and root signature version this layer can honour. Nothing in the runtime compiles DXIL: the @@ -3460,6 +3463,14 @@ class PipelineState final log_once("geometry shaders need the Vulkan geometryShader feature; stage", 0); return E_NOTIMPL; } + // The console's rectangle topology type (19) draws as triangles through a generated geometry stage that adds + // each rectangle's fourth corner (src/rect_list_geometry.h); it needs the same device feature, and no GS of + // the application's own. + const bool rect_list = !mesh && desc.PrimitiveTopologyType == leonida::topology_type_rect_list; + if (rect_list && (geometry || !device_.info.features.geometryShader)) { + log_once("a rectangle-list pipeline needs the geometryShader feature and no geometry shader; stage", 0); + return geometry ? E_INVALIDARG : E_NOTIMPL; + } if (geometry && desc.PrimitiveTopologyType != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) { log_once("a translated geometry shader takes triangles; topology type", desc.PrimitiveTopologyType); return E_INVALIDARG; @@ -3640,6 +3651,26 @@ class PipelineState final subgroup_size_for(*stage.entry, required_sizes[stage_infos.size()], info); stage_infos.push_back(info); } + if (rect_list) { // the stage that adds each rectangle's fourth corner, from the vertex shader's outputs + std::string why; + const std::vector words = leonida::rect_list_geometry(vs_stage.words, why); + if (words.empty()) { + std::fprintf(stderr, "[rt] d3d12: %s cannot be drawn as a rectangle list: %s\n", + vs_stage.entry->name.c_str(), why.c_str()); + return E_NOTIMPL; + } + VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + module_info.codeSize = words.size() * 4; + module_info.pCode = words.data(); + VkShaderModule module = VK_NULL_HANDLE; + if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) return E_FAIL; + modules_.push_back(module); + VkPipelineShaderStageCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; + info.stage = VK_SHADER_STAGE_GEOMETRY_BIT; + info.module = module; + info.pName = "main"; + stage_infos.push_back(info); + } if (depth24_fragment && !ps_stage.entry) { // no pixel shader: a built-in one writes the depth const std::vector words = leonida::depth24_depth_only_fragment(depth24_bias); VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; @@ -3714,7 +3745,8 @@ class PipelineState final } } VkPipelineInputAssemblyStateCreateInfo assembly{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; - switch (mesh ? D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE : desc.PrimitiveTopologyType) { // mesh: not used + // Type 19 is the console's rectangles, drawn as triangle lists through the geometry stage added above. + switch (mesh || rect_list ? D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE : desc.PrimitiveTopologyType) { // mesh: not used case D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT: assembly.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST; break; case D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_LINE_LIST; break; case D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; break; @@ -5448,7 +5480,11 @@ class Device final return false; } arena.mapped = static_cast(mapped); - std::memset(arena.mapped, 0, kArenaReserved); // the zero page unbound vertex and index buffers read + std::memset(arena.mapped, 0, kZeroPage); // the zero page unbound vertex and index buffers read + { + auto* iota = reinterpret_cast(arena.mapped + kZeroPage); + for (std::uint32_t i = 0; i < kQuadIndexCount; ++i) iota[i] = i; + } VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; address.buffer = arena.buffer; arena.address = vk.vkGetBufferDeviceAddress(state_.info.device, &address); @@ -5459,7 +5495,8 @@ class Device final length = 0; arena.log = getenv_s(&length, log, "LEONIDA_ARENA_LOG") == 0 && length > 1 && log[0] != '0'; state_.context->set_heap_base(arena.address); - state_.context->set_zero_page(arena.buffer, 0, kArenaReserved); + state_.context->set_zero_page(arena.buffer, 0, kZeroPage); + state_.context->set_quad_indices(arena.buffer, kZeroPage, kQuadIndexCount); return true; } diff --git a/runtime/src/rect_list_geometry.h b/runtime/src/rect_list_geometry.h new file mode 100644 index 0000000000..ee7d69905c --- /dev/null +++ b/runtime/src/rect_list_geometry.h @@ -0,0 +1,214 @@ +#pragma once + +// Console rectangle lists on Vulkan, which has no such primitive. +// +// A rectangle is three corners (v1, v2, v3) and the hardware makes the fourth, v2 + v3 - v1, for the position and for +// every interpolant, after the vertex stage. A list topology of rectangles (D3D_PRIMITIVE_TOPOLOGY 17) and a pipeline +// whose topology type is 19 are console-only. The fact comes from xvalkyrie (GPL-3.0, commit 53af7df77c10, notes in +// its backlog); no code is taken from it. +// +// The fourth vertex depends on what the vertex stage wrote, not on what it read, so the expansion has to sit after +// the vertex stage: a pre-pass over the vertex buffers is wrong for any shader that is not linear in its inputs (and +// the translated vertex shaders fetch by V# themselves, so there is no vertex buffer to expand). The pipeline gets a +// small geometry stage instead, built here from the vertex shader's own SPIR-V: it takes the triangle (v1, v2, v3) +// the list draws, and emits the strip v1, v2, v3, v4, which is the two triangles (v1, v2, v3) and (v3, v2, v4) of the +// parallelogram with the same winding. Every Location output of the vertex stage is a vec4 float in the translator's +// output (rdna2spirv.py), and so is the stage's Position; the generated stage reads and writes exactly those. A value +// that is the same bit pattern at all three corners (a flat attribute, which may hold integer bits) is copied rather +// than computed, so it cannot turn into a NaN. +// +// Not covered, and refused with a reason: a vertex stage that writes ClipDistance, CullDistance, Layer or +// ViewportIndex, or a Location output that is not a vec4 float. +// +// Plain word editing, standard library only. + +#include +#include +#include +#include +#include +#include +#include + +namespace leonida { + +// D3D_PRIMITIVE_TOPOLOGY values and the PSO topology type of the console's rectangle and quad lists. +constexpr std::uint32_t topology_rect_list = 17; +constexpr std::uint32_t topology_quad_list = 19; +constexpr std::uint32_t topology_type_rect_list = 19; + +// The geometry stage for `vertex_words`' outputs; empty, with `why` set, when the vertex stage cannot be expanded. +inline std::vector rect_list_geometry(const std::vector& vertex_words, std::string& why) { + enum : std::uint32_t { + op_entry_point = 15, op_type_void = 19, op_type_bool = 20, op_type_int = 21, op_type_float = 22, + op_type_vector = 23, op_type_array = 28, op_type_pointer = 32, op_type_function = 33, op_constant = 43, + op_function = 54, op_function_end = 56, op_variable = 59, op_load = 61, op_store = 62, op_access_chain = 65, + op_decorate = 71, op_bitcast = 124, op_fadd = 129, op_fsub = 131, op_logical_and = 167, op_select = 169, + op_iequal = 170, op_emit_vertex = 218, op_end_primitive = 219, op_label = 248, op_return = 253, + op_capability = 17, op_memory_model = 14, op_execution_mode = 16, + deco_builtin = 11, deco_location = 30, builtin_position = 0, builtin_point_size = 1, + storage_input = 1, storage_output = 3 + }; + why.clear(); + if (vertex_words.size() < 6 || vertex_words[0] != 0x07230203u) { + why = "the vertex shader is not a SPIR-V module"; + return {}; + } + // What the vertex stage declares: types, Output variables, and the decorations that name them. + struct Type { std::uint32_t op = 0, component = 0, count = 0, width = 0; }; + std::map types; + std::map variable_type; // Output variable -> its pointer type + std::map location, builtin; // variable id -> value + std::set outputs; + for (std::size_t i = 5; i < vertex_words.size();) { + const std::uint32_t op = vertex_words[i] & 0xffffu, n = vertex_words[i] >> 16; + if (!n || i + n > vertex_words.size()) { + why = "the vertex shader's SPIR-V is cut short"; + return {}; + } + const std::uint32_t* w = &vertex_words[i]; + if (op == op_type_float && n >= 3) types[w[1]] = {op, 0, 0, w[2]}; + else if (op == op_type_vector && n >= 4) types[w[1]] = {op, w[2], w[3], 0}; + else if (op == op_type_pointer && n >= 4) types[w[1]] = {op, w[3], w[2], 0}; + else if (op == op_variable && n >= 4 && w[3] == storage_output) outputs.insert(w[2]), variable_type[w[2]] = w[1]; + else if (op == op_decorate && n >= 4 && w[2] == deco_location) location[w[1]] = w[3]; + else if (op == op_decorate && n >= 4 && w[2] == deco_builtin) builtin[w[1]] = w[3]; + i += n; + } + std::uint32_t position = 0; + std::vector params; // Location values, ascending + for (std::uint32_t id : outputs) { + const auto b = builtin.find(id); + if (b != builtin.end()) { + if (b->second == builtin_position) position = id; + else if (b->second != builtin_point_size) { + why = "the vertex shader writes ClipDistance, CullDistance, Layer or ViewportIndex"; + return {}; + } + continue; + } + const auto l = location.find(id); + if (l == location.end()) continue; + const Type& ptr = types[variable_type[id]]; + const Type& vec = types[ptr.component]; + const Type& scalar = types[vec.component]; + if (vec.op != op_type_vector || vec.count != 4 || scalar.op != op_type_float || scalar.width != 32) { + why = "a vertex output is not a vec4 float"; + return {}; + } + params.push_back(l->second); + } + if (!position) { + why = "the vertex shader writes no Position"; + return {}; + } + std::sort(params.begin(), params.end()); + params.erase(std::unique(params.begin(), params.end()), params.end()); + + // The module: a fixed prelude, then per variable ids, then the body. Ids count up from 1. + std::uint32_t next = 1; + const auto id = [&] { return next++; }; + std::vector head, annotations, globals, body; + const auto emit = [](std::vector& to, std::uint32_t op, std::initializer_list args) { + to.push_back((std::uint32_t(args.size()) + 1) << 16 | op); + to.insert(to.end(), args.begin(), args.end()); + }; + const std::uint32_t t_void = id(), t_fn = id(), t_uint = id(), t_float = id(), t_v4 = id(), t_bool = id(), + t_v4bool = id(), t_v4uint = id(), c3 = id(), t_arr = id(), t_pin_arr = id(), t_pin_v4 = id(), + t_pout_v4 = id(), c0 = id(), c1 = id(), c2 = id(); + emit(globals, op_type_void, {t_void}); + emit(globals, op_type_function, {t_fn, t_void}); + emit(globals, op_type_int, {t_uint, 32, 0}); + emit(globals, op_type_float, {t_float, 32}); + emit(globals, op_type_vector, {t_v4, t_float, 4}); + emit(globals, op_type_bool, {t_bool}); + emit(globals, op_type_vector, {t_v4bool, t_bool, 4}); + emit(globals, op_type_vector, {t_v4uint, t_uint, 4}); + emit(globals, op_constant, {t_uint, c3, 3}); + emit(globals, op_constant, {t_uint, c0, 0}); + emit(globals, op_constant, {t_uint, c1, 1}); + emit(globals, op_constant, {t_uint, c2, 2}); + emit(globals, op_type_array, {t_arr, t_v4, c3}); + emit(globals, op_type_pointer, {t_pin_arr, storage_input, t_arr}); + emit(globals, op_type_pointer, {t_pin_v4, storage_input, t_v4}); + emit(globals, op_type_pointer, {t_pout_v4, storage_output, t_v4}); + + struct Var { std::uint32_t in, out; bool is_position; }; + std::vector vars; + vars.push_back({id(), id(), true}); + for (std::size_t i = 0; i < params.size(); ++i) vars.push_back({id(), id(), false}); + std::vector io_vars; + emit(annotations, op_decorate, {vars[0].in, deco_builtin, builtin_position}); + emit(annotations, op_decorate, {vars[0].out, deco_builtin, builtin_position}); + for (std::size_t i = 0; i < params.size(); ++i) { + emit(annotations, op_decorate, {vars[i + 1].in, deco_location, params[i]}); + emit(annotations, op_decorate, {vars[i + 1].out, deco_location, params[i]}); + } + for (const Var& v : vars) { + emit(globals, op_variable, {t_pin_arr, v.in, storage_input}); + emit(globals, op_variable, {t_pout_v4, v.out, storage_output}); + io_vars.push_back(v.in); + io_vars.push_back(v.out); + } + + const std::uint32_t main_fn = id(), entry_label = id(); + emit(body, op_function, {t_void, main_fn, 0, t_fn}); + emit(body, op_label, {entry_label}); + // Per variable: the three corners, and the fourth. The fourth is v2 + v3 - v1, except where all three corners + // have the same bits (a flat value), where it is v1. + struct Corners { std::uint32_t v[4]; }; + std::vector corners; + const std::uint32_t cs[3] = {c0, c1, c2}; + for (const Var& v : vars) { + Corners c{}; + for (int k = 0; k < 3; ++k) { + const std::uint32_t ptr = id(); + c.v[k] = id(); + emit(body, op_access_chain, {t_pin_v4, ptr, v.in, cs[k]}); + emit(body, op_load, {t_v4, c.v[k], ptr}); + } + const std::uint32_t sum = id(), diff = id(); + emit(body, op_fadd, {t_v4, sum, c.v[1], c.v[2]}); + emit(body, op_fsub, {t_v4, diff, sum, c.v[0]}); + if (v.is_position) { + c.v[3] = diff; + } else { + const std::uint32_t b0 = id(), b1 = id(), b2 = id(), e1 = id(), e2 = id(), same = id(), pick = id(); + emit(body, op_bitcast, {t_v4uint, b0, c.v[0]}); + emit(body, op_bitcast, {t_v4uint, b1, c.v[1]}); + emit(body, op_bitcast, {t_v4uint, b2, c.v[2]}); + emit(body, op_iequal, {t_v4bool, e1, b1, b0}); + emit(body, op_iequal, {t_v4bool, e2, b2, b0}); + emit(body, op_logical_and, {t_v4bool, same, e1, e2}); + emit(body, op_select, {t_v4, pick, same, c.v[0], diff}); + c.v[3] = pick; + } + corners.push_back(c); + } + // The strip v1, v2, v3, v4. + for (int k = 0; k < 4; ++k) { + for (std::size_t i = 0; i < vars.size(); ++i) emit(body, op_store, {vars[i].out, corners[i].v[k]}); + emit(body, op_emit_vertex, {}); + } + emit(body, op_end_primitive, {}); + emit(body, op_return, {}); + emit(body, op_function_end, {}); + + std::vector out{0x07230203u, 0x00010000u, 0, next, 0}; + emit(out, op_capability, {19}); // Geometry + emit(out, op_memory_model, {0, 1}); // Logical, GLSL450 + std::vector entry{3, main_fn, 0x6e69616du, 0}; // Geometry, %main, "main" + entry.insert(entry.end(), io_vars.begin(), io_vars.end()); + out.push_back((std::uint32_t(entry.size()) + 1) << 16 | op_entry_point); + out.insert(out.end(), entry.begin(), entry.end()); + emit(out, op_execution_mode, {main_fn, 22}); // Triangles + emit(out, op_execution_mode, {main_fn, 0, 1}); // Invocations 1 + emit(out, op_execution_mode, {main_fn, 29}); // OutputTriangleStrip + emit(out, op_execution_mode, {main_fn, 26, 4}); // OutputVertices 4 + out.insert(out.end(), annotations.begin(), annotations.end()); + out.insert(out.end(), globals.begin(), globals.end()); + out.insert(out.end(), body.begin(), body.end()); + return out; +} + +} // namespace leonida diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index e3e4defe89..c049698582 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -1268,6 +1268,14 @@ class VulkanContext { replay_.zero_size = size; } + // 0, 1, 2, ... as 32-bit indices, for non-indexed quad lists (ReplayFunctions::quad_indices). + void set_quad_indices(VkBuffer buffer, VkDeviceSize offset, std::uint32_t count) { + std::unique_lock lock(resource_mutex_); + replay_.quad_indices = buffer; + replay_.quad_indices_offset = offset; + replay_.quad_index_count = count; + } + // Physical-device COLOR_ATTACHMENT format check for reinterpreted UAV clears. void set_color_attachment_format(std::function check) { std::unique_lock lock(resource_mutex_); diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 889bb71f72..9a1f0f404e 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -32,6 +32,7 @@ #include "command_list.h" #include "depth24.h" +#include "rect_list_geometry.h" #include "uav_clear.h" #include @@ -869,6 +870,10 @@ struct ReplayFunctions { VkBuffer zero_buffer = VK_NULL_HANDLE; VkDeviceSize zero_offset = 0; VkDeviceSize zero_size = 0; + // 0, 1, 2, ... as 32-bit indices: what a non-indexed quad list is drawn with (quad_index_count of them). + VkBuffer quad_indices = VK_NULL_HANDLE; + VkDeviceSize quad_indices_offset = 0; + std::uint32_t quad_index_count = 0; std::uint64_t heap_base = 0; // device address of the GPU address arena (push-constant dwords 32-33) // Resolves available binary-occlusion queries to 64-bit 0/1 values, outside conditional rendering. std::functionzero_step_slots & (1u << slot)) ? 0 : view.stride; } + // A non-indexed quad list is drawn from the shared 0, 1, 2, ... index buffer (emit). + if (!draw.indexed && !draw.mesh && draw.topology == topology_quad_list && !vk.quad_indices) + return ReplayResult::unresolved_resource; if (draw.indexed) { if (draw.index.format == 57) p.index_type = VK_INDEX_TYPE_UINT16; else if (draw.index.format == 42) p.index_type = VK_INDEX_TYPE_UINT32; @@ -2227,6 +2235,11 @@ inline VkPrimitiveTopology vulkan_topology(std::uint32_t topology) { case 11: return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY; case 12: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY; case 13: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY; + // The console's lists (rect_list_geometry.h). A rectangle list is drawn as the triangle list of its three + // corners, the pipeline's geometry stage adds the fourth. A quad (v0 v1 v2 v3) is the fan (v0 v1 v2) (v0 v2 v3), + // which is the index pattern 0 1 2, 0 2 3; the draw below issues one fan per quad. + case topology_rect_list: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + case topology_quad_list: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN; default: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; } } @@ -4207,6 +4220,22 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c } if (draw->mesh) { vk.draw_mesh_tasks(command_buffer, draw->count, draw->instances, draw->first); + } else if (draw->topology == topology_quad_list) { + // One four-vertex fan per quad. The translated vertex shaders take their vertex id from the index + // value (VertexIndex - BaseVertex), so a fan must be drawn with the index values 4q..4q+3: an + // indexed draw reads them from the application's index buffer, a non-indexed one from the + // shared 0, 1, 2, ... buffer (quad_indices), with the draw's first vertex as the vertex offset, as + // VertexIndex is first + i for a plain draw. + const bool generated = !draw->indexed; // prepare() has checked that quad_indices is there + if (generated) + vk.bind_index_buffer(command_buffer, vk.quad_indices, vk.quad_indices_offset, VK_INDEX_TYPE_UINT32); + else + vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); + const std::uint32_t quads = std::min(draw->count / 4, generated ? vk.quad_index_count / 4 : UINT32_MAX); + const std::int32_t vertex_offset = generated ? std::int32_t(draw->first) : draw->base_vertex; + for (std::uint32_t quad = 0; quad < quads; ++quad) + vk.draw_indexed(command_buffer, 4, draw->instances, (generated ? 0 : draw->first) + 4 * quad, + vertex_offset, draw->first_instance); } else if (draw->indexed) { vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); vk.draw_indexed(command_buffer, draw->count, draw->instances, draw->first, draw->base_vertex, diff --git a/runtime/test/d3d12_rect_list_test.cpp b/runtime/test/d3d12_rect_list_test.cpp new file mode 100644 index 0000000000..05b90a81c8 --- /dev/null +++ b/runtime/test/d3d12_rect_list_test.cpp @@ -0,0 +1,341 @@ +// The console's rectangle and quad lists drawn through the D3D12-on-Vulkan layer (src/rect_list_geometry.h). +// +// Built like d3d12_translated_draw_test.cpp, from the same translated vs_m15 / ps_m15 (the VS fetches its vertices +// through a V#; the PS multiplies the colour by (0.5, 2, 1, 1) and adds the bias, 0 here), so the shaders are real +// translator output found by the SHA-256 of their FSSM programs. +// frame 1, rectangle list: PSO topology type 19, IASetPrimitiveTopology(17), DrawInstanced(3). The three corners +// v1 (-1, 1), v2 (1, 1), v3 (-1, -1) cover the top-left, top-right and bottom-left of the 64x64 target; the fourth +// corner, v2 + v3 - v1 = (1, -1) with colour c2 + c3 - c1, is made by the layer. Every pixel must carry the plane +// through the three corner colours; the bottom-right quadrant is only right when the fourth corner is. +// frame 2, quad list: PSO topology type TRIANGLE, IASetPrimitiveTopology(19), DrawInstanced(8): two quads (corners +// in order around the quad), the top-left and bottom-right quadrants, each one colour. These pixels are exact. +// Pixels are read back and compared; the other two quadrants of frame 2 stay the clear colour. LEONIDA_VK_VALIDATION=1 +// runs it under the validation layer. +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/gfx10_descriptors.h" +#include "../src/shader_library.h" + +#include +#include +#include +#include +#include +#include + +#ifndef LEONIDA_TEST_M15_DIR +#error "LEONIDA_TEST_M15_DIR must name the folder build.py wrote (spirv/index.json, fssm/*.fssm)" +#endif + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +using namespace d3d12test; +using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX + +namespace { + +std::vector read_file(const std::filesystem::path& path) { + std::ifstream in(path, std::ios::binary); + return {std::istreambuf_iterator(in), std::istreambuf_iterator()}; +} + +struct Vertex { // 32 bytes, as vs_m15.asm reads it + float position[4]; + float color[4]; +}; + +using Pixel = std::array; +constexpr UINT target_extent = 64; +constexpr UINT pitch = target_extent * sizeof(Pixel); +constexpr D3D_PRIMITIVE_TOPOLOGY rect_list = D3D_PRIMITIVE_TOPOLOGY(17), quad_list = D3D_PRIMITIVE_TOPOLOGY(19); +const std::uint32_t rect_type_value = 19; // not an enumerator of D3D12_PRIMITIVE_TOPOLOGY_TYPE + +std::array make_vsharp(std::uint64_t base, std::uint32_t records) { + leonida::gfx10::Buffer buffer; + buffer.address = base; + buffer.stride = 32; + buffer.num_records = records; + buffer.format = 77; // GFX10_FORMAT_32_32_32_32_FLOAT + buffer.oob_select = leonida::gfx10::OobSelect::structured; + return leonida::gfx10::encode(buffer); +} + +Vertex vertex(float x, float y, const float* c) { return Vertex{{x, y, 0.0f, 1.0f}, {c[0], c[1], c[2], c[3]}}; } + +} // namespace + +int main() { + vktest::Device d; + const auto device_status = d.initialize(); + if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips + EXPECT(device_status == vktest::DeviceStatus::ready); + if (!d.enabled.geometryShader) { + std::printf("SKIP: no geometryShader on this GPU\n"); + return 77; + } + const std::filesystem::path root_dir = LEONIDA_TEST_M15_DIR; + const auto vs_program = read_file(root_dir / "fssm" / "vs_m15.fssm"); + const auto ps_program = read_file(root_dir / "fssm" / "ps_m15.fssm"); + EXPECT(vs_program.size() >= 4 && ps_program.size() == 0x110); + const auto vs_container = shader_container(vs_program), ps_container = shader_container(ps_program); + + // Frame 1: the rectangle's three corners. Vertices 0..2. Frame 2: two quads, vertices 3..10. + const float ca[4] = {0.0f, 0.0f, 0.0f, 1.0f}, cb[4] = {1.0f, 0.0f, 0.5f, 1.0f}, cc[4] = {0.0f, 0.5f, 1.0f, 1.0f}; + const float q1[4] = {0.25f, 0.5f, 0.75f, 1.0f}, q2[4] = {1.0f, 0.0f, 0.5f, 1.0f}; + const Vertex vertices[11] = {vertex(-1, 1, ca), vertex(1, 1, cb), vertex(-1, -1, cc), + vertex(-1, 1, q1), vertex(0, 1, q1), vertex(0, 0, q1), vertex(-1, 0, q1), + vertex(0, 0, q2), vertex(1, 0, q2), vertex(1, -1, q2), vertex(0, -1, q2)}; + static_assert(sizeof(Vertex) == 32 && sizeof(vertices) == 352); + + std::vector rect_pixels(target_extent * target_extent), quad_pixels(target_extent * target_extent); + { + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = d.instance_proc; + info.instance = d.instance; + info.physical = d.physical; + info.device = d.device; + info.queue = d.queue; + info.queue_family = d.family; + info.buffer_device_address = true; + info.features = d.enabled; // geometryShader: the rectangle stage needs it + info.shader_dir = (root_dir / "spirv").string(); + ID3D12Device* inner = nullptr; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); + Ref device; + EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), + reinterpret_cast(&device.p)))); + rt::d3d12::set_device_outer(inner, device.p); + + D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + D3D12_ROOT_PARAMETER params[2] = {}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[0].DescriptorTable = {1, &range}; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[1].Constants = {0, 0, 4}; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + root_desc.Desc_1_0 = {2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + const auto root_blob = serialize_root_signature(root_desc); + EXPECT(!root_blob.empty()); + Ref root; + EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p)))); + + D3D12_GRAPHICS_PIPELINE_STATE_DESC pso_desc{}; + pso_desc.pRootSignature = root.p; + pso_desc.VS = {vs_container.data(), vs_container.size()}; + pso_desc.PS = {ps_container.data(), ps_container.size()}; + pso_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + pso_desc.SampleMask = 0xffffffff; + pso_desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pso_desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pso_desc.RasterizerState.DepthClipEnable = TRUE; + pso_desc.NumRenderTargets = 1; + pso_desc.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT; + pso_desc.SampleDesc.Count = 1; + Ref rect_pso, quad_pso; + std::memcpy(&pso_desc.PrimitiveTopologyType, &rect_type_value, sizeof(rect_type_value)); // 19: rectangles + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&rect_pso.p)))); + pso_desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&quad_pso.p)))); + + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; + const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + Ref vertex_buffer, upload, readback, target; + const auto vb_desc = buffer_desc(sizeof(vertices)); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &vb_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&vertex_buffer.p)))); + const auto upload_desc = buffer_desc(1024); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &upload_desc, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&upload.p)))); + const auto readback_desc = buffer_desc(pitch * target_extent); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + D3D12_RESOURCE_DESC rt_desc{}; + rt_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + rt_desc.Width = rt_desc.Height = target_extent; + rt_desc.DepthOrArraySize = 1; + rt_desc.MipLevels = 1; + rt_desc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + rt_desc.SampleDesc.Count = 1; + rt_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &rt_desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&target.p)))); + std::uint8_t* up = nullptr; + EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast(&up)))); + std::memcpy(up, vertices, sizeof(vertices)); + + // Two V#s over the one vertex buffer: slot 0 the rectangle's three corners, slot 1 the eight quad corners. + const D3D12_DESCRIPTOR_HEAP_DESC srv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + Ref srv_heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&srv_heap_desc, IID_PPV_ARGS(&srv_heap.p)))); + const std::uint64_t cpu = reinterpret_cast(slot(srv_heap.p, 9))(srv_heap.p); + const std::uint64_t gpu = reinterpret_cast(slot(srv_heap.p, 10))(srv_heap.p); + const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + EXPECT(cpu && gpu >= 0x10000 && gpu < (1ull << 32) && step >= 16); + const std::uint64_t buffer_va = vertex_buffer->GetGPUVirtualAddress(); + EXPECT(buffer_va >= 0x10000); + const std::array vsharps[2] = {make_vsharp(buffer_va, 3), + make_vsharp(buffer_va + 3 * sizeof(Vertex), 8)}; + for (unsigned i = 0; i < 2; ++i) + std::memcpy(reinterpret_cast(cpu + std::uint64_t(i) * step), vsharps[i].data(), 16); + + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + Ref rtv_heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&rtv_heap.p)))); + const D3D12_CPU_DESCRIPTOR_HANDLE rtv{ + SIZE_T(reinterpret_cast(slot(rtv_heap.p, 9))(rtv_heap.p))}; + device->CreateRenderTargetView(target.p, nullptr, rtv); + + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + Ref queue; + Ref allocator; + Ref list; + Ref fence; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, rect_pso.p, + IID_PPV_ARGS(&list.p)))); + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + + list->CopyBufferRegion(vertex_buffer.p, 0, upload.p, 0, sizeof(vertices)); + D3D12_RESOURCE_BARRIER barriers[2] = { + transition(vertex_buffer.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE), + transition(target.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET)}; + list->ResourceBarrier(2, barriers); + + const auto render_frame = [&](UINT64 frame, ID3D12PipelineState* pso, D3D_PRIMITIVE_TOPOLOGY topology, + unsigned vsharp_slot, UINT vertex_count, std::vector& out) -> int { + if (frame > 1) { + EXPECT(SUCCEEDED(allocator->Reset())); + EXPECT(SUCCEEDED(list->Reset(allocator.p, pso))); + auto to_target = transition(target.p, D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_RENDER_TARGET); + list->ResourceBarrier(1, &to_target); + } else { + list->SetPipelineState(pso); + } + const FLOAT clear[4] = {0.5f, 0.125f, 0.25f, 0.5f}; + list->ClearRenderTargetView(rtv, clear, 0, nullptr); + list->SetGraphicsRootSignature(root.p); + ID3D12DescriptorHeap* heaps[] = {srv_heap.p}; + list->SetDescriptorHeaps(1, heaps); + list->IASetPrimitiveTopology(topology); + const D3D12_VIEWPORT viewport{0, 0, float(target_extent), float(target_extent), 0, 1}; + const D3D12_RECT scissor{0, 0, LONG(target_extent), LONG(target_extent)}; + list->RSSetViewports(1, &viewport); + list->RSSetScissorRects(1, &scissor); + list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); + const float constants[4] = {0, 0, 0, 0}; // no offset, no bias + list->SetGraphicsRootDescriptorTable(0, D3D12_GPU_DESCRIPTOR_HANDLE{gpu + std::uint64_t(vsharp_slot) * step}); + list->SetGraphicsRoot32BitConstants(1, 4, constants, 0); + list->DrawInstanced(vertex_count, 1, 0, 0); + D3D12_RESOURCE_BARRIER to_copy = transition(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &to_copy); + D3D12_TEXTURE_COPY_LOCATION dst{}; + dst.pResource = readback.p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = {0, {DXGI_FORMAT_R32G32B32A32_FLOAT, target_extent, target_extent, 1, pitch}}; + D3D12_TEXTURE_COPY_LOCATION src{}; + src.pResource = target.p; + src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + EXPECT(list->Close() == S_OK); + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(queue->Signal(fence.p, frame))); + EXPECT(SUCCEEDED(fence->SetEventOnCompletion(frame, nullptr))); + void* mapped = nullptr; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); + std::memcpy(out.data(), mapped, out.size() * sizeof(Pixel)); + readback->Unmap(0, nullptr); + return 0; + }; + EXPECT(render_frame(1, rect_pso.p, rect_list, 0, 3, rect_pixels) == 0); + EXPECT(render_frame(2, quad_pso.p, quad_list, 1, 8, quad_pixels) == 0); + for (auto* r : {&vertex_buffer, &upload, &readback, &target}) r->reset(); + rect_pso.reset(); + quad_pso.reset(); + root.reset(); + srv_heap.reset(); + rtv_heap.reset(); + list.reset(); + allocator.reset(); + queue.reset(); + fence.reset(); + EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); + } + + // Rectangle: the plane through the three corner colours, at each pixel centre, through the PS's scale. + const float scale[4] = {0.5f, 2.0f, 1.0f, 1.0f}; + unsigned covered = 0, off = 0; + float worst = 0.0f; + for (UINT row = 0; row < target_extent; ++row) { + for (UINT col = 0; col < target_extent; ++col) { + const float u = (float(col) + 0.5f) / target_extent, v = (float(row) + 0.5f) / target_extent; + const Pixel& got = rect_pixels[row * target_extent + col]; + bool pixel_ok = true; + for (int c = 0; c < 4; ++c) { + const float want = (ca[c] + u * (cb[c] - ca[c]) + v * (cc[c] - ca[c])) * scale[c]; + const float error = std::fabs(got[c] - want); + worst = std::fmax(worst, error); + if (!(error <= 2e-5f)) pixel_ok = false; + } + covered += pixel_ok; + if (!pixel_ok && off++ < 8) + std::fprintf(stderr, "rect pixel (%u, %u): got %g,%g,%g,%g\n", col, row, got[0], got[1], got[2], got[3]); + } + } + // The four quadrant centres on their own, so a wrong fourth corner is named by quadrant. + const char* names[4] = {"top left", "top right", "bottom left", "bottom right"}; + for (int quadrant = 0; quadrant < 4; ++quadrant) { + const UINT col = (quadrant & 1 ? 48 : 16), row = (quadrant & 2 ? 48 : 16); + const Pixel& got = rect_pixels[row * target_extent + col]; + const float u = (float(col) + 0.5f) / target_extent, v = (float(row) + 0.5f) / target_extent; + for (int c = 0; c < 4; ++c) { + const float want = (ca[c] + u * (cb[c] - ca[c]) + v * (cc[c] - ca[c])) * scale[c]; + if (!(std::fabs(got[c] - want) <= 2e-5f)) { + std::fprintf(stderr, "rect %s quadrant: channel %d got %g want %g\n", names[quadrant], c, got[c], want); + return 1; + } + } + } + EXPECT(covered == target_extent * target_extent); + + // Quad list: whole-bit comparison; two quadrants one colour each, the rest the clear colour. + const Pixel clear_color = {0.5f, 0.125f, 0.25f, 0.5f}; + const Pixel top_left = {q1[0] * scale[0], q1[1] * scale[1], q1[2], q1[3]}; + const Pixel bottom_right = {q2[0] * scale[0], q2[1] * scale[1], q2[2], q2[3]}; + unsigned quad_wrong = 0; + for (UINT row = 0; row < target_extent; ++row) { + for (UINT col = 0; col < target_extent; ++col) { + const bool top = row < target_extent / 2, left = col < target_extent / 2; + const Pixel& want = top && left ? top_left : (!top && !left ? bottom_right : clear_color); + const Pixel& got = quad_pixels[row * target_extent + col]; + if (std::memcmp(&got, &want, sizeof(Pixel)) == 0) continue; + if (quad_wrong++ < 8) + std::fprintf(stderr, "quad pixel (%u, %u): got %g,%g,%g,%g want %g,%g,%g,%g\n", col, row, got[0], got[1], + got[2], got[3], want[0], want[1], want[2], want[3]); + } + } + EXPECT(!quad_wrong); + if (d.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); + return 1; + } + std::printf("rect list: %u of %u pixels on the colour plane (worst error %g), all four quadrants; quad list: " + "%u of %u pixels exact\n", + covered, target_extent * target_extent, double(worst), target_extent * target_extent - quad_wrong, + target_extent * target_extent); + return 0; +} From 0688b839baf12e7a80795744c908a6ee3e4fdcc1 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Mon, 23 Nov 2026 17:48:05 +0100 Subject: [PATCH 061/110] d3d12: rectangle list stage emits (v1 v2 v4) (v1 v4 v3) with capability Geometry, log cut-off quads (review fixes) --- docs/d3d12_vulkan.md | 2 +- runtime/src/rect_list_geometry.h | 57 ++++++++++++-------------------- runtime/src/vulkan_replay.h | 11 +++++- 3 files changed, 33 insertions(+), 37 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 51a3a4a9ed..9db4505959 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2122,7 +2122,7 @@ The trace will enumerate them. The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiveTopology(17)`, with a PSO whose topology type is 19) and quad list (`IASetPrimitiveTopology(19)`). The facts are from xvalkyrie (GPL-3.0, commit `53af7df77c10`; no code taken): a rectangle is three corners and the fourth is v2 + v3 - v1 for the position and every interpolant, after the vertex stage; a quad is four vertices. The layer draws both as triangles (`d3d12_rect_list_test`, RTX 4090: 4096 of 4096 pixels, the colour plane exact, quad list bit-exact). - **Rectangle list**: PSO type 19 builds a triangle-list pipeline plus a generated geometry stage (`src/rect_list_geometry.h`, written from the vertex shader's own outputs) that takes the three corners and emits the strip v1 v2 v3 v4 (same winding). It has to be post-vertex-stage: the translated vertex shaders fetch by V# themselves, and the fourth corner is a function of what they write. A corner value with the same bits at all three corners (a flat attribute) is copied. Needs `geometryShader` (else `E_NOTIMPL`), no application GS, and a vertex shader with no ClipDistance, CullDistance, Layer or ViewportIndex output. -- **Quad list**: one four-vertex triangle fan per quad (the pattern 0 1 2, 0 2 3). The translated vertex id is `VertexIndex - BaseVertex`, so each fan reads the index values 4q..4q+3: from the application's index buffer when the draw is indexed, else from a shared 0, 1, 2, ... buffer in the arena's reserved pages (16384 quads per draw at most), with the draw's first vertex as the vertex offset. The PSO type is the ordinary triangle type. +- **Quad list**: one four-vertex triangle fan per quad (the pattern 0 1 2, 0 2 3). The translated vertex id is `VertexIndex - BaseVertex`, so each fan reads the index values 4q..4q+3: from the application's index buffer when the draw is indexed, else from a shared 0, 1, 2, ... buffer in the arena's reserved pages (16384 quads per draw at most, more are cut off with a log line), with the draw's first vertex as the vertex offset. A quad's instances are drawn together, so several overlapping blended instances rasterize quad by quad rather than instance by instance. The PSO type is the ordinary triangle type. ## 4. Object model mapping diff --git a/runtime/src/rect_list_geometry.h b/runtime/src/rect_list_geometry.h index ee7d69905c..335e4db00e 100644 --- a/runtime/src/rect_list_geometry.h +++ b/runtime/src/rect_list_geometry.h @@ -11,11 +11,10 @@ // the vertex stage: a pre-pass over the vertex buffers is wrong for any shader that is not linear in its inputs (and // the translated vertex shaders fetch by V# themselves, so there is no vertex buffer to expand). The pipeline gets a // small geometry stage instead, built here from the vertex shader's own SPIR-V: it takes the triangle (v1, v2, v3) -// the list draws, and emits the strip v1, v2, v3, v4, which is the two triangles (v1, v2, v3) and (v3, v2, v4) of the -// parallelogram with the same winding. Every Location output of the vertex stage is a vec4 float in the translator's -// output (rdna2spirv.py), and so is the stage's Position; the generated stage reads and writes exactly those. A value -// that is the same bit pattern at all three corners (a flat attribute, which may hold integer bits) is copied rather -// than computed, so it cannot turn into a NaN. +// the list draws and emits the parallelogram as the two triangles (v1, v2, v4) and (v1, v4, v3), with the winding of +// (v1, v2, v3). Both start at v1, so a flat input (taken from a triangle's first vertex) is v1's over the whole +// rectangle. Every Location output of the vertex stage is a vec4 float in the translator's output (rdna2spirv.py), +// and so is the stage's Position; the generated stage reads and writes exactly those. // // Not covered, and refused with a reason: a vertex stage that writes ClipDistance, CullDistance, Layer or // ViewportIndex, or a Location output that is not a vec4 float. @@ -40,11 +39,10 @@ constexpr std::uint32_t topology_type_rect_list = 19; // The geometry stage for `vertex_words`' outputs; empty, with `why` set, when the vertex stage cannot be expanded. inline std::vector rect_list_geometry(const std::vector& vertex_words, std::string& why) { enum : std::uint32_t { - op_entry_point = 15, op_type_void = 19, op_type_bool = 20, op_type_int = 21, op_type_float = 22, + op_entry_point = 15, op_type_void = 19, op_type_int = 21, op_type_float = 22, op_type_vector = 23, op_type_array = 28, op_type_pointer = 32, op_type_function = 33, op_constant = 43, op_function = 54, op_function_end = 56, op_variable = 59, op_load = 61, op_store = 62, op_access_chain = 65, - op_decorate = 71, op_bitcast = 124, op_fadd = 129, op_fsub = 131, op_logical_and = 167, op_select = 169, - op_iequal = 170, op_emit_vertex = 218, op_end_primitive = 219, op_label = 248, op_return = 253, + op_decorate = 71, op_fadd = 129, op_fsub = 131, op_emit_vertex = 218, op_end_primitive = 219, op_label = 248, op_return = 253, op_capability = 17, op_memory_model = 14, op_execution_mode = 16, deco_builtin = 11, deco_location = 30, builtin_position = 0, builtin_point_size = 1, storage_input = 1, storage_output = 3 @@ -113,17 +111,14 @@ inline std::vector rect_list_geometry(const std::vector rect_list_geometry(const std::vector corners; const std::uint32_t cs[3] = {c0, c1, c2}; @@ -170,32 +164,25 @@ inline std::vector rect_list_geometry(const std::vector out{0x07230203u, 0x00010000u, 0, next, 0}; - emit(out, op_capability, {19}); // Geometry + emit(out, op_capability, {2}); // Geometry emit(out, op_memory_model, {0, 1}); // Logical, GLSL450 std::vector entry{3, main_fn, 0x6e69616du, 0}; // Geometry, %main, "main" entry.insert(entry.end(), io_vars.begin(), io_vars.end()); @@ -204,7 +191,7 @@ inline std::vector rect_list_geometry(const std::vector #include #include +#include #include #include #include @@ -4231,8 +4232,16 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c vk.bind_index_buffer(command_buffer, vk.quad_indices, vk.quad_indices_offset, VK_INDEX_TYPE_UINT32); else vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); - const std::uint32_t quads = std::min(draw->count / 4, generated ? vk.quad_index_count / 4 : UINT32_MAX); + // The shared buffer holds quad_index_count / 4 quads: more are cut off here and said so. + const std::uint32_t wanted = draw->count / 4, room = generated ? vk.quad_index_count / 4 : UINT32_MAX; + const std::uint32_t quads = std::min(wanted, room); + if (quads < wanted) + std::fprintf(stderr, "[rt] d3d12: a non-indexed quad list of %u quads draws only the first %u\n", + wanted, quads); const std::int32_t vertex_offset = generated ? std::int32_t(draw->first) : draw->base_vertex; + // All the instances of a quad are drawn together (a split by instance would zero the translated + // instance id, InstanceIndex - BaseInstance), so with several instances the primitive order is quad + // by quad, not instance by instance: only overlapping blended instances can tell. for (std::uint32_t quad = 0; quad < quads; ++quad) vk.draw_indexed(command_buffer, 4, draw->instances, (generated ? 0 : draw->first) + 4 * quad, vertex_offset, draw->first_instance); From abe64d495b0a22a78ccf9106f1980c2f550778e0 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Mon, 23 Nov 2026 21:11:37 +0100 Subject: [PATCH 062/110] d3d12: quad lists draw as triangle-list indices (0 1 2) (0 2 3) so flat inputs use the first quad vertex, and the PSO topology type is read as raw bits Taken from the follow-up patch of @matheuskshn (930e78a2, tested by them on an RTX 4070 Ti: replay_quad_list_test fails the two non-indexed cases on a6b31d51 and passes with it). Re-run here: replay_quad_list_test and d3d12_rect_list_test exit 0 on the pod (Wine, RTX 4090). --- docs/d3d12_vulkan.md | 7 +- runtime/CMakeLists.txt | 6 ++ runtime/shims/d3d12_vulkan_device.cpp | 28 ++++--- runtime/src/rect_list_geometry.h | 2 + runtime/src/vulkan_backend.h | 2 +- runtime/src/vulkan_replay.h | 54 ++++++------ runtime/test/replay_quad_list_test.cpp | 110 +++++++++++++++++++++++++ 7 files changed, 168 insertions(+), 41 deletions(-) create mode 100644 runtime/test/replay_quad_list_test.cpp diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 9db4505959..6ecc34081d 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2122,7 +2122,12 @@ The trace will enumerate them. The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiveTopology(17)`, with a PSO whose topology type is 19) and quad list (`IASetPrimitiveTopology(19)`). The facts are from xvalkyrie (GPL-3.0, commit `53af7df77c10`; no code taken): a rectangle is three corners and the fourth is v2 + v3 - v1 for the position and every interpolant, after the vertex stage; a quad is four vertices. The layer draws both as triangles (`d3d12_rect_list_test`, RTX 4090: 4096 of 4096 pixels, the colour plane exact, quad list bit-exact). - **Rectangle list**: PSO type 19 builds a triangle-list pipeline plus a generated geometry stage (`src/rect_list_geometry.h`, written from the vertex shader's own outputs) that takes the three corners and emits the strip v1 v2 v3 v4 (same winding). It has to be post-vertex-stage: the translated vertex shaders fetch by V# themselves, and the fourth corner is a function of what they write. A corner value with the same bits at all three corners (a flat attribute) is copied. Needs `geometryShader` (else `E_NOTIMPL`), no application GS, and a vertex shader with no ClipDistance, CullDistance, Layer or ViewportIndex output. -- **Quad list**: one four-vertex triangle fan per quad (the pattern 0 1 2, 0 2 3). The translated vertex id is `VertexIndex - BaseVertex`, so each fan reads the index values 4q..4q+3: from the application's index buffer when the draw is indexed, else from a shared 0, 1, 2, ... buffer in the arena's reserved pages (16384 quads per draw at most, more are cut off with a log line), with the draw's first vertex as the vertex offset. A quad's instances are drawn together, so several overlapping blended instances rasterize quad by quad rather than instance by instance. The PSO type is the ordinary triangle type. +- **Quad list**: a non-indexed draw uses a shared index buffer containing the triangle-list pattern + `0 1 2, 0 2 3` for each quad. Both triangles start at the first vertex for flat inputs. One draw preserves instance + order and supports up to 16384 quads. The draw's first vertex becomes the vertex offset. Indexed draws still + read the application's index buffer as one four-vertex fan per quad. Vulkan fans use a different provoking + vertex for flat inputs, and overlapping blended instances rasterize quad by quad in this path. The PSO type + is the ordinary triangle type. ## 4. Object model mapping diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index c422368d05..be338e70d3 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -3257,6 +3257,12 @@ if(TARGET Vulkan::Headers) target_compile_definitions(replay_readback_stages_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) endif() add_test(NAME replay_readback_stages COMMAND replay_readback_stages_test) + add_executable(replay_quad_list_test test/replay_quad_list_test.cpp) + target_link_libraries(replay_quad_list_test PRIVATE Vulkan::Headers) + if(WIN32) + target_compile_definitions(replay_quad_list_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + add_test(NAME replay_quad_list COMMAND replay_quad_list_test) # emit of an enhanced texture barrier: no heap allocation for one layout piece, one barrier for each piece (no GPU). add_executable(replay_texture_barrier_test test/replay_texture_barrier_test.cpp) target_link_libraries(replay_texture_barrier_test PRIVATE Vulkan::Headers) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index f6f7b50046..945d10512b 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -67,7 +67,8 @@ constexpr UINT kDescriptorSize = descriptor_size; // The first 64 KiB of the GPU address arena are never handed out: VA 0 stays invalid, and the page is kept zero // for unbound vertex and index buffers to read (D3D12 reads zeros there). constexpr VkDeviceSize kZeroPage = 64 * 1024; // zeroed: what unbound vertex and index buffers read -constexpr std::uint32_t kQuadIndexCount = 64 * 1024; // 0, 1, 2, ... that non-indexed quad lists draw with (16384 quads) +constexpr std::uint32_t kQuadIndicesPerQuad = leonida::quad_triangle_indices.size(); +constexpr std::uint32_t kQuadIndexCount = 16 * 1024 * kQuadIndicesPerQuad; constexpr VkDeviceSize kArenaReserved = kZeroPage + VkDeviceSize(kQuadIndexCount) * sizeof(std::uint32_t); static_assert(sizeof(leonida::TargetView) <= kDescriptorSize); @@ -3066,7 +3067,8 @@ leonida::cached_pso::Key pipeline_key(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& key.text(e.SemanticName).u32(e.SemanticIndex).u32(e.Format).u32(e.InputSlot).u32(e.AlignedByteOffset); key.u32(e.InputSlotClass).u32(e.InstanceDataStepRate); } - key.u32(desc.IBStripCutValue).u32(desc.PrimitiveTopologyType).u32(desc.NumRenderTargets); + key.u32(desc.IBStripCutValue).u32(std::bit_cast(desc.PrimitiveTopologyType)) + .u32(desc.NumRenderTargets); for (const DXGI_FORMAT format : desc.RTVFormats) key.u32(format); key.u32(desc.DSVFormat).u32(desc.SampleDesc.Count).u32(desc.SampleDesc.Quality).u32(desc.NodeMask); return leonida::sha256_hex(key.data()); @@ -3466,13 +3468,15 @@ class PipelineState final // The console's rectangle topology type (19) draws as triangles through a generated geometry stage that adds // each rectangle's fourth corner (src/rect_list_geometry.h); it needs the same device feature, and no GS of // the application's own. - const bool rect_list = !mesh && desc.PrimitiveTopologyType == leonida::topology_type_rect_list; + // Decode the ABI field as bits. The console's value is outside the PC enum's range. + const auto topology_type = std::bit_cast(desc.PrimitiveTopologyType); + const bool rect_list = !mesh && topology_type == leonida::topology_type_rect_list; if (rect_list && (geometry || !device_.info.features.geometryShader)) { log_once("a rectangle-list pipeline needs the geometryShader feature and no geometry shader; stage", 0); return geometry ? E_INVALIDARG : E_NOTIMPL; } - if (geometry && desc.PrimitiveTopologyType != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) { - log_once("a translated geometry shader takes triangles; topology type", desc.PrimitiveTopologyType); + if (geometry && topology_type != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) { + log_once("a translated geometry shader takes triangles; topology type", topology_type); return E_INVALIDARG; } const UINT samples = desc.SampleDesc.Count; @@ -3746,12 +3750,12 @@ class PipelineState final } VkPipelineInputAssemblyStateCreateInfo assembly{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; // Type 19 is the console's rectangles, drawn as triangle lists through the geometry stage added above. - switch (mesh || rect_list ? D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE : desc.PrimitiveTopologyType) { // mesh: not used + switch (mesh || rect_list ? D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE : topology_type) { // mesh: not used case D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT: assembly.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST; break; case D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_LINE_LIST; break; case D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; break; default: - log_once("primitive topology type not supported:", desc.PrimitiveTopologyType); + log_once("primitive topology type not supported:", topology_type); return E_INVALIDARG; } if (!mesh) { // a mesh PSO has no index buffer: its strip cut is ignored @@ -3773,7 +3777,7 @@ class PipelineState final return E_INVALIDARG; } if (r.FillMode != D3D12_FILL_MODE_SOLID || - desc.PrimitiveTopologyType != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) return E_INVALIDARG; + topology_type != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) return E_INVALIDARG; // Target-independent rasterization is a separate pipeline path; do not silently ignore its count. if (r.ForcedSampleCount) return E_NOTIMPL; } @@ -5481,9 +5485,11 @@ class Device final } arena.mapped = static_cast(mapped); std::memset(arena.mapped, 0, kZeroPage); // the zero page unbound vertex and index buffers read - { - auto* iota = reinterpret_cast(arena.mapped + kZeroPage); - for (std::uint32_t i = 0; i < kQuadIndexCount; ++i) iota[i] = i; + auto* indices = reinterpret_cast(arena.mapped + kZeroPage); + for (std::uint32_t i = 0; i < kQuadIndexCount; i += kQuadIndicesPerQuad) { + const std::uint32_t base = i / kQuadIndicesPerQuad * 4; + std::transform(leonida::quad_triangle_indices.begin(), leonida::quad_triangle_indices.end(), indices + i, + [base](std::uint32_t index) { return base + index; }); } VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; address.buffer = arena.buffer; diff --git a/runtime/src/rect_list_geometry.h b/runtime/src/rect_list_geometry.h index 335e4db00e..86826317c6 100644 --- a/runtime/src/rect_list_geometry.h +++ b/runtime/src/rect_list_geometry.h @@ -22,6 +22,7 @@ // Plain word editing, standard library only. #include +#include #include #include #include @@ -35,6 +36,7 @@ namespace leonida { constexpr std::uint32_t topology_rect_list = 17; constexpr std::uint32_t topology_quad_list = 19; constexpr std::uint32_t topology_type_rect_list = 19; +constexpr std::array quad_triangle_indices{0, 1, 2, 0, 2, 3}; // The geometry stage for `vertex_words`' outputs; empty, with `why` set, when the vertex stage cannot be expanded. inline std::vector rect_list_geometry(const std::vector& vertex_words, std::string& why) { diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index c049698582..02fdad1a09 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -1268,7 +1268,7 @@ class VulkanContext { replay_.zero_size = size; } - // 0, 1, 2, ... as 32-bit indices, for non-indexed quad lists (ReplayFunctions::quad_indices). + // Pre-expanded 32-bit triangle indices for non-indexed quad lists (ReplayFunctions::quad_indices). void set_quad_indices(VkBuffer buffer, VkDeviceSize offset, std::uint32_t count) { std::unique_lock lock(resource_mutex_); replay_.quad_indices = buffer; diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 49554653ce..f9dfb6b030 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -871,7 +871,7 @@ struct ReplayFunctions { VkBuffer zero_buffer = VK_NULL_HANDLE; VkDeviceSize zero_offset = 0; VkDeviceSize zero_size = 0; - // 0, 1, 2, ... as 32-bit indices: what a non-indexed quad list is drawn with (quad_index_count of them). + // 32-bit triangle indices for non-indexed quad lists: 0, 1, 2, 0, 2, 3, then the same pattern for each quad. VkBuffer quad_indices = VK_NULL_HANDLE; VkDeviceSize quad_indices_offset = 0; std::uint32_t quad_index_count = 0; @@ -2199,7 +2199,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct p.vertex_sizes[slot] = size; p.vertex_strides[slot] = (pipeline->zero_step_slots & (1u << slot)) ? 0 : view.stride; } - // A non-indexed quad list is drawn from the shared 0, 1, 2, ... index buffer (emit). + // A non-indexed quad list is drawn from the shared triangle index buffer (emit). if (!draw.indexed && !draw.mesh && draw.topology == topology_quad_list && !vk.quad_indices) return ReplayResult::unresolved_resource; if (draw.indexed) { @@ -2236,9 +2236,8 @@ inline VkPrimitiveTopology vulkan_topology(std::uint32_t topology) { case 11: return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY; case 12: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY; case 13: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY; - // The console's lists (rect_list_geometry.h). A rectangle list is drawn as the triangle list of its three - // corners, the pipeline's geometry stage adds the fourth. A quad (v0 v1 v2 v3) is the fan (v0 v1 v2) (v0 v2 v3), - // which is the index pattern 0 1 2, 0 2 3; the draw below issues one fan per quad. + // Rectangles draw as triangle lists through a geometry stage. Indexed quads draw as separate fans; + // emit() overrides non-indexed quads to a triangle list backed by the shared indices. case topology_rect_list: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; case topology_quad_list: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN; default: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; @@ -4204,7 +4203,8 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c // A mesh pipeline has no input assembly: its topology comes from the shader, and neither the topology // nor primitive restart is dynamic state there (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065). if (!draw->mesh) { - const VkPrimitiveTopology topology = detail::vulkan_topology(draw->topology); + const VkPrimitiveTopology topology = draw->topology == topology_quad_list && !draw->indexed + ? VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST : detail::vulkan_topology(draw->topology); vk.set_primitive_topology(command_buffer, topology); const bool restart = draw->indexed && detail::strip_topology(topology) && ((graphics.strip_cut == 1 && d.index_type == VK_INDEX_TYPE_UINT16) || @@ -4222,29 +4222,27 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c if (draw->mesh) { vk.draw_mesh_tasks(command_buffer, draw->count, draw->instances, draw->first); } else if (draw->topology == topology_quad_list) { - // One four-vertex fan per quad. The translated vertex shaders take their vertex id from the index - // value (VertexIndex - BaseVertex), so a fan must be drawn with the index values 4q..4q+3: an - // indexed draw reads them from the application's index buffer, a non-indexed one from the - // shared 0, 1, 2, ... buffer (quad_indices), with the draw's first vertex as the vertex offset, as - // VertexIndex is first + i for a plain draw. - const bool generated = !draw->indexed; // prepare() has checked that quad_indices is there - if (generated) - vk.bind_index_buffer(command_buffer, vk.quad_indices, vk.quad_indices_offset, VK_INDEX_TYPE_UINT32); - else + if (draw->indexed) { + // Indexed quads still read their vertices from the application's index buffer, one fan per quad. vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); - // The shared buffer holds quad_index_count / 4 quads: more are cut off here and said so. - const std::uint32_t wanted = draw->count / 4, room = generated ? vk.quad_index_count / 4 : UINT32_MAX; - const std::uint32_t quads = std::min(wanted, room); - if (quads < wanted) - std::fprintf(stderr, "[rt] d3d12: a non-indexed quad list of %u quads draws only the first %u\n", - wanted, quads); - const std::int32_t vertex_offset = generated ? std::int32_t(draw->first) : draw->base_vertex; - // All the instances of a quad are drawn together (a split by instance would zero the translated - // instance id, InstanceIndex - BaseInstance), so with several instances the primitive order is quad - // by quad, not instance by instance: only overlapping blended instances can tell. - for (std::uint32_t quad = 0; quad < quads; ++quad) - vk.draw_indexed(command_buffer, 4, draw->instances, (generated ? 0 : draw->first) + 4 * quad, - vertex_offset, draw->first_instance); + for (std::uint32_t quad = 0; quad < draw->count / 4; ++quad) + vk.draw_indexed(command_buffer, 4, draw->instances, draw->first + 4 * quad, + draw->base_vertex, draw->first_instance); + } else { + // Both triangles start at the quad's first vertex for flat inputs. One draw also preserves + // the original instance order, and VertexIndex - BaseVertex still gives 4q + k. + constexpr std::uint32_t indices_per_quad = quad_triangle_indices.size(); + const std::uint32_t wanted = draw->count / 4; + const std::uint32_t quads = std::min(wanted, vk.quad_index_count / indices_per_quad); + if (quads < wanted) + std::fprintf(stderr, "[rt] d3d12: a non-indexed quad list of %u quads draws only the first %u\n", + wanted, quads); + if (quads) { + vk.bind_index_buffer(command_buffer, vk.quad_indices, vk.quad_indices_offset, VK_INDEX_TYPE_UINT32); + vk.draw_indexed(command_buffer, quads * indices_per_quad, draw->instances, 0, + std::int32_t(draw->first), draw->first_instance); + } + } } else if (draw->indexed) { vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); vk.draw_indexed(command_buffer, draw->count, draw->instances, draw->first, draw->base_vertex, diff --git a/runtime/test/replay_quad_list_test.cpp b/runtime/test/replay_quad_list_test.cpp new file mode 100644 index 0000000000..15b0c7e781 --- /dev/null +++ b/runtime/test/replay_quad_list_test.cpp @@ -0,0 +1,110 @@ +// Quad lists without an index buffer are one triangle-list draw. A switch back to Vulkan triangle fans +// changes the provoking vertex for flat attributes and the order of overlapping blended instances. +#include "../src/vulkan_replay.h" + +#include +#include +#include + +namespace { +using namespace leonida; + +struct DrawCall { + VkPrimitiveTopology topology; + VkBuffer buffer; + VkDeviceSize offset; + VkIndexType index_type; + std::uint32_t count, instances, first_index; + std::int32_t base_vertex; + std::uint32_t first_instance; + bool operator==(const DrawCall&) const = default; +}; + +DrawCall recorded{}; +std::vector calls; + +bool check(bool condition, const char* description) { + if (!condition) std::fprintf(stderr, "FAIL: %s\n", description); + return condition; +} +} + +int main() { + using namespace leonida; + ReplayFunctions vk{}; + vk.begin_rendering = +[](VkCommandBuffer, const VkRenderingInfo*) {}; + vk.end_rendering = +[](VkCommandBuffer) {}; + vk.bind_pipeline = +[](VkCommandBuffer, VkPipelineBindPoint, VkPipeline) {}; + vk.push_constants = +[](VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags, std::uint32_t, + std::uint32_t, const void*) {}; + vk.set_viewport = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, const VkViewport*) {}; + vk.set_scissor = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, const VkRect2D*) {}; + vk.set_primitive_topology = +[](VkCommandBuffer, VkPrimitiveTopology topology) { recorded.topology = topology; }; + vk.set_primitive_restart_enable = +[](VkCommandBuffer, VkBool32) {}; + vk.set_stencil_reference = +[](VkCommandBuffer, VkStencilFaceFlags, std::uint32_t) {}; + vk.set_blend_constants = +[](VkCommandBuffer, const float*) {}; + vk.bind_index_buffer = +[](VkCommandBuffer, VkBuffer buffer, VkDeviceSize offset, VkIndexType type) { + recorded.buffer = buffer; + recorded.offset = offset; + recorded.index_type = type; + }; + vk.draw_indexed = +[](VkCommandBuffer, std::uint32_t count, std::uint32_t instances, std::uint32_t first, + std::int32_t base, std::uint32_t first_instance) { + recorded.count = count; + recorded.instances = instances; + recorded.first_index = first; + recorded.base_vertex = base; + recorded.first_instance = first_instance; + calls.push_back(recorded); + }; + + vk.quad_indices = reinterpret_cast(std::uintptr_t{1}); + vk.quad_indices_offset = 64; + vk.quad_index_count = 12; + const auto app_buffer = reinterpret_cast(std::uintptr_t{2}); + + GraphicsPipeline graphics{}; + const auto collect = [&](const Draw& draw) { + calls.clear(); + CommandList list; + if (!list.draw(draw) || !list.close()) return false; + PreparedList prepared; + prepared.list = &list; + prepared.commands.resize(1); + prepared.commands[0].draw = 0; + auto& entry = prepared.draws.emplace_back(); + entry.graphics = &graphics; + entry.index_buffer = app_buffer; + entry.index_offset = 32; + emit(prepared, VK_NULL_HANDLE, vk); + return true; + }; + + Draw draw{}; + draw.pipeline = 1; + draw.topology = topology_quad_list; + draw.count = 8; + draw.instances = 2; + draw.first = 13; + draw.first_instance = 7; + + const DrawCall triangles{VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, vk.quad_indices, 64, VK_INDEX_TYPE_UINT32, + 12, 2, 0, 13, 7}; + bool ok = check(collect(draw) && calls == std::vector{triangles}, + "non-indexed quads use one triangle-list draw and preserve draw bases"); + draw.count = 13; + ok &= check(collect(draw) && calls == std::vector{triangles}, + "a draw is limited to whole quads in the generated index buffer"); + draw.count = 3; + ok &= check(collect(draw) && calls.empty(), "an incomplete quad emits no draw"); + + draw.indexed = true; + draw.count = 8; + draw.first = 5; + draw.base_vertex = -2; + const DrawCall first_fan{VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN, app_buffer, 32, VK_INDEX_TYPE_UINT16, 4, 2, 5, -2, 7}; + const DrawCall second_fan{VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN, app_buffer, 32, VK_INDEX_TYPE_UINT16, 4, 2, 9, -2, 7}; + ok &= check(collect(draw) && calls == std::vector{first_fan, second_fan}, + "indexed quads use the application's index buffer and base vertex"); + return ok ? 0 : 1; +} From e3c22cc24693eb654be1bbea7cca32ebc62fd8b7 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Mon, 23 Nov 2026 21:19:02 +0100 Subject: [PATCH 063/110] d3d12: rect_list_geometry records that packed f16 attributes cannot be told apart from float outputs on the vertex side (comment only) --- runtime/src/rect_list_geometry.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/runtime/src/rect_list_geometry.h b/runtime/src/rect_list_geometry.h index 86826317c6..15d7368d34 100644 --- a/runtime/src/rect_list_geometry.h +++ b/runtime/src/rect_list_geometry.h @@ -92,6 +92,10 @@ inline std::vector rect_list_geometry(const std::vector Date: Mon, 23 Nov 2026 21:52:35 +0100 Subject: [PATCH 064/110] d3d12: rectangle list geometry picks the right-angle corner per rectangle (the vertex opposite the longest screen edge) instead of assuming the first; tests for the corner at the second and third vertex and for a non-right triangle --- runtime/src/rect_list_geometry.h | 85 +++++++++++++++++++++----- runtime/test/d3d12_rect_list_test.cpp | 86 +++++++++++++++++++++++---- 2 files changed, 144 insertions(+), 27 deletions(-) diff --git a/runtime/src/rect_list_geometry.h b/runtime/src/rect_list_geometry.h index 15d7368d34..69b52f7e7f 100644 --- a/runtime/src/rect_list_geometry.h +++ b/runtime/src/rect_list_geometry.h @@ -2,8 +2,10 @@ // Console rectangle lists on Vulkan, which has no such primitive. // -// A rectangle is three corners (v1, v2, v3) and the hardware makes the fourth, v2 + v3 - v1, for the position and for -// every interpolant, after the vertex stage. A list topology of rectangles (D3D_PRIMITIVE_TOPOLOGY 17) and a pipeline +// A rectangle is three corners and the hardware makes the fourth, a + b - p (p the right-angle corner, a and b its +// neighbours), for the position and for every interpolant, after the vertex stage. Which vertex is p is not fixed: +// the retail boot's full-screen rectangle has it at the second vertex. The stage picks the vertex opposite the longest +// screen-space edge, and the first vertex on a tie. A list topology of rectangles (D3D_PRIMITIVE_TOPOLOGY 17) and a pipeline // whose topology type is 19 are console-only. The fact comes from xvalkyrie (GPL-3.0, commit 53af7df77c10, notes in // its backlog); no code is taken from it. // @@ -11,8 +13,8 @@ // the vertex stage: a pre-pass over the vertex buffers is wrong for any shader that is not linear in its inputs (and // the translated vertex shaders fetch by V# themselves, so there is no vertex buffer to expand). The pipeline gets a // small geometry stage instead, built here from the vertex shader's own SPIR-V: it takes the triangle (v1, v2, v3) -// the list draws and emits the parallelogram as the two triangles (v1, v2, v4) and (v1, v4, v3), with the winding of -// (v1, v2, v3). Both start at v1, so a flat input (taken from a triangle's first vertex) is v1's over the whole +// the list draws and emits the parallelogram as the two triangles (p, a, f) and (p, f, b), with the winding of +// (v1, v2, v3). Both start at p, so a flat input (taken from a triangle's first vertex) is p's over the whole // rectangle. Every Location output of the vertex stage is a vec4 float in the translator's output (rdna2spirv.py), // and so is the stage's Position; the generated stage reads and writes exactly those. // @@ -44,7 +46,9 @@ inline std::vector rect_list_geometry(const std::vector rect_list_geometry(const std::vector rect_list_geometry(const std::vector rect_list_geometry(const std::vector corners; + std::vector> loaded; const std::uint32_t cs[3] = {c0, c1, c2}; for (const Var& v : vars) { - Corners c{}; + std::array three{}; for (int k = 0; k < 3; ++k) { const std::uint32_t ptr = id(); - c.v[k] = id(); + three[k] = id(); emit(body, op_access_chain, {t_pin_v4, ptr, v.in, cs[k]}); - emit(body, op_load, {t_v4, c.v[k], ptr}); + emit(body, op_load, {t_v4, three[k], ptr}); } + loaded.push_back(three); + } + // Which vertex is the right angle: the one opposite the longest edge, measured on screen (position.xy / position.w; + // a right triangle's longest edge is its hypotenuse). Ties go to the first vertex, which keeps the plain + // "v1 is the corner" order for every rectangle whose right angle is there. A triangle that is not a right + // triangle gets the same rule, so the choice is at least consistent. + std::uint32_t screen[3][2]; + for (int k = 0; k < 3; ++k) { + const std::uint32_t x = id(), y = id(), w = id(); + emit(body, op_composite_extract, {t_float, x, loaded[0][k], 0}); + emit(body, op_composite_extract, {t_float, y, loaded[0][k], 1}); + emit(body, op_composite_extract, {t_float, w, loaded[0][k], 3}); + screen[k][0] = id(); + screen[k][1] = id(); + emit(body, op_fdiv, {t_float, screen[k][0], x, w}); + emit(body, op_fdiv, {t_float, screen[k][1], y, w}); + } + const auto squared_edge = [&](int a, int b) { + const std::uint32_t dx = id(), dy = id(), xx = id(), yy = id(), sum = id(); + emit(body, op_fsub, {t_float, dx, screen[a][0], screen[b][0]}); + emit(body, op_fsub, {t_float, dy, screen[a][1], screen[b][1]}); + emit(body, op_fmul, {t_float, xx, dx, dx}); + emit(body, op_fmul, {t_float, yy, dy, dy}); + emit(body, op_fadd, {t_float, sum, xx, yy}); + return sum; + }; + const std::uint32_t e01 = squared_edge(0, 1), e02 = squared_edge(0, 2), e12 = squared_edge(1, 2); + const std::uint32_t g12_01 = id(), g12_02 = id(), at_first = id(), g02_01 = id(), not_first = id(), at_second = id(); + emit(body, op_ford_greater_equal, {t_bool, g12_01, e12, e01}); + emit(body, op_ford_greater_equal, {t_bool, g12_02, e12, e02}); + emit(body, op_logical_and, {t_bool, at_first, g12_01, g12_02}); // the edge opposite v1 is longest: v1 is the corner + emit(body, op_ford_greater_equal, {t_bool, g02_01, e02, e01}); + emit(body, op_logical_not, {t_bool, not_first, at_first}); + emit(body, op_logical_and, {t_bool, at_second, not_first, g02_01}); // else the edge opposite v2: v2; else v3 + const std::uint32_t first4 = id(), second4 = id(); + emit(body, op_composite_construct, {t_bool4, first4, at_first, at_first, at_first, at_first}); + emit(body, op_composite_construct, {t_bool4, second4, at_second, at_second, at_second, at_second}); + // The corner p, its neighbours a = next and b = the one after (the same cyclic order as v1 v2 v3, so the winding + // is the drawn triangle's), and the fourth corner a + b - p, for the position and for every interpolant alike. + for (const auto& three : loaded) { + Corners c{}; + const auto pick = [&](std::uint32_t first, std::uint32_t second, std::uint32_t third) { + const std::uint32_t inner = id(), outer = id(); + emit(body, op_select, {t_v4, inner, second4, second, third}); + emit(body, op_select, {t_v4, outer, first4, first, inner}); + return outer; + }; + c.v[0] = pick(three[0], three[1], three[2]); + c.v[1] = pick(three[1], three[2], three[0]); + c.v[2] = pick(three[2], three[0], three[1]); const std::uint32_t sum = id(), diff = id(); emit(body, op_fadd, {t_v4, sum, c.v[1], c.v[2]}); emit(body, op_fsub, {t_v4, diff, sum, c.v[0]}); c.v[3] = diff; corners.push_back(c); } - // Two triangles, (v1, v2, v4) and (v1, v4, v3): the diagonal is v1 to v4, so both start at v1 and a flat input - // (which Vulkan takes from a triangle's first vertex) is v1's over the whole rectangle. The attributes are + // Two triangles, (p, a, f) and (p, f, b): the diagonal is p to f, so both start at p and a flat input + // (which Vulkan takes from a triangle's first vertex) is p's over the whole rectangle. The attributes are // affine over the parallelogram, so the split does not change any interpolated value. const int triangles[2][3] = {{0, 1, 3}, {0, 3, 2}}; for (const auto& triangle : triangles) { diff --git a/runtime/test/d3d12_rect_list_test.cpp b/runtime/test/d3d12_rect_list_test.cpp index 05b90a81c8..5ab5611163 100644 --- a/runtime/test/d3d12_rect_list_test.cpp +++ b/runtime/test/d3d12_rect_list_test.cpp @@ -7,6 +7,10 @@ // v1 (-1, 1), v2 (1, 1), v3 (-1, -1) cover the top-left, top-right and bottom-left of the 64x64 target; the fourth // corner, v2 + v3 - v1 = (1, -1) with colour c2 + c3 - c1, is made by the layer. Every pixel must carry the plane // through the three corner colours; the bottom-right quadrant is only right when the fourth corner is. +// frames 3 to 5, rectangle lists whose right angle is at the second vertex, at the third vertex, and a triangle with +// no right angle at all. The layer takes the right-angle corner as the vertex opposite the longest screen edge, so +// the first two must cover all 64x64 pixels on the colour plane too (the retail boot's full-screen draw has its +// right angle at the second vertex); the third only has to draw something and not fail. // frame 2, quad list: PSO topology type TRIANGLE, IASetPrimitiveTopology(19), DrawInstanced(8): two quads (corners // in order around the quad), the top-left and bottom-right quadrants, each one colour. These pixels are exact. // Pixels are read back and compared; the other two quadrants of frame 2 stay the clear colour. LEONIDA_VK_VALIDATION=1 @@ -86,12 +90,19 @@ int main() { // Frame 1: the rectangle's three corners. Vertices 0..2. Frame 2: two quads, vertices 3..10. const float ca[4] = {0.0f, 0.0f, 0.0f, 1.0f}, cb[4] = {1.0f, 0.0f, 0.5f, 1.0f}, cc[4] = {0.0f, 0.5f, 1.0f, 1.0f}; const float q1[4] = {0.25f, 0.5f, 0.75f, 1.0f}, q2[4] = {1.0f, 0.0f, 0.5f, 1.0f}; - const Vertex vertices[11] = {vertex(-1, 1, ca), vertex(1, 1, cb), vertex(-1, -1, cc), + const Vertex vertices[20] = {vertex(-1, 1, ca), vertex(1, 1, cb), vertex(-1, -1, cc), vertex(-1, 1, q1), vertex(0, 1, q1), vertex(0, 0, q1), vertex(-1, 0, q1), - vertex(0, 0, q2), vertex(1, 0, q2), vertex(1, -1, q2), vertex(0, -1, q2)}; - static_assert(sizeof(Vertex) == 32 && sizeof(vertices) == 352); + vertex(0, 0, q2), vertex(1, 0, q2), vertex(1, -1, q2), vertex(0, -1, q2), + // vertices 11..13: right angle at the second vertex; 14..16: at the third; 17..19: none + vertex(-1, 1, ca), vertex(1, 1, cb), vertex(1, -1, cc), + vertex(-1, 1, ca), vertex(1, -1, cb), vertex(-1, -1, cc), + vertex(-1, 1, ca), vertex(0.5f, 0.75f, cb), vertex(-0.25f, -1, cc)}; + static_assert(sizeof(Vertex) == 32 && sizeof(vertices) == 640); + const Vertex* const corner_cases[2] = {&vertices[11], &vertices[14]}; - std::vector rect_pixels(target_extent * target_extent), quad_pixels(target_extent * target_extent); + std::vector rect_pixels(target_extent * target_extent), quad_pixels(target_extent * target_extent), + second_pixels(target_extent * target_extent), third_pixels(target_extent * target_extent), + skew_pixels(target_extent * target_extent); { rt::d3d12::VulkanDeviceInfo info{}; info.get_instance_proc = d.instance_proc; @@ -172,8 +183,9 @@ int main() { EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast(&up)))); std::memcpy(up, vertices, sizeof(vertices)); - // Two V#s over the one vertex buffer: slot 0 the rectangle's three corners, slot 1 the eight quad corners. - const D3D12_DESCRIPTOR_HEAP_DESC srv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2, + // V#s over the one vertex buffer: slot 0 the rectangle's three corners, slot 1 the eight quad corners, slots 2 to 4 + // the three more rectangles. + const D3D12_DESCRIPTOR_HEAP_DESC srv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 5, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; Ref srv_heap; EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&srv_heap_desc, IID_PPV_ARGS(&srv_heap.p)))); @@ -183,9 +195,12 @@ int main() { EXPECT(cpu && gpu >= 0x10000 && gpu < (1ull << 32) && step >= 16); const std::uint64_t buffer_va = vertex_buffer->GetGPUVirtualAddress(); EXPECT(buffer_va >= 0x10000); - const std::array vsharps[2] = {make_vsharp(buffer_va, 3), - make_vsharp(buffer_va + 3 * sizeof(Vertex), 8)}; - for (unsigned i = 0; i < 2; ++i) + const std::array vsharps[5] = {make_vsharp(buffer_va, 3), + make_vsharp(buffer_va + 3 * sizeof(Vertex), 8), + make_vsharp(buffer_va + 11 * sizeof(Vertex), 3), + make_vsharp(buffer_va + 14 * sizeof(Vertex), 3), + make_vsharp(buffer_va + 17 * sizeof(Vertex), 3)}; + for (unsigned i = 0; i < 5; ++i) std::memcpy(reinterpret_cast(cpu + std::uint64_t(i) * step), vsharps[i].data(), 16); const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; @@ -263,6 +278,9 @@ int main() { }; EXPECT(render_frame(1, rect_pso.p, rect_list, 0, 3, rect_pixels) == 0); EXPECT(render_frame(2, quad_pso.p, quad_list, 1, 8, quad_pixels) == 0); + EXPECT(render_frame(3, rect_pso.p, rect_list, 2, 3, second_pixels) == 0); + EXPECT(render_frame(4, rect_pso.p, rect_list, 3, 3, third_pixels) == 0); + EXPECT(render_frame(5, rect_pso.p, rect_list, 4, 3, skew_pixels) == 0); for (auto* r : {&vertex_buffer, &upload, &readback, &target}) r->reset(); rect_pso.reset(); quad_pso.reset(); @@ -312,6 +330,46 @@ int main() { } EXPECT(covered == target_extent * target_extent); + // Right angle at the second and at the third vertex: the plane through the three drawn corners, everywhere. + const std::vector* const corner_pixels[2] = {&second_pixels, &third_pixels}; + const char* const corner_names[2] = {"second", "third"}; + unsigned corner_covered[2] = {0, 0}; + float corner_worst = 0.0f; + for (int which = 0; which < 2; ++which) { + const Vertex* t = corner_cases[which]; + const float x0 = t[0].position[0], y0 = t[0].position[1]; + const float ax = t[1].position[0] - x0, ay = t[1].position[1] - y0; + const float bx = t[2].position[0] - x0, by = t[2].position[1] - y0; + const float det = ax * by - ay * bx; + for (UINT row = 0; row < target_extent; ++row) { + for (UINT col = 0; col < target_extent; ++col) { + const float px = 2.0f * (float(col) + 0.5f) / target_extent - 1.0f - x0; + const float py = 1.0f - 2.0f * (float(row) + 0.5f) / target_extent - y0; + const float s = (px * by - py * bx) / det, r = (ax * py - ay * px) / det; + const Pixel& got = (*corner_pixels[which])[row * target_extent + col]; + bool pixel_ok = true; + for (int c = 0; c < 4; ++c) { + const float want = (t[0].color[c] + s * (t[1].color[c] - t[0].color[c]) + + r * (t[2].color[c] - t[0].color[c])) * scale[c]; + const float error = std::fabs(got[c] - want); + corner_worst = std::fmax(corner_worst, error); + if (!(error <= 2e-5f)) pixel_ok = false; + } + corner_covered[which] += pixel_ok; + } + } + if (corner_covered[which] != target_extent * target_extent) { + std::fprintf(stderr, "rect list with the right angle at the %s vertex: %u of %u pixels on the plane\n", + corner_names[which], corner_covered[which], target_extent * target_extent); + return 1; + } + } + // Not a right triangle: any consistent corner, but it must draw (some pixel differs from the clear colour). + const Pixel clear_pixel = {0.5f, 0.125f, 0.25f, 0.5f}; + unsigned skew_drawn = 0; + for (const Pixel& p : skew_pixels) skew_drawn += std::memcmp(&p, &clear_pixel, sizeof(Pixel)) != 0; + EXPECT(skew_drawn > 0); + // Quad list: whole-bit comparison; two quadrants one colour each, the rest the clear colour. const Pixel clear_color = {0.5f, 0.125f, 0.25f, 0.5f}; const Pixel top_left = {q1[0] * scale[0], q1[1] * scale[1], q1[2], q1[3]}; @@ -333,9 +391,11 @@ int main() { std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); return 1; } - std::printf("rect list: %u of %u pixels on the colour plane (worst error %g), all four quadrants; quad list: " - "%u of %u pixels exact\n", - covered, target_extent * target_extent, double(worst), target_extent * target_extent - quad_wrong, - target_extent * target_extent); + std::printf("rect list: %u of %u pixels on the colour plane (worst error %g), all four quadrants; right angle at " + "the second vertex %u and at the third %u of %u (worst error %g); no right angle: %u pixels drawn; " + "quad list: %u of %u pixels exact\n", + covered, target_extent * target_extent, double(worst), corner_covered[0], corner_covered[1], + target_extent * target_extent, double(corner_worst), skew_drawn, + target_extent * target_extent - quad_wrong, target_extent * target_extent); return 0; } From ee9db97988cb8c8ee36ab835becffb3b9e1d6bae Mon Sep 17 00:00:00 2001 From: tedin7 Date: Mon, 23 Nov 2026 21:53:37 +0100 Subject: [PATCH 065/110] d3d12: rect list test: every pixel well inside a non-right triangle is drawn; geometry notes edges are measured in NDC --- runtime/src/rect_list_geometry.h | 4 ++++ runtime/test/d3d12_rect_list_test.cpp | 28 +++++++++++++++++++++++---- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/runtime/src/rect_list_geometry.h b/runtime/src/rect_list_geometry.h index 69b52f7e7f..e90173095d 100644 --- a/runtime/src/rect_list_geometry.h +++ b/runtime/src/rect_list_geometry.h @@ -18,6 +18,10 @@ // rectangle. Every Location output of the vertex stage is a vec4 float in the translator's output (rdna2spirv.py), // and so is the stage's Position; the generated stage reads and writes exactly those. // +// The edges are measured in normalized device coordinates, not pixels (the stage does not know the viewport). For the +// usual axis-aligned rectangle that is exact; a rotated rectangle drawn into a very non-square viewport can pick a +// different corner than the pixel-space right angle. +// // Not covered, and refused with a reason: a vertex stage that writes ClipDistance, CullDistance, Layer or // ViewportIndex, or a Location output that is not a vec4 float. // diff --git a/runtime/test/d3d12_rect_list_test.cpp b/runtime/test/d3d12_rect_list_test.cpp index 5ab5611163..a6d4d25b85 100644 --- a/runtime/test/d3d12_rect_list_test.cpp +++ b/runtime/test/d3d12_rect_list_test.cpp @@ -364,11 +364,31 @@ int main() { return 1; } } - // Not a right triangle: any consistent corner, but it must draw (some pixel differs from the clear colour). + // Not a right triangle: any consistent corner is fine, but every corner choice makes a parallelogram that holds the + // drawn triangle, so each pixel well inside the triangle must be drawn (not the clear colour). const Pixel clear_pixel = {0.5f, 0.125f, 0.25f, 0.5f}; - unsigned skew_drawn = 0; - for (const Pixel& p : skew_pixels) skew_drawn += std::memcmp(&p, &clear_pixel, sizeof(Pixel)) != 0; - EXPECT(skew_drawn > 0); + unsigned skew_drawn = 0, skew_inside = 0, skew_missing = 0; + { + const Vertex* t = &vertices[17]; + const float x0 = t[0].position[0], y0 = t[0].position[1]; + const float ax = t[1].position[0] - x0, ay = t[1].position[1] - y0; + const float bx = t[2].position[0] - x0, by = t[2].position[1] - y0; + const float det = ax * by - ay * bx; + for (UINT row = 0; row < target_extent; ++row) { + for (UINT col = 0; col < target_extent; ++col) { + const float px = 2.0f * (float(col) + 0.5f) / target_extent - 1.0f - x0; + const float py = 1.0f - 2.0f * (float(row) + 0.5f) / target_extent - y0; + const float s = (px * by - py * bx) / det, r = (ax * py - ay * px) / det; + const bool drawn = std::memcmp(&skew_pixels[row * target_extent + col], &clear_pixel, sizeof(Pixel)) != 0; + skew_drawn += drawn; + if (s > 0.02f && r > 0.02f && s + r < 0.98f) { + ++skew_inside; + skew_missing += !drawn; + } + } + } + } + EXPECT(skew_inside > 1000 && skew_missing == 0); // Quad list: whole-bit comparison; two quadrants one colour each, the rest the clear colour. const Pixel clear_color = {0.5f, 0.125f, 0.25f, 0.5f}; From 8311d8918c3d6ec5cafbfbb6577aad69c6d1a06b Mon Sep 17 00:00:00 2001 From: QemmHD <290605352+QemmHD@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:08:20 -0500 Subject: [PATCH 066/110] d3d12: the quad list index counts are 32-bit constants, not narrowed from size_t (C4267) std::array::size() is a size_t, and the two constants made from it are 32-bit. MSVC warned once in d3d12_vulkan_device.cpp and once in every file that includes vulkan_replay.h: 124 C4267 warnings in a Windows build of the runtime and its tests. The values (6 indices for a quad) are unchanged. AI-assisted (Claude Code; Claude Opus 5.5 and Claude Fable 5.2). Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01SR1Fv7eQNgZjM6miWPKjHf --- runtime/shims/d3d12_vulkan_device.cpp | 2 +- runtime/src/vulkan_replay.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 945d10512b..bf5c58d40a 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -67,7 +67,7 @@ constexpr UINT kDescriptorSize = descriptor_size; // The first 64 KiB of the GPU address arena are never handed out: VA 0 stays invalid, and the page is kept zero // for unbound vertex and index buffers to read (D3D12 reads zeros there). constexpr VkDeviceSize kZeroPage = 64 * 1024; // zeroed: what unbound vertex and index buffers read -constexpr std::uint32_t kQuadIndicesPerQuad = leonida::quad_triangle_indices.size(); +constexpr auto kQuadIndicesPerQuad = std::uint32_t(leonida::quad_triangle_indices.size()); constexpr std::uint32_t kQuadIndexCount = 16 * 1024 * kQuadIndicesPerQuad; constexpr VkDeviceSize kArenaReserved = kZeroPage + VkDeviceSize(kQuadIndexCount) * sizeof(std::uint32_t); static_assert(sizeof(leonida::TargetView) <= kDescriptorSize); diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index f9dfb6b030..5ffa65c95f 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -4231,7 +4231,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c } else { // Both triangles start at the quad's first vertex for flat inputs. One draw also preserves // the original instance order, and VertexIndex - BaseVertex still gives 4q + k. - constexpr std::uint32_t indices_per_quad = quad_triangle_indices.size(); + constexpr auto indices_per_quad = std::uint32_t(quad_triangle_indices.size()); const std::uint32_t wanted = draw->count / 4; const std::uint32_t quads = std::min(wanted, vk.quad_index_count / indices_per_quad); if (quads < wanted) From 7739895421f52326ab9523690848ec105e99e2e5 Mon Sep 17 00:00:00 2001 From: QemmHD <290605352+QemmHD@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:08:57 -0500 Subject: [PATCH 067/110] vulkan_scratch: the chunks can take usage beyond transfer source and destination ScratchBuffers creates every chunk as a transfer source and destination, which is all the staged copies need. Its owner can now add usage flags: the expanded indices of indexed quad lists (next commit) live in the same scratch, as an index buffer that a compute pass writes through its device address. The default is unchanged. vulkan_scratch_test checks the usage a chunk is created with, with and without the flags. AI-assisted (Claude Code; Claude Opus 5.5 and Claude Fable 5.2). Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01SR1Fv7eQNgZjM6miWPKjHf --- runtime/src/vulkan_scratch.h | 9 ++++++--- runtime/test/vulkan_scratch_test.cpp | 26 +++++++++++++++++++++++++- 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/runtime/src/vulkan_scratch.h b/runtime/src/vulkan_scratch.h index 4a8a59ddd7..c12d909e66 100644 --- a/runtime/src/vulkan_scratch.h +++ b/runtime/src/vulkan_scratch.h @@ -3,6 +3,8 @@ // it. The replay stages copies Vulkan cannot do in one command through them (vulkan_replay.h, depth <-> colour // copies). Single-threaded: the caller holds the context's lock. The same life cycle as the depth24 converter's own // scratch (vulkan_depth24.h), which also needs descriptor pools and exists only on GPUs without D24. +// The chunks are transfer sources and destinations; `extra_usage` adds what another user needs (the expanded indices +// of quad lists, quad_index_expand.h: an index buffer written through its device address). #pragma once #ifndef VK_NO_PROTOTYPES @@ -23,8 +25,8 @@ class ScratchBuffers { // A device-local allocation for a chunk; null on failure. using Allocate = std::function; - ScratchBuffers(PFN_vkGetDeviceProcAddr get, VkDevice device, Allocate allocate) - : device_(device), allocate_(std::move(allocate)) { + ScratchBuffers(PFN_vkGetDeviceProcAddr get, VkDevice device, Allocate allocate, VkBufferUsageFlags extra_usage = 0) + : device_(device), allocate_(std::move(allocate)), extra_usage_(extra_usage) { loaded_ = vk_.load(get, device); } @@ -148,7 +150,7 @@ class ScratchBuffers { bool make_chunk(std::uint64_t size, Chunk& out) { VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; info.size = size; - info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; + info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | extra_usage_; if (vk_.vkCreateBuffer(device_, &info, nullptr, &out.buffer) != VK_SUCCESS) return false; VkMemoryRequirements requirements{}; vk_.vkGetBufferMemoryRequirements(device_, out.buffer, &requirements); @@ -172,6 +174,7 @@ class ScratchBuffers { VkDevice device_; Allocate allocate_; + VkBufferUsageFlags extra_usage_ = 0; Functions vk_; bool loaded_ = false; Batch current_; // handed out, not yet submitted diff --git a/runtime/test/vulkan_scratch_test.cpp b/runtime/test/vulkan_scratch_test.cpp index 8ca6a819a3..1d8e20d552 100644 --- a/runtime/test/vulkan_scratch_test.cpp +++ b/runtime/test/vulkan_scratch_test.cpp @@ -1,5 +1,6 @@ // Unit tests for ScratchBuffers (runtime/src/vulkan_scratch.h). CPU-only, no Vulkan instance and no GPU: -// synthetic device procs exercise alignment, minimum chunk size, failure cleanup, retire/collect/forget, and spare cap. +// synthetic device procs exercise alignment, minimum chunk size, failure cleanup, retire/collect/forget, spare cap, +// and the usage a chunk is created with. #ifndef VK_NO_PROTOTYPES #define VK_NO_PROTOTYPES #endif @@ -37,6 +38,7 @@ struct FakeVulkan { int free_memory_calls = 0; int wait_idle_calls = 0; int get_counter_calls = 0; + VkBufferUsageFlags last_usage = 0; // of the last chunk created VkResult create_buffer_result = VK_SUCCESS; VkResult bind_result = VK_SUCCESS; @@ -55,6 +57,7 @@ VKAPI_ATTR VkResult VKAPI_CALL fake_create_buffer( if (g_vk->create_buffer_result != VK_SUCCESS) return g_vk->create_buffer_result; const std::uintptr_t id = g_vk->next_buffer++; g_vk->live_buffers[id] = info->size; + g_vk->last_usage = info->usage; *out = make_handle(id); return VK_SUCCESS; } @@ -289,6 +292,27 @@ int main() { EXPECT(vk.live_buffers.empty() && vk.live_memory.empty()); } + // A chunk is a transfer source and destination, plus whatever usage the owner asks for (the expanded indices of + // quad lists are an index buffer written through its device address). + { + FakeVulkan vk; + g_vk = &vk; + constexpr VkBufferUsageFlags transfer = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; + constexpr VkBufferUsageFlags extra = + VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + VkBuffer buf = VK_NULL_HANDLE; + VkDeviceSize off = 0; + { + ScratchBuffers scratch(fake_get_device_proc, k_device, fake_allocate); + EXPECT(scratch.get(256, buf, off) && vk.last_usage == transfer); + } + { + ScratchBuffers scratch(fake_get_device_proc, k_device, fake_allocate, extra); + EXPECT(scratch.get(256, buf, off) && vk.last_usage == (transfer | extra)); + } + EXPECT(vk.live_buffers.empty() && vk.live_memory.empty()); + } + std::printf("vulkan_scratch: all checks passed\n"); return 0; } From a9fb8058aa14d7686c6af11d1b14064924fe50d2 Mon Sep 17 00:00:00 2001 From: QemmHD <290605352+QemmHD@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:09:17 -0500 Subject: [PATCH 068/110] d3d12: indexed quad lists draw from triangle indices a compute pass expands on the GPU (OLD-9940) An indexed quad list was one triangle fan per quad over the application's index buffer. That is wrong in two ways, both measured on #207 (RTX 4070 Ti there, RTX 4070 SUPER here): - A fan's triangles are (v1 v2 v0) and (v2 v3 v0), and Vulkan takes a flat input from a triangle's first vertex. So a quad showed its second and third vertex, never its first: a quad with a red first vertex came out black and blue, 0 of 4096 pixels red. - One draw per quad runs every instance of quad 0 before quad 1. D3D12 draws instance by instance, so where instances overlap the wrong one ended on top (2048 of 4096 pixels). Neither can be fixed inside that scheme (VK_EXT_provoking_vertex cannot name a fan's hub either), so the indices are rewritten: a compute pass (quad_index_expand.comp) reads the application's index buffer on the GPU and writes (i0 i1 i2) (i0 i2 i3) for each quad as 32-bit indices into copy scratch, and the draw is one indexed triangle list over that scratch with the application's instance count, base vertex and first instance. Both triangles start at the quad's first vertex, like the non-indexed path. - The host never reads the indices: a copy or a shader earlier in the list can have written them. The pass runs before the draw's rendering scope, between a barrier for those writes and one for its own, and between two segments of an active pipeline-statistics query, as the other helper dispatches do (D3D-162). - 16-bit and 32-bit indices, read as whole words, so a 16-bit view at an address of 2 modulo 4 works. Index values are copied as they are: VertexIndex - BaseVertex is still the application's index. - The strip-cut values are ordinary indices, as in every list topology. An index past the view reads 0, as in D3D12, and the pass reads nothing past the view. A draw's last one to three indices are dropped. - It needs bufferDeviceAddress. Without it, or inside a statistics query that cannot be split, the list is refused as unsupported. - vulkan_topology(19) is a triangle list for both paths; nothing draws a fan any more (MoltenVK has no fans). replay_quad_list_test replays indexed draws through prepare() and the real expander on a recording device: one dispatch before the rendering scope and one draw in it, the push constants for both index sizes, the view's end, the split of a draw larger than one dispatch, the refusals, and the order inside a statistics query. AI-assisted (Claude Code; Claude Opus 5.5 and Claude Fable 5.2). Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01SR1Fv7eQNgZjM6miWPKjHf --- runtime/shims/d3d12_vulkan_device.cpp | 15 +- runtime/src/quad_index_expand.comp | 44 ++++ runtime/src/quad_index_expand.h | 182 ++++++++++++++ runtime/src/quad_index_expand_spv.h | 148 +++++++++++ runtime/src/vulkan_backend.h | 29 ++- runtime/src/vulkan_replay.h | 97 ++++++-- runtime/test/replay_quad_list_test.cpp | 328 +++++++++++++++++++++++-- 7 files changed, 802 insertions(+), 41 deletions(-) create mode 100644 runtime/src/quad_index_expand.comp create mode 100644 runtime/src/quad_index_expand.h create mode 100644 runtime/src/quad_index_expand_spv.h diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index bf5c58d40a..b88a372e70 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -5190,16 +5190,23 @@ class Device final if (info.host_pointer_alignment) state_.get_host_pointer_properties = reinterpret_cast( get_device(info.device, "vkGetMemoryHostPointerPropertiesEXT")); - // Depth <-> colour copies are staged through scratch buffers (vulkan_scratch.h), on every GPU. - state_.context->enable_copy_scratch(get_device, [this](const VkMemoryRequirements& requirements) { - return state_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); - }); + // Depth <-> colour copies are staged through scratch buffers (vulkan_scratch.h), on every GPU. With buffer + // device addresses the same scratch holds the triangle indices of indexed quad lists (quad_index_expand.h): + // a compute pass writes them through the chunk's address and the draw binds the chunk as its index buffer. + const bool index_scratch = info.buffer_device_address; + state_.context->enable_copy_scratch( + get_device, + [this, index_scratch](const VkMemoryRequirements& requirements) { + return state_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, nullptr, index_scratch); + }, + index_scratch ? VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT : 0); if (info.buffer_device_address && info.physical && info.get_instance_proc) { if (const auto get_props = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties"))) { VkPhysicalDeviceProperties props{}; get_props(info.physical, &props); state_.context->configure_counted_dispatch(get_device, state_.memory, props.limits); + state_.context->configure_quad_indices(get_device, props.limits); } } // The copies of a D24 texture stored as D32 convert on the GPU (vulkan_depth24.h), and so do the copies of diff --git a/runtime/src/quad_index_expand.comp b/runtime/src/quad_index_expand.comp new file mode 100644 index 0000000000..697cf7665d --- /dev/null +++ b/runtime/src/quad_index_expand.comp @@ -0,0 +1,44 @@ +// Expand the index buffer of a console quad list into triangle-list indices without reading it on the CPU +// (quad_index_expand.h). Each quad (i0 i1 i2 i3) becomes (i0 i1 i2) (i0 i2 i3) as six 32-bit indices: both +// triangles start at the quad's first vertex, the one a flat input is taken from. +#version 460 +#extension GL_EXT_buffer_reference : require +layout(local_size_x = 64) in; +layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer WordsIn { + uint data[]; +}; +layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer WordsOut { + uint data[]; +}; +layout(push_constant) uniform Params { + WordsIn source; // the 4-byte aligned word that holds this dispatch's first index + WordsOut triangles; // six words for each quad of this dispatch + uint first_half; // 16-bit indices: 1 when the first index is the high half of its word + uint index_bits; // 16 or 32 + uint limit; // how many of this dispatch's indices the index buffer view holds; the rest read 0 + uint quads; +} p; + +uint index_at(uint i) { + if (i >= p.limit) return 0u; + if (p.index_bits == 32u) return p.source.data[i]; + const uint slot = i + p.first_half; + return (p.source.data[slot >> 1u] >> ((slot & 1u) * 16u)) & 0xffffu; +} + +void main() { + const uint quad = gl_GlobalInvocationID.x; + if (quad >= p.quads) return; + const uint first = quad * 4u; + const uint i0 = index_at(first); + const uint i1 = index_at(first + 1u); + const uint i2 = index_at(first + 2u); + const uint i3 = index_at(first + 3u); + const uint target = quad * 6u; + p.triangles.data[target] = i0; + p.triangles.data[target + 1u] = i1; + p.triangles.data[target + 2u] = i2; + p.triangles.data[target + 3u] = i0; + p.triangles.data[target + 4u] = i2; + p.triangles.data[target + 5u] = i3; +} diff --git a/runtime/src/quad_index_expand.h b/runtime/src/quad_index_expand.h new file mode 100644 index 0000000000..3c539a5406 --- /dev/null +++ b/runtime/src/quad_index_expand.h @@ -0,0 +1,182 @@ +// Indexed console quad lists (D3D_PRIMITIVE_TOPOLOGY 19) on Vulkan, which has no quad primitive. +// +// A quad is four indices and Vulkan can only draw it as triangles. A triangle fan per quad reads the application's +// index buffer in place, but gets two things wrong: a fan takes a flat input from each triangle's own first vertex +// (the quad's second and third), where the quad takes it from its first, and one draw per quad runs every instance +// of quad 0 before quad 1, where D3D12 draws instance by instance (visible when instances overlap). So the indices +// are rewritten instead: a compute pass (quad_index_expand.comp) reads the application's index buffer on the GPU and +// writes (i0 i1 i2) (i0 i2 i3) for each quad as 32-bit indices into scratch that lives until the submission +// completes (vulkan_scratch.h), and the draw is one indexed triangle list over that scratch with the application's +// instance count, base vertex and first instance. Both triangles start at the quad's first vertex, so a flat input +// is the first vertex's over the whole quad, and one draw keeps D3D12's instance order. +// +// The indices are read on the GPU, never on the host: an index buffer can be written by a copy or a shader earlier +// in the same list. Index values are copied as they are (a 16-bit index is zero-extended), so VertexIndex - +// BaseVertex is still the application's index. That includes the strip-cut value: 0xFFFF and 0xFFFFFFFF are +// ordinary indices in a quad list, as in every list topology (the replay enables primitive restart for strips only), +// and 0xFFFF stays vertex 65535 after the widening. An index past the end of the index buffer view reads 0, as +// D3D12 defines it, and a draw's last one to three indices that do not make a quad are dropped. +// +// Needs bufferDeviceAddress (the pass reads and writes through device addresses, no descriptors) and scratch with +// INDEX_BUFFER and SHADER_DEVICE_ADDRESS usage. Non-indexed quad lists do not come here: they draw from a shared +// constant index buffer (ReplayFunctions::quad_indices). +#pragma once +#ifndef VK_NO_PROTOTYPES +#define VK_NO_PROTOTYPES +#endif +#include +#include +#include +#include "quad_index_expand_spv.h" + +namespace leonida { + +// One indexed quad-list draw's expansion. `buffer` is null for a draw that needs none. +struct QuadIndexExpansion { + VkBuffer buffer = VK_NULL_HANDLE; // the triangle-list indices, 32-bit: six for each quad + VkDeviceSize offset = 0; + VkDeviceAddress source = 0; // the 4-byte aligned word that holds the draw's first index + VkDeviceAddress triangles = 0; // `buffer` + `offset` + std::uint64_t readable = 0; // indices from the draw's first one that the index buffer view holds + std::uint32_t first_half = 0; // 16-bit indices: 1 when the first index is the high half of its word + std::uint32_t index_bits = 0; // 16 or 32 + std::uint32_t quads = 0; +}; + +class QuadIndexExpander { +public: + static constexpr std::uint32_t indices_per_quad = 6; + // vkCmdDrawIndexed counts the expanded indices in 32 bits. + static constexpr std::uint32_t max_quads = UINT32_MAX / indices_per_quad; + // The scratch bytes `quads` quads expand into. + static constexpr VkDeviceSize bytes(std::uint32_t quads) { + return VkDeviceSize(quads) * indices_per_quad * sizeof(std::uint32_t); + } + + QuadIndexExpander(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceLimits& limits) + : get_(get), device_(device), limits_(limits) {} + ~QuadIndexExpander() { + if (pipeline_) fn("vkDestroyPipeline")(device_, pipeline_, nullptr); + if (layout_) fn("vkDestroyPipelineLayout")(device_, layout_, nullptr); + } + QuadIndexExpander(const QuadIndexExpander&) = delete; + QuadIndexExpander& operator=(const QuadIndexExpander&) = delete; + + // `quads` quads from the indices at `index_offset` in `indices` (the draw's first index), of which the view holds + // `readable`, into bytes(quads) of `scratch` at `scratch_offset`. The pipeline is made on the first call; the + // caller serializes calls. False, with `out` cleared, when the draw cannot be expanded. + bool prepare(VkBuffer indices, VkDeviceSize index_offset, VkIndexType type, std::uint64_t readable, + std::uint32_t quads, VkBuffer scratch, VkDeviceSize scratch_offset, QuadIndexExpansion& out) { + out = {}; + const std::uint32_t index_bytes = type == VK_INDEX_TYPE_UINT16 ? 2 : type == VK_INDEX_TYPE_UINT32 ? 4 : 0; + if (!indices || !scratch || !index_bytes || !quads || quads > max_quads || index_offset % index_bytes || + scratch_offset % sizeof(std::uint32_t) || !limits_.maxComputeWorkGroupCount[0] || !make_pipeline()) + return false; + const auto address = fn("vkGetBufferDeviceAddress"); + VkBufferDeviceAddressInfo info{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; + info.buffer = indices; + const VkDeviceAddress source = address(device_, &info); + info.buffer = scratch; + const VkDeviceAddress target = address(device_, &info); + if (!source || !target || index_offset > UINT64_MAX - source || scratch_offset > UINT64_MAX - target || + (source % sizeof(std::uint32_t)) || (target % sizeof(std::uint32_t))) + return false; + out.buffer = scratch; + out.offset = scratch_offset; + // The shader reads whole words: a 16-bit index at an address of 2 modulo 4 is the high half of its word. + out.source = (source + index_offset) & ~VkDeviceAddress(3); + out.first_half = std::uint32_t((index_offset & 3) / 2); + out.triangles = target + scratch_offset; + out.readable = readable; + out.index_bits = index_bytes * 8; + out.quads = quads; + return true; + } + + // Records the pass: outside a render pass, before the draw that binds job.buffer as its index buffer. + void emit(VkCommandBuffer cb, const QuadIndexExpansion& job) const { + const auto barrier = fn("vkCmdPipelineBarrier"); + // Whatever wrote the application's indices earlier in the command buffer (a copy, a shader) is visible. + VkMemoryBarrier before{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + before.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT; + before.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; + barrier(cb, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + 0, 1, &before, 0, nullptr, 0, nullptr); + fn("vkCmdBindPipeline")(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_); + struct Push { + VkDeviceAddress source, triangles; + std::uint32_t first_half, index_bits, limit, quads; + }; + static_assert(sizeof(Push) == push_bytes); + // A dispatch indexes its quads and their indices in 32 bits: 4 * quad + 4 and 6 * quad + 5 must fit. + constexpr VkDeviceSize index_limit = 1u << 28; + const VkDeviceSize chunk_limit = + std::min(VkDeviceSize(limits_.maxComputeWorkGroupCount[0]) * group_size, index_limit); + for (VkDeviceSize first = 0; first < job.quads;) { + const std::uint32_t quads = std::uint32_t(std::min(chunk_limit, job.quads - first)); + const VkDeviceSize first_index = first * 4; + // 16-bit indices: `first_index` is even, so the chunk starts at the same half of a word as the draw. + const VkDeviceSize source_bytes = first_index * (job.index_bits / 8); + const std::uint64_t left = job.readable > first_index ? job.readable - first_index : 0; + const Push push{job.source + source_bytes, job.triangles + first * indices_per_quad * 4, + job.first_half, job.index_bits, std::uint32_t(std::min(left, UINT32_MAX)), + quads}; + fn("vkCmdPushConstants")(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, + sizeof(push), &push); + fn("vkCmdDispatch")(cb, (quads - 1u) / group_size + 1u, 1, 1); + first += quads; + } + VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + after.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; + after.dstAccessMask = VK_ACCESS_INDEX_READ_BIT; + barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, + 0, 1, &after, 0, nullptr, 0, nullptr); + } + +private: + static constexpr std::uint32_t group_size = 64; // local_size_x of quad_index_expand.comp + static constexpr std::uint32_t push_bytes = 32; + template T fn(const char* name) const { return reinterpret_cast(get_(device_, name)); } + bool make_pipeline() { + if (pipeline_) return true; + for (const char* name : {"vkGetBufferDeviceAddress", "vkCreateShaderModule", "vkDestroyShaderModule", + "vkCreatePipelineLayout", "vkDestroyPipelineLayout", "vkCreateComputePipelines", "vkDestroyPipeline", + "vkCmdPipelineBarrier", "vkCmdBindPipeline", "vkCmdPushConstants", "vkCmdDispatch"}) + if (!get_(device_, name)) return false; + VkShaderModule module = VK_NULL_HANDLE; + VkPipelineLayout layout = VK_NULL_HANDLE; + VkPipeline pipeline = VK_NULL_HANDLE; + VkShaderModuleCreateInfo shader{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + shader.codeSize = sizeof(quad_index_expand_spirv); + shader.pCode = quad_index_expand_spirv; + bool ok = fn("vkCreateShaderModule")(device_, &shader, nullptr, &module) == VK_SUCCESS; + const VkPushConstantRange range{VK_SHADER_STAGE_COMPUTE_BIT, 0, push_bytes}; + VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + layout_info.pushConstantRangeCount = 1; + layout_info.pPushConstantRanges = ⦥ + ok = ok && fn("vkCreatePipelineLayout")(device_, &layout_info, nullptr, &layout) == VK_SUCCESS; + VkComputePipelineCreateInfo info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; + info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; + info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; + info.stage.module = module; + info.stage.pName = "main"; + info.layout = layout; + ok = ok && fn("vkCreateComputePipelines")( + device_, VK_NULL_HANDLE, 1, &info, nullptr, &pipeline) == VK_SUCCESS; + if (module) fn("vkDestroyShaderModule")(device_, module, nullptr); + if (!ok) { + if (pipeline) fn("vkDestroyPipeline")(device_, pipeline, nullptr); + if (layout) fn("vkDestroyPipelineLayout")(device_, layout, nullptr); + return false; + } + layout_ = layout; + pipeline_ = pipeline; + return true; + } + PFN_vkGetDeviceProcAddr get_; + VkDevice device_; + VkPhysicalDeviceLimits limits_; + VkPipelineLayout layout_ = VK_NULL_HANDLE; + VkPipeline pipeline_ = VK_NULL_HANDLE; +}; +} // namespace leonida diff --git a/runtime/src/quad_index_expand_spv.h b/runtime/src/quad_index_expand_spv.h new file mode 100644 index 0000000000..c7bb4b5c5f --- /dev/null +++ b/runtime/src/quad_index_expand_spv.h @@ -0,0 +1,148 @@ +// Generated with glslang 16.6.0: glslangValidator -V --target-env vulkan1.2 -Os --spirv-val quad_index_expand.comp +#pragma once +#include +namespace leonida { +inline constexpr std::uint32_t quad_index_expand_spirv[] = { + 0x07230203u, 0x00010500u, 0x0008000bu, 0x00000149u, 0x00000000u, 0x00020011u, 0x00000001u, 0x00020011u, + 0x000014e3u, 0x0006000bu, 0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, + 0x000014e4u, 0x00000001u, 0x0007000fu, 0x00000005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00000015u, + 0x0000004au, 0x00060010u, 0x00000004u, 0x00000011u, 0x00000040u, 0x00000001u, 0x00000001u, 0x00030003u, + 0x00000002u, 0x000001ccu, 0x00070004u, 0x455f4c47u, 0x625f5458u, 0x65666675u, 0x65725f72u, 0x65726566u, + 0x0065636eu, 0x00040005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00040005u, 0x0000000fu, 0x61726150u, + 0x0000736du, 0x00050006u, 0x0000000fu, 0x00000000u, 0x72756f73u, 0x00006563u, 0x00060006u, 0x0000000fu, + 0x00000001u, 0x61697274u, 0x656c676eu, 0x00000073u, 0x00060006u, 0x0000000fu, 0x00000002u, 0x73726966u, + 0x61685f74u, 0x0000666cu, 0x00060006u, 0x0000000fu, 0x00000003u, 0x65646e69u, 0x69625f78u, 0x00007374u, + 0x00050006u, 0x0000000fu, 0x00000004u, 0x696d696cu, 0x00000074u, 0x00050006u, 0x0000000fu, 0x00000005u, + 0x64617571u, 0x00000073u, 0x00040005u, 0x00000011u, 0x64726f57u, 0x006e4973u, 0x00050006u, 0x00000011u, + 0x00000000u, 0x61746164u, 0x00000000u, 0x00050005u, 0x00000013u, 0x64726f57u, 0x74754f73u, 0x00000000u, + 0x00050006u, 0x00000013u, 0x00000000u, 0x61746164u, 0x00000000u, 0x00030005u, 0x00000015u, 0x00000070u, + 0x00080005u, 0x0000004au, 0x475f6c67u, 0x61626f6cu, 0x766e496cu, 0x7461636fu, 0x496e6f69u, 0x00000044u, + 0x00030047u, 0x0000000fu, 0x00000002u, 0x00050048u, 0x0000000fu, 0x00000000u, 0x00000023u, 0x00000000u, + 0x00050048u, 0x0000000fu, 0x00000001u, 0x00000023u, 0x00000008u, 0x00050048u, 0x0000000fu, 0x00000002u, + 0x00000023u, 0x00000010u, 0x00050048u, 0x0000000fu, 0x00000003u, 0x00000023u, 0x00000014u, 0x00050048u, + 0x0000000fu, 0x00000004u, 0x00000023u, 0x00000018u, 0x00050048u, 0x0000000fu, 0x00000005u, 0x00000023u, + 0x0000001cu, 0x00040047u, 0x00000010u, 0x00000006u, 0x00000004u, 0x00030047u, 0x00000011u, 0x00000002u, + 0x00040048u, 0x00000011u, 0x00000000u, 0x00000018u, 0x00050048u, 0x00000011u, 0x00000000u, 0x00000023u, + 0x00000000u, 0x00040047u, 0x00000012u, 0x00000006u, 0x00000004u, 0x00030047u, 0x00000013u, 0x00000002u, + 0x00040048u, 0x00000013u, 0x00000000u, 0x00000019u, 0x00050048u, 0x00000013u, 0x00000000u, 0x00000023u, + 0x00000000u, 0x00040047u, 0x0000004au, 0x0000000bu, 0x0000001cu, 0x00040047u, 0x0000009au, 0x0000000bu, + 0x00000019u, 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u, 0x00040015u, 0x00000006u, + 0x00000020u, 0x00000000u, 0x00030027u, 0x0000000du, 0x000014e5u, 0x00030027u, 0x0000000eu, 0x000014e5u, + 0x0008001eu, 0x0000000fu, 0x0000000du, 0x0000000eu, 0x00000006u, 0x00000006u, 0x00000006u, 0x00000006u, + 0x0003001du, 0x00000010u, 0x00000006u, 0x0003001eu, 0x00000011u, 0x00000010u, 0x00040020u, 0x0000000du, + 0x000014e5u, 0x00000011u, 0x0003001du, 0x00000012u, 0x00000006u, 0x0003001eu, 0x00000013u, 0x00000012u, + 0x00040020u, 0x0000000eu, 0x000014e5u, 0x00000013u, 0x00040020u, 0x00000014u, 0x00000009u, 0x0000000fu, + 0x0004003bu, 0x00000014u, 0x00000015u, 0x00000009u, 0x00040015u, 0x00000016u, 0x00000020u, 0x00000001u, + 0x0004002bu, 0x00000016u, 0x00000017u, 0x00000004u, 0x00040020u, 0x00000018u, 0x00000009u, 0x00000006u, + 0x00020014u, 0x0000001bu, 0x0004002bu, 0x00000006u, 0x0000001fu, 0x00000000u, 0x0004002bu, 0x00000016u, + 0x00000021u, 0x00000003u, 0x0004002bu, 0x00000006u, 0x00000024u, 0x00000020u, 0x0004002bu, 0x00000016u, + 0x00000028u, 0x00000000u, 0x00040020u, 0x00000029u, 0x00000009u, 0x0000000du, 0x00040020u, 0x0000002du, + 0x000014e5u, 0x00000006u, 0x0004002bu, 0x00000016u, 0x00000033u, 0x00000002u, 0x0004002bu, 0x00000006u, + 0x0000003au, 0x00000001u, 0x0004002bu, 0x00000006u, 0x00000040u, 0x00000010u, 0x0004002bu, 0x00000006u, + 0x00000043u, 0x0000ffffu, 0x00040017u, 0x00000048u, 0x00000006u, 0x00000003u, 0x00040020u, 0x00000049u, + 0x00000001u, 0x00000048u, 0x0004003bu, 0x00000049u, 0x0000004au, 0x00000001u, 0x00040020u, 0x0000004bu, + 0x00000001u, 0x00000006u, 0x0004002bu, 0x00000016u, 0x0000004fu, 0x00000005u, 0x0004002bu, 0x00000006u, + 0x00000058u, 0x00000004u, 0x0004002bu, 0x00000006u, 0x00000065u, 0x00000002u, 0x0004002bu, 0x00000006u, + 0x0000006bu, 0x00000003u, 0x0004002bu, 0x00000006u, 0x00000071u, 0x00000006u, 0x0004002bu, 0x00000016u, + 0x00000073u, 0x00000001u, 0x00040020u, 0x00000074u, 0x00000009u, 0x0000000eu, 0x0004002bu, 0x00000006u, + 0x00000095u, 0x00000005u, 0x0004002bu, 0x00000006u, 0x00000099u, 0x00000040u, 0x0006002cu, 0x00000048u, + 0x0000009au, 0x00000099u, 0x0000003au, 0x0000003au, 0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u, + 0x00000003u, 0x000200f8u, 0x00000005u, 0x000300f7u, 0x0000009bu, 0x00000000u, 0x000300fbu, 0x0000001fu, + 0x0000009cu, 0x000200f8u, 0x0000009cu, 0x00050041u, 0x0000004bu, 0x0000004cu, 0x0000004au, 0x0000001fu, + 0x0004003du, 0x00000006u, 0x0000004du, 0x0000004cu, 0x00050041u, 0x00000018u, 0x00000050u, 0x00000015u, + 0x0000004fu, 0x0004003du, 0x00000006u, 0x00000051u, 0x00000050u, 0x000500aeu, 0x0000001bu, 0x00000052u, + 0x0000004du, 0x00000051u, 0x000300f7u, 0x00000054u, 0x00000000u, 0x000400fau, 0x00000052u, 0x00000053u, + 0x00000054u, 0x000200f8u, 0x00000053u, 0x000200f9u, 0x0000009bu, 0x000200f8u, 0x00000054u, 0x00050084u, + 0x00000006u, 0x00000059u, 0x0000004du, 0x00000058u, 0x000300f7u, 0x000000cbu, 0x00000000u, 0x000300fbu, + 0x0000001fu, 0x000000abu, 0x000200f8u, 0x000000abu, 0x00050041u, 0x00000018u, 0x000000adu, 0x00000015u, + 0x00000017u, 0x0004003du, 0x00000006u, 0x000000aeu, 0x000000adu, 0x000500aeu, 0x0000001bu, 0x000000afu, + 0x00000059u, 0x000000aeu, 0x000300f7u, 0x000000b1u, 0x00000000u, 0x000400fau, 0x000000afu, 0x000000b0u, + 0x000000b1u, 0x000200f8u, 0x000000b0u, 0x000200f9u, 0x000000cbu, 0x000200f8u, 0x000000b1u, 0x00050041u, + 0x00000018u, 0x000000b2u, 0x00000015u, 0x00000021u, 0x0004003du, 0x00000006u, 0x000000b3u, 0x000000b2u, + 0x000500aau, 0x0000001bu, 0x000000b4u, 0x000000b3u, 0x00000024u, 0x000300f7u, 0x000000bbu, 0x00000000u, + 0x000400fau, 0x000000b4u, 0x000000b5u, 0x000000bbu, 0x000200f8u, 0x000000b5u, 0x00050041u, 0x00000029u, + 0x000000b6u, 0x00000015u, 0x00000028u, 0x0004003du, 0x0000000du, 0x000000b7u, 0x000000b6u, 0x00060041u, + 0x0000002du, 0x000000b9u, 0x000000b7u, 0x00000028u, 0x00000059u, 0x0006003du, 0x00000006u, 0x000000bau, + 0x000000b9u, 0x00000002u, 0x00000004u, 0x000200f9u, 0x000000cbu, 0x000200f8u, 0x000000bbu, 0x00050041u, + 0x00000018u, 0x000000bdu, 0x00000015u, 0x00000033u, 0x0004003du, 0x00000006u, 0x000000beu, 0x000000bdu, + 0x00050080u, 0x00000006u, 0x000000bfu, 0x00000059u, 0x000000beu, 0x00050041u, 0x00000029u, 0x000000c0u, + 0x00000015u, 0x00000028u, 0x0004003du, 0x0000000du, 0x000000c1u, 0x000000c0u, 0x000500c2u, 0x00000006u, + 0x000000c3u, 0x000000bfu, 0x0000003au, 0x00060041u, 0x0000002du, 0x000000c4u, 0x000000c1u, 0x00000028u, + 0x000000c3u, 0x0006003du, 0x00000006u, 0x000000c5u, 0x000000c4u, 0x00000002u, 0x00000004u, 0x000500c7u, + 0x00000006u, 0x000000c7u, 0x000000bfu, 0x0000003au, 0x00050084u, 0x00000006u, 0x000000c8u, 0x000000c7u, + 0x00000040u, 0x000500c2u, 0x00000006u, 0x000000c9u, 0x000000c5u, 0x000000c8u, 0x000500c7u, 0x00000006u, + 0x000000cau, 0x000000c9u, 0x00000043u, 0x000200f9u, 0x000000cbu, 0x000200f8u, 0x000000cbu, 0x000900f5u, + 0x00000006u, 0x00000142u, 0x0000001fu, 0x000000b0u, 0x000000bau, 0x000000b5u, 0x000000cau, 0x000000bbu, + 0x00050080u, 0x00000006u, 0x00000060u, 0x00000059u, 0x0000003au, 0x000300f7u, 0x000000f2u, 0x00000000u, + 0x000300fbu, 0x0000001fu, 0x000000d2u, 0x000200f8u, 0x000000d2u, 0x000500aeu, 0x0000001bu, 0x000000d6u, + 0x00000060u, 0x000000aeu, 0x000300f7u, 0x000000d8u, 0x00000000u, 0x000400fau, 0x000000d6u, 0x000000d7u, + 0x000000d8u, 0x000200f8u, 0x000000d7u, 0x000200f9u, 0x000000f2u, 0x000200f8u, 0x000000d8u, 0x00050041u, + 0x00000018u, 0x000000d9u, 0x00000015u, 0x00000021u, 0x0004003du, 0x00000006u, 0x000000dau, 0x000000d9u, + 0x000500aau, 0x0000001bu, 0x000000dbu, 0x000000dau, 0x00000024u, 0x000300f7u, 0x000000e2u, 0x00000000u, + 0x000400fau, 0x000000dbu, 0x000000dcu, 0x000000e2u, 0x000200f8u, 0x000000dcu, 0x00050041u, 0x00000029u, + 0x000000ddu, 0x00000015u, 0x00000028u, 0x0004003du, 0x0000000du, 0x000000deu, 0x000000ddu, 0x00060041u, + 0x0000002du, 0x000000e0u, 0x000000deu, 0x00000028u, 0x00000060u, 0x0006003du, 0x00000006u, 0x000000e1u, + 0x000000e0u, 0x00000002u, 0x00000004u, 0x000200f9u, 0x000000f2u, 0x000200f8u, 0x000000e2u, 0x00050041u, + 0x00000018u, 0x000000e4u, 0x00000015u, 0x00000033u, 0x0004003du, 0x00000006u, 0x000000e5u, 0x000000e4u, + 0x00050080u, 0x00000006u, 0x000000e6u, 0x00000060u, 0x000000e5u, 0x00050041u, 0x00000029u, 0x000000e7u, + 0x00000015u, 0x00000028u, 0x0004003du, 0x0000000du, 0x000000e8u, 0x000000e7u, 0x000500c2u, 0x00000006u, + 0x000000eau, 0x000000e6u, 0x0000003au, 0x00060041u, 0x0000002du, 0x000000ebu, 0x000000e8u, 0x00000028u, + 0x000000eau, 0x0006003du, 0x00000006u, 0x000000ecu, 0x000000ebu, 0x00000002u, 0x00000004u, 0x000500c7u, + 0x00000006u, 0x000000eeu, 0x000000e6u, 0x0000003au, 0x00050084u, 0x00000006u, 0x000000efu, 0x000000eeu, + 0x00000040u, 0x000500c2u, 0x00000006u, 0x000000f0u, 0x000000ecu, 0x000000efu, 0x000500c7u, 0x00000006u, + 0x000000f1u, 0x000000f0u, 0x00000043u, 0x000200f9u, 0x000000f2u, 0x000200f8u, 0x000000f2u, 0x000900f5u, + 0x00000006u, 0x00000144u, 0x0000001fu, 0x000000d7u, 0x000000e1u, 0x000000dcu, 0x000000f1u, 0x000000e2u, + 0x00050080u, 0x00000006u, 0x00000066u, 0x00000059u, 0x00000065u, 0x000300f7u, 0x00000119u, 0x00000000u, + 0x000300fbu, 0x0000001fu, 0x000000f9u, 0x000200f8u, 0x000000f9u, 0x000500aeu, 0x0000001bu, 0x000000fdu, + 0x00000066u, 0x000000aeu, 0x000300f7u, 0x000000ffu, 0x00000000u, 0x000400fau, 0x000000fdu, 0x000000feu, + 0x000000ffu, 0x000200f8u, 0x000000feu, 0x000200f9u, 0x00000119u, 0x000200f8u, 0x000000ffu, 0x00050041u, + 0x00000018u, 0x00000100u, 0x00000015u, 0x00000021u, 0x0004003du, 0x00000006u, 0x00000101u, 0x00000100u, + 0x000500aau, 0x0000001bu, 0x00000102u, 0x00000101u, 0x00000024u, 0x000300f7u, 0x00000109u, 0x00000000u, + 0x000400fau, 0x00000102u, 0x00000103u, 0x00000109u, 0x000200f8u, 0x00000103u, 0x00050041u, 0x00000029u, + 0x00000104u, 0x00000015u, 0x00000028u, 0x0004003du, 0x0000000du, 0x00000105u, 0x00000104u, 0x00060041u, + 0x0000002du, 0x00000107u, 0x00000105u, 0x00000028u, 0x00000066u, 0x0006003du, 0x00000006u, 0x00000108u, + 0x00000107u, 0x00000002u, 0x00000004u, 0x000200f9u, 0x00000119u, 0x000200f8u, 0x00000109u, 0x00050041u, + 0x00000018u, 0x0000010bu, 0x00000015u, 0x00000033u, 0x0004003du, 0x00000006u, 0x0000010cu, 0x0000010bu, + 0x00050080u, 0x00000006u, 0x0000010du, 0x00000066u, 0x0000010cu, 0x00050041u, 0x00000029u, 0x0000010eu, + 0x00000015u, 0x00000028u, 0x0004003du, 0x0000000du, 0x0000010fu, 0x0000010eu, 0x000500c2u, 0x00000006u, + 0x00000111u, 0x0000010du, 0x0000003au, 0x00060041u, 0x0000002du, 0x00000112u, 0x0000010fu, 0x00000028u, + 0x00000111u, 0x0006003du, 0x00000006u, 0x00000113u, 0x00000112u, 0x00000002u, 0x00000004u, 0x000500c7u, + 0x00000006u, 0x00000115u, 0x0000010du, 0x0000003au, 0x00050084u, 0x00000006u, 0x00000116u, 0x00000115u, + 0x00000040u, 0x000500c2u, 0x00000006u, 0x00000117u, 0x00000113u, 0x00000116u, 0x000500c7u, 0x00000006u, + 0x00000118u, 0x00000117u, 0x00000043u, 0x000200f9u, 0x00000119u, 0x000200f8u, 0x00000119u, 0x000900f5u, + 0x00000006u, 0x00000146u, 0x0000001fu, 0x000000feu, 0x00000108u, 0x00000103u, 0x00000118u, 0x00000109u, + 0x00050080u, 0x00000006u, 0x0000006cu, 0x00000059u, 0x0000006bu, 0x000300f7u, 0x00000140u, 0x00000000u, + 0x000300fbu, 0x0000001fu, 0x00000120u, 0x000200f8u, 0x00000120u, 0x000500aeu, 0x0000001bu, 0x00000124u, + 0x0000006cu, 0x000000aeu, 0x000300f7u, 0x00000126u, 0x00000000u, 0x000400fau, 0x00000124u, 0x00000125u, + 0x00000126u, 0x000200f8u, 0x00000125u, 0x000200f9u, 0x00000140u, 0x000200f8u, 0x00000126u, 0x00050041u, + 0x00000018u, 0x00000127u, 0x00000015u, 0x00000021u, 0x0004003du, 0x00000006u, 0x00000128u, 0x00000127u, + 0x000500aau, 0x0000001bu, 0x00000129u, 0x00000128u, 0x00000024u, 0x000300f7u, 0x00000130u, 0x00000000u, + 0x000400fau, 0x00000129u, 0x0000012au, 0x00000130u, 0x000200f8u, 0x0000012au, 0x00050041u, 0x00000029u, + 0x0000012bu, 0x00000015u, 0x00000028u, 0x0004003du, 0x0000000du, 0x0000012cu, 0x0000012bu, 0x00060041u, + 0x0000002du, 0x0000012eu, 0x0000012cu, 0x00000028u, 0x0000006cu, 0x0006003du, 0x00000006u, 0x0000012fu, + 0x0000012eu, 0x00000002u, 0x00000004u, 0x000200f9u, 0x00000140u, 0x000200f8u, 0x00000130u, 0x00050041u, + 0x00000018u, 0x00000132u, 0x00000015u, 0x00000033u, 0x0004003du, 0x00000006u, 0x00000133u, 0x00000132u, + 0x00050080u, 0x00000006u, 0x00000134u, 0x0000006cu, 0x00000133u, 0x00050041u, 0x00000029u, 0x00000135u, + 0x00000015u, 0x00000028u, 0x0004003du, 0x0000000du, 0x00000136u, 0x00000135u, 0x000500c2u, 0x00000006u, + 0x00000138u, 0x00000134u, 0x0000003au, 0x00060041u, 0x0000002du, 0x00000139u, 0x00000136u, 0x00000028u, + 0x00000138u, 0x0006003du, 0x00000006u, 0x0000013au, 0x00000139u, 0x00000002u, 0x00000004u, 0x000500c7u, + 0x00000006u, 0x0000013cu, 0x00000134u, 0x0000003au, 0x00050084u, 0x00000006u, 0x0000013du, 0x0000013cu, + 0x00000040u, 0x000500c2u, 0x00000006u, 0x0000013eu, 0x0000013au, 0x0000013du, 0x000500c7u, 0x00000006u, + 0x0000013fu, 0x0000013eu, 0x00000043u, 0x000200f9u, 0x00000140u, 0x000200f8u, 0x00000140u, 0x000900f5u, + 0x00000006u, 0x00000148u, 0x0000001fu, 0x00000125u, 0x0000012fu, 0x0000012au, 0x0000013fu, 0x00000130u, + 0x00050084u, 0x00000006u, 0x00000072u, 0x0000004du, 0x00000071u, 0x00050041u, 0x00000074u, 0x00000075u, + 0x00000015u, 0x00000073u, 0x0004003du, 0x0000000eu, 0x00000076u, 0x00000075u, 0x00060041u, 0x0000002du, + 0x00000079u, 0x00000076u, 0x00000028u, 0x00000072u, 0x0005003eu, 0x00000079u, 0x00000142u, 0x00000002u, + 0x00000004u, 0x00050080u, 0x00000006u, 0x0000007du, 0x00000072u, 0x0000003au, 0x00060041u, 0x0000002du, + 0x0000007fu, 0x00000076u, 0x00000028u, 0x0000007du, 0x0005003eu, 0x0000007fu, 0x00000144u, 0x00000002u, + 0x00000004u, 0x00050080u, 0x00000006u, 0x00000083u, 0x00000072u, 0x00000065u, 0x00060041u, 0x0000002du, + 0x00000085u, 0x00000076u, 0x00000028u, 0x00000083u, 0x0005003eu, 0x00000085u, 0x00000146u, 0x00000002u, + 0x00000004u, 0x00050080u, 0x00000006u, 0x00000089u, 0x00000072u, 0x0000006bu, 0x00060041u, 0x0000002du, + 0x0000008bu, 0x00000076u, 0x00000028u, 0x00000089u, 0x0005003eu, 0x0000008bu, 0x00000142u, 0x00000002u, + 0x00000004u, 0x00050080u, 0x00000006u, 0x0000008fu, 0x00000072u, 0x00000058u, 0x00060041u, 0x0000002du, + 0x00000091u, 0x00000076u, 0x00000028u, 0x0000008fu, 0x0005003eu, 0x00000091u, 0x00000146u, 0x00000002u, + 0x00000004u, 0x00050080u, 0x00000006u, 0x00000096u, 0x00000072u, 0x00000095u, 0x00060041u, 0x0000002du, + 0x00000098u, 0x00000076u, 0x00000028u, 0x00000096u, 0x0005003eu, 0x00000098u, 0x00000148u, 0x00000002u, + 0x00000004u, 0x000200f9u, 0x0000009bu, 0x000200f8u, 0x0000009bu, 0x000100fdu, 0x00010038u, +}; +} // namespace leonida diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 02fdad1a09..a041825c2a 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -1116,6 +1116,13 @@ class VulkanContext { std::unique_lock lock(resource_mutex_); counted_dispatch_ = std::make_unique(get, device_, memory, limits); } + // Indexed quad lists are drawn from triangle indices a compute pass writes into the copy scratch + // (quad_index_expand.h). Call only with bufferDeviceAddress enabled and after an enable_copy_scratch whose chunks + // have INDEX_BUFFER and SHADER_DEVICE_ADDRESS usage on memory allocated with a device address. + void configure_quad_indices(PFN_vkGetDeviceProcAddr get, const VkPhysicalDeviceLimits& limits) { + std::unique_lock lock(resource_mutex_); + quad_indices_ = std::make_unique(get, device_, limits); + } VkDevice device() const { return device_; } // Debug markers become labels from here on; call before any queue or list uses the context. Incomplete sets @@ -1413,10 +1420,12 @@ class VulkanContext { } // Copies the replay stages through a buffer (depth <-> colour, vulkan_replay.h) take device-local scratch from - // `allocate`. Without this such a copy is refused as unsupported. - void enable_copy_scratch(PFN_vkGetDeviceProcAddr get, ScratchBuffers::Allocate allocate) { + // `allocate`. Without this such a copy is refused as unsupported. `extra_usage` is added to the chunks' transfer + // usage, for configure_quad_indices. + void enable_copy_scratch(PFN_vkGetDeviceProcAddr get, ScratchBuffers::Allocate allocate, + VkBufferUsageFlags extra_usage = 0) { std::unique_lock lock(resource_mutex_); - scratch_ = std::make_unique(get, device_, std::move(allocate)); + scratch_ = std::make_unique(get, device_, std::move(allocate), extra_usage); if (!scratch_->loaded()) scratch_.reset(); } @@ -1723,6 +1732,7 @@ class VulkanContext { std::unique_ptr predicate_reducer_; std::unique_ptr predicated_copier_; std::unique_ptr counted_dispatch_; + std::unique_ptr quad_indices_; std::uint32_t predicate_family_ = UINT32_MAX; std::uint32_t transfer_only_family_ = UINT32_MAX; DebugLabelFunctions labels_; @@ -2379,6 +2389,19 @@ class VulkanQueue : private QueueHolds::Holder { context_.counted_dispatch_->emit(cb, job); }; } + if (kind_ != QueueKind::copy && context_.quad_indices_ && context_.scratch_) { + replay.prepare_quad_indices = [this, &tracker_lock]( + VkBuffer indices, VkDeviceSize offset, VkIndexType type, std::uint64_t readable, std::uint32_t quads, + VkBuffer scratch, VkDeviceSize scratch_offset, QuadIndexExpansion& out) { + // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation. + if (!tracker_lock.owns_lock()) tracker_lock.lock(); + return context_.quad_indices_->prepare(indices, offset, type, readable, quads, scratch, + scratch_offset, out); + }; + replay.emit_quad_indices = [this](VkCommandBuffer cb, const QuadIndexExpansion& job) { + context_.quad_indices_->emit(cb, job); + }; + } if (context_.depth24_ && !transfer_only) { replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job, std::vector& parts) { diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 5ffa65c95f..3225cffeb3 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -32,6 +32,7 @@ #include "command_list.h" #include "depth24.h" +#include "quad_index_expand.h" #include "rect_list_geometry.h" #include "uav_clear.h" @@ -904,6 +905,14 @@ struct ReplayFunctions { std::function prepare_counted_dispatch; std::function emit_counted_dispatch; + // An indexed quad list draws from triangle-list indices that a compute prepass writes from the application's + // index buffer (quad_index_expand.h): the index buffer and the offset of the draw's first index, the index type, + // how many indices from there the view holds, the quads, and QuadIndexExpander::bytes(quads) of `copy_scratch`. + // That scratch must be usable as an index buffer and through its device address. Without both such a draw is + // unsupported. + std::function prepare_quad_indices; + std::function emit_quad_indices; // Optional VK_KHR_acceleration_structure: BuildRaytracingAccelerationStructure. PFN_vkCmdBuildAccelerationStructuresKHR build_acceleration_structures = nullptr; // A KHR TLAS built from D3D12_ELEMENTS_LAYOUT_ARRAY_OF_POINTERS needs a pointer array whose entries are Vulkan @@ -947,7 +956,8 @@ struct ReplayFunctions { std::function&)> depth24_prepare; // whole copy in, dispatches out std::function depth24_run; // `bytes` of transfer scratch that stays alive until the submission completes (vulkan_scratch.h): depth <-> colour - // copies go through it, image to buffer to image. Without it such a copy is unsupported. + // copies go through it, image to buffer to image. Without it such a copy is unsupported. The expanded indices of + // an indexed quad list are written there too (prepare_quad_indices). std::function copy_scratch; // Returns the query heap with that ID, or nullptr; it stays valid while the lists that use it run. std::function query_pool; @@ -1070,7 +1080,9 @@ struct PreparedDraw { std::vector vertex_offsets, vertex_sizes, vertex_strides; VkBuffer index_buffer = VK_NULL_HANDLE; VkDeviceSize index_offset = 0; + VkDeviceSize index_size = 0; // the bytes of the index buffer view inside its buffer; 0 with no index buffer VkIndexType index_type = VK_INDEX_TYPE_UINT16; + QuadIndexExpansion quad_indices; // an indexed quad list: the triangle indices its draw binds instead VkExtent2D area{}; std::uint32_t layers = 1; // the fewest layers any bound attachment view has @@ -1086,7 +1098,9 @@ struct PreparedDraw { vertex_strides.clear(); index_buffer = VK_NULL_HANDLE; index_offset = 0; + index_size = 0; index_type = VK_INDEX_TYPE_UINT16; + quad_indices = {}; area = {}; layers = 1; } @@ -2214,11 +2228,36 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct std::uint64_t size = draw.index.size; if (!vk.buffer_at(draw.index.va, size, p.index_buffer, p.index_offset)) return ReplayResult::unresolved_resource; + p.index_size = size; } } return ReplayResult::success; } +// An indexed quad list (D3D_PRIMITIVE_TOPOLOGY 19): the scratch and the compute job that turn the application's +// indices into triangle-list indices (quad_index_expand.h). `p` is the draw as prepare_draw left it. A draw of +// fewer than four indices has no quad and needs nothing. +inline ReplayResult prepare_quad_indices(const Draw& draw, const ReplayFunctions& vk, PreparedDraw& p) { + const std::uint32_t quads = draw.count / 4; + if (!quads) return ReplayResult::success; + if (!vk.prepare_quad_indices || !vk.emit_quad_indices || !vk.copy_scratch || + quads > QuadIndexExpander::max_quads) + return ReplayResult::unsupported; + // The indices from the draw's first one that the view holds; the pass reads the rest as 0, like D3D12. With no + // index buffer (the zero page) that is all of them. + const std::uint32_t index_bytes = p.index_type == VK_INDEX_TYPE_UINT16 ? 2 : 4; + const std::uint64_t in_view = p.index_size / index_bytes; + const std::uint64_t readable = in_view > draw.first ? in_view - draw.first : 0; + const VkDeviceSize first = readable ? p.index_offset + VkDeviceSize(draw.first) * index_bytes : p.index_offset; + VkBuffer scratch = VK_NULL_HANDLE; + VkDeviceSize scratch_offset = 0; + if (!vk.copy_scratch(QuadIndexExpander::bytes(quads), scratch, scratch_offset) || + !vk.prepare_quad_indices(p.index_buffer, first, p.index_type, readable, quads, scratch, scratch_offset, + p.quad_indices)) + return ReplayResult::unsupported; + return ReplayResult::success; +} + inline bool strip_topology(VkPrimitiveTopology topology) { return topology == VK_PRIMITIVE_TOPOLOGY_LINE_STRIP || topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP || topology == VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY || @@ -2236,10 +2275,10 @@ inline VkPrimitiveTopology vulkan_topology(std::uint32_t topology) { case 11: return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY; case 12: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY; case 13: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY; - // Rectangles draw as triangle lists through a geometry stage. Indexed quads draw as separate fans; - // emit() overrides non-indexed quads to a triangle list backed by the shared indices. + // Rectangles draw as triangle lists through a geometry stage, quads as triangle lists through indices: the + // shared ones for a non-indexed draw, the application's own, expanded, for an indexed one (emit). case topology_rect_list: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; - case topology_quad_list: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN; + case topology_quad_list: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; default: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; } } @@ -2354,6 +2393,16 @@ inline ReplayResult plan_occlusion_segments(PreparedList& out) { return active.empty() ? ReplayResult::success : ReplayResult::invalid_query; } +// True for a command that records a compute dispatch of the layer's own before the application's work: a predicate +// capture, a predicated copy, a depth24 or rgb96 conversion, the count clamp of an ExecuteIndirect dispatch, or the +// index expansion of an indexed quad list (which is also a draw). +inline bool has_helper_dispatch(const PreparedList& out, std::size_t i) { + const auto& p = out.commands[i]; + if (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24 || p.counted_dispatch.indirect) + return true; + return std::holds_alternative(out.list->commands()[i]) && out.draws[p.draw].quad_indices.buffer; +} + // Helper dispatches must not contribute to the application's CSInvocations (D3D-162). Query resolves and // ordinary helper commands share one sequence of physical statistics segments. Resolve dispatch requirements // depend on heap state at planning time, so every non-timestamp resolve splits conservatively. @@ -2373,8 +2422,7 @@ inline void plan_statistics_segments(PreparedList& out) { const auto commands = out.list->commands(); for (std::size_t i = 0; i < out.commands.size(); ++i) { auto& p = out.commands[i]; - if (begin && (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24 || - p.counted_dispatch.indirect)) { + if (begin && has_helper_dispatch(out, i)) { inner.push_back({&p.statistics_end, &p.statistics_begin, -1}); splits = true; } @@ -2459,13 +2507,12 @@ inline ReplayResult plan_overlapping_statistics_segments(PreparedList& out) { query = &out.queries[next_query++]; if (!query) { // A helper dispatch while a query runs would be counted into it (D3D-162): close the shared physical - // segment before it and open a new one after, the way resolves do. - if (!active.empty() && (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24 || - p.counted_dispatch.indirect)) { + // segment before it and open a new one after, the way resolves do. An indexed quad list is a helper and + // a draw: the new segment is the one its draw runs in, and its kind is recorded below. + if (!active.empty() && has_helper_dispatch(out, i)) { p.statistics_end = current; current = open(); p.statistics_begin = current; - continue; } // A draw of the other kind than the open segment's starts a segment in its own pool (D3D-291). int draw = -1; @@ -3163,6 +3210,12 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun p.draw = std::uint32_t(out.draw_count++); if (const auto r = detail::prepare_draw(*draw, resolve, vk, prepared_draw); r != ReplayResult::success) return r; + if (draw->indexed && !draw->mesh && draw->topology == topology_quad_list) { + // The index expansion is a helper dispatch: inside a statistics query it needs the segment pool. + if (statistics_active && !statistics_helpers && draw->count >= 4) return ReplayResult::unsupported; + if (const auto r = detail::prepare_quad_indices(*draw, vk, prepared_draw); r != ReplayResult::success) + return r; + } } } if (ordinary_active || binary_active) return ReplayResult::invalid_query; @@ -3455,9 +3508,13 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c detail::begin_statistics_segment(prepared, p.statistics_begin, command_buffer, vk); }; // A draw of the other kind inside a statistics query starts a segment in its pool (D3D-291), before the - // draw's own rendering scope begins. + // draw's own rendering scope begins. The index expansion of an indexed quad list runs here too: outside the + // rendering scope, and between the segments so that no query counts its dispatch (D3D-162). It stays inside + // the predicate, which skips it together with its draw. if (std::holds_alternative(command) || std::holds_alternative(command)) { end_statistics(); + if (std::holds_alternative(command) && prepared.draws[p.draw].quad_indices.buffer) + vk.emit_quad_indices(command_buffer, prepared.draws[p.draw].quad_indices); begin_statistics(); } if (const auto* predication = std::get_if(&command)) { @@ -4203,8 +4260,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c // A mesh pipeline has no input assembly: its topology comes from the shader, and neither the topology // nor primitive restart is dynamic state there (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065). if (!draw->mesh) { - const VkPrimitiveTopology topology = draw->topology == topology_quad_list && !draw->indexed - ? VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST : detail::vulkan_topology(draw->topology); + const VkPrimitiveTopology topology = detail::vulkan_topology(draw->topology); vk.set_primitive_topology(command_buffer, topology); const bool restart = draw->indexed && detail::strip_topology(topology) && ((graphics.strip_cut == 1 && d.index_type == VK_INDEX_TYPE_UINT16) || @@ -4223,11 +4279,16 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c vk.draw_mesh_tasks(command_buffer, draw->count, draw->instances, draw->first); } else if (draw->topology == topology_quad_list) { if (draw->indexed) { - // Indexed quads still read their vertices from the application's index buffer, one fan per quad. - vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); - for (std::uint32_t quad = 0; quad < draw->count / 4; ++quad) - vk.draw_indexed(command_buffer, 4, draw->instances, draw->first + 4 * quad, - draw->base_vertex, draw->first_instance); + // The triangle indices the compute pass wrote before this rendering scope, (i0 i1 i2) (i0 i2 i3) + // for each quad of the application's indices from draw->first on: one draw, so instances run + // in D3D12's order, flat inputs come from each quad's first vertex, and VertexIndex - BaseVertex + // is still the application's index. A draw of fewer than four indices has no quad. + const QuadIndexExpansion& quads = d.quad_indices; + if (quads.buffer) { + vk.bind_index_buffer(command_buffer, quads.buffer, quads.offset, VK_INDEX_TYPE_UINT32); + vk.draw_indexed(command_buffer, quads.quads * QuadIndexExpander::indices_per_quad, + draw->instances, 0, draw->base_vertex, draw->first_instance); + } } else { // Both triangles start at the quad's first vertex for flat inputs. One draw also preserves // the original instance order, and VertexIndex - BaseVertex still gives 4q + k. diff --git a/runtime/test/replay_quad_list_test.cpp b/runtime/test/replay_quad_list_test.cpp index 15b0c7e781..0557a3e577 100644 --- a/runtime/test/replay_quad_list_test.cpp +++ b/runtime/test/replay_quad_list_test.cpp @@ -1,9 +1,18 @@ -// Quad lists without an index buffer are one triangle-list draw. A switch back to Vulkan triangle fans -// changes the provoking vertex for flat attributes and the order of overlapping blended instances. +// Quad lists are triangle-list draws. A switch back to Vulkan triangle fans changes the provoking vertex for flat +// attributes and the order of overlapping blended instances. +// - Without an index buffer: one draw over the shared triangle indices. +// - With one: one compute dispatch that expands the application's indices into scratch (src/quad_index_expand.h), +// then one draw over that scratch. The dispatch runs before the draw's rendering scope and outside a +// pipeline-statistics query, reads no index past the view, and a draw with more quads than one dispatch may +// cover is split into several. +// No GPU: the Vulkan calls are recorded. #include "../src/vulkan_replay.h" #include #include +#include +#include +#include #include namespace { @@ -20,27 +29,129 @@ struct DrawCall { bool operator==(const DrawCall&) const = default; }; +// What quad_index_expand.comp reads from its push constants. +struct Push { + VkDeviceAddress source, triangles; + std::uint32_t first_half, index_bits, limit, quads; + bool operator==(const Push&) const = default; +}; + +struct Barrier { + VkPipelineStageFlags src_stages, dst_stages; + VkAccessFlags src_access, dst_access; + bool operator==(const Barrier&) const = default; +}; + DrawCall recorded{}; std::vector calls; +std::vector pushes; +std::vector dispatches; // group counts +std::vector barriers; +std::vector events; // the order of everything recorded +std::vector scratch_requests; + +template +T handle(std::uintptr_t n) { + return reinterpret_cast(n); +} bool check(bool condition, const char* description) { if (!condition) std::fprintf(stderr, "FAIL: %s\n", description); return condition; } + +// The device the expander sees: every buffer's address is 0x1000 times its handle. +VKAPI_ATTR VkDeviceAddress VKAPI_CALL device_address(VkDevice, const VkBufferDeviceAddressInfo* info) { + return VkDeviceAddress(reinterpret_cast(info->buffer)) * 0x1000; +} +VKAPI_ATTR VkResult VKAPI_CALL create_module(VkDevice, const VkShaderModuleCreateInfo* info, + const VkAllocationCallbacks*, VkShaderModule* out) { + *out = handle(20); + return info->codeSize && info->pCode[0] == 0x07230203u ? VK_SUCCESS : VK_ERROR_INITIALIZATION_FAILED; +} +VKAPI_ATTR void VKAPI_CALL destroy_module(VkDevice, VkShaderModule, const VkAllocationCallbacks*) {} +VKAPI_ATTR VkResult VKAPI_CALL create_layout(VkDevice, const VkPipelineLayoutCreateInfo* info, + const VkAllocationCallbacks*, VkPipelineLayout* out) { + *out = handle(21); + return info->pushConstantRangeCount == 1 && info->pPushConstantRanges[0].size == sizeof(Push) + ? VK_SUCCESS : VK_ERROR_INITIALIZATION_FAILED; +} +VKAPI_ATTR void VKAPI_CALL destroy_layout(VkDevice, VkPipelineLayout, const VkAllocationCallbacks*) {} +VKAPI_ATTR VkResult VKAPI_CALL create_pipelines(VkDevice, VkPipelineCache, std::uint32_t, + const VkComputePipelineCreateInfo*, const VkAllocationCallbacks*, + VkPipeline* out) { + *out = handle(22); + return VK_SUCCESS; +} +VKAPI_ATTR void VKAPI_CALL destroy_pipeline(VkDevice, VkPipeline, const VkAllocationCallbacks*) {} +VKAPI_ATTR void VKAPI_CALL cmd_barrier(VkCommandBuffer, VkPipelineStageFlags src, VkPipelineStageFlags dst, + VkDependencyFlags, std::uint32_t count, const VkMemoryBarrier* memory, + std::uint32_t, const VkBufferMemoryBarrier*, std::uint32_t, + const VkImageMemoryBarrier*) { + barriers.push_back({src, dst, count == 1 ? memory->srcAccessMask : 0, count == 1 ? memory->dstAccessMask : 0}); + events.push_back("barrier"); +} +VKAPI_ATTR void VKAPI_CALL cmd_bind_pipeline(VkCommandBuffer, VkPipelineBindPoint point, VkPipeline) { + events.push_back(point == VK_PIPELINE_BIND_POINT_COMPUTE ? "bind_compute" : "bind_graphics"); +} +VKAPI_ATTR void VKAPI_CALL cmd_push_constants(VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags stages, + std::uint32_t, std::uint32_t size, const void* values) { + if (stages != VK_SHADER_STAGE_COMPUTE_BIT || size != sizeof(Push)) return; // the draw's own user data + std::memcpy(&pushes.emplace_back(), values, sizeof(Push)); +} +VKAPI_ATTR void VKAPI_CALL cmd_dispatch(VkCommandBuffer, std::uint32_t x, std::uint32_t y, std::uint32_t z) { + dispatches.push_back(y == 1 && z == 1 ? x : 0); + events.push_back("dispatch"); +} +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL device_proc(VkDevice, const char* name) { +#define PROC(vk_name, function) \ + if (std::strcmp(name, vk_name) == 0) return reinterpret_cast(function) + PROC("vkGetBufferDeviceAddress", device_address); + PROC("vkCreateShaderModule", create_module); + PROC("vkDestroyShaderModule", destroy_module); + PROC("vkCreatePipelineLayout", create_layout); + PROC("vkDestroyPipelineLayout", destroy_layout); + PROC("vkCreateComputePipelines", create_pipelines); + PROC("vkDestroyPipeline", destroy_pipeline); + PROC("vkCmdPipelineBarrier", cmd_barrier); + PROC("vkCmdBindPipeline", cmd_bind_pipeline); + PROC("vkCmdPushConstants", cmd_push_constants); + PROC("vkCmdDispatch", cmd_dispatch); +#undef PROC + return nullptr; +} + +VKAPI_ATTR void VKAPI_CALL begin_query(VkCommandBuffer, VkQueryPool, std::uint32_t index, VkQueryControlFlags) { + events.push_back("begin_query " + std::to_string(index)); +} +VKAPI_ATTR void VKAPI_CALL end_query(VkCommandBuffer, VkQueryPool, std::uint32_t index) { + events.push_back("end_query " + std::to_string(index)); +} +VKAPI_ATTR void VKAPI_CALL destroy_query_pool(VkDevice, VkQueryPool, const VkAllocationCallbacks*) {} + +void reset() { + calls.clear(); + pushes.clear(); + dispatches.clear(); + barriers.clear(); + events.clear(); + scratch_requests.clear(); +} } int main() { using namespace leonida; ReplayFunctions vk{}; - vk.begin_rendering = +[](VkCommandBuffer, const VkRenderingInfo*) {}; - vk.end_rendering = +[](VkCommandBuffer) {}; - vk.bind_pipeline = +[](VkCommandBuffer, VkPipelineBindPoint, VkPipeline) {}; - vk.push_constants = +[](VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags, std::uint32_t, - std::uint32_t, const void*) {}; + vk.begin_rendering = +[](VkCommandBuffer, const VkRenderingInfo*) { events.push_back("begin_rendering"); }; + vk.end_rendering = +[](VkCommandBuffer) { events.push_back("end_rendering"); }; + vk.bind_pipeline = cmd_bind_pipeline; + vk.push_constants = cmd_push_constants; vk.set_viewport = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, const VkViewport*) {}; vk.set_scissor = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, const VkRect2D*) {}; vk.set_primitive_topology = +[](VkCommandBuffer, VkPrimitiveTopology topology) { recorded.topology = topology; }; - vk.set_primitive_restart_enable = +[](VkCommandBuffer, VkBool32) {}; + vk.set_primitive_restart_enable = +[](VkCommandBuffer, VkBool32 enable) { + if (enable) events.push_back("primitive_restart"); + }; vk.set_stencil_reference = +[](VkCommandBuffer, VkStencilFaceFlags, std::uint32_t) {}; vk.set_blend_constants = +[](VkCommandBuffer, const float*) {}; vk.bind_index_buffer = +[](VkCommandBuffer, VkBuffer buffer, VkDeviceSize offset, VkIndexType type) { @@ -56,16 +167,19 @@ int main() { recorded.base_vertex = base; recorded.first_instance = first_instance; calls.push_back(recorded); + events.push_back("draw_indexed"); }; - vk.quad_indices = reinterpret_cast(std::uintptr_t{1}); + vk.quad_indices = handle(1); vk.quad_indices_offset = 64; vk.quad_index_count = 12; - const auto app_buffer = reinterpret_cast(std::uintptr_t{2}); + const auto app_buffer = handle(2); GraphicsPipeline graphics{}; + graphics.pipeline = handle(3); + graphics.strip_cut = 1; // 0xFFFF cuts strips: it must not make a quad list restart const auto collect = [&](const Draw& draw) { - calls.clear(); + reset(); CommandList list; if (!list.draw(draw) || !list.close()) return false; PreparedList prepared; @@ -92,19 +206,201 @@ int main() { 12, 2, 0, 13, 7}; bool ok = check(collect(draw) && calls == std::vector{triangles}, "non-indexed quads use one triangle-list draw and preserve draw bases"); + ok &= check(dispatches.empty(), "non-indexed quads need no index expansion"); draw.count = 13; ok &= check(collect(draw) && calls == std::vector{triangles}, "a draw is limited to whole quads in the generated index buffer"); draw.count = 3; ok &= check(collect(draw) && calls.empty(), "an incomplete quad emits no draw"); + // Indexed quads, through prepare(): the real expander on the recording device above. + VkPhysicalDeviceLimits limits{}; + limits.maxComputeWorkGroupCount[0] = 65535; + QuadIndexExpander expander(device_proc, handle(9), limits); + const auto scratch = handle(5), zero_page = handle(6); + constexpr VkDeviceSize scratch_offset = 512; + std::uint64_t app_bytes = 64; // the application's buffer past the view's start + vk.graphics_pipeline = [&](std::uintptr_t) -> const GraphicsPipeline* { return &graphics; }; + vk.buffer_at = [&](std::uint64_t va, std::uint64_t& size, VkBuffer& buffer, VkDeviceSize& offset) { + buffer = app_buffer; + offset = va; // the console VA is the offset in this test + size = std::min(size, app_bytes); + return true; + }; + vk.image_view = [](const ResourceBinding&, const VkImageSubresourceRange&) { return VkImageView{}; }; + vk.bind_vertex_buffers2 = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, const VkBuffer*, + const VkDeviceSize*, const VkDeviceSize*, const VkDeviceSize*) {}; + vk.draw = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t, std::uint32_t) {}; + vk.zero_buffer = zero_page; + vk.zero_size = 65536; + vk.copy_scratch = [&](VkDeviceSize bytes, VkBuffer& buffer, VkDeviceSize& offset) { + scratch_requests.push_back(bytes); + buffer = scratch; + offset = scratch_offset; + return true; + }; + const auto wire = [](ReplayFunctions& functions, QuadIndexExpander& to) { + functions.prepare_quad_indices = [&to](VkBuffer indices, VkDeviceSize offset, VkIndexType type, + std::uint64_t readable, std::uint32_t quads, VkBuffer target, + VkDeviceSize target_offset, QuadIndexExpansion& out) { + return to.prepare(indices, offset, type, readable, quads, target, target_offset, out); + }; + functions.emit_quad_indices = [&to](VkCommandBuffer cb, const QuadIndexExpansion& job) { to.emit(cb, job); }; + }; + wire(vk, expander); + const auto resolve = [](ResourceId) -> const ResourceBinding* { return nullptr; }; + const auto run = [&](const Draw& indexed, const ReplayFunctions& functions) { + reset(); + CommandList list; + if (!list.draw(indexed) || !list.close()) return ReplayResult::list_open; + PreparedList prepared; + const auto result = prepare(list, resolve, functions, prepared); + if (result == ReplayResult::success) emit(prepared, VK_NULL_HANDLE, functions); + return result; + }; + + constexpr VkDeviceAddress app_address = 2 * 0x1000, scratch_address = 5 * 0x1000 + scratch_offset; + const Barrier before{VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + VK_ACCESS_MEMORY_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT}; + const Barrier after{VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, + VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_INDEX_READ_BIT}; + const std::vector one_dispatch_one_draw{ + "barrier", "bind_compute", "dispatch", "barrier", "begin_rendering", "bind_graphics", "draw_indexed", + "end_rendering"}; + + // 16-bit indices: two quads and a ninth index, from index 5 of a view at byte 32 (the first index is at byte 42, + // the high half of the word at 40). The view holds 32 indices, 27 of them from index 5 on. draw.indexed = true; - draw.count = 8; + draw.index = {32, 64, 57}; // DXGI_FORMAT_R16_UINT + draw.count = 9; draw.first = 5; draw.base_vertex = -2; - const DrawCall first_fan{VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN, app_buffer, 32, VK_INDEX_TYPE_UINT16, 4, 2, 5, -2, 7}; - const DrawCall second_fan{VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN, app_buffer, 32, VK_INDEX_TYPE_UINT16, 4, 2, 9, -2, 7}; - ok &= check(collect(draw) && calls == std::vector{first_fan, second_fan}, - "indexed quads use the application's index buffer and base vertex"); + const DrawCall expanded{VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, scratch, scratch_offset, VK_INDEX_TYPE_UINT32, + 12, 2, 0, -2, 7}; + ok &= check(run(draw, vk) == ReplayResult::success && events == one_dispatch_one_draw, + "indexed quads are one dispatch before the rendering scope and one draw inside it"); + ok &= check(calls == std::vector{expanded}, + "indexed quads draw the expanded indices once, with the draw's instances and bases"); + ok &= check(dispatches == std::vector{1} && scratch_requests == std::vector{48}, + "two quads are one work group and 48 bytes of scratch"); + ok &= check(pushes == std::vector{Push{app_address + 40, scratch_address, 1, 16, 27, 2}}, + "16-bit indices are read from the word that holds the first one, up to the view's end"); + ok &= check(barriers == std::vector{before, after}, + "earlier writes are visible to the pass, and its indices to the draw"); + + // 32-bit indices through a view of six: the last two of the second quad read 0. + draw.index = {64, 24, 42}; // DXGI_FORMAT_R32_UINT + draw.count = 8; + draw.first = 0; + ok &= check(run(draw, vk) == ReplayResult::success && events == one_dispatch_one_draw && + pushes == std::vector{Push{app_address + 64, scratch_address, 0, 32, 6, 2}}, + "32-bit indices past the view are not read"); + // A view that runs past its buffer ends where the buffer does. + draw.index = {64, 4096, 42}; + app_bytes = 20; + ok &= check(run(draw, vk) == ReplayResult::success && pushes.size() == 1 && pushes[0].limit == 5, + "a view is cut at the end of its buffer"); + app_bytes = 64; + // The first index past the view, and no index buffer at all: every index reads 0. + draw.index = {64, 24, 42}; + draw.first = 6; + ok &= check(run(draw, vk) == ReplayResult::success && calls.size() == 1 && pushes.size() == 1 && + pushes[0].limit == 0 && pushes[0].source == app_address + 64, + "a draw that starts past the view reads no index"); + draw.index = {0, 0, 57}; + draw.first = 0; + ok &= check(run(draw, vk) == ReplayResult::success && calls.size() == 1 && pushes.size() == 1 && + pushes[0].limit == 0 && pushes[0].source == 6 * 0x1000, + "without an index buffer every index reads 0"); + + // Fewer than four indices: nothing to expand, nothing to draw. + draw.index = {32, 64, 57}; + draw.count = 3; + ok &= check(run(draw, vk) == ReplayResult::success && calls.empty() && dispatches.empty() && + scratch_requests.empty(), + "an incomplete indexed quad needs no scratch and emits no draw"); + + // What cannot be expanded is refused when the list is prepared. + draw.count = 8; + { + ReplayFunctions without = vk; + without.prepare_quad_indices = {}; + ok &= check(run(draw, without) == ReplayResult::unsupported && events.empty(), + "indexed quads are unsupported without the expander"); + without = vk; + without.copy_scratch = [](VkDeviceSize, VkBuffer&, VkDeviceSize&) { return false; }; + ok &= check(run(draw, without) == ReplayResult::unsupported && events.empty(), + "indexed quads are unsupported without scratch"); + Draw odd = draw; + odd.index = {33, 64, 57}; + ok &= check(run(odd, vk) == ReplayResult::unsupported && events.empty(), + "16-bit indices at an odd address are refused"); + Draw huge = draw; + huge.count = UINT32_MAX; // 6 indices for each quad would not fit vkCmdDrawIndexed's count + ok &= check(run(huge, vk) == ReplayResult::unsupported && scratch_requests.empty(), + "a draw whose expanded index count overflows 32 bits is refused before taking scratch"); + } + + // More quads than one dispatch may cover: 300 quads with two work groups (128 quads) for each dispatch. Every + // dispatch starts 512 indices (1024 bytes) and 128 * 24 bytes of scratch after the one before, and the view's + // 1000 indices from the first one run out in the second. + { + VkPhysicalDeviceLimits small{}; + small.maxComputeWorkGroupCount[0] = 2; + QuadIndexExpander chunked(device_proc, handle(9), small); + ReplayFunctions split = vk; + wire(split, chunked); + Draw many = draw; + many.index = {32, 2010, 57}; + many.count = 1200; + many.first = 5; + app_bytes = 4096; + const std::vector want{{app_address + 40, scratch_address, 1, 16, 1000, 128}, + {app_address + 40 + 1024, scratch_address + 128 * 24, 1, 16, 488, 128}, + {app_address + 40 + 2048, scratch_address + 256 * 24, 1, 16, 0, 44}}; + ok &= check(run(many, split) == ReplayResult::success && pushes == want && + dispatches == std::vector{2, 2, 1}, + "a large draw is expanded by several dispatches that continue where the last one stopped"); + ok &= check(calls.size() == 1 && calls[0].count == 1800 && scratch_requests == std::vector{7200}, + "a large draw is still one draw over one piece of scratch"); + app_bytes = 64; + } + + // Inside a pipeline-statistics query the dispatch must not be counted (CSInvocations): the query's segment ends + // before it and a new one begins after it, for the draw. Without a segment pool the list is refused. + { + QueryPool heap{handle(7), d3d12_query_heap::pipeline_statistics, 1, false, {false}, {}}; + ReplayFunctions queries = vk; + queries.reset_query_pool = +[](VkCommandBuffer, VkQueryPool, std::uint32_t, std::uint32_t) {}; + queries.begin_query = begin_query; + queries.end_query = end_query; + queries.write_timestamp = +[](VkCommandBuffer, VkPipelineStageFlagBits, VkQueryPool, std::uint32_t) {}; + queries.copy_query_pool_results = +[](VkCommandBuffer, VkQueryPool, std::uint32_t, std::uint32_t, VkBuffer, + VkDeviceSize, VkDeviceSize, VkQueryResultFlags) {}; + queries.fill_buffer = +[](VkCommandBuffer, VkBuffer, VkDeviceSize, VkDeviceSize, std::uint32_t) {}; + queries.query_pool = [&](QueryHeapId) { return &heap; }; + reset(); + CommandList list; + ok &= check(list.begin_query({6, d3d12_query::pipeline_statistics, 0}) && list.draw(draw) && + list.end_query({6, d3d12_query::pipeline_statistics, 0}) && list.close(), + "record a quad draw inside a statistics query"); + PreparedList prepared; + ok &= check(prepare(list, resolve, queries, prepared) == ReplayResult::unsupported && + scratch_requests.empty(), + "without a segment pool the expansion inside a statistics query is refused before its scratch"); + ok &= check(prepare(list, resolve, queries, prepared, true) == ReplayResult::success && + prepared.statistics_segment_count == 2, + "the expansion splits the statistics query in two segments"); + auto pool = std::make_shared(); + pool->pool = handle(8); + pool->destroy = destroy_query_pool; + QueryReplay plan; + ok &= check(plan.plan(prepared, {}, 0, true, pool, 4) == ReplayResult::success, "plan the split query"); + emit(prepared, VK_NULL_HANDLE, queries); + const std::vector want{ + "begin_query 4", "end_query 4", "barrier", "bind_compute", "dispatch", "barrier", "begin_query 5", + "begin_rendering", "bind_graphics", "draw_indexed", "end_rendering", "end_query 5"}; + ok &= check(events == want, "the dispatch runs between the query's two segments, the draw in the second"); + } return ok ? 0 : 1; } From 6ce66cf219c9036195f3abe429fa4893867057ca Mon Sep 17 00:00:00 2001 From: QemmHD <290605352+QemmHD@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:09:40 -0500 Subject: [PATCH 069/110] d3d12: GPU test for indexed quad lists: both index sizes, a base vertex, flat inputs, overlapping instances (d3d12_quad_index) d3d12_rect_list draws its quads without an index buffer, so it could not see what #207's review measured on indexed ones. d3d12_quad_index_test draws six 64x64 frames through DrawIndexedInstanced with IASetPrimitiveTopology(19) and compares every pixel bit for bit: 0 non-indexed control 1 16-bit indices, a quad whose corners all differ: the first vertex's colour everywhere 2 32-bit indices from StartIndexLocation 3 3 16-bit indices from StartIndexLocation 5 (an address of 2 modulo 4), BaseVertexLocation 3 4 two quads and two instances whose quads overlap: the later instance on top 5 a view that ends inside the second quad: its last two indices read 0 The index buffer is in a DEFAULT heap and filled by a copy in the first list, so only the GPU can read it. Two translated fixtures, like vs_m15 and ps_m15: vs_quad_inst.asm reads the instance id (v3) to move and recolour each later instance, ps_quad_flat.asm reads its colour with v_interp_mov, which makes the input Flat. RTX 4070 SUPER (621.24), Windows 11, LEONIDA_VK_VALIDATION=1: on the six commits of #207: frames 1, 2, 3 and 5 match in 0 of 4096 pixels (black and blue, the second and third vertex), frame 4 in 2048, frame 0 in 4096; exit 1 with the expansion: 4096 of 4096 in all six, 0 validation errors run_gpu_tests.py lists the two fixtures as run by this test, and docs/testing.md names the test (and d3d12_rect_list) among those that need llvm-mc and the SPIR-V tools. AI-assisted (Claude Code; Claude Opus 5.5 and Claude Fable 5.2). Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01SR1Fv7eQNgZjM6miWPKjHf --- docs/testing.md | 6 +- runtime/CMakeLists.txt | 25 ++ runtime/test/d3d12_quad_index_test.cpp | 341 +++++++++++++++++++++++++ runtime/test/shaders/ps_quad_flat.asm | 15 ++ runtime/test/shaders/vs_quad_inst.asm | 28 ++ scripts/run_gpu_tests.py | 3 +- 6 files changed, 414 insertions(+), 4 deletions(-) create mode 100644 runtime/test/d3d12_quad_index_test.cpp create mode 100644 runtime/test/shaders/ps_quad_flat.asm create mode 100644 runtime/test/shaders/vs_quad_inst.asm diff --git a/docs/testing.md b/docs/testing.md index 743d7b6406..29a075548d 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -55,9 +55,9 @@ This page collects the setup steps and the problems testers have run into so far ## Build the test programs -On a Windows runtime build with Vulkan enabled, CMake only registers `d3d12_translated_draw`, `d3d12_m2_textured`, -`d3d12_m2_formats`, `d3d12_m3_frame`, `d3d12_m4_compute` and `d3d12_buffer_uav` when it finds `llvm-mc`, -`spirv-as` and `spirv-val`. It registers `d3d12_subgroup` only when it finds `llvm-mc` and `glslangValidator`. +On a Windows runtime build with Vulkan enabled, CMake only registers `d3d12_translated_draw`, `d3d12_rect_list`, +`d3d12_quad_index`, `d3d12_m2_textured`, `d3d12_m2_formats`, `d3d12_m3_frame`, `d3d12_m4_compute` and +`d3d12_buffer_uav` when it finds `llvm-mc`, `spirv-as` and `spirv-val`. It registers `d3d12_subgroup` only when it finds `llvm-mc` and `glslangValidator`. Without `glslangValidator`, other tests are also omitted, including `d3d12_compute`, `d3d12_draw`, `d3d12_set0_compute` and `d3d12_mesh`; some registered tests run only part of their checks. These tests can be **absent**, not reported as skipped, when their build prerequisites are missing, so a passing `ctest` percentage diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index be338e70d3..b7acb791d0 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2437,6 +2437,31 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_rect_list COMMAND d3d12_rect_list_test) set_tests_properties(d3d12_rect_list PROPERTIES SKIP_RETURN_CODE 77) + # Indexed quad lists (src/quad_index_expand.h): a vertex shader that reads the instance id and a pixel shader + # with a flat colour input, translated like vs_m15 and ps_m15. + set(LEONIDA_QUAD_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/quad_shaders) + set(LEONIDA_QUAD_FILES ${LEONIDA_QUAD_DIR}/spirv/index.json ${LEONIDA_QUAD_DIR}/fssm/vs_quad_inst.fssm + ${LEONIDA_QUAD_DIR}/fssm/ps_quad_flat.fssm) + add_custom_command( + OUTPUT ${LEONIDA_QUAD_FILES} + COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_QUAD_DIR} + COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${LEONIDA_SPIRV_TOOLS_NATIVE}" + $ -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py + ${LEONIDA_QUAD_DIR} vs_quad_inst ps_quad_flat + DEPENDS ${LEONIDA_TRANSLATOR_DEPS} + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/vs_quad_inst.asm + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_quad_flat.asm + COMMENT "Translating vs_quad_inst and ps_quad_flat for the indexed quad list test" + VERBATIM) + add_executable(d3d12_quad_index_test test/d3d12_quad_index_test.cpp shims/d3d12_xs_device.cpp + ${LEONIDA_QUAD_FILES}) + target_link_libraries(d3d12_quad_index_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_quad_index_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_QUAD_DIR="${LEONIDA_QUAD_DIR}") + target_compile_options(d3d12_quad_index_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_quad_index COMMAND d3d12_quad_index_test) + set_tests_properties(d3d12_quad_index PROPERTIES SKIP_RETURN_CODE 77) + # vk_bindless_test (the bindless set and its table at the Vulkan level, no D3D12) takes the translated vs_ids, # ps_tex and ps_imgatomic; it was only run by scripts/run_gpu_tests.py and check.py until D3D-314 needed it. set(LEONIDA_BINDLESS_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/bindless_shaders) diff --git a/runtime/test/d3d12_quad_index_test.cpp b/runtime/test/d3d12_quad_index_test.cpp new file mode 100644 index 0000000000..2d41f52189 --- /dev/null +++ b/runtime/test/d3d12_quad_index_test.cpp @@ -0,0 +1,341 @@ +// Indexed console quad lists (IASetPrimitiveTopology(19) with DrawIndexedInstanced) through the D3D12-on-Vulkan +// layer (src/quad_index_expand.h). +// +// Built like d3d12_rect_list_test.cpp, with two translated shaders of its own: vs_quad_inst (vertex fetch through a +// V#, each instance after the first moved by a root constant and its red and green swapped) and ps_quad_flat (the +// colour as a Flat input, so a quad shows the colour of the vertex it takes flat inputs from: its first). Vertices +// 0..3 and 4..7 are full-screen quads with a different colour at every corner; 8..11 and 12..15 are the left and the +// right half of the target, red at every corner. The index buffer is in a DEFAULT heap and is written by a copy in +// the first command list, so nothing but the GPU can read it when the draw is recorded. Six 64x64 frames: +// frame 0, control: a non-indexed quad, DrawInstanced(4) over vertices 0..3. Red (vertex 0) everywhere. +// frame 1: 16-bit indices 0 1 2 3. Red everywhere; a triangle fan shows vertices 1 and 2 (black and blue). +// frame 2: 32-bit indices 7 4 5 6 from StartIndexLocation 3. Green (vertex 7) everywhere. +// frame 3: 16-bit indices 0 1 2 3 from StartIndexLocation 5 (an address of 2 modulo 4) with BaseVertexLocation 3. +// The translated vertex shader's vertex id is the index without the base vertex, so this is frame 1 again; the +// base added into the indices would fetch vertices 3..6 instead (white). +// frame 4: two quads (left half, right half) and two instances; instance 1 is green and one half to the right, so +// its first quad lands on instance 0's second. D3D12 draws instance by instance: the right half ends green. +// Drawn quad by quad, instance 0's second quad comes last and leaves it red. +// frame 5: eight 16-bit indices, 0 1 2 3 and 7 4 5 6, through a view that ends after the sixth. The last two read +// 0 (D3D12: an index outside the view), which makes the second quad empty: red everywhere. Read past the view, +// the second quad covers the target in green. +// Every pixel is compared, bit for bit. LEONIDA_VK_VALIDATION=1 runs it under the validation layer. +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/gfx10_descriptors.h" +#include "../src/shader_library.h" + +#include +#include +#include +#include +#include + +#ifndef LEONIDA_TEST_QUAD_DIR +#error "LEONIDA_TEST_QUAD_DIR must name the folder build.py wrote (spirv/index.json, fssm/*.fssm)" +#endif + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +using namespace d3d12test; +using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX + +namespace { + +std::vector read_file(const std::filesystem::path& path) { + std::ifstream in(path, std::ios::binary); + return {std::istreambuf_iterator(in), std::istreambuf_iterator()}; +} + +struct Vertex { // 32 bytes, as vs_quad_inst.asm reads it + float position[4]; + float color[4]; +}; + +using Pixel = std::array; +constexpr UINT target_extent = 64; +constexpr UINT pitch = target_extent * sizeof(Pixel); +constexpr D3D_PRIMITIVE_TOPOLOGY quad_list = D3D_PRIMITIVE_TOPOLOGY(19); +constexpr Pixel red = {1, 0, 0, 1}, green = {0, 1, 0, 1}, blue = {0, 0, 1, 1}, black = {0, 0, 0, 1}, + white = {1, 1, 1, 1}; + +Vertex vertex(float x, float y, const Pixel& c) { return Vertex{{x, y, 0.0f, 1.0f}, {c[0], c[1], c[2], c[3]}}; } + +struct Frame { + const char* name; + DXGI_FORMAT index_format; // DXGI_FORMAT_UNKNOWN: DrawInstanced + UINT view_offset, view_bytes; // the index buffer view, in the index buffer + UINT count, instances, start; + INT base_vertex; + Pixel left, right; // what the left and the right half of the target must hold +}; + +} // namespace + +int main() { + vktest::Device d; + const auto device_status = d.initialize(); + if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips + EXPECT(device_status == vktest::DeviceStatus::ready); + const std::filesystem::path root_dir = LEONIDA_TEST_QUAD_DIR; + const auto vs_program = read_file(root_dir / "fssm" / "vs_quad_inst.fssm"); + const auto ps_program = read_file(root_dir / "fssm" / "ps_quad_flat.fssm"); + EXPECT(vs_program.size() >= 4 && ps_program.size() >= 4); + const auto vs_container = shader_container(vs_program), ps_container = shader_container(ps_program); + + const Vertex vertices[16] = { + vertex(-1, 1, red), vertex(1, 1, black), vertex(1, -1, blue), vertex(-1, -1, white), + vertex(-1, 1, black), vertex(1, 1, blue), vertex(1, -1, white), vertex(-1, -1, green), + vertex(-1, 1, red), vertex(0, 1, red), vertex(0, -1, red), vertex(-1, -1, red), + vertex(0, 1, red), vertex(1, 1, red), vertex(1, -1, red), vertex(0, -1, red)}; + static_assert(sizeof(Vertex) == 32 && sizeof(vertices) == 512); + // Index 15 fills the gaps: a draw that starts at the wrong index shows it. + const std::uint16_t indices16[28] = {0, 1, 2, 3, 15, 0, 1, 2, 3, 15, 8, 9, 10, 11, 12, 13, 14, 15, 15, 15, + 0, 1, 2, 3, 7, 4, 5, 6}; + const std::uint32_t indices32[7] = {15, 15, 15, 7, 4, 5, 6}; + constexpr UINT indices32_offset = 64, index_bytes = 128; + static_assert(sizeof(indices16) <= indices32_offset && indices32_offset + sizeof(indices32) <= index_bytes); + const Frame frames[] = { + {"non-indexed (control)", DXGI_FORMAT_UNKNOWN, 0, 0, 4, 1, 0, 0, red, red}, + {"16-bit indices", DXGI_FORMAT_R16_UINT, 0, sizeof(indices16), 4, 1, 0, 0, red, red}, + {"32-bit indices, first index 3", DXGI_FORMAT_R32_UINT, indices32_offset, sizeof(indices32), 4, 1, 3, 0, + green, green}, + {"16-bit indices, first index 5, base vertex 3", DXGI_FORMAT_R16_UINT, 0, sizeof(indices16), 4, 1, 5, 3, + red, red}, + {"two overlapping instances", DXGI_FORMAT_R16_UINT, 0, sizeof(indices16), 8, 2, 10, 0, red, green}, + {"view ends inside the second quad", DXGI_FORMAT_R16_UINT, 20 * sizeof(std::uint16_t), + 6 * sizeof(std::uint16_t), 8, 1, 0, 0, red, red}, + }; + constexpr std::size_t frame_count = std::size(frames); + std::vector pixels[frame_count]; + for (auto& p : pixels) p.resize(target_extent * target_extent); + { + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = d.instance_proc; + info.instance = d.instance; + info.physical = d.physical; + info.device = d.device; + info.queue = d.queue; + info.queue_family = d.family; + info.buffer_device_address = true; + info.features = d.enabled; + info.shader_dir = (root_dir / "spirv").string(); + ID3D12Device* inner = nullptr; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); + Ref device; + EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), + reinterpret_cast(&device.p)))); + rt::d3d12::set_device_outer(inner, device.p); + + D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + D3D12_ROOT_PARAMETER params[2] = {}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[0].DescriptorTable = {1, &range}; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[1].Constants = {0, 0, 4}; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + root_desc.Desc_1_0 = {2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + const auto root_blob = serialize_root_signature(root_desc); + EXPECT(!root_blob.empty()); + Ref root; + EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p)))); + + D3D12_GRAPHICS_PIPELINE_STATE_DESC pso_desc{}; + pso_desc.pRootSignature = root.p; + pso_desc.VS = {vs_container.data(), vs_container.size()}; + pso_desc.PS = {ps_container.data(), ps_container.size()}; + pso_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + pso_desc.SampleMask = 0xffffffff; + pso_desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pso_desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pso_desc.RasterizerState.DepthClipEnable = TRUE; + pso_desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; // quads use the triangle type + pso_desc.NumRenderTargets = 1; + pso_desc.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT; + pso_desc.SampleDesc.Count = 1; + Ref pso; + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&pso.p)))); + + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; + const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + Ref vertex_buffer, index_buffer, upload, readback, target; + const auto vb_desc = buffer_desc(sizeof(vertices)); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &vb_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&vertex_buffer.p)))); + const auto ib_desc = buffer_desc(index_bytes); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &ib_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&index_buffer.p)))); + constexpr UINT upload_indices = 512; // where the index bytes sit in the upload buffer + const auto upload_desc = buffer_desc(1024); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &upload_desc, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&upload.p)))); + const auto readback_desc = buffer_desc(pitch * target_extent); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + D3D12_RESOURCE_DESC rt_desc{}; + rt_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + rt_desc.Width = rt_desc.Height = target_extent; + rt_desc.DepthOrArraySize = 1; + rt_desc.MipLevels = 1; + rt_desc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + rt_desc.SampleDesc.Count = 1; + rt_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &rt_desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&target.p)))); + std::uint8_t* up = nullptr; + EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast(&up)))); + std::memcpy(up, vertices, sizeof(vertices)); + std::memset(up + upload_indices, 0xee, index_bytes); // an index read from a gap is far out of the V# + std::memcpy(up + upload_indices, indices16, sizeof(indices16)); + std::memcpy(up + upload_indices + indices32_offset, indices32, sizeof(indices32)); + + // One V# over the sixteen vertices. + const D3D12_DESCRIPTOR_HEAP_DESC srv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + Ref srv_heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&srv_heap_desc, IID_PPV_ARGS(&srv_heap.p)))); + const std::uint64_t cpu = reinterpret_cast(slot(srv_heap.p, 9))(srv_heap.p); + const std::uint64_t gpu = reinterpret_cast(slot(srv_heap.p, 10))(srv_heap.p); + EXPECT(cpu && gpu >= 0x10000 && gpu < (1ull << 32)); + const std::uint64_t buffer_va = vertex_buffer->GetGPUVirtualAddress(); + const std::uint64_t index_va = index_buffer->GetGPUVirtualAddress(); + EXPECT(buffer_va >= 0x10000 && index_va >= 0x10000 && index_va % 4 == 0); + leonida::gfx10::Buffer vsharp; + vsharp.address = buffer_va; + vsharp.stride = 32; + vsharp.num_records = std::uint32_t(std::size(vertices)); + vsharp.format = 77; // GFX10_FORMAT_32_32_32_32_FLOAT + vsharp.oob_select = leonida::gfx10::OobSelect::structured; + const std::array vsharp_words = leonida::gfx10::encode(vsharp); + std::memcpy(reinterpret_cast(cpu), vsharp_words.data(), 16); + + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + Ref rtv_heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&rtv_heap.p)))); + const D3D12_CPU_DESCRIPTOR_HANDLE rtv{ + SIZE_T(reinterpret_cast(slot(rtv_heap.p, 9))(rtv_heap.p))}; + device->CreateRenderTargetView(target.p, nullptr, rtv); + + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + Ref queue; + Ref allocator; + Ref list; + Ref fence; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, pso.p, + IID_PPV_ARGS(&list.p)))); + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + + // The copies that fill the vertex and index buffers are in the first frame's list, before its draw. + list->CopyBufferRegion(vertex_buffer.p, 0, upload.p, 0, sizeof(vertices)); + list->CopyBufferRegion(index_buffer.p, 0, upload.p, upload_indices, index_bytes); + D3D12_RESOURCE_BARRIER barriers[3] = { + transition(vertex_buffer.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE), + transition(index_buffer.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDEX_BUFFER), + transition(target.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET)}; + list->ResourceBarrier(3, barriers); + + const auto render_frame = [&](UINT64 number, const Frame& frame, std::vector& out) -> int { + if (number > 1) { + EXPECT(SUCCEEDED(allocator->Reset())); + EXPECT(SUCCEEDED(list->Reset(allocator.p, pso.p))); + auto to_target = transition(target.p, D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_RENDER_TARGET); + list->ResourceBarrier(1, &to_target); + } + const FLOAT clear[4] = {0.5f, 0.125f, 0.25f, 0.5f}; + list->ClearRenderTargetView(rtv, clear, 0, nullptr); + list->SetGraphicsRootSignature(root.p); + ID3D12DescriptorHeap* heaps[] = {srv_heap.p}; + list->SetDescriptorHeaps(1, heaps); + list->IASetPrimitiveTopology(quad_list); + const D3D12_VIEWPORT viewport{0, 0, float(target_extent), float(target_extent), 0, 1}; + const D3D12_RECT scissor{0, 0, LONG(target_extent), LONG(target_extent)}; + list->RSSetViewports(1, &viewport); + list->RSSetScissorRects(1, &scissor); + list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); + const float constants[4] = {1, 0, 0, 0}; // each later instance: half the target to the right + list->SetGraphicsRootDescriptorTable(0, D3D12_GPU_DESCRIPTOR_HANDLE{gpu}); + list->SetGraphicsRoot32BitConstants(1, 4, constants, 0); + if (frame.index_format == DXGI_FORMAT_UNKNOWN) { + list->DrawInstanced(frame.count, frame.instances, frame.start, 0); + } else { + const D3D12_INDEX_BUFFER_VIEW view{index_va + frame.view_offset, frame.view_bytes, frame.index_format}; + list->IASetIndexBuffer(&view); + list->DrawIndexedInstanced(frame.count, frame.instances, frame.start, frame.base_vertex, 0); + } + D3D12_RESOURCE_BARRIER to_copy = transition(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &to_copy); + D3D12_TEXTURE_COPY_LOCATION dst{}; + dst.pResource = readback.p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = {0, {DXGI_FORMAT_R32G32B32A32_FLOAT, target_extent, target_extent, 1, pitch}}; + D3D12_TEXTURE_COPY_LOCATION src{}; + src.pResource = target.p; + src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + EXPECT(list->Close() == S_OK); + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(queue->Signal(fence.p, number))); + EXPECT(SUCCEEDED(fence->SetEventOnCompletion(number, nullptr))); + void* mapped = nullptr; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); + std::memcpy(out.data(), mapped, out.size() * sizeof(Pixel)); + readback->Unmap(0, nullptr); + return 0; + }; + for (std::size_t i = 0; i < frame_count; ++i) EXPECT(render_frame(i + 1, frames[i], pixels[i]) == 0); + for (auto* r : {&vertex_buffer, &index_buffer, &upload, &readback, &target}) r->reset(); + pso.reset(); + root.reset(); + srv_heap.reset(); + rtv_heap.reset(); + list.reset(); + allocator.reset(); + queue.reset(); + fence.reset(); + EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); + } + + constexpr unsigned all = target_extent * target_extent; + bool ok = true; + for (std::size_t i = 0; i < frame_count; ++i) { + unsigned exact = 0, reported = 0; + for (UINT row = 0; row < target_extent; ++row) { + for (UINT col = 0; col < target_extent; ++col) { + const Pixel& want = col < target_extent / 2 ? frames[i].left : frames[i].right; + const Pixel& got = pixels[i][row * target_extent + col]; + if (std::memcmp(&got, &want, sizeof(Pixel)) == 0) { + ++exact; + } else if (reported++ < 2) { + std::fprintf(stderr, "frame %zu (%s) pixel (%u, %u): got %g,%g,%g,%g want %g,%g,%g,%g\n", i, + frames[i].name, col, row, got[0], got[1], got[2], got[3], want[0], want[1], + want[2], want[3]); + } + } + } + std::printf("frame %zu, %s: %u of %u pixels exact\n", i, frames[i].name, exact, all); + ok = ok && exact == all; + } + if (d.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); + return 1; + } + if (!ok) return 1; + std::printf("indexed quad lists: %zu frames of %u pixels exact\n", frame_count, all); + return 0; +} diff --git a/runtime/test/shaders/ps_quad_flat.asm b/runtime/test/shaders/ps_quad_flat.asm new file mode 100644 index 0000000000..ae84247241 --- /dev/null +++ b/runtime/test/shaders/ps_quad_flat.asm @@ -0,0 +1,15 @@ +; Pixel shader for the indexed quad-list test: param0 (a colour) read only with v_interp_mov, so the input is Flat +; and every pixel of a primitive gets the provoking vertex's colour, unscaled. Run: d3d12_quad_index_test, with +; vs_quad_inst. +; mrt0 = param0 of the primitive's provoking vertex +; A quad list takes it from the quad's first vertex. The test's quads have a different colour at each corner, so +; a quad drawn from any other vertex shows that vertex's colour instead; the colours are 0 and 1, exact in the float +; render target. +; fssm-at: 0x10 +; fssm-data: 0x44415551 0x20535020 +v_interp_mov_f32_e32 v2, p0, attr0.x +v_interp_mov_f32_e32 v3, p0, attr0.y +v_interp_mov_f32_e32 v4, p0, attr0.z +v_interp_mov_f32_e32 v5, p0, attr0.w +exp mrt0 v2, v3, v4, v5 done vm +s_endpgm diff --git a/runtime/test/shaders/vs_quad_inst.asm b/runtime/test/shaders/vs_quad_inst.asm new file mode 100644 index 0000000000..48adac14af --- /dev/null +++ b/runtime/test/shaders/vs_quad_inst.asm @@ -0,0 +1,28 @@ +; Vertex shader for the indexed quad-list test: vs_m15's vertex fetch through a V#, plus the instance id. Run: +; d3d12_quad_index_test (through a D3D12 graphics PSO found by the SHA-256 of its FSSM program), with ps_quad_flat. +; +; User data, from the root signature [0] descriptor table, [1] four 32-bit constants (docs/d3d12_vulkan.md 3.5): +; s[0:1] = console VA of the table's first slot: the 16 bytes of a V# (base VA, stride 32) +; s2, s3 = the clip-space offset (x, y) of each instance after the first, as floats +; v0 = the vertex id and v3 = the instance id, both zero-based as on the hardware (vs_base_ids.asm): in an indexed +; draw v0 is the index the application wrote, without the draw's base vertex. +; Vertex record, 32 bytes: position xyzw at 0, colour rgba at 16 (both float). +; pos0 = (position.x + instance * s2, position.y + instance * s3, position.z, position.w) +; param0 = colour for instance 0, colour.grba (red and green swapped) for every later instance +; The test draws red quads with two instances: instance 0 stays red, instance 1 is green and one offset further on. +; fssm-at: 0x10 +; fssm-data: 0x44415551 0x20535620 +s_load_dwordx4 s[8:11], s[0:1], 0x0 +s_waitcnt lgkmcnt(0) +buffer_load_dwordx4 v[4:7], v0, s[8:11], 0 idxen +buffer_load_dwordx4 v[8:11], v0, s[8:11], 0 idxen offset:16 +s_waitcnt vmcnt(0) +v_cvt_f32_u32_e32 v12, v3 +v_fma_f32 v4, v12, s2, v4 +v_fma_f32 v5, v12, s3, v5 +v_cmp_ne_u32_e32 vcc_lo, 0, v3 +v_cndmask_b32_e32 v13, v8, v9, vcc_lo +v_cndmask_b32_e32 v14, v9, v8, vcc_lo +exp pos0 v4, v5, v6, v7 done +exp param0 v13, v14, v10, v11 +s_endpgm diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index a075c876a4..ae5f064249 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -659,7 +659,8 @@ def check_clip_half(raw_path: str, want_b: float, want_a: float) -> tuple[bool, "cs_m4_fill": "d3d12_m4_compute_test", "cs_m4_indirect": "d3d12_m4_compute_test", "cs_buf_typed": "d3d12_buffer_uav_test", "cs_buf_counter": "d3d12_buffer_uav_test", "ps_live_width": "w64_graphics.py", - "ps_heap_index": "d3d12_heap_index_test"} + "ps_heap_index": "d3d12_heap_index_test", + "ps_quad_flat": "d3d12_quad_index_test", "vs_quad_inst": "d3d12_quad_index_test"} # Shaders a selected test draws with, built even when the filter leaves them out (#192). From a60f66ee95b2bd9c08f7fa7fe2a624fc400c09eb Mon Sep 17 00:00:00 2001 From: QemmHD <290605352+QemmHD@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:09:40 -0500 Subject: [PATCH 070/110] docs: d3d12_vulkan: how quad lists are drawn, indexed ones through the index expansion The quad list entry of "Console rectangle and quad lists" described the fan per quad and its two faults. It now describes both paths as one triangle-list draw, the compute pass for indexed draws and where it runs, what it does with the base vertex, the strip-cut values and indices past the view, what it needs, the measurement that replaced the fans, and what is still not covered (ExecuteIndirect draws, which record no topology). AI-assisted (Claude Code; Claude Opus 5.5 and Claude Fable 5.2). Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01SR1Fv7eQNgZjM6miWPKjHf --- docs/d3d12_vulkan.md | 37 ++++++++++++++++++++++++++++++------- 1 file changed, 30 insertions(+), 7 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 6ecc34081d..7ff1303e13 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2120,14 +2120,37 @@ The trace will enumerate them. ### Console rectangle and quad lists -The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiveTopology(17)`, with a PSO whose topology type is 19) and quad list (`IASetPrimitiveTopology(19)`). The facts are from xvalkyrie (GPL-3.0, commit `53af7df77c10`; no code taken): a rectangle is three corners and the fourth is v2 + v3 - v1 for the position and every interpolant, after the vertex stage; a quad is four vertices. The layer draws both as triangles (`d3d12_rect_list_test`, RTX 4090: 4096 of 4096 pixels, the colour plane exact, quad list bit-exact). +The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiveTopology(17)`, with a PSO whose topology type is 19) and quad list (`IASetPrimitiveTopology(19)`). The facts are from xvalkyrie (GPL-3.0, commit `53af7df77c10`; no code taken): a rectangle is three corners and the fourth is v2 + v3 - v1 for the position and every interpolant, after the vertex stage; a quad is four vertices. The layer draws both as triangles (`d3d12_rect_list_test`, RTX 4090: 4096 of 4096 pixels, the colour plane exact, quad list bit-exact; `d3d12_quad_index_test` for indexed quads). - **Rectangle list**: PSO type 19 builds a triangle-list pipeline plus a generated geometry stage (`src/rect_list_geometry.h`, written from the vertex shader's own outputs) that takes the three corners and emits the strip v1 v2 v3 v4 (same winding). It has to be post-vertex-stage: the translated vertex shaders fetch by V# themselves, and the fourth corner is a function of what they write. A corner value with the same bits at all three corners (a flat attribute) is copied. Needs `geometryShader` (else `E_NOTIMPL`), no application GS, and a vertex shader with no ClipDistance, CullDistance, Layer or ViewportIndex output. -- **Quad list**: a non-indexed draw uses a shared index buffer containing the triangle-list pattern - `0 1 2, 0 2 3` for each quad. Both triangles start at the first vertex for flat inputs. One draw preserves instance - order and supports up to 16384 quads. The draw's first vertex becomes the vertex offset. Indexed draws still - read the application's index buffer as one four-vertex fan per quad. Vulkan fans use a different provoking - vertex for flat inputs, and overlapping blended instances rasterize quad by quad in this path. The PSO type - is the ordinary triangle type. +- **Quad list**: one triangle-list draw whose indices are `i0 i1 i2, i0 i2 i3` for each quad. Both triangles start + at the quad's first vertex, the one Vulkan takes flat inputs from, and one draw keeps D3D12's instance order + (instance by instance, not quad by quad). The PSO type is the ordinary triangle type. + - **Non-indexed**: a shared index buffer in the arena holds the pattern `0 1 2, 0 2 3` for 16384 quads (a draw + with more is cut off there, with a log line). The draw's first vertex becomes the vertex offset. + - **Indexed**: a compute pass (`src/quad_index_expand.comp`, run by `src/quad_index_expand.h`) reads the + application's index buffer on the GPU and writes the six 32-bit indices of each quad into copy scratch + (`src/vulkan_scratch.h`); the draw binds that scratch with the application's instance count, base vertex and + first instance. The host never reads the indices: a copy or a shader earlier in the same list can have written + them. The pass runs before the draw's rendering scope, after a barrier that makes earlier writes visible to it + and before one that makes its indices visible to the draw, and between two segments of an active + pipeline-statistics query so that `CSInvocations` does not count it (as for the other helper dispatches, + D3D-162). + - Index values are copied as they are, a 16-bit one zero-extended, so `VertexIndex - BaseVertex` is still the + application's index in a translated vertex shader. + - The strip-cut values `0xFFFF` and `0xFFFFFFFF` are ordinary indices, as in every list topology: the replay + enables primitive restart for strips only. What the console does with one inside a quad is not measured. + - An index past the end of the index buffer view reads 0, as in D3D12; the pass never reads past the view. + A draw's last one to three indices that do not make a quad are dropped. + - Needs `bufferDeviceAddress` (the pass uses device addresses, no descriptors). Without it, and inside a + statistics query that cannot be split, the list fails as unsupported instead of drawing something else. + - **Why not a triangle fan per quad** (the first version of the indexed path): a fan takes a flat input from + each triangle's own first vertex, the quad's second and third, and a draw per quad runs every instance of one + quad before the next quad. `d3d12_quad_index_test` shows both on an RTX 4070 SUPER: a quad with a red first + vertex came out black and blue (0 of 4096 pixels red), and of two overlapping instances the first one's + second quad ended on top (2048 of 4096 pixels right). With the expansion all six frames are exact: 16-bit and + 32-bit indices, a first index at an address of 2 modulo 4, a base vertex, two instances, and a view that ends + inside the second quad. + - **Not covered**: quad and rectangle lists through `ExecuteIndirect`, whose draws do not record a topology. ## 4. Object model mapping From 2bd97967bacf41b9c3cb02f729a8fad8b3c33696 Mon Sep 17 00:00:00 2001 From: QemmHD <290605352+QemmHD@users.noreply.github.com> Date: Tue, 24 Nov 2026 06:49:48 -0500 Subject: [PATCH 071/110] d3d12: align standalone shader-addressable quad index buffers --- docs/d3d12_vulkan.md | 10 +++++---- runtime/shims/d3d12_vulkan_device.cpp | 26 +++++++++++++++--------- runtime/test/d3d12_quad_index_test.cpp | 28 +++++++++++++++++++++----- 3 files changed, 45 insertions(+), 19 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 7ff1303e13..e777fce430 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2139,17 +2139,19 @@ The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiv application's index in a translated vertex shader. - The strip-cut values `0xFFFF` and `0xFFFFFFFF` are ordinary indices, as in every list topology: the replay enables primitive restart for strips only. What the console does with one inside a quad is not measured. - - An index past the end of the index buffer view reads 0, as in D3D12; the pass never reads past the view. - A draw's last one to three indices that do not make a quad are dropped. + - An index past the end of the index buffer view reads 0, as in D3D12. The pass reads a 16-bit index from its + aligned 32-bit word, so standalone shader-addressable Vulkan buffers round their backing size up to a word. + The D3D buffer size and view bounds are unchanged. A draw's last one to three indices that do not make a quad + are dropped. - Needs `bufferDeviceAddress` (the pass uses device addresses, no descriptors). Without it, and inside a statistics query that cannot be split, the list fails as unsupported instead of drawing something else. - **Why not a triangle fan per quad** (the first version of the indexed path): a fan takes a flat input from each triangle's own first vertex, the quad's second and third, and a draw per quad runs every instance of one quad before the next quad. `d3d12_quad_index_test` shows both on an RTX 4070 SUPER: a quad with a red first vertex came out black and blue (0 of 4096 pixels red), and of two overlapping instances the first one's - second quad ended on top (2048 of 4096 pixels right). With the expansion all six frames are exact: 16-bit and + second quad ended on top (2048 of 4096 pixels right). With the expansion the seven test frames cover 16-bit and 32-bit indices, a first index at an address of 2 modulo 4, a base vertex, two instances, and a view that ends - inside the second quad. + inside the second quad, plus a 16-bit draw that reaches the end of a standalone upload buffer. - **Not covered**: quad and rectangle lists through `ExecuteIndirect`, whose draws do not record a topology. ## 4. Object model mapping diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index b88a372e70..a952bcbc3b 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -72,6 +72,11 @@ constexpr std::uint32_t kQuadIndexCount = 16 * 1024 * kQuadIndicesPerQuad; constexpr VkDeviceSize kArenaReserved = kZeroPage + VkDeviceSize(kQuadIndexCount) * sizeof(std::uint32_t); static_assert(sizeof(leonida::TargetView) <= kDescriptorSize); +// Saturates at the last multiple of `to` instead of wrapping, as the PC runtime's totals do. +UINT64 align_up(UINT64 value, UINT64 to) { + return value > UINT64_MAX - (to - 1) ? UINT64_MAX / to * to : (value + to - 1) / to * to; +} + // The shader model and root signature version this layer can honour. Nothing in the runtime compiles DXIL: the // game's shaders arrive as SPIR-V from the offline translator, and the only DXIL path (the BVH builder) is lowered // to standard DXIL, whose baseline is 6.0. Answering the driver's own maximum would tell the game it can hand this @@ -1895,7 +1900,9 @@ class Resource final const bool addressable = device_.arena.buffer != VK_NULL_HANDLE; const bool need_bda = device_.info.buffer_device_address || device_.info.ray_tracing; VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - info.size = desc_.Width; + // The indexed quad pass loads 16-bit indices from aligned 32-bit words. Keep the final word inside the + // Vulkan buffer while the D3D resource and views still use desc_.Width. + info.size = addressable || need_bda ? align_up(desc_.Width, sizeof(std::uint32_t)) : desc_.Width; info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | @@ -1933,7 +1940,7 @@ class Resource final if (host) { if (vk.vkMapMemory(device_.info.device, memory_, 0, VK_WHOLE_SIZE, 0, &mapped_) != VK_SUCCESS) return E_OUTOFMEMORY; - std::memset(mapped_, 0, std::size_t(desc_.Width)); // committed resources start zeroed + std::memset(mapped_, 0, std::size_t(info.size)); // committed resources and private padding start zeroed } if (need_bda && vk.vkGetBufferDeviceAddress) { VkBufferDeviceAddressInfo bda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; @@ -1986,13 +1993,17 @@ class Resource final if (!device_.get_host_pointer_properties || !alignment) return E_NOTIMPL; const auto start = reinterpret_cast(address); if (!address || !desc_.Width || desc_.Width > UINT64_MAX - 2 * alignment) return E_INVALIDARG; + const bool need_bda = device_.info.buffer_device_address || device_.arena.buffer != VK_NULL_HANDLE; + // Apply the same backing size rule to imports. The committed-range check and Vulkan bind requirements + // below cover the padding as well. The import never initializes or writes the caller's padding. + const VkDeviceSize backing_size = need_bda ? align_up(desc_.Width, sizeof(std::uint32_t)) : desc_.Width; // The import starts at the page that holds `address`, and the buffer is bound at the offset inside it: the // title places small buffers inside a page too (a 16-byte UAV at a 64-byte-aligned address on an RTX 5090, // found in review), which an import of `address` itself would refuse. const std::uintptr_t base = start & ~static_cast(alignment - 1); void* const base_address = reinterpret_cast(base); const VkDeviceSize offset = start - base; - const VkDeviceSize bytes = (offset + desc_.Width + alignment - 1) & ~(alignment - 1); + const VkDeviceSize bytes = align_up(offset + backing_size, alignment); // An imported buffer's VA is its host address, and it joins the same BufferVaIndex as default-heap buffers, // whose VAs are offsets in [0, arena size). A host range that reaches into that window (low host addresses, // as under Wine) would shadow arena buffers in the index's nearest-start lookup, so it takes the fallback @@ -2018,11 +2029,10 @@ class Resource final at = region_end - base; } if (!importable) return E_NOTIMPL; - const bool need_bda = device_.info.buffer_device_address || device_.arena.buffer != VK_NULL_HANDLE; VkExternalMemoryBufferCreateInfo external{VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO}; external.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, &external}; - info.size = desc_.Width; + info.size = backing_size; info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | @@ -2040,7 +2050,7 @@ class Resource final return E_NOTIMPL; const std::uint32_t types = host.memoryTypeBits & requirements.memoryTypeBits; // An offset off the buffer's own alignment cannot be bound: the fallback answers. - if (!types || (offset % requirements.alignment) || bytes < offset + requirements.size) return E_NOTIMPL; + if (!types || (offset % requirements.alignment) || requirements.size > bytes - offset) return E_NOTIMPL; VkImportMemoryHostPointerInfoEXT import{VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT}; import.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; import.pHostPointer = base_address; @@ -8329,10 +8339,6 @@ class Device final static constexpr D3D12_RESOURCE_ALLOCATION_INFO kInvalidAllocation{UINT64_MAX, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT}; - // Saturates at the last multiple of `to` instead of wrapping, as the PC runtime's totals do. - static UINT64 align_up(UINT64 value, UINT64 to) { - return value > UINT64_MAX - (to - 1) ? UINT64_MAX / to * to : (value + to - 1) / to * to; - } // Lays `count` resources out one after another; `each` (optional) gets every resource's offset, size and // alignment. As on the PC runtime, the total is rounded up to the largest alignment (1 for no resources) and diff --git a/runtime/test/d3d12_quad_index_test.cpp b/runtime/test/d3d12_quad_index_test.cpp index 2d41f52189..03ce0a0eec 100644 --- a/runtime/test/d3d12_quad_index_test.cpp +++ b/runtime/test/d3d12_quad_index_test.cpp @@ -5,8 +5,8 @@ // V#, each instance after the first moved by a root constant and its red and green swapped) and ps_quad_flat (the // colour as a Flat input, so a quad shows the colour of the vertex it takes flat inputs from: its first). Vertices // 0..3 and 4..7 are full-screen quads with a different colour at every corner; 8..11 and 12..15 are the left and the -// right half of the target, red at every corner. The index buffer is in a DEFAULT heap and is written by a copy in -// the first command list, so nothing but the GPU can read it when the draw is recorded. Six 64x64 frames: +// right half of the target, red at every corner. Most cases use a DEFAULT heap index buffer written by a copy in +// the first command list, so nothing but the GPU can read it when the draw is recorded. Seven 64x64 frames: // frame 0, control: a non-indexed quad, DrawInstanced(4) over vertices 0..3. Red (vertex 0) everywhere. // frame 1: 16-bit indices 0 1 2 3. Red everywhere; a triangle fan shows vertices 1 and 2 (black and blue). // frame 2: 32-bit indices 7 4 5 6 from StartIndexLocation 3. Green (vertex 7) everywhere. @@ -19,6 +19,8 @@ // frame 5: eight 16-bit indices, 0 1 2 3 and 7 4 5 6, through a view that ends after the sixth. The last two read // 0 (D3D12: an index outside the view), which makes the second quad empty: red everywhere. Read past the view, // the second quad covers the target in green. +// frame 6: a standalone 10-byte UPLOAD index buffer, first index 1. All four 16-bit indices are readable, with +// the last one at the end of the resource. The backing buffer must accommodate the full word load. // Every pixel is compared, bit for bit. LEONIDA_VK_VALIDATION=1 runs it under the validation layer. #include "vk_test_device.h" #include "d3d12_test_shaders.h" @@ -72,6 +74,7 @@ struct Frame { UINT count, instances, start; INT base_vertex; Pixel left, right; // what the left and the right half of the target must hold + bool use_upload_indices = false; }; } // namespace @@ -97,6 +100,7 @@ int main() { const std::uint16_t indices16[28] = {0, 1, 2, 3, 15, 0, 1, 2, 3, 15, 8, 9, 10, 11, 12, 13, 14, 15, 15, 15, 0, 1, 2, 3, 7, 4, 5, 6}; const std::uint32_t indices32[7] = {15, 15, 15, 7, 4, 5, 6}; + const std::uint16_t upload_indices16[] = {15, 0, 1, 2, 3}; constexpr UINT indices32_offset = 64, index_bytes = 128; static_assert(sizeof(indices16) <= indices32_offset && indices32_offset + sizeof(indices32) <= index_bytes); const Frame frames[] = { @@ -109,6 +113,8 @@ int main() { {"two overlapping instances", DXGI_FORMAT_R16_UINT, 0, sizeof(indices16), 8, 2, 10, 0, red, green}, {"view ends inside the second quad", DXGI_FORMAT_R16_UINT, 20 * sizeof(std::uint16_t), 6 * sizeof(std::uint16_t), 8, 1, 0, 0, red, red}, + {"16-bit indices at the end of an upload buffer", DXGI_FORMAT_R16_UINT, 0, + sizeof(upload_indices16), 4, 1, 1, 0, red, red, true}, }; constexpr std::size_t frame_count = std::size(frames); std::vector pixels[frame_count]; @@ -164,7 +170,7 @@ int main() { const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; - Ref vertex_buffer, index_buffer, upload, readback, target; + Ref vertex_buffer, index_buffer, upload_index_buffer, upload, readback, target; const auto vb_desc = buffer_desc(sizeof(vertices)); EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &vb_desc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, @@ -173,6 +179,15 @@ int main() { EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &ib_desc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&index_buffer.p)))); + const auto upload_ib_desc = buffer_desc(sizeof(upload_indices16)); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &upload_ib_desc, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&upload_index_buffer.p)))); + EXPECT(upload_index_buffer->GetDesc().Width == sizeof(upload_indices16)); + void* index_map = nullptr; + EXPECT(SUCCEEDED(upload_index_buffer->Map(0, nullptr, &index_map))); + std::memcpy(index_map, upload_indices16, sizeof(upload_indices16)); + upload_index_buffer->Unmap(0, nullptr); constexpr UINT upload_indices = 512; // where the index bytes sit in the upload buffer const auto upload_desc = buffer_desc(1024); EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &upload_desc, @@ -209,7 +224,9 @@ int main() { EXPECT(cpu && gpu >= 0x10000 && gpu < (1ull << 32)); const std::uint64_t buffer_va = vertex_buffer->GetGPUVirtualAddress(); const std::uint64_t index_va = index_buffer->GetGPUVirtualAddress(); + const std::uint64_t upload_index_va = upload_index_buffer->GetGPUVirtualAddress(); EXPECT(buffer_va >= 0x10000 && index_va >= 0x10000 && index_va % 4 == 0); + EXPECT(upload_index_va && upload_index_va % 4 == 0); leonida::gfx10::Buffer vsharp; vsharp.address = buffer_va; vsharp.stride = 32; @@ -271,7 +288,8 @@ int main() { if (frame.index_format == DXGI_FORMAT_UNKNOWN) { list->DrawInstanced(frame.count, frame.instances, frame.start, 0); } else { - const D3D12_INDEX_BUFFER_VIEW view{index_va + frame.view_offset, frame.view_bytes, frame.index_format}; + const std::uint64_t frame_index_va = frame.use_upload_indices ? upload_index_va : index_va; + const D3D12_INDEX_BUFFER_VIEW view{frame_index_va + frame.view_offset, frame.view_bytes, frame.index_format}; list->IASetIndexBuffer(&view); list->DrawIndexedInstanced(frame.count, frame.instances, frame.start, frame.base_vertex, 0); } @@ -299,7 +317,7 @@ int main() { return 0; }; for (std::size_t i = 0; i < frame_count; ++i) EXPECT(render_frame(i + 1, frames[i], pixels[i]) == 0); - for (auto* r : {&vertex_buffer, &index_buffer, &upload, &readback, &target}) r->reset(); + for (auto* r : {&vertex_buffer, &index_buffer, &upload_index_buffer, &upload, &readback, &target}) r->reset(); pso.reset(); root.reset(); srv_heap.reset(); From 6aa8eb11c66e66cf38a8f789c76bf7c7200a842d Mon Sep 17 00:00:00 2001 From: QemmHD <290605352+QemmHD@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:21:07 -0500 Subject: [PATCH 072/110] d3d12: check prepared draw index before query planning --- runtime/src/vulkan_replay.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 3225cffeb3..7b6613d502 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -2400,7 +2400,8 @@ inline bool has_helper_dispatch(const PreparedList& out, std::size_t i) { const auto& p = out.commands[i]; if (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24 || p.counted_dispatch.indirect) return true; - return std::holds_alternative(out.list->commands()[i]) && out.draws[p.draw].quad_indices.buffer; + return std::holds_alternative(out.list->commands()[i]) && p.draw < out.draws.size() && + out.draws[p.draw].quad_indices.buffer; } // Helper dispatches must not contribute to the application's CSInvocations (D3D-162). Query resolves and From b10e0e9d5a24c90bfc1a6d2370fcfcf641f3fbc7 Mon Sep 17 00:00:00 2001 From: Rain156 <77776581+Rain156@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:36:55 +0800 Subject: [PATCH 073/110] runtime: reuse the Xbox rectangle geometry generator from #682 Carry only runtime/src/rect_list_geometry.h, byte-for-byte from 6aa8eb11c. The stage generator and its original commits are by tedin7 (#207, carried forward in #682). This makes the draw-time change buildable against main while the explicit rectangle/quad work is in review. --- runtime/src/rect_list_geometry.h | 268 +++++++++++++++++++++++++++++++ 1 file changed, 268 insertions(+) create mode 100644 runtime/src/rect_list_geometry.h diff --git a/runtime/src/rect_list_geometry.h b/runtime/src/rect_list_geometry.h new file mode 100644 index 0000000000..e90173095d --- /dev/null +++ b/runtime/src/rect_list_geometry.h @@ -0,0 +1,268 @@ +#pragma once + +// Console rectangle lists on Vulkan, which has no such primitive. +// +// A rectangle is three corners and the hardware makes the fourth, a + b - p (p the right-angle corner, a and b its +// neighbours), for the position and for every interpolant, after the vertex stage. Which vertex is p is not fixed: +// the retail boot's full-screen rectangle has it at the second vertex. The stage picks the vertex opposite the longest +// screen-space edge, and the first vertex on a tie. A list topology of rectangles (D3D_PRIMITIVE_TOPOLOGY 17) and a pipeline +// whose topology type is 19 are console-only. The fact comes from xvalkyrie (GPL-3.0, commit 53af7df77c10, notes in +// its backlog); no code is taken from it. +// +// The fourth vertex depends on what the vertex stage wrote, not on what it read, so the expansion has to sit after +// the vertex stage: a pre-pass over the vertex buffers is wrong for any shader that is not linear in its inputs (and +// the translated vertex shaders fetch by V# themselves, so there is no vertex buffer to expand). The pipeline gets a +// small geometry stage instead, built here from the vertex shader's own SPIR-V: it takes the triangle (v1, v2, v3) +// the list draws and emits the parallelogram as the two triangles (p, a, f) and (p, f, b), with the winding of +// (v1, v2, v3). Both start at p, so a flat input (taken from a triangle's first vertex) is p's over the whole +// rectangle. Every Location output of the vertex stage is a vec4 float in the translator's output (rdna2spirv.py), +// and so is the stage's Position; the generated stage reads and writes exactly those. +// +// The edges are measured in normalized device coordinates, not pixels (the stage does not know the viewport). For the +// usual axis-aligned rectangle that is exact; a rotated rectangle drawn into a very non-square viewport can pick a +// different corner than the pixel-space right angle. +// +// Not covered, and refused with a reason: a vertex stage that writes ClipDistance, CullDistance, Layer or +// ViewportIndex, or a Location output that is not a vec4 float. +// +// Plain word editing, standard library only. + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace leonida { + +// D3D_PRIMITIVE_TOPOLOGY values and the PSO topology type of the console's rectangle and quad lists. +constexpr std::uint32_t topology_rect_list = 17; +constexpr std::uint32_t topology_quad_list = 19; +constexpr std::uint32_t topology_type_rect_list = 19; +constexpr std::array quad_triangle_indices{0, 1, 2, 0, 2, 3}; + +// The geometry stage for `vertex_words`' outputs; empty, with `why` set, when the vertex stage cannot be expanded. +inline std::vector rect_list_geometry(const std::vector& vertex_words, std::string& why) { + enum : std::uint32_t { + op_entry_point = 15, op_type_void = 19, op_type_int = 21, op_type_float = 22, + op_type_vector = 23, op_type_array = 28, op_type_pointer = 32, op_type_function = 33, op_constant = 43, + op_function = 54, op_function_end = 56, op_variable = 59, op_load = 61, op_store = 62, op_access_chain = 65, + op_decorate = 71, op_fadd = 129, op_fsub = 131, op_fmul = 133, op_fdiv = 136, + op_type_bool = 20, op_composite_construct = 80, op_composite_extract = 81, op_logical_and = 167, + op_logical_not = 168, op_select = 169, op_ford_greater_equal = 190, op_emit_vertex = 218, op_end_primitive = 219, op_label = 248, op_return = 253, + op_capability = 17, op_memory_model = 14, op_execution_mode = 16, + deco_builtin = 11, deco_location = 30, builtin_position = 0, builtin_point_size = 1, + storage_input = 1, storage_output = 3 + }; + why.clear(); + if (vertex_words.size() < 6 || vertex_words[0] != 0x07230203u) { + why = "the vertex shader is not a SPIR-V module"; + return {}; + } + // What the vertex stage declares: types, Output variables, and the decorations that name them. + struct Type { std::uint32_t op = 0, component = 0, count = 0, width = 0; }; + std::map types; + std::map variable_type; // Output variable -> its pointer type + std::map location, builtin; // variable id -> value + std::set outputs; + for (std::size_t i = 5; i < vertex_words.size();) { + const std::uint32_t op = vertex_words[i] & 0xffffu, n = vertex_words[i] >> 16; + if (!n || i + n > vertex_words.size()) { + why = "the vertex shader's SPIR-V is cut short"; + return {}; + } + const std::uint32_t* w = &vertex_words[i]; + if (op == op_type_float && n >= 3) types[w[1]] = {op, 0, 0, w[2]}; + else if (op == op_type_vector && n >= 4) types[w[1]] = {op, w[2], w[3], 0}; + else if (op == op_type_pointer && n >= 4) types[w[1]] = {op, w[3], w[2], 0}; + else if (op == op_variable && n >= 4 && w[3] == storage_output) outputs.insert(w[2]), variable_type[w[2]] = w[1]; + else if (op == op_decorate && n >= 4 && w[2] == deco_location) location[w[1]] = w[3]; + else if (op == op_decorate && n >= 4 && w[2] == deco_builtin) builtin[w[1]] = w[3]; + i += n; + } + std::uint32_t position = 0; + std::vector params; // Location values, ascending + for (std::uint32_t id : outputs) { + const auto b = builtin.find(id); + if (b != builtin.end()) { + if (b->second == builtin_position) position = id; + else if (b->second != builtin_point_size) { + why = "the vertex shader writes ClipDistance, CullDistance, Layer or ViewportIndex"; + return {}; + } + continue; + } + const auto l = location.find(id); + if (l == location.end()) continue; + const Type& ptr = types[variable_type[id]]; + const Type& vec = types[ptr.component]; + const Type& scalar = types[vec.component]; + // Known limit: every vec4 float output gets the plain a + b - p corner. The translator can export an attribute + // as the register's raw bits with two packed f16 halves (only the pixel shader knows, through per_vertex in + // tools/rdna2spirv.py), and nothing on the vertex side tells those apart, so such an output would get a wrong + // fourth corner. Fixing it needs the pixel shader's words here and a per-channel marker from the translator. + if (vec.op != op_type_vector || vec.count != 4 || scalar.op != op_type_float || scalar.width != 32) { + why = "a vertex output is not a vec4 float"; + return {}; + } + params.push_back(l->second); + } + if (!position) { + why = "the vertex shader writes no Position"; + return {}; + } + std::sort(params.begin(), params.end()); + params.erase(std::unique(params.begin(), params.end()), params.end()); + + // The module: a fixed prelude, then per variable ids, then the body. Ids count up from 1. + std::uint32_t next = 1; + const auto id = [&] { return next++; }; + std::vector head, annotations, globals, body; + const auto emit = [](std::vector& to, std::uint32_t op, std::initializer_list args) { + to.push_back((std::uint32_t(args.size()) + 1) << 16 | op); + to.insert(to.end(), args.begin(), args.end()); + }; + const std::uint32_t t_void = id(), t_fn = id(), t_uint = id(), t_float = id(), t_v4 = id(), + c3 = id(), t_arr = id(), t_pin_arr = id(), t_pin_v4 = id(), + t_pout_v4 = id(), c0 = id(), c1 = id(), c2 = id(), t_bool = id(), t_bool4 = id(); + emit(globals, op_type_void, {t_void}); + emit(globals, op_type_function, {t_fn, t_void}); + emit(globals, op_type_int, {t_uint, 32, 0}); + emit(globals, op_type_float, {t_float, 32}); + emit(globals, op_type_vector, {t_v4, t_float, 4}); + emit(globals, op_type_bool, {t_bool}); + emit(globals, op_type_vector, {t_bool4, t_bool, 4}); + emit(globals, op_constant, {t_uint, c3, 3}); + emit(globals, op_constant, {t_uint, c0, 0}); + emit(globals, op_constant, {t_uint, c1, 1}); + emit(globals, op_constant, {t_uint, c2, 2}); + emit(globals, op_type_array, {t_arr, t_v4, c3}); + emit(globals, op_type_pointer, {t_pin_arr, storage_input, t_arr}); + emit(globals, op_type_pointer, {t_pin_v4, storage_input, t_v4}); + emit(globals, op_type_pointer, {t_pout_v4, storage_output, t_v4}); + + struct Var { std::uint32_t in, out; bool is_position; }; + std::vector vars; + vars.push_back({id(), id(), true}); + for (std::size_t i = 0; i < params.size(); ++i) vars.push_back({id(), id(), false}); + std::vector io_vars; + emit(annotations, op_decorate, {vars[0].in, deco_builtin, builtin_position}); + emit(annotations, op_decorate, {vars[0].out, deco_builtin, builtin_position}); + for (std::size_t i = 0; i < params.size(); ++i) { + emit(annotations, op_decorate, {vars[i + 1].in, deco_location, params[i]}); + emit(annotations, op_decorate, {vars[i + 1].out, deco_location, params[i]}); + } + for (const Var& v : vars) { + emit(globals, op_variable, {t_pin_arr, v.in, storage_input}); + emit(globals, op_variable, {t_pout_v4, v.out, storage_output}); + io_vars.push_back(v.in); + io_vars.push_back(v.out); + } + + const std::uint32_t main_fn = id(), entry_label = id(); + emit(body, op_function, {t_void, main_fn, 0, t_fn}); + emit(body, op_label, {entry_label}); + // Per variable: the three vertices as drawn, loaded first. + struct Corners { std::uint32_t v[4]; }; // v[0] the right-angle corner, v[1], v[2] its neighbours, v[3] the fourth + std::vector corners; + std::vector> loaded; + const std::uint32_t cs[3] = {c0, c1, c2}; + for (const Var& v : vars) { + std::array three{}; + for (int k = 0; k < 3; ++k) { + const std::uint32_t ptr = id(); + three[k] = id(); + emit(body, op_access_chain, {t_pin_v4, ptr, v.in, cs[k]}); + emit(body, op_load, {t_v4, three[k], ptr}); + } + loaded.push_back(three); + } + // Which vertex is the right angle: the one opposite the longest edge, measured on screen (position.xy / position.w; + // a right triangle's longest edge is its hypotenuse). Ties go to the first vertex, which keeps the plain + // "v1 is the corner" order for every rectangle whose right angle is there. A triangle that is not a right + // triangle gets the same rule, so the choice is at least consistent. + std::uint32_t screen[3][2]; + for (int k = 0; k < 3; ++k) { + const std::uint32_t x = id(), y = id(), w = id(); + emit(body, op_composite_extract, {t_float, x, loaded[0][k], 0}); + emit(body, op_composite_extract, {t_float, y, loaded[0][k], 1}); + emit(body, op_composite_extract, {t_float, w, loaded[0][k], 3}); + screen[k][0] = id(); + screen[k][1] = id(); + emit(body, op_fdiv, {t_float, screen[k][0], x, w}); + emit(body, op_fdiv, {t_float, screen[k][1], y, w}); + } + const auto squared_edge = [&](int a, int b) { + const std::uint32_t dx = id(), dy = id(), xx = id(), yy = id(), sum = id(); + emit(body, op_fsub, {t_float, dx, screen[a][0], screen[b][0]}); + emit(body, op_fsub, {t_float, dy, screen[a][1], screen[b][1]}); + emit(body, op_fmul, {t_float, xx, dx, dx}); + emit(body, op_fmul, {t_float, yy, dy, dy}); + emit(body, op_fadd, {t_float, sum, xx, yy}); + return sum; + }; + const std::uint32_t e01 = squared_edge(0, 1), e02 = squared_edge(0, 2), e12 = squared_edge(1, 2); + const std::uint32_t g12_01 = id(), g12_02 = id(), at_first = id(), g02_01 = id(), not_first = id(), at_second = id(); + emit(body, op_ford_greater_equal, {t_bool, g12_01, e12, e01}); + emit(body, op_ford_greater_equal, {t_bool, g12_02, e12, e02}); + emit(body, op_logical_and, {t_bool, at_first, g12_01, g12_02}); // the edge opposite v1 is longest: v1 is the corner + emit(body, op_ford_greater_equal, {t_bool, g02_01, e02, e01}); + emit(body, op_logical_not, {t_bool, not_first, at_first}); + emit(body, op_logical_and, {t_bool, at_second, not_first, g02_01}); // else the edge opposite v2: v2; else v3 + const std::uint32_t first4 = id(), second4 = id(); + emit(body, op_composite_construct, {t_bool4, first4, at_first, at_first, at_first, at_first}); + emit(body, op_composite_construct, {t_bool4, second4, at_second, at_second, at_second, at_second}); + // The corner p, its neighbours a = next and b = the one after (the same cyclic order as v1 v2 v3, so the winding + // is the drawn triangle's), and the fourth corner a + b - p, for the position and for every interpolant alike. + for (const auto& three : loaded) { + Corners c{}; + const auto pick = [&](std::uint32_t first, std::uint32_t second, std::uint32_t third) { + const std::uint32_t inner = id(), outer = id(); + emit(body, op_select, {t_v4, inner, second4, second, third}); + emit(body, op_select, {t_v4, outer, first4, first, inner}); + return outer; + }; + c.v[0] = pick(three[0], three[1], three[2]); + c.v[1] = pick(three[1], three[2], three[0]); + c.v[2] = pick(three[2], three[0], three[1]); + const std::uint32_t sum = id(), diff = id(); + emit(body, op_fadd, {t_v4, sum, c.v[1], c.v[2]}); + emit(body, op_fsub, {t_v4, diff, sum, c.v[0]}); + c.v[3] = diff; + corners.push_back(c); + } + // Two triangles, (p, a, f) and (p, f, b): the diagonal is p to f, so both start at p and a flat input + // (which Vulkan takes from a triangle's first vertex) is p's over the whole rectangle. The attributes are + // affine over the parallelogram, so the split does not change any interpolated value. + const int triangles[2][3] = {{0, 1, 3}, {0, 3, 2}}; + for (const auto& triangle : triangles) { + for (int k : triangle) { + for (std::size_t i = 0; i < vars.size(); ++i) emit(body, op_store, {vars[i].out, corners[i].v[k]}); + emit(body, op_emit_vertex, {}); + } + emit(body, op_end_primitive, {}); + } + emit(body, op_return, {}); + emit(body, op_function_end, {}); + + std::vector out{0x07230203u, 0x00010000u, 0, next, 0}; + emit(out, op_capability, {2}); // Geometry + emit(out, op_memory_model, {0, 1}); // Logical, GLSL450 + std::vector entry{3, main_fn, 0x6e69616du, 0}; // Geometry, %main, "main" + entry.insert(entry.end(), io_vars.begin(), io_vars.end()); + out.push_back((std::uint32_t(entry.size()) + 1) << 16 | op_entry_point); + out.insert(out.end(), entry.begin(), entry.end()); + emit(out, op_execution_mode, {main_fn, 22}); // Triangles + emit(out, op_execution_mode, {main_fn, 0, 1}); // Invocations 1 + emit(out, op_execution_mode, {main_fn, 29}); // OutputTriangleStrip + emit(out, op_execution_mode, {main_fn, 26, 6}); // OutputVertices 6 + out.insert(out.end(), annotations.begin(), annotations.end()); + out.insert(out.end(), globals.begin(), globals.end()); + out.insert(out.end(), body.begin(), body.end()); + return out; +} + +} // namespace leonida From c55ecc9cbf4e7cde8b80b032b827e5943d451a9e Mon Sep 17 00:00:00 2001 From: Rain156 <77776581+Rain156@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:40:44 +0800 Subject: [PATCH 074/110] d3d12: expand rectangle draws through triangle-family pipelines Select the geometry-stage variant when the input assembler requests an Xbox rectangle and cache it alongside the attachment-format variants. Keep a shared snapshot of the linked vertex program for that draw. Exercise alternating rectangle and triangle draws through the same PSO and compare the complete target after each switch. --- docs/d3d12_vulkan.md | 4 ++ runtime/shims/d3d12_vulkan_device.cpp | 67 +++++++++++++++++++++ runtime/src/vulkan_replay.h | 7 ++- runtime/test/d3d12_translated_draw_test.cpp | 30 ++++++++- 4 files changed, 106 insertions(+), 2 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 3ae29163e5..42a886b811 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -832,6 +832,10 @@ The compute path, end to end: `d3d12_state_sweep_test` checks the mapping against the host on the same adapter: 482 full-screen draws over every blend factor pair, blend operation, write mask, comparison function and stencil operation, with the stencil plane read back, are byte-identical on an RTX 5080 and a Radeon iGPU. + - A triangle-family PSO can draw Xbox rectangle lists. When the input assembler selects topology 17, replay + selects a geometry-stage variant that emits the fourth corner after vertex shading. It requires + `geometryShader` and a vertex pipeline without an application geometry stage. A later triangle draw uses the + original PSO. The translated-draw GPU test switches between both primitives on one PSO and checks every pixel. - **Logic ops** come from `RenderTarget[0]`, as in D3D12, and apply to every target (Vulkan has one per pipeline; it skips float formats). **`DepthClipEnable = FALSE`** is depth clamping: D3D12 clamps output depth to the viewport's range anyway. diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 0273f9339b..868f01f545 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -18,6 +18,7 @@ #include "../src/arena_size.h" #include "../src/gfx10_descriptors.h" #include "../src/depth24_fragment.h" +#include "../src/rect_list_geometry.h" #include "../src/uav_clear.h" #include "../src/vulkan_bindless.h" #include "../src/vulkan_memory.h" @@ -803,6 +804,23 @@ struct DeviceState { return shader_library.loaded() ? &shader_library : nullptr; } + // PSOs that differ only in fixed state can share the linked vertex program. The pixel entry distinguishes + // f16 interface variants. Compare the actual words as well, and let the last PSO release its snapshot. + using VertexWords = std::vector; + std::mutex rectangle_vertices_mutex; + std::map, + std::weak_ptr> rectangle_vertices; + + std::shared_ptr retain_rectangle_vertex(const leonida::ShaderEntry* vs, + const leonida::ShaderEntry* linked_ps, const VertexWords& words) { + std::lock_guard lock(rectangle_vertices_mutex); + auto& weak = rectangle_vertices[{vs, linked_ps}]; + if (auto shared = weak.lock(); shared && *shared == words) return shared; + auto shared = std::make_shared(words); + weak = shared; + return shared; + } + bool depth_usable(VkFormat format) const { VkFormatProperties properties{}; format_properties(info.physical, format, &properties); @@ -3613,6 +3631,15 @@ class PipelineState final pixel ? "fragmentStoresAndAtomics" : "vertexPipelineStoresAndAtomics"); return E_NOTIMPL; } + const auto topology_bits = std::bit_cast(desc.PrimitiveTopologyType); + if (!mesh && topology_bits != leonida::topology_type_rect_list) + graphics_.rectangle_variant_topology = leonida::topology_rect_list; + if (!mesh && !geometry && device_.info.features.geometryShader && + topology_bits == D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) { + const bool linked = + ps_stage.entry && (!ps_stage.entry->f16_halves.empty() || !vs_stage.entry->f16_halves.empty()); + rectangle_vertex_ = device_.retain_rectangle_vertex(vs_stage.entry, linked ? ps_stage.entry : nullptr, vs_stage.words); + } for (Stage& stage : stages) { if (!stage.entry) continue; // After the f16 link above, which can also edit the pixel shader's words. @@ -4179,6 +4206,17 @@ class PipelineState final info.pColorBlendState = &blend; info.pDynamicState = &dynamic; info.layout = graphics_.layout; + std::vector rectangle_stages; + if (unbound & leonida::GraphicsPipeline::rectangle_stage) { + rectangle_stages.assign(info.pStages, info.pStages + info.stageCount); + VkPipelineShaderStageCreateInfo geometry{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; + geometry.stage = VK_SHADER_STAGE_GEOMETRY_BIT; + geometry.module = rectangle_module_; + geometry.pName = "main"; + rectangle_stages.push_back(geometry); + info.stageCount = static_cast(rectangle_stages.size()); + info.pStages = rectangle_stages.data(); + } VkPipeline pipeline = VK_NULL_HANDLE; if (device_.context->vk.vkCreateGraphicsPipelines(device_.info.device, device_.pipeline_cache(), 1, &info, nullptr, &pipeline) != VK_SUCCESS) @@ -4186,10 +4224,37 @@ class PipelineState final return pipeline; } + // Called under variants_mutex_. Attachment combinations reuse the same geometry module. + VkShaderModule rectangle_module() { + if (rectangle_module_ || !rectangle_vertex_) return rectangle_module_; + std::string why; + const auto words = leonida::rect_list_geometry(*rectangle_vertex_, why); + if (words.empty()) { + std::fprintf(stderr, "[rt] d3d12: cannot draw rectangle list: %s\n", why.c_str()); + rectangle_vertex_.reset(); + return VK_NULL_HANDLE; + } + VkShaderModuleCreateInfo module{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + module.codeSize = words.size() * sizeof(words.front()); + module.pCode = words.data(); + VkShaderModule handle = VK_NULL_HANDLE; + if (device_.context->vk.vkCreateShaderModule(device_.info.device, &module, nullptr, &handle) != VK_SUCCESS) + return VK_NULL_HANDLE; + modules_.push_back(handle); + rectangle_module_ = handle; + rectangle_vertex_.reset(); + return handle; + } + // Built on first use and kept until the PSO is released (replay may call this from any queue). VkPipeline variant(std::uint32_t unbound) { std::lock_guard lock(variants_mutex_); if (const auto it = variants_.find(unbound); it != variants_.end()) return it->second; + if ((unbound & leonida::GraphicsPipeline::rectangle_stage) && !rectangle_module()) { + log_once("a rectangle-list draw needs a compatible vertex pipeline and geometryShader; topology", + leonida::topology_rect_list); + return VK_NULL_HANDLE; + } const VkPipeline pipeline = build(unbound); if (!pipeline) { log_once("a pipeline variant for unbound attachment slots could not be built; slots", int(unbound)); @@ -4207,6 +4272,8 @@ class PipelineState final std::map variants_; VkShaderModule module_ = VK_NULL_HANDLE; std::vector modules_; + std::shared_ptr rectangle_vertex_; + VkShaderModule rectangle_module_ = VK_NULL_HANDLE; VkDeviceSize code_base_ = 0; VkDeviceSize code_bytes_ = 0; bool registered_ = false; diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 889bb71f72..f7702f128d 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -773,7 +773,10 @@ struct GraphicsPipeline { // unbound (D3D12 allows it; dynamic rendering needs the formats to agree). Bit i: colour slot i, bit 8: depth // and stencil. Null when it cannot be built. static constexpr std::uint32_t unbound_depth = 1u << 8; - std::function variant; + static constexpr std::uint32_t rectangle_stage = 1u << 9; + // 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; std::uint32_t samples = 1; // rasterizationSamples; every bound attachment must have this count }; @@ -2160,6 +2163,8 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct // Slots the pipeline has a format for but the draw leaves unbound take a variant whose format there is // VK_FORMAT_UNDEFINED: D3D12 discards those writes, Vulkan wants the formats to match the attachments. std::uint32_t unbound = 0; + if (pipeline->rectangle_variant_topology && draw.topology == pipeline->rectangle_variant_topology) + unbound |= GraphicsPipeline::rectangle_stage; 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; diff --git a/runtime/test/d3d12_translated_draw_test.cpp b/runtime/test/d3d12_translated_draw_test.cpp index 62ce7b65cb..a489c660a0 100644 --- a/runtime/test/d3d12_translated_draw_test.cpp +++ b/runtime/test/d3d12_translated_draw_test.cpp @@ -175,6 +175,7 @@ int main() { info.queue = d.queue; info.queue_family = d.family; info.buffer_device_address = true; + info.features = d.enabled; info.shader_dir = (root_dir / "spirv").string(); ID3D12Device* inner = nullptr; EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); @@ -293,7 +294,8 @@ int main() { list->ResourceBarrier(2, barriers); // The first command list already contains the vertex upload. Reuse it for subsequent frames // after the preceding submission's fence has completed and its readback is available. - const auto render_frame = [&](UINT64 frame, float x_offset, float bias) -> int { + const auto render_frame = [&](UINT64 frame, float x_offset, float bias, + D3D_PRIMITIVE_TOPOLOGY last_topology = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST) -> int { if (frame > 1) { EXPECT(SUCCEEDED(allocator->Reset())); EXPECT(SUCCEEDED(list->Reset(allocator.p, pso.p))); @@ -323,6 +325,7 @@ int main() { {0, {1, -1, 0.125f + bias, 0}, 6}, // bottom right: same V#, other constants {1, {0, 0, 0.25f + bias, 0}, 3}}; // bottom left: the second V# for (const Draw& draw : draws) { + if (draw.slot == 1) list->IASetPrimitiveTopology(last_topology); list->SetGraphicsRootDescriptorTable(0, D3D12_GPU_DESCRIPTOR_HANDLE{gpu + std::uint64_t(draw.slot) * step}); list->SetGraphicsRoot32BitConstants(1, 4, draw.constants, 0); list->DrawInstanced(draw.vertices, 1, 0, 0); @@ -370,6 +373,31 @@ int main() { } #endif EXPECT(render_frame(1, 0.0f, 0.0f) == 0); +#ifndef LEONIDA_M15_GUEST + if (d.enabled.geometryShader) { + // The last draw covers half the lower-left quadrant as a triangle. The Xbox rectangle primitive + // fills the quadrant through the same PSO. The other three quadrants keep their original values. + const auto triangles = pixels; + constexpr auto rectangles = static_cast(17); + const Pixel lower_left = {0.75f, 0.25f, 0.75f, 1.0f}; + for (UINT64 frame : {2u, 4u}) { + EXPECT(render_frame(frame, 0.0f, 0.0f, rectangles) == 0); + for (UINT y = 0; y < target_extent; ++y) { + for (UINT x = 0; x < target_extent; ++x) { + const auto i = y * target_extent + x; + const auto& want = y >= target_extent / 2 && x < target_extent / 2 ? lower_left : triangles[i]; + if (pixels[i] != want) { + std::fprintf(stderr, "rectangle draw mismatch at (%u, %u) in frame %llu\n", x, y, + static_cast(frame)); + return 1; + } + } + } + EXPECT(render_frame(frame + 1, 0.0f, 0.0f) == 0); + EXPECT(pixels == triangles); + } + } +#endif for (auto* r : {&vertex_buffer, &upload, &readback, &target}) r->reset(); pso.reset(); root.reset(); From ed5ed7afe4d43c66719e1856b7a62a22d7304fba Mon Sep 17 00:00:00 2001 From: Rain156 <77776581+Rain156@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:12:08 +0800 Subject: [PATCH 075/110] Translate VCC used as the address of a scalar memory load --- docs/design.md | 1 + runtime/test/shaders/cs_smem_vcc_base.asm | 20 ++++++++++++++++++++ tests/semantic/test_scalar_mem_smem.py | 15 +++++++++++++++ tools/rdna2spirv.py | 13 +++++++++++++ 4 files changed, 49 insertions(+) create mode 100644 runtime/test/shaders/cs_smem_vcc_base.asm diff --git a/docs/design.md b/docs/design.md index 127bf88743..c43bdcc38f 100644 --- a/docs/design.md +++ b/docs/design.md @@ -406,6 +406,7 @@ How the generated SPIR-V expects the runtime to work: | Metadata index | `spirv/index.json`: one entry per translated shader with its stage, `wave64` / `subgroup_size`, SPIR-V capabilities and extensions, the Vulkan **features** to enable (barycentrics, interlock, mesh, geometry, Float64, Int64, buffer device address, write-without-format, `shaderFmaFloat32` for `--fma khr`, …), `needs_maintenance8`, the descriptor bindings it uses (set 0), push-constant size, `local_size`, `user_sgprs` (CS), `lds_bytes`, mesh `max_vertices`/`max_primitives`/`params`, geometry inputs/outputs, vertex-input locations and types, full `vertex_input_signature` (ISG1 register/mask/system-value/component-type, for PSO lookup), `wave64_emulated` (true for VS/PS/GS wave64, which the translator emits as per-subgroup code with no cross-half exchange, and for compute/mesh translated with `--wave64-emulate`; the runtime does not use it: it reads `wave64`, `subgroup_size` and `wave64_exchange`), `dynamic_format` (runtime V# FORMAT: codes outside FORMATS decode to 0) / `fixed_format_codes`, `src_sha256` and optional `fssm_sha256` (via `--fssm-dir`), PS system inputs, `bary_fallback_input` (`--bary-fallback`: the location of the barycentric input), `mesh_compute` (`--mesh-compute`: the slot layout and push-constant size), `pc_tail` (`--pc-tail-ubo`: the set, binding and size of the uniform block that holds the push-constant tail), and input/output locations. A shader translated with `--wave64-emulate` carries `wave64_exchange: "workgroup"` and `subgroup_size: null`: any subgroup size is exact, request none. Otherwise `subgroup_size` (64 for wave64, 32) is what the PSO asks for through `VkPipelineShaderStageRequiredSubgroupSizeCreateInfo` where the device lists the stage in `requiredSubgroupSizeStages` (docs/d3d12_vulkan.md section 3.2): that list is the driver's, not "compute/mesh only". The AMD Windows driver reports FRAGMENT, COMPUTE, TASK and MESH (measured on a Radeon 880M, driver 26.11.2, sizes 32..64), and current Mesa RADV on GFX10+ reports COMPUTE, FRAGMENT and task/mesh (`src/amd/vulkan/radv_physical_device.c`, `requiredSubgroupSizeStages`, Mesa main at 152b9cde; older Mesa: compute only), so wave64 pixel shaders can run exact there. NVIDIA lists every stage but only size 32, so there a native wave64 shader cannot get 64 and wave64 PS/VS/GS stay 2x32. A runtime can create every pipeline at load time from it without parsing SPIR-V. | | Full-corpus pipeline build | `vk_pipeline_check pipeline_cache.bin --jobs 4` on an RTX 4060 Ti (NVIDIA 595 driver): **all 26,503 shaders become real pipelines, 0 failures** (cs 2,689, ps 12,101, ms 9,282, vs 2,236, gs 195; graphics stages with generated stub partners). Compile time 40,784 s of CPU (2.84 h wall on 4 threads): cs 23,633 s (mean 8.8 s; the ray-tracing ScreenProbes/RTShadowTrace shaders take 2-19 min each), ps 11,481 s, ms 5,395 s, vs 275 s. The resulting `VkPipelineCache` is 3.81 GB; seeding a run with it makes those pipelines instant, which is what a fast first boot needs. The cache is per driver and GPU, and a shader whose SPIR-V changes compiles again (the checker resumes from the file). Neither register storage (one variable per register) nor smaller SPIR-V cut NVIDIA compile time: the big ray-tracing shaders are expensive as such, so the runtime should compile them in the background rather than block on them. | | `v_cndmask_b32` source modifiers | `v_cndmask_b32` only moves bits, so a VOP3 `abs` on `src0`/`src1` clears bit 31 and `neg` flips it (`abs` first) as plain bit moves (`OpBitwiseAnd 0x7FFFFFFF`, then `OpBitwiseXor 0x80000000`, `Gen.src_u_sign_mods`), never `FAbs`/`OpFNegate`: a signalling NaN stays signalling and a denormal isn't flushed. Until 2026-11-23 the sources went through `Gen.modify`, and the mini interpreter quieted them (`-v1` of `0x7F800001` gave `0xFFC00001`, not `0xFF800001`). **Not measured on hardware for this instruction**: the rule follows the same VOP3 input modifiers measured as sign-bit moves on `v_cmp_class_f32` (gfx1036, all four IEEE/denorm modes, row "Floating-point class compare" above), and LLVM's AMDGPU backend moves `fneg`/`fabs` through a select into `v_cndmask_b32_e64`'s source modifiers (`AMDGPUTargetLowering::foldFreeOpFromSelect`), which is only exact if they are sign-bit moves. Checked on the CPU and with `spirv-val` by `tests/semantic/test_cndmask_sign_mods.py` (15 words including signalling/quiet NaNs, denormals, zeros and infinities x `v`, `-v`, `\|v\|`, `-\|v\|` x both operands). | +| VCC as an SMEM address | A scalar load that takes VCC as an ordinary 64-bit address uses the stored low and high words. The SMEM interpreter test checks both halves and the resulting addresses. The synthetic `cs_smem_vcc_base.asm` reads eight initialized words through this pair. | | Wave-uniform branches | VCC and EXEC are wave-wide registers, but one invocation holds only its own lane's bit. `s_cbranch_vccz/vccnz/execz/execnz` therefore reduce the condition across the subgroup (`OpGroupNonUniformAny`), so the whole wave takes the branch together, as on hardware. Before this, each lane decided alone. A lane could skip scalar instructions that the hardware wave executes (its SGPRs went stale for later code), and cross-lane ops or barriers inside the block saw a split wave. `v_cmp`/`v_cmp_class`/64-bit compares now write 0 for inactive lanes (hardware VOPC behaviour), so the reduction sees the true mask. GPU-checked with `runtime/test/shaders/ps_uniform_branch.asm`: lanes whose own VCC bit is 0 run the block's scalar add when their wave has any set bit. `s_cbranch_scc0/1` stay per lane; SCC is uniform as long as the SGPRs feeding it are. | | Compute shaders | FSSM header word **0x138 = `COMPUTE_PGM_RSRC2`**: USER_SGPR [5:1], TGID_X/Y/Z_EN [9:7], TG_SIZE_EN [10], TIDIG_COMP_CNT [12:11], LDS_SIZE [23:15] in 512-byte units. Words **0x13C/0x140/0x144 = thread-group size**. Counted over all 2,689 CS listings of 1.0.2.1 by the SGPRs each reads before writing (operand roles from `shader_meta._split_operands`, over the code `translate()` keeps; in wave64 code a lane mask printed as one SGPR covers the pair; an earlier check gave 2,281 exact): 2,540 read nothing past the user SGPRs and enabled TGIDs (2,193 up to the last of them, 342 fewer, 5 none), and the other 149 overshoot only through loop-carried registers in the straight-line check: every extra read follows a branch, and the register is written later in program order. Followed through the CFG (written on every path before the read), 22 still overshoot; each extra register is written on some other path (only loop-carried ones in 15), so these are values undefined on some path, not a missing input. Read raw, 268 overshoot: the other 119 are listings with embedded data words, decoded as instructions. 0x110, which looked similar, doesn't match. Layout: s0..user−1 = user data (push constants), then the enabled workgroup IDs (`WorkgroupId`), and v0/v1/v2 = thread ID x/y/z (`LocalInvocationId`, separate VGPRs on GFX10). Example: the 1,013 shaders with RSRC2 `0x998` have 12 user SGPRs, group ID x/y in s12/s13, and compute x = s12·32 + v0. Shaders with TG_SIZE_EN are rejected for now. GPU-checked with `runtime/test/shaders/cs_lds.asm` through `runtime/test/vk_compute_test.cpp`: 4 groups × 64 threads, LDS exchange between the two waves of a group behind `s_barrier`, store through a V# into the device-address heap, 0 mismatches. | | Signed-byte dot products | `v_dot4_i32_i8 D, S0, S1, S2` (VOP3P) is S2 plus the sum of the four products of the sign-extended bytes of S0 and S1, modulo 2^32; `v_dot4c_i32_i8 D, S0, S1` (VOP2) adds the same sum to D. Emitted as four pairs of `OpBitFieldSExtract`, `OpIMul` and `OpIAdd`. **Confirmed on RDNA2 hardware** (gfx1036, raw kernels through `tools/hw_oracle`): 10 operand sets, both instructions and both source orders of the accumulating one, with sign-mixed bytes and sums that wrap; the measured words are the table in `tests/semantic/test_alu_dot4_i8.py`. `clamp` and `op_sel`/`op_sel_hi` are translated and checked against the same `gfx1036` hardware table: `clamp` saturates `v_dot4_i32_i8` to signed 32-bit `[-2^31, 2^31-1]` (both overflowing sets), and `op_sel`/`op_sel_hi` pick the 16-bit half of S0/S1 for byte pairs 0..1 and 2..3 (e.g. `op_sel` 2 / `op_sel_hi` 5 exchanges the 16-bit halves of S1, matching all 5 measured sets — the form of the 89 words `llvm-mc` does not decode, [fspx.md](fspx.md)); non-default S2 half selection stays refused. `neg_lo`/`neg_hi`, which `llvm-mc` accepts on `v_dot4_i32_i8` only, are not ignored (`neg_lo` flips bit 15 and `neg_hi` bit 31 of S0 or S1, and on S2 `neg_hi` clears bit 31 before `neg_lo` flips it; 5 sets under 8 forms, 45 words): any set bit stays Unsupported, while an all-zero field is the plain instruction. Counts: the 29 FSPX programs use the pair 27,271 times (`v_dot4c_i32_i8` 25,813, `v_dot4_i32_i8` 1,458), all in 13 programs; none of the game's own 26,503 shaders has either encoding (0 of the 12,791 words `llvm-mc` cannot decode there with gfx1013). | diff --git a/runtime/test/shaders/cs_smem_vcc_base.asm b/runtime/test/shaders/cs_smem_vcc_base.asm new file mode 100644 index 0000000000..d40f9a5a83 --- /dev/null +++ b/runtime/test/shaders/cs_smem_vcc_base.asm @@ -0,0 +1,20 @@ +; group: 1,1,1 +; Read the eight application-initialized words at byte 128 through VCC as an ordinary pointer pair. +s_mov_b32 s4, 128 +s_mov_b32 s5, 0 +s_mov_b64 vcc, s[4:5] +s_load_dwordx8 s[8:15], vcc, 0 +s_waitcnt lgkmcnt(0) +v_mov_b32 v0, 0 +v_mov_b32 v1, s8 +v_mov_b32 v2, s9 +v_mov_b32 v3, s10 +v_mov_b32 v4, s11 +buffer_store_dwordx4 v[1:4], v0, s[0:3], 0 offen +v_mov_b32 v0, 16 +v_mov_b32 v1, s12 +v_mov_b32 v2, s13 +v_mov_b32 v3, s14 +v_mov_b32 v4, s15 +buffer_store_dwordx4 v[1:4], v0, s[0:3], 0 offen +s_endpgm diff --git a/tests/semantic/test_scalar_mem_smem.py b/tests/semantic/test_scalar_mem_smem.py index 1ea98ba3e4..05d5efb680 100644 --- a/tests/semantic/test_scalar_mem_smem.py +++ b/tests/semantic/test_scalar_mem_smem.py @@ -429,6 +429,8 @@ def __init__(self, gen, sgpr, memory, heap_base=0): def _value(self, name): if name == "%heap_base": # built once in the entry block, outside the body run here return self.heap_base + if name in ("%vcc", "%vcc_hi"): + return ("sgpr", 106 if name == "%vcc" else 107) if name == "%c64_32": return 32 if name in self.ids: @@ -612,6 +614,19 @@ def test_heap_base_is_added_once(self): heap_base=0x0000007F00000000) self.assertEqual(ev.reads, [0x0000007F00000000 + 0x1000 + 12]) + def test_vcc_data_pointer_reads_both_halves(self): + for width in (4, 8): + ins = parse_line(f"s_load_dwordx{width} s[8:{7 + width}], vcc, 0x10") + g = rdna2spirv.Gen("cs") + g.scalar_load(ins["op"], ins["args"], ins["mods"]) + bank = SmemMemoryBank() + addresses = [self.POINTER + 16 + 4 * n for n in range(width)] + for n, address in enumerate(addresses): + bank.write_dword(address, 0x7210 + n) + result = SmemBodyEvaluator(g, {106: self.POINTER & MASK32, 107: self.POINTER >> 32}, bank) + self.assertEqual(result.reads, addresses) + self.assertEqual([result.sgpr[r] for r in range(8, 8 + width)], list(range(0x7210, 0x7210 + width))) + def test_offset_forms_the_assembler_rejects_raise(self): # llvm-mc accepts none of these; hand-written or damaged listings must not translate to a guessed address. for line in ("s_buffer_load_dword s12, s[24:27], 0x8 offset:0x4", # immediate operand and offset modifier diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index cc7d149c85..7bed0bd157 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -328,6 +328,7 @@ def __init__(self, stage, hoist_reg_ptrs=False, cache_active=False): self.lane_masks = {} # id(instruction) -> registers holding a lane mask there (lane_masks.py) self.ever_mask = set() # SGPRs that held a lane mask anywhere in the shader (conservative) self.cur_masks = {} + self.vcc_scalar_pointer = False self.cur_ins = None self.mask_writes = set() # id(instruction) of the ones that write a lane mask to a VGPR self.write_all_lanes = False @@ -1780,6 +1781,12 @@ def mov64(self, d, s): if d["k"] == "special" and d["t"] == "exec": self.set_exec(self.mask_src(s)) return + if (self.vcc_scalar_pointer and d["k"] == "special" and d["t"] == "vcc" and + s["k"] == "sgpr" and s.get("n") == 2 and not self.holds_lane_mask(s) and + all(s["r"] + word not in self.ever_mask for word in range(2))): + self.emit(f"OpStore %vcc {self.load_reg('sgpr', s['r'])}") + self.emit(f"OpStore %vcc_hi {self.load_reg('sgpr', s['r'] + 1)}") + return if d["k"] == "special" and d["t"] in ("vcc", "vcc_lo"): self.emit(f"OpStore %vcc {self.mask_src(s)}") return @@ -12450,6 +12457,10 @@ def scalar_load(self, op, a, mods): slist_dst = d["k"] == "slist" and len(d["r"]) == n base_slots = (list(range(base["r"], base["r"] + base.get("n", 1))) if base["k"] == "sgpr" else list(base["r"]) if base["k"] == "slist" else None) + # A scalar base pair may be the two VCC registers holding ordinary scalar data. + # A wave64 lane mask is represented per lane and cannot be read as this scalar pair. + if base["k"] == "special" and base.get("t") == "vcc" and not op.startswith("s_buffer") and "vcc" not in self.cur_masks: + base_slots = ("vcc_lo", "vcc_hi") if (d["k"] != "sgpr" and not single_special and not slist_dst) or base_slots is None: raise Unsupported(f"{op} operands {d.get('t', d['k'])} {base.get('t', base['k'])}") @@ -17613,6 +17624,8 @@ def translate(path): else: check_printed_encodings(path, info) g = Gen(stage, hoist_reg_ptrs=True, cache_active=True) + g.vcc_scalar_pointer = any(i["op"].startswith("s_load_dword") and len(i["args"]) >= 2 and + i["args"][1].get("t") == "vcc" for i in insns) g.exec_static_true = not any(writes_exec(i) for i in insns) g.atomic_volume_tsharps = {g.tsharp_regs(i["args"][2]) for i in insns if base_op(i["op"]) in (*Gen.IMG_ATOMICS, *Gen.IMG_ATOMICS_EXTRA, From db19bbd3455a757c3fe986c6e6db36998f275150 Mon Sep 17 00:00:00 2001 From: Rain156 <77776581+Rain156@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:19:30 +0800 Subject: [PATCH 076/110] runtime: connect native pipelines and title resources to the offline first-run UI Build on the public frame-loop integration in #321. Carry the texture-view and depth work from #213 and #261, the layout provider from #461, the responsive window from #526, and the rectangle generator from #682. Integrate the Xbox constant-buffer row addressing measured in #513 and the draw-time rectangle selection in #722. Keep all fixtures synthetic. The Windows GPU path resolves title-owned shader objects, retires geometry uploads per submission, materializes texture views on use, maps linear surfaces, and delivers completed GPU label writes. A first-run UI launch selects the tested settings for these paths. --- docs/d3d12_vulkan.md | 99 +- docs/runtime_imports.md | 20 +- docs/testing.md | 24 +- runtime/CMakeLists.txt | 159 +- runtime/shims/d3d12_com.cpp | 159 +- runtime/shims/d3d12_com.h | 32 +- runtime/shims/d3d12_vulkan_device.cpp | 1776 ++++++++++++++--- runtime/shims/d3d12_xs_device.cpp | 495 ++++- runtime/shims/d3d12_xs_device.h | 62 +- runtime/shims/d3d12_xs_native_pso.h | 234 +++ runtime/shims/d3d12_xs_placed_depth.h | 134 ++ runtime/shims/d3d12_xs_pso_stream.cpp | 340 ++++ runtime/shims/d3d12_xs_pso_stream.h | 85 + runtime/shims/dstorage.cpp | 28 +- runtime/shims/file_system.cpp | 36 + runtime/shims/present_window.h | 72 + runtime/shims/xg_xs.cpp | 490 ++++- runtime/shims/xgameruntime_offline.cpp | 67 +- runtime/shims/xmem.cpp | 386 ++-- runtime/shims/xmem.h | 3 + runtime/src/command_list.h | 9 +- runtime/src/console_texture_layout.h | 610 ++++++ runtime/src/depth24_fragment.h | 18 +- runtime/src/frame_pacer.h | 23 +- runtime/src/gfx10_descriptors.h | 20 + runtime/src/gpu_label_memory.h | 77 + runtime/src/main.cpp | 46 +- runtime/src/native_pso.h | 332 +++ runtime/src/queue_families.h | 10 + runtime/src/rect_list_geometry.h | 108 +- runtime/src/rgba4_fragment.h | 81 + runtime/src/title_va_alias.h | 30 +- runtime/src/vulkan13_features.h | 6 + runtime/src/vulkan_backend.h | 79 +- runtime/src/vulkan_bindless.h | 81 +- runtime/src/vulkan_gpu_labels.h | 156 ++ runtime/src/vulkan_graphics_shader_modules.h | 61 + runtime/src/vulkan_replay.h | 342 +++- runtime/src/vulkan_scratch.h | 9 +- runtime/test/bindless_sizing_test.cpp | 52 +- runtime/test/d3d12_bundle_test.cpp | 89 +- runtime/test/d3d12_compute_test.cpp | 8 +- runtime/test/d3d12_depth_stencil_uav_test.cpp | 556 ++++++ runtime/test/d3d12_depth_stencil_uav_views.h | 79 + runtime/test/d3d12_draw_test.cpp | 41 +- runtime/test/d3d12_m2_textured_test.cpp | 252 ++- runtime/test/d3d12_mesh_test.cpp | 3 + runtime/test/d3d12_native_graphics_fixture.h | 55 + runtime/test/d3d12_placed_depth_test.h | 141 ++ runtime/test/d3d12_r9g9b9e5_uav_test.cpp | 98 +- runtime/test/d3d12_rect_list_test.cpp | 125 +- runtime/test/d3d12_test_shaders.h | 15 +- runtime/test/d3d12_texture1d_target_test.cpp | 4 + runtime/test/d3d12_texture1d_test.cpp | 15 +- runtime/test/d3d12_texture_uav_oracle.h | 279 +++ runtime/test/d3d12_texture_uav_test.cpp | 629 ++++++ runtime/test/d3d12_title_va_test.cpp | 146 +- runtime/test/d3d12_translated_draw_test.cpp | 67 +- runtime/test/d3d12_xmem_placed_test.cpp | 110 +- runtime/test/device_proxy_test.cpp | 16 + runtime/test/file_system_test.cpp | 59 + runtime/test/frame_pacer_test.cpp | 23 + runtime/test/glsl/cs_depth_stencil_uav.comp | 55 + runtime/test/glsl/cs_r9g9b9e5_uav.comp | 21 +- runtime/test/glsl/cs_user_data.comp | 18 +- runtime/test/pso_stream_test.cpp | 268 +++ runtime/test/replay_texture_barrier_test.cpp | 175 ++ runtime/test/replay_uav_clear_offset_test.cpp | 38 + runtime/test/shaders/check.py | 30 +- runtime/test/shaders/cs_cbv_vector_rows.asm | 42 + runtime/test/shaders/cs_imgatomic3d.asm | 4 +- runtime/test/shaders/cs_imgload_mip.asm | 44 + runtime/test/shaders/cs_texture_uav.asm | 105 + runtime/test/shaders/ps_imgatomic.asm | 4 +- runtime/test/vk_bindless_test.cpp | 62 +- runtime/test/vk_pipeline_check.cpp | 63 +- runtime/test/vk_store_test.cpp | 99 +- runtime/test/vk_test_device.h | 72 +- runtime/test/vulkan_scratch_test.cpp | 8 +- runtime/test/xbox_cbv_vector_test.cpp | 55 + runtime/test/xbox_d16s8_surface_test.cpp | 48 + runtime/test/xbox_depth_storage_test.cpp | 243 +++ runtime/test/xbox_gpu_label_test.cpp | 59 + runtime/test/xg_xs_test.cpp | 391 +++- runtime/test/xmem_test.cpp | 285 ++- scripts/run_gpu_tests.py | 17 +- tests/test_run_gpu_tests.py | 71 + tests/test_shader_checks.py | 27 +- 88 files changed, 10907 insertions(+), 1058 deletions(-) create mode 100644 runtime/shims/d3d12_xs_native_pso.h create mode 100644 runtime/shims/d3d12_xs_placed_depth.h create mode 100644 runtime/shims/d3d12_xs_pso_stream.cpp create mode 100644 runtime/shims/d3d12_xs_pso_stream.h create mode 100644 runtime/shims/present_window.h create mode 100644 runtime/src/console_texture_layout.h create mode 100644 runtime/src/gpu_label_memory.h create mode 100644 runtime/src/native_pso.h create mode 100644 runtime/src/rgba4_fragment.h create mode 100644 runtime/src/vulkan_gpu_labels.h create mode 100644 runtime/src/vulkan_graphics_shader_modules.h create mode 100644 runtime/test/d3d12_depth_stencil_uav_test.cpp create mode 100644 runtime/test/d3d12_depth_stencil_uav_views.h create mode 100644 runtime/test/d3d12_native_graphics_fixture.h create mode 100644 runtime/test/d3d12_placed_depth_test.h create mode 100644 runtime/test/d3d12_texture_uav_oracle.h create mode 100644 runtime/test/d3d12_texture_uav_test.cpp create mode 100644 runtime/test/glsl/cs_depth_stencil_uav.comp create mode 100644 runtime/test/pso_stream_test.cpp create mode 100644 runtime/test/shaders/cs_cbv_vector_rows.asm create mode 100644 runtime/test/shaders/cs_imgload_mip.asm create mode 100644 runtime/test/shaders/cs_texture_uav.asm create mode 100644 runtime/test/xbox_cbv_vector_test.cpp create mode 100644 runtime/test/xbox_d16s8_surface_test.cpp create mode 100644 runtime/test/xbox_depth_storage_test.cpp create mode 100644 runtime/test/xbox_gpu_label_test.cpp diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 2eb07eeb81..38913f3139 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -610,7 +610,8 @@ What is implemented (all of it testable without the game): Descriptors and the bindless set (milestone M2, without the pipelines that will bind the set), from the shader's side inwards: -- **`runtime/src/vulkan_bindless.h`**: set 0 includes the twenty bindings the translator declares, and +- **`runtime/src/vulkan_bindless.h`**: set 0 includes the single-sample bindings the translator declares, optional + multisample bindings, and `DescriptorTable` (`runtime/src/descriptor_table.h`, section 5.1) behind binding 2. One set for the device. The translator declares every array as a runtime array, so the counts are the runtime's choice. Details: - The device sizes the arrays once, when it creates the set. It does not recreate the set, because pipeline @@ -624,7 +625,7 @@ side inwards: - samplers: up to 4096, and at most `maxSamplerAllocationCount` less 64 for samplers outside the set. That covers a full 2048-sampler D3D12 heap plus room for literal and static S#s. - 2D images: up to 65536. - - storage arrays: up to 4096 each. + - storage arrays: up to 4096 each, capped by their dimension's sampled array or by 256 for storage-only 1D arrays. Growth leaves 64 descriptors of each limit to the other sets of a pipeline layout. It also stays within `maxPerSetDescriptors`, which never shrinks the default counts, because a layout past it may still be @@ -640,17 +641,19 @@ side inwards: shader reads the fallback. `d3d12_descriptor_test` then fills each short array to its last index and checks that the next view and sampler are refused. The other arrays keep their default counts. On an RTX 5070 (driver 621.24, 1048576 of each type - and 4000 samplers) the set has 65536 2D images, 3936 samplers and 4096 storage indices in 2D: 93793 - descriptors, 3-6 MiB at 32-64 bytes a descriptor. The device prints the counts it chose, and - `bindless_sizing_test` checks the rules on synthetic limits. - - An image has one index in its dimension (2D, 2D array, 3D, 1D, 2DMS or 2DMS array), shared by the + and 4000 samplers) the sizing rules give 65536 2D images, 3936 samplers and 4096 storage indices in 2D: + 94561 descriptors with all MS classes, 3-6 MiB at 32-64 bytes a descriptor. The device prints the counts + it chose, and `bindless_sizing_test` checks the rules on synthetic limits. + - An image view has one index in its dimension (2D, 2D array, 3D, 1D, 2DMS, 2DMS array or 1D array), shared by the bindings for that dimension. The runtime adds sampled-image bindings in pairs for 2DMS and 2DMS array: 20/21 for floating-point and normalized color, 22/23 for unsigned integers, and 24/25 for signed integers. The runtime enables pairs that fit the device's descriptor limits and have a multisampled zero fallback of the matching numeric class. A missed key reads zero at texel (0, 0), layer 0, sample 0. + The 1D-array dimension uses storage bindings 26–28 and has no sampled binding. - The storage arrays are shorter (`BindlessSet::storage_capacity`). Each array holds at most as many images as its dimension, and the 2D r32ui array is the same size as the other 2D storage arrays. So an image with a storage view gets an index the storage arrays hold, and a read-only one goes above where there is room. + Index 0 is reserved, so 256 descriptors hold 255 live views in each 1D-array storage binding. - Index 0 of every array is a fallback (a 1x1 image of zeros, a nearest clamping sampler), because a miss is index 0. - Changes are queued and written by `flush()`, one write a slot, so a view that is removed before the next @@ -672,8 +675,8 @@ side inwards: written as zero. - **Device**: `CreateShaderResourceView` and `CreateUnorderedAccessView` of textures write a T# into the slot, `CreateSampler` an S#; each then makes sure set 0 has the view or sampler and the table has the key. Details: - - The key is the descriptor's bytes, so a copied descriptor needs nothing more, and an unordered-access view - and a shader-resource view of the same mip are one entry. + - The key is the descriptor's bytes, so a copied descriptor needs nothing more. An SRV and UAV with identical + bytes can share an entry; a partial 3D UAV carries a W-range tag and remains separate from the unsliced SRV. - A D3D12 comparison sampler with function NEVER and an ordinary sampler both encode zero in the hardware depth comparison field. The layer marks the NEVER comparison in S# word 3, bit 12 (unused with DERIV_ADJUST_EN clear) to give it a separate lookup key and a comparison-enabled Vulkan sampler. @@ -689,7 +692,7 @@ side inwards: images and storage buffers. The standalone device enables them where the GPU has them. - Every `ExecuteCommandLists` flushes the set before its commands are written. - `rt::d3d12::bindless_set` and `bindless_set_layout` hand out the set and its layout: what a pipeline whose - shader declares set-0 bindings is created with and binds. Nothing in the layer creates such a pipeline yet. + shader declares set-0 bindings is created with and binds. - **Layouts.** A descriptor in set 0 has one image layout for as long as it lives, but D3D12 lets a texture be sampled in a shader-resource state and also while promoted from `COMMON`, which is `GENERAL` here (section 4.3). So with the bindless set, a texture's shader-resource states use `GENERAL` too @@ -710,7 +713,7 @@ volume, plus minimum-LOD clamped views (inside the mip range via `VK_EXT_image_v Known gaps in the descriptor path: buffer shader-resource views and constant-buffer views (the V# a shader would load for them; the structure is in `gfx10_descriptors.h`, the views are not written; buffer UAVs of every kind are, section 3.4 "Buffer UAVs", `d3d12_m4_compute_test` and `d3d12_buffer_uav_test`); -1D-array SRVs, 1D and 3D storage views, other typeless volume formats, multisampled depth/stencil and typeless +1D-array SRVs, other typeless volume formats, multisampled depth/stencil and typeless color SRVs, and shader-translator lowering for multisample loads. Single-sampled depth-plane views (`R24_UNORM_X8_TYPELESS`, `R32_FLOAT_X8X24_TYPELESS`) are a T# of the texture's depth format (8_24_UNORM, X24_8_32_FLOAT) through the depth aspect (the texture's backing format, so X24_8_32_FLOAT for a D24 texture where the layer stores it as @@ -1341,13 +1344,19 @@ and any validation error fails them. - That set 0 holds them: a compute shader (`test/glsl/cs_sample.comp`, GLSL, compiled with `glslangValidator`; skipped without it) is handed a slot's T# and the sampler's S#, looks them up in the hash table as a translated shader does, and samples. The sampler wraps in U and the shader samples one tile to the right, - so a missed S# shows too: the fallback sampler clamps. The layer has no pipelines yet, so the test creates - this one in Vulkan and binds the device's set. It reads the texture through the view's own slot and through + so a missed S# shows too: the fallback sampler clamps. The test creates the pipeline in Vulkan and binds + the device's set. It reads the texture through the view's own slot and through a copy of it, and gets the fallback from a slot of bytes no view was made for and, after the texture is destroyed, from the view's own bytes. - Capacity: 5000 distinct SRVs of that texture and one more, and 2100 distinct wrapping samplers in two 2048-slot heaps. The last view through the last sampler reads the texture one tile to the right. With the sizes of before, both were past their arrays ("array is full") and the shader read the fallback. +- `d3d12_texture_uav_test` (D3D-78): creates 1D, 1D-array, 3D and 2D control UAVs through the D3D12 device, + checks rejected descriptors, copies descriptors between slots, and dispatches a translated hand-written + shader from a Vulkan compute pipeline on the actual set 0, not through D3D12 `Dispatch`. It reads back every + texel; the UINT read/modify/write cases (not atomics) also run on Windows WARP. The D3D12 command-list path + is used separately to flush the set and to test clears. + The tests dispatch past the selected array/W range, so writes to an adjacent layer or slice fail the check. - `d3d12_compute_test`: the compute path through the proxy. It creates a root signature from the PC serializer's blob, and a PSO through slot 62 from a container shaped like the game's, found in a translator-style index by its FSSM hash (an unknown program is refused). It sets root constants, a root UAV and a descriptor table whose @@ -1745,10 +1754,31 @@ The layer's descriptor model: If the logical device lacks the feature, the runtime logs the unsupported view and its descriptor resolves to the fallback. A clamp at or below the first mip needs no extension. Above the last mip, the view retains its dimensions and maps sampled channels to zero while preserving constant channels. +- D3D-78: a `Texture1DArray` UAV gets a 1D-array view with the requested array subrange and storage bindings + 26–28 (float, UINT, SINT); `ArraySize = UINT_MAX` selects the remaining layers. A non-array `Texture1D` + view of a 1D array selects layer 0, as checked on native D3D12. A `Texture3D` UAV gets a 3D view with a single mip + and Vulkan array range `{0, 1}`. + A partial W range requires `VK_EXT_image_sliced_view_of_3d` and `robustImageAccess` on the logical device: + `VkImageViewSlicedCreateInfoEXT` rebases storage-image Z to `FirstWSlice` and limits it to `WSize` (`UINT_MAX` + means the remaining mip depth). It does not slice the sampled view. The generated T# tags the W range for + whole-mip and partial UAVs, distinguishes them from SRVs in the hash table, and rebases typed sampled fetches; + see the contract in `docs/design.md`. + Without those features a partial W view is logged and left null, not made writable across the whole mip. + Shader-visible 1D, 1D-array and 3D UAVs require both formatless storage read and write support for the actual + Vulkan view format. `image_load ... glc` uses the storage view for 1D and 3D, and 1D-array loads always use it. + The emulated RGB9E5 raw `R32_UINT` storage view is formatted and is exempt. Vulkan 1.3 permits these SPIR-V + capabilities even without the legacy `shaderStorageImage{Read,Write}WithoutFormat` feature bits. The + caller-owned device test leaves both legacy bits off and masks each per-format bit to verify safe rejection. + `ClearUnorderedAccessView*` refuses partial W ranges and 1D/3D format reinterprets: the transfer clear + cannot target a slice interval or guarantee preserving the reinterpreted bits. + Shader access to the new UAVs requires `robustImageAccess` (whole-mip CPU clears do not). + A separate native D3D12 probe on the RTX 4090 and UHD 770 clipped typed writes to the view's W range. + WARP 10.0.26100.9818 rebased the view but did not clip writes past a finite `WSize` in that probe. The + regression compares in-range writes with WARP and checks preservation of out-of-range slices independently. - Set 0 is a fixed bindless layout, sized once when the device creates it. The defaults are 4096 sampled 2D images, 1024 samplers, 1024 2D-array images, 256 1D, 256 3D and 256 per storage dimension/class. The 2D, sampler and - storage arrays grow to what the device's limits allow, up to 65536, 4096 and 4096 (see `vulkan_bindless.h` - above). The set is not recreated to grow, because recreating it would invalidate the pipeline + storage arrays grow to what the device's limits allow, up to 65536, 4096 and 4096 (1D-array storage stays + capped at 256; see `vulkan_bindless.h` above). The set is not recreated to grow, because recreating it would invalidate the pipeline layouts built on it. Use `UPDATE_AFTER_BIND` and `PARTIALLY_BOUND` so a new view does not require rewriting every descriptor; without those features, rebuild the set when it changes. - The command buffer binds set 0 once; descriptor-heap changes only update the arrays and the hash table. @@ -2182,7 +2212,7 @@ The trace will enumerate them. ### Console rectangle and quad lists The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiveTopology(17)`, with a PSO whose topology type is 19) and quad list (`IASetPrimitiveTopology(19)`). The facts are from xvalkyrie (GPL-3.0, commit `53af7df77c10`; no code taken): a rectangle is three corners and the fourth is v2 + v3 - v1 for the position and every interpolant, after the vertex stage; a quad is four vertices. The layer draws both as triangles (`d3d12_rect_list_test`, RTX 4090: 4096 of 4096 pixels, the colour plane exact, quad list bit-exact). -- **Rectangle list**: PSO type 19 builds a triangle-list pipeline plus a generated geometry stage (`src/rect_list_geometry.h`, written from the vertex shader's own outputs) that takes the three corners and emits the strip v1 v2 v3 v4 (same winding). It has to be post-vertex-stage: the translated vertex shaders fetch by V# themselves, and the fourth corner is a function of what they write. A corner value with the same bits at all three corners (a flat attribute) is copied. Needs `geometryShader` (else `E_NOTIMPL`), no application GS, and a vertex shader with no ClipDistance, CullDistance, Layer or ViewportIndex output. +- **Rectangle list**: PSO type 19 builds a triangle-list pipeline plus a generated geometry stage (`src/rect_list_geometry.h`, written from the vertex shader's own outputs) that takes three corners and emits two triangles with their original winding. It has to be post-vertex-stage: the translated vertex shaders fetch by V# themselves, and the fourth corner is a function of what they write. For axis-aligned rectangles the stage finds the right angle opposite the longest edge in normalized device coordinates. Both output triangles begin at the first submitted vertex so flat inputs retain its value. The integration override `LEONIDA_RECT_FOURTH=v1v3` still forces the second input to be the right-angle corner. Needs `geometryShader` (else `E_NOTIMPL`), no application GS, and a vertex shader with no ClipDistance, CullDistance, Layer or ViewportIndex output. - **Quad list**: a non-indexed draw uses a shared index buffer containing the triangle-list pattern `0 1 2, 0 2 3` for each quad. Both triangles start at the first vertex for flat inputs. One draw preserves instance order and supports up to 16384 quads. The draw's first vertex becomes the vertex offset. Indexed draws still @@ -2272,16 +2302,13 @@ The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiv and resolve bits also require the format's image-usage/sample-count query to succeed. D3D12's per-format rules then apply, as native D3D12 reports them (RX 9070 XT, AMD 26.11.2, and WARP): - `MIP` wherever the image can have more than one level. - - `SHADER_GATHER` with `SHADER_SAMPLE`, including `A8_UNORM`. Its swizzled R8 view gathered the same four - alpha values as native D3D12 and WARP on 49 footprints. `d3d12_descriptor` also verifies a view that forces - alpha to zero. - - `UAV_TYPED_LOAD` with every typed UAV. Typed UAV texture reads use the sampled binding (`image_read_typed`), - not a storage-image read. Typed buffer UAVs: the layer now writes their V# (section 3.4, "Buffer UAVs"); the - gap left is `rdna2spirv.py` `FORMATS`, which decodes only some buffer formats (the 32-bit SINT ones, but no - 8/16-bit SINT/UINT other than the RGBA8 and RGBA16 UINT ones, and no 10_11_11). - - The UAV atomic bits other than exchange for `R32_UINT`, whose UAV views get the `r32ui` storage view. Today - that works on 2D UAVs only: the translator's image atomics and the `r32ui` slots cover 2D and 3D, and the - layer creates no 3D UAV views yet. There is no `image_atomic_swap`, and `R32_SINT` gets no `r32ui` view. + - `SHADER_GATHER` with `SHADER_SAMPLE`, including `A8_UNORM` where the 49-footprint WARP regression verified alpha selection. + - `UAV_TYPED_LOAD` with every typed UAV. Ordinary typed UAV texture reads use the sampled binding + (`image_read_typed`), while coherent `glc` loads and storage-only 1D-array loads use storage-image reads. + Typed buffer UAVs: the layer writes their V# (section 3.4, "Buffer UAVs"); `rdna2spirv.py` `FORMATS` + still limits decoded buffer formats (including gaps in 8/16-bit and 10_11_11 formats). + - The UAV atomic bits other than exchange for `R32_UINT` where Vulkan supports storage image atomics. + The translator and set 0 use the formatted `r32ui` views for 2D and 3D; `R32_SINT` has no `r32ui` view. - `MULTISAMPLE_RENDERTARGET` for depth formats, from the same usages `MULTISAMPLE_QUALITY_LEVELS` queries. - No integer resolve, no 1D block-compressed. Depth formats are 2D and cube only: no 3D, shader reads, UAVs, buffer or vertex use, and no 1D, which native D3D12 allows but the layer's resource creation refuses. @@ -2599,6 +2626,24 @@ The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiv `DEPTH_STENCIL_ATTACHMENT`, `ALLOW_UNORDERED_ACCESS` → `STORAGE`, `ALLOW_SIMULTANEOUS_ACCESS` → concurrent sharing, `DENY_*` → omit the corresponding usage. Buffers get the union of usages their states and flags imply; images copy dimension, format, mip levels, array layers and sample count. +- Xbox depth textures with `ALLOW_DEPTH_STENCIL | ALLOW_UNORDERED_ACCESS` can use legacy committed creation + (slot 76), `CreateCommittedResource3` (forwarded by Xbox slot 127 in the boot stack), or placement at a guest + address (slot 133). Device10 and slot 133 take an initial `D3D12_BARRIER_LAYOUT`. Both check the layout + against the logical texture flags and validate the optimized clear against the native depth format. + Xbox allocation queries return the attachment's placement size for XMem accounting; the writable + planes are private backend allocations. The supported shapes are single-sample, single-mip 2D + textures and 2D arrays. For `R32G8X24_TYPELESS`, use `R32_FLOAT` on depth plane 0 and `R8_UINT` on stencil + plane 1. For `R16_TYPELESS`, use `R16_UINT` on plane 0 to access the raw D16 bits. An array UAV selects a + contiguous range of layers. The depth/stencil and shader-resource views continue to use the attachment image. + Slot 133 keeps the guest address. Identical, live placements share their image and writable planes across + distinct COM objects. A partial overlap or incompatible reinterpretation is refused. +- Legacy and enhanced texture transitions copy the selected planes and layers to or from their storage images. + Fence-ordered graphics and compute queues can share UAV access. A dedicated compute family can perform + the plane transfer itself when `VK_KHR_maintenance10` and the format's depth/stencil copy flags allow it. + Otherwise the graphics queue issues the explicit transitions on either side of the compute work. The two + queue-specific COMMON layouts allow implicit UAV access, so replay refuses them for these textures. + Generic COMMON remains available for copies, shader reads and queue handoffs. + `d3d12_depth_stencil_uav_test` verifies these paths with a synthetic shader and per-pixel readback. - Copies: `CopyBufferRegion` → `vkCmdCopyBuffer` with arena offsets; `CopyTextureRegion` → `vkCmdCopyBufferToImage`/`vkCmdCopyImageToBuffer`/`vkCmdCopyImage`, using the `D3D12_PLACED_SUBRESOURCE_FOOTPRINT` row pitch and height; `CopyResource` → a whole-subresource copy; colour resolves → `vkCmdResolveImage`; @@ -3655,9 +3700,9 @@ store, load, mesh, geometry and BVH tests; this layer is the other half. | `heap_base` (dwords 32–33) | The arena's `vkGetBufferDeviceAddress`. One value per command buffer; updated only if the arena is recreated. | | `code_base` (dwords 34–35) | The console VA of the current shader's FSSM blob in the arena. Per-stage conflict: see below. | | Descriptor hash table (set 0, binding 2) | `uint mask` + entries of `key[8], index, pad`; FNV-1a over the 8 key dwords; linear probe up to 8; miss = index 0. Implemented in `runtime/src/descriptor_table.h` (`DescriptorTable`). The layer inserts every T#/S# it sees and keeps a fallback image/sampler at index 0. | -| Bindless images (bindings 0, 3, 5, 6) | 2D, 2D-array/cube, 1D, 3D sampled-image arrays; one `VkImageView` per distinct T#. Cube textures are 6-layer 2D arrays and cube arrays 6N-layer ones, as the translator expects. | +| Bindless images (bindings 0, 3, 5, 6) | 2D, 2D-array/cube, 1D, 3D sampled-image arrays; typed single-sample shader declarations alias the same binding numbers. Cube textures are 6-layer 2D arrays and cube arrays 6N-layer ones. The runtime also reserves optional MS SRV pairs at 20–25; the translator does not use them yet. | | Samplers (binding 1) | One `VkSampler` per distinct S#; literal S# values from shader constants are pre-registered. | -| Storage images (bindings 4, 7, 8–19) | r32ui/float/sint views by dimension and numeric class; the layer binds each storage image into the float/uint/sint arrays of its dimension (the translator picks by the T# format at run time), with all three arrays as the safe default. | +| Storage images (bindings 4, 7, 8–19, 26–28) | Bindings 4 and 7 are formatted `r32ui` for 2D and 3D atomics. Bindings 8–19 are float/UINT/SINT triples for 2D, 2D-array, 3D and 1D. Bindings 26–28 are the float/UINT/SINT triple for 1D arrays, which have no sampled binding. The translator picks the numeric class from the T# format; the arrays for a dimension share the same index. | | Buffer/image binding | Descriptors contain console VAs, never host BDAs. Buffers are in the arena at their VA; images are keyed by T# through the hash table. | | Vertex fetch | PSO input layout + ISG1 signature; location = D3D input register; format from `DXGI_FORMAT`; instance step rate from the layout. The fetch subroutine is already replaced by Vulkan inputs. | | PS system inputs | `FragCoord` (xy/z/w), `FrontFacing`, barycentrics; enable `fragmentShaderBarycentric` and `fragmentShaderPixelInterlock` when the index entry asks. | diff --git a/docs/runtime_imports.md b/docs/runtime_imports.md index 5cba370c6e..51aba517ca 100644 --- a/docs/runtime_imports.md +++ b/docs/runtime_imports.md @@ -165,13 +165,19 @@ policy "other" (none is counted as returning an `HRESULT`), and they come from s The game executable imports two functions from `xg_xs.dll`, the console's texture layout library: `XGSuggestSwizzleMode` (2 call sites, in the helper that fills a texture description) and `XGCreateTextureComputer` -(4 call sites, which use slots 1, 2, 8 and 10 of the returned object's vtable). The runtime has no model of the console -resource layout, so `runtime/shims/xg_xs.cpp` computes none: both return `E_NOTIMPL` and write no layout. Two of the -four `XGCreateTextureComputer` callers ignore the HRESULT and call through the object at once, so the shim still stores -a static object in the out pointer; its slot 1 (read as `Release`) does nothing, and every other slot up to 31 logs its -index and caller once and returns `E_NOTIMPL` without writing its arguments. The call shapes and the reasoning are at -the top of the file; `xg_xs_test` covers them. Textures whose layout the game asks for are therefore not laid out yet. -The table above was measured before this shim and still lists these two as unimplemented; they are served now. +(4 call sites, which use slots 1, 2, 8 and 10 of the returned object's vtable). `runtime/shims/xg_xs.cpp` answers them +from a model of the console's texture layouts, `runtime/src/console_texture_layout.h` (AMD addrlib's GFX10 rules for +the linear, 256 B, 4 KiB and 64 KiB modes: block shapes, mip tails, the micro tile patterns, a separate stencil plane), +ported with the computer's method table and layout structure from Marvisak/VIctory (GPL-3.0, `xg.rs` and `texture.rs` +at `d2a4bae1f`). `XGSuggestSwizzleMode` writes `0x100 | mode` (linear for 1D, `64KB_Z_X` for depth, `64KB_R_X` for +render targets, else `4KB_S`); the computer fills the layout (slot 2), gives an element's offset (slot 6), copies a +subresource into (slot 8) and out of (slot 9) tiled memory, and reports the 64 KiB tiling (slot 10). Not modelled: +compression metadata planes, and addressing or copies for the pipe/bank XOR modes and MSAA (`E_NOTIMPL`). A description +it cannot lay out still gets a computer in the out pointer with `E_INVALIDARG`, because two of the four callers ignore +the HRESULT and call through the object at once; that object answers every slot with `E_NOTIMPL` and writes nothing. +`xg_xs_test` covers the model (hand-checked addresses, mip tails, a bijection and round trip over every element) and the +shim's slots. The table above was measured before this shim and still lists these two as unimplemented; they are served +now. Only two of these DLLs have a shim in the repository (`xmem.dll` and `d3d12_xs.dll`), and they are not complete: they hold 8 of the 30 unimplemented imports. The other 22 are in five DLLs (`xg_xs.dll`, `XCRDAPI.dll`, `chad.dll`, diff --git a/docs/testing.md b/docs/testing.md index 71edca6cc1..eff61f475a 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -178,7 +178,29 @@ python -I runtime/test/shaders/build.py vs_ids ps_mullit python -I runtime/test/shaders/mullit_readback.py ``` -For D3D12/runtime tests, `LEONIDA_VK_VALIDATION=1` enables `VK_LAYER_KHRONOS_validation`. When running with validation, set `DISABLE_RTSS_LAYER=1` and `DISABLE_VULKAN_OBS_CAPTURE=1` if MSI Afterburner (RivaTuner) or OBS is installed: their overlay layers can add unsupported swapchain usage, and in an elevated (administrator) terminal the loader ignores `VK_LOADER_LAYERS_DISABLE=~implicit~` (see "Known problems"). +For D3D12/runtime tests, `LEONIDA_VK_VALIDATION=1` enables `VK_LAYER_KHRONOS_validation`. When running with +validation, set `DISABLE_RTSS_LAYER=1` and `DISABLE_VULKAN_OBS_CAPTURE=1` if MSI Afterburner (RivaTuner) or OBS is +installed: their overlay layers can add unsupported swapchain usage, and in an elevated (administrator) terminal +the loader ignores `VK_LOADER_LAYERS_DISABLE=~implicit~` (see "Known problems"). + +On Windows, `run_gpu_tests.py` assembles and translates the D3D-78 fixture and runs the UAV readback and WARP +comparison from the same build folder. Use `--filter cs_texture_uav` to run only this case: + +```powershell +$env:LEONIDA_VK_VALIDATION = "1" +python -I scripts/run_gpu_tests.py --build runtime/build --filter cs_texture_uav +``` + +Use the actual configuration subfolder for the executables with a multi-config generator. The native Windows +case reports SKIP without WARP or a sufficiently capable Vulkan device; failed translation, a missing test +executable on Windows, and readback mismatches fail the runner. Devices without sliced 3D views still run the 1D, +array and whole-mip cases and check that partial views are refused. + +CTest runs the same D3D-78 descriptor creation, copy, range/refusal and clear checks with `--descriptors-only`. +That mode requires Vulkan, but not a translated shader or WARP. The GPU runner still exercises dispatch and readback. + +Use `--filter cs_imgload_mip` to check 2D `image_load_mip` on FLOAT (UNORM), UINT and SINT sampled views with +both full-width and D16 loads; mip 0 contains decoy data and mip 1 holds the expected texels. `vk_compute_test`, `vk_bindless_test` and `vk_image_fuzz` read `LEONIDA_VK_VALIDATION` too (`vk_compute_test` through `runtime/test/vk_validation.h`): each validation message goes to stderr and a validation error makes the diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index a094719f93..2b4174cc81 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -118,7 +118,7 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) shims/xg_xs.cpp shims/acphal.cpp shims/d3d12_xs.cpp - shims/d3d12_xs_device.cpp + shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp shims/xgameruntime.cpp shims/xgameruntime_user.cpp shims/xgameruntime_gamesave.cpp @@ -172,7 +172,7 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) test/root_sig_test.cpp shims/registry.cpp shims/d3d12_xs.cpp - shims/d3d12_xs_device.cpp + shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ) target_link_libraries(root_sig_test PRIVATE gta6rt_d3d12_xs_rootsig ${D3D12_LIBRARY}) target_compile_definitions(root_sig_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) @@ -196,7 +196,7 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) test/device_proxy_test.cpp shims/registry.cpp shims/d3d12_xs.cpp - shims/d3d12_xs_device.cpp + shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ) target_link_libraries(device_proxy_test PRIVATE gta6rt_d3d12_xs_rootsig ${D3D12_LIBRARY} ${DXGI_LIBRARY}) target_compile_definitions(device_proxy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) @@ -209,7 +209,7 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) # patches its own import table to inject failures, so the proxy source is compiled into it alone. add_executable(xs_proxy_mock_test test/xs_proxy_mock_test.cpp - shims/d3d12_xs_device.cpp + shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ) target_compile_definitions(xs_proxy_mock_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) target_compile_options(xs_proxy_mock_test PRIVATE /W4 /permissive- /utf-8 /EHsc) @@ -668,7 +668,7 @@ if(BUILD_TESTING) shims/registry.cpp shims/xmem.cpp shims/d3d12_xs.cpp - shims/d3d12_xs_device.cpp + shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ) target_include_directories(pe_loader_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src @@ -809,7 +809,7 @@ if(BUILD_TESTING) shims/registry.cpp shims/xmem.cpp shims/d3d12_xs.cpp - shims/d3d12_xs_device.cpp + shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ) target_include_directories(test_pe_loader_bounds PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src @@ -833,7 +833,7 @@ if(BUILD_TESTING) shims/registry.cpp shims/xmem.cpp shims/d3d12_xs.cpp - shims/d3d12_xs_device.cpp + shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ) target_include_directories(pe_loader_fuzz PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src @@ -1079,6 +1079,10 @@ if(BUILD_TESTING) if(TARGET device_proxy_test) add_test(NAME device_proxy COMMAND device_proxy_test) + add_executable(pso_stream_test test/pso_stream_test.cpp shims/d3d12_xs_pso_stream.cpp) + target_include_directories(pso_stream_test PRIVATE shims) + add_test(NAME pso_stream_records COMMAND pso_stream_test) + set_tests_properties(device_proxy PROPERTIES SKIP_RETURN_CODE 77) # no WARP adapter (Wine) # With --trace-d3d12 the 24 D3D12XboxCreateDevice parameter words still print (docs/boot.md, question 1), # and the line with run-specific pointers does not. @@ -1183,7 +1187,7 @@ if(BUILD_TESTING) shims/registry.cpp shims/xmem.cpp shims/d3d12_xs.cpp - shims/d3d12_xs_device.cpp + shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ) target_compile_definitions(fsr_dispatch_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) target_compile_options(fsr_dispatch_test PRIVATE /W4 /permissive- /EHsc /utf-8) @@ -1200,7 +1204,7 @@ if(BUILD_TESTING) shims/registry.cpp shims/xmem.cpp shims/d3d12_xs.cpp - shims/d3d12_xs_device.cpp + shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ) target_compile_definitions(bvh_builder_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) target_compile_options(bvh_builder_test PRIVATE /W4 /permissive- /EHsc /utf-8) @@ -1430,7 +1434,7 @@ if(LEONIDA_D3D12_SHIM_TESTS) test/d3d12_xs_root_signature_test.cpp shims/d3d12_xs.cpp shims/registry.cpp - shims/d3d12_xs_device.cpp + shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ) target_include_directories(d3d12_xs_root_signature_test PRIVATE shims) target_compile_definitions(d3d12_xs_root_signature_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) @@ -1775,7 +1779,7 @@ if(TARGET Vulkan::Headers) DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/../tools/gen_d3d12_stubs.py ${LEONIDA_D3D12_HEADER} COMMENT "Generating D3D12 COM stubs" VERBATIM) - add_library(gta6rt_d3d12_com STATIC shims/d3d12_com.cpp shims/d3d12_vulkan_device.cpp shims/d3d12_xs_device.cpp shims/xbox_present.cpp + add_library(gta6rt_d3d12_com STATIC shims/d3d12_com.cpp shims/d3d12_vulkan_device.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp shims/xbox_present.cpp shims/dxgi_com.cpp ${LEONIDA_STUBS}) # d3d12_vulkan_device.cpp reads the PC device behind the proxy (#224) target_include_directories(gta6rt_d3d12_com PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/generated) target_link_libraries(gta6rt_d3d12_com PUBLIC Vulkan::Headers gta6rt_root_signature) @@ -2100,6 +2104,10 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_xmem_placed_test PRIVATE /W4 /permissive- /utf-8) target_link_options(d3d12_xmem_placed_test PRIVATE /OPT:NOREF) add_test(NAME d3d12_xmem_placed COMMAND d3d12_xmem_placed_test) + add_test(NAME xbox_linear_texture_map COMMAND d3d12_xmem_placed_test --linear-map) + add_test(NAME xbox_linear_gpu_staging COMMAND d3d12_xmem_placed_test --linear-staging) + set_tests_properties(xbox_linear_gpu_staging PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30) + set_tests_properties(xbox_linear_texture_map PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30) set_tests_properties(d3d12_xmem_placed PROPERTIES SKIP_RETURN_CODE 77) # Fences and timing (D3D-30): multiple-fence waits, clock calibration, adapter LUID, custom heap properties. @@ -2259,6 +2267,14 @@ if(TARGET Vulkan::Headers) set_tests_properties(pipeline_cache_seed PROPERTIES SKIP_REGULAR_EXPRESSION "SKIP: ") endif() + # Test descriptor creation and clears in CTest without shader tools. The GPU runner passes the translated + # cs_texture_uav.spv to also exercise dispatches through set 0 and compare texels with Windows WARP. + add_executable(d3d12_texture_uav_test test/d3d12_texture_uav_test.cpp) + target_link_libraries(d3d12_texture_uav_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_texture_uav_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_texture_uav_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_texture_uav COMMAND d3d12_texture_uav_test --descriptors-only) + set_tests_properties(d3d12_texture_uav PROPERTIES SKIP_RETURN_CODE 77) # What Close returns after one recorded call, against WARP; today's differences are listed in the test. add_executable(d3d12_close_parity_test test/d3d12_close_parity_test.cpp) target_link_libraries(d3d12_close_parity_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) @@ -2462,6 +2478,28 @@ if(TARGET Vulkan::Headers) set_tests_properties(d3d12_pipeline_library_host PROPERTIES SKIP_RETURN_CODE 77) # Milestone M0: a window, 60 cleared frames presented through the proxy on Vulkan. + add_executable(xbox_cbv_vector_test test/xbox_cbv_vector_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp) + target_link_libraries(xbox_cbv_vector_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(xbox_cbv_vector_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_VULKAN_DEVICE) + add_test(NAME xbox_cbv_vectors COMMAND xbox_cbv_vector_test) + set_tests_properties(xbox_cbv_vectors PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 20) + add_executable(xbox_depth_storage_test test/xbox_depth_storage_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp) + target_link_libraries(xbox_depth_storage_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(xbox_depth_storage_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_VULKAN_DEVICE) + add_test(NAME xbox_depth_storage COMMAND xbox_depth_storage_test) + add_test(NAME xbox_d16s8_storage COMMAND xbox_depth_storage_test) + set_tests_properties(xbox_d16s8_storage PROPERTIES ENVIRONMENT "LEONIDA_TEST_D16S8_UAV=1" SKIP_RETURN_CODE 77 TIMEOUT 30) + set_tests_properties(xbox_depth_storage PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30) + add_executable(xbox_d16s8_surface_test test/xbox_d16s8_surface_test.cpp) + target_link_libraries(xbox_d16s8_surface_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(xbox_d16s8_surface_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + add_test(NAME xbox_d16s8_surface COMMAND xbox_d16s8_surface_test) + set_tests_properties(xbox_d16s8_surface PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 20) + add_executable(xbox_gpu_label_test test/xbox_gpu_label_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp) + target_link_libraries(xbox_gpu_label_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(xbox_gpu_label_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_VULKAN_DEVICE) + add_test(NAME xbox_gpu_label_completion COMMAND xbox_gpu_label_test) + set_tests_properties(xbox_gpu_label_completion PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 20) add_executable(d3d12_present_test test/d3d12_present_test.cpp) target_link_libraries(d3d12_present_test PRIVATE gta6rt_d3d12_com user32 gdi32 dxgi) target_compile_definitions(d3d12_present_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) @@ -2470,7 +2508,7 @@ if(TARGET Vulkan::Headers) set_tests_properties(d3d12_present PROPERTIES SKIP_RETURN_CODE 77) # Per-pipeline --f16-interp-fallback linking (SHADER-378): 16-param VS + colliding PS rendered on Vulkan. - add_executable(d3d12_f16_halves_test test/d3d12_f16_halves_test.cpp shims/d3d12_xs_device.cpp) + add_executable(d3d12_f16_halves_test test/d3d12_f16_halves_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp) target_link_libraries(d3d12_f16_halves_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) target_compile_definitions(d3d12_f16_halves_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) target_compile_options(d3d12_f16_halves_test PRIVATE /W4 /permissive- /utf-8) @@ -2506,7 +2544,7 @@ if(TARGET Vulkan::Headers) # First light through D3D12 (docs/first_light.md): the real model and translated VS/PS that tools/first_light.py # wrote to LEONIDA_FIRST_LIGHT_DIR, drawn through the device proxy. Skips (77) unless that variable is set. - add_executable(d3d12_first_light_test test/d3d12_first_light_test.cpp shims/d3d12_xs_device.cpp) + add_executable(d3d12_first_light_test test/d3d12_first_light_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp) target_link_libraries(d3d12_first_light_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_first_light_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) target_compile_options(d3d12_first_light_test PRIVATE /W4 /permissive- /utf-8) @@ -2546,17 +2584,21 @@ if(TARGET Vulkan::Headers) ${CMAKE_CURRENT_SOURCE_DIR}/../tools/rdna2spirv.py COMMENT "Translating vs_m15 and ps_m15 for the translated draw test" VERBATIM) - add_executable(d3d12_translated_draw_test test/d3d12_translated_draw_test.cpp shims/d3d12_xs_device.cpp + add_executable(d3d12_translated_draw_test test/d3d12_translated_draw_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_M15_FILES}) target_link_libraries(d3d12_translated_draw_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_translated_draw_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_TEST_M15_DIR="${LEONIDA_M15_DIR}") target_compile_options(d3d12_translated_draw_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_translated_draw COMMAND d3d12_translated_draw_test) + add_test(NAME xbox_native_base_draw COMMAND d3d12_translated_draw_test --native-pso) + add_test(NAME xbox_derived_mask_zero COMMAND d3d12_translated_draw_test --derived-zero) + add_test(NAME xbox_derived_mask_restore COMMAND d3d12_translated_draw_test --derived-restore) + set_tests_properties(d3d12_translated_draw PROPERTIES SKIP_RETURN_CODE 77) # The console's rectangle and quad lists (src/rect_list_geometry.h), through the same translated vs_m15 / ps_m15. - add_executable(d3d12_rect_list_test test/d3d12_rect_list_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_M15_FILES}) + add_executable(d3d12_rect_list_test test/d3d12_rect_list_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_M15_FILES}) target_link_libraries(d3d12_rect_list_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_rect_list_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_TEST_M15_DIR="${LEONIDA_M15_DIR}") @@ -2612,13 +2654,31 @@ if(TARGET Vulkan::Headers) ${CMAKE_CURRENT_SOURCE_DIR}/../tools/rdna2spirv.py COMMENT "Translating vs_m2 and ps_m2 for the textured draw test" VERBATIM) - add_executable(d3d12_m2_textured_test test/d3d12_m2_textured_test.cpp shims/d3d12_xs_device.cpp + add_executable(d3d12_m2_textured_test test/d3d12_m2_textured_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_M2_FILES}) target_link_libraries(d3d12_m2_textured_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_m2_textured_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_TEST_M2_DIR="${LEONIDA_M2_DIR}") target_compile_options(d3d12_m2_textured_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_m2_textured COMMAND d3d12_m2_textured_test) + add_test(NAME xbox_visible_texture_views COMMAND d3d12_m2_textured_test) + set_tests_properties(xbox_visible_texture_views PROPERTIES ENVIRONMENT "LEONIDA_TEST_VISIBLE_VIEWS=1" SKIP_RETURN_CODE 77 TIMEOUT 25) + add_test(NAME xbox_staged_texture_views COMMAND d3d12_m2_textured_test) + set_tests_properties(xbox_staged_texture_views PROPERTIES ENVIRONMENT "LEONIDA_TEST_STAGED_VIEWS=1" SKIP_RETURN_CODE 77 TIMEOUT 25) + add_test(NAME xbox_placed_texture_first_use COMMAND d3d12_m2_textured_test) + set_tests_properties(xbox_placed_texture_first_use PROPERTIES ENVIRONMENT "LEONIDA_TEST_PLACED_FIRST_USE=1" SKIP_RETURN_CODE 77 TIMEOUT 25) + add_test(NAME xbox_raw_2d_stripes COMMAND d3d12_m2_textured_test) + set_tests_properties(xbox_raw_2d_stripes PROPERTIES ENVIRONMENT "LEONIDA_TEST_LARGE_RAW_TEXTURE=1" SKIP_RETURN_CODE 77 TIMEOUT 35) + add_test(NAME xbox_raw_2d_surface COMMAND d3d12_m2_textured_test) + set_tests_properties(xbox_raw_2d_surface PROPERTIES ENVIRONMENT "LEONIDA_TEST_RAW_TEXTURE=1" SKIP_RETURN_CODE 77 TIMEOUT 25) + add_test(NAME xbox_packed4444_clear_sample COMMAND d3d12_m2_textured_test) + set_tests_properties(xbox_packed4444_clear_sample PROPERTIES ENVIRONMENT "LEONIDA_TEST_FIXED4=1" SKIP_RETURN_CODE 77) + add_test(NAME d3d12_m2_sampler_refresh COMMAND d3d12_m2_textured_test --refresh-samplers) + add_test(NAME d3d12_m2_unbounded_sampler_refresh COMMAND d3d12_m2_textured_test --refresh-unbounded-samplers) + set_tests_properties(d3d12_m2_sampler_refresh d3d12_m2_unbounded_sampler_refresh PROPERTIES + SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_DESC_MIRROR=1") + add_test(NAME d3d12_m2_sampler_refresh_off COMMAND d3d12_m2_textured_test --refresh-samplers-off) + set_tests_properties(d3d12_m2_sampler_refresh_off PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_DESC_MIRROR=0") set_tests_properties(d3d12_m2_textured PROPERTIES SKIP_RETURN_CODE 77) # M2, formats: BC1 and BC7 textures with mip chains and an R8G8B8A8 2D array through the same descriptor path. @@ -2640,7 +2700,7 @@ if(TARGET Vulkan::Headers) ${CMAKE_CURRENT_SOURCE_DIR}/../tools/rdna2spirv.py COMMENT "Translating vs_m2, ps_m2 and ps_m2_array for the M2 formats test" VERBATIM) - add_executable(d3d12_m2_formats_test test/d3d12_m2_formats_test.cpp shims/d3d12_xs_device.cpp + add_executable(d3d12_m2_formats_test test/d3d12_m2_formats_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_M2F_FILES}) target_link_libraries(d3d12_m2_formats_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_m2_formats_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX @@ -2672,7 +2732,7 @@ if(TARGET Vulkan::Headers) ${CMAKE_CURRENT_SOURCE_DIR}/../tools/rdna2spirv.py COMMENT "Translating M3 frame and single-output occlusion-probe shaders" VERBATIM) - add_executable(d3d12_m3_frame_test test/d3d12_m3_frame_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_M3_FILES}) + add_executable(d3d12_m3_frame_test test/d3d12_m3_frame_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_M3_FILES}) target_link_libraries(d3d12_m3_frame_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_m3_frame_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_TEST_M3_DIR="${LEONIDA_M3_DIR}") @@ -2705,7 +2765,7 @@ if(TARGET Vulkan::Headers) ${CMAKE_CURRENT_SOURCE_DIR}/../tools/rdna2spirv.py COMMENT "Translating cs_m4_fill and cs_m4_indirect for the compute test" VERBATIM) - add_executable(d3d12_m4_compute_test test/d3d12_m4_compute_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_M4_FILES}) + add_executable(d3d12_m4_compute_test test/d3d12_m4_compute_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_M4_FILES}) target_link_libraries(d3d12_m4_compute_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_m4_compute_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_TEST_M4_DIR="${LEONIDA_M4_DIR}") @@ -2735,7 +2795,7 @@ if(TARGET Vulkan::Headers) ${CMAKE_CURRENT_SOURCE_DIR}/../tools/rdna2spirv.py COMMENT "Translating cs_buf_typed and cs_buf_counter for the buffer UAV test" VERBATIM) - add_executable(d3d12_buffer_uav_test test/d3d12_buffer_uav_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_BUFFER_UAV_FILES}) + add_executable(d3d12_buffer_uav_test test/d3d12_buffer_uav_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_BUFFER_UAV_FILES}) target_link_libraries(d3d12_buffer_uav_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_buffer_uav_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_TEST_BUFFER_UAV_DIR="${LEONIDA_BUFFER_UAV_DIR}") @@ -2756,7 +2816,7 @@ if(TARGET Vulkan::Headers) # Console Xbox CreateDescriptorHeap extended ABI (issue #313 comment 7107265058): the title passes address/size # after the PC desc and expects GetCPU/GPUDescriptorHandleForHeapStart() == address. Synthetic test; no title-memory # aliasing / §3.3 backing coverage. - add_executable(d3d12_console_descriptor_heap_test test/d3d12_console_descriptor_heap_test.cpp shims/d3d12_xs_device.cpp) + add_executable(d3d12_console_descriptor_heap_test test/d3d12_console_descriptor_heap_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp) target_link_libraries(d3d12_console_descriptor_heap_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) target_compile_definitions(d3d12_console_descriptor_heap_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) target_compile_options(d3d12_console_descriptor_heap_test PRIVATE /W4 /permissive- /utf-8) @@ -2890,7 +2950,7 @@ if(TARGET Vulkan::Headers) DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_user_data.comp COMMENT "Compiling the compute test shader" VERBATIM) - add_executable(d3d12_compute_test test/d3d12_compute_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_CS}) + add_executable(d3d12_compute_test test/d3d12_compute_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_TEST_CS}) target_link_libraries(d3d12_compute_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_compute_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_TEST_CS_SPV="${LEONIDA_TEST_CS}") @@ -2898,15 +2958,25 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_compute COMMAND d3d12_compute_test) set_tests_properties(d3d12_compute PROPERTIES SKIP_RETURN_CODE 77) # A buffer at the title's own VA (device slot 133) read by the same shader through a root view and a V#. - add_executable(d3d12_title_va_test test/d3d12_title_va_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_CS}) + add_executable(d3d12_title_va_test test/d3d12_title_va_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_TEST_CS}) target_link_libraries(d3d12_title_va_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_title_va_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_TEST_CS_SPV="${LEONIDA_TEST_CS}") target_compile_options(d3d12_title_va_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_title_va COMMAND d3d12_title_va_test) set_tests_properties(d3d12_title_va PROPERTIES SKIP_RETURN_CODE 77) + add_test(NAME d3d12_api_descriptor_copy COMMAND d3d12_title_va_test --api-descriptor-copy) + set_tests_properties(d3d12_api_descriptor_copy PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_DESC_MIRROR=1") + add_test(NAME d3d12_api_descriptor_copy_off COMMAND d3d12_title_va_test --api-descriptor-copy-off) + set_tests_properties(d3d12_api_descriptor_copy_off PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_DESC_MIRROR=0") + add_test(NAME d3d12_rebound_tables COMMAND d3d12_title_va_test --rebound-tables) + set_tests_properties(d3d12_rebound_tables PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_DESC_MIRROR=1") + add_test(NAME d3d12_rebound_tables_off COMMAND d3d12_title_va_test --rebound-tables-off) + set_tests_properties(d3d12_rebound_tables_off PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_DESC_MIRROR=0") + add_test(NAME d3d12_rebound_second_device COMMAND d3d12_title_va_test --rebound-second-device) + set_tests_properties(d3d12_rebound_second_device PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_DESC_MIRROR=1") # Compute PSOs from FSPX programs (docs/fspx.md): an ACCC container at slot 62 and a bare kind-6 program. - add_executable(d3d12_fspx_compute_test test/d3d12_fspx_compute_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_CS}) + add_executable(d3d12_fspx_compute_test test/d3d12_fspx_compute_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_TEST_CS}) target_link_libraries(d3d12_fspx_compute_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_fspx_compute_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_TEST_CS_SPV="${LEONIDA_TEST_CS}") @@ -2933,7 +3003,7 @@ if(TARGET Vulkan::Headers) COMMENT "Compiling the draw test shader ${source}" VERBATIM) endforeach() - add_executable(d3d12_draw_test test/d3d12_draw_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_VS} + add_executable(d3d12_draw_test test/d3d12_draw_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_TEST_VS} ${LEONIDA_TEST_PS} ${LEONIDA_TEST_PS_UINT} ${LEONIDA_TEST_VS_FULLSCREEN} ${LEONIDA_TEST_VS_INT}) target_link_libraries(d3d12_draw_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_draw_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX @@ -2943,6 +3013,8 @@ if(TARGET Vulkan::Headers) LEONIDA_TEST_VS_INT_SPV="${LEONIDA_TEST_VS_INT}") target_compile_options(d3d12_draw_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_draw COMMAND d3d12_draw_test) + add_test(NAME xbox_geometry_upload_batch COMMAND d3d12_draw_test) + set_tests_properties(xbox_geometry_upload_batch PROPERTIES ENVIRONMENT "LEONIDA_TEST_GEOMETRY_BATCH=1" SKIP_RETURN_CODE 77 TIMEOUT 40) set_tests_properties(d3d12_draw PROPERTIES SKIP_RETURN_CODE 77) # Graphics & compute PSO descriptor validation parity against live Windows D3D12 (WARP and HW). add_executable(d3d12_pso_validation_test test/d3d12_pso_validation_test.cpp ${LEONIDA_TEST_VS} @@ -3013,7 +3085,7 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_conservative_tier3 COMMAND d3d12_conservative_tier3_test) set_tests_properties(d3d12_inner_coverage_guards d3d12_inner_coverage_native d3d12_conservative_tier3 PROPERTIES SKIP_RETURN_CODE 77) - add_executable(d3d12_msaa_draw_test test/d3d12_msaa_draw_test.cpp shims/d3d12_xs_device.cpp + add_executable(d3d12_msaa_draw_test test/d3d12_msaa_draw_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_TEST_VS} ${LEONIDA_TEST_PS}) target_link_libraries(d3d12_msaa_draw_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_msaa_draw_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX @@ -3022,7 +3094,7 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_msaa_draw COMMAND d3d12_msaa_draw_test) set_tests_properties(d3d12_msaa_draw 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 + 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}) target_link_libraries(d3d12_geometry_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_geometry_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX @@ -3049,7 +3121,7 @@ if(TARGET Vulkan::Headers) COMMENT "Compiling the D24 draw test shader ${source}" VERBATIM) endforeach() - add_executable(d3d12_depth24_draw_test test/d3d12_depth24_draw_test.cpp shims/d3d12_xs_device.cpp + add_executable(d3d12_depth24_draw_test test/d3d12_depth24_draw_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_TEST_VS_DEPTH} ${LEONIDA_TEST_PS_DEPTH_EMPTY} ${LEONIDA_TEST_PS_DEPTH_WRITE} ${LEONIDA_TEST_GS_DEPTH}) target_link_libraries(d3d12_depth24_draw_test PRIVATE gta6rt_d3d12_com) @@ -3071,7 +3143,7 @@ if(TARGET Vulkan::Headers) DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_set0_sample.comp COMMENT "Compiling the set-0 compute test shader" VERBATIM) - add_executable(d3d12_set0_compute_test test/d3d12_set0_compute_test.cpp shims/d3d12_xs_device.cpp + add_executable(d3d12_set0_compute_test test/d3d12_set0_compute_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_TEST_CS_SET0_SAMPLE}) target_link_libraries(d3d12_set0_compute_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_set0_compute_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX @@ -3079,9 +3151,28 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_set0_compute_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_set0_compute COMMAND d3d12_set0_compute_test) set_tests_properties(d3d12_set0_compute PROPERTIES SKIP_RETURN_CODE 77) + set(depth_uav_shader ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_depth_stencil_uav.comp) + foreach(variant IN ITEMS DEPTH_STENCIL_2D DEPTH_STENCIL_ARRAY DEPTH16_2D DEPTH16_ARRAY) + set(spv ${CMAKE_CURRENT_BINARY_DIR}/generated/cs_depth_uav_${variant}.spv) + add_custom_command(OUTPUT ${spv} + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_CURRENT_BINARY_DIR}/generated + COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -D${variant}=1 + -o ${spv} ${depth_uav_shader} + DEPENDS ${depth_uav_shader} VERBATIM) + list(APPEND depth_uav_shaders ${spv}) + list(APPEND depth_uav_definitions LEONIDA_${variant}_SPV="${spv}") + endforeach() + add_executable(d3d12_depth_stencil_uav_test test/d3d12_depth_stencil_uav_test.cpp + shims/d3d12_xs_device.cpp ${depth_uav_shaders}) + target_link_libraries(d3d12_depth_stencil_uav_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_depth_stencil_uav_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + ${depth_uav_definitions}) + target_compile_options(d3d12_depth_stencil_uav_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_depth_stencil_uav COMMAND d3d12_depth_stencil_uav_test) + set_tests_properties(d3d12_depth_stencil_uav PROPERTIES SKIP_RETURN_CODE 77) # Bindless table churn on a direct and a compute queue: the table grows and live keys move without a # device-idle wait (D3D-314); the same shader, run twice (deferred retirement, and the old wait for timing). - add_executable(d3d12_bindless_churn_test test/d3d12_bindless_churn_test.cpp shims/d3d12_xs_device.cpp + add_executable(d3d12_bindless_churn_test test/d3d12_bindless_churn_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_TEST_CS_SET0_SAMPLE}) target_link_libraries(d3d12_bindless_churn_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_bindless_churn_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX @@ -3109,6 +3200,10 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_bundle_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_bundle COMMAND d3d12_bundle_test) set_tests_properties(d3d12_bundle PROPERTIES SKIP_RETURN_CODE 77) + add_test(NAME d3d12_root_layout_compact COMMAND d3d12_bundle_test --compact) + add_test(NAME d3d12_root_layout_legacy COMMAND d3d12_bundle_test --legacy) + set_tests_properties(d3d12_root_layout_compact PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_GRAPHICS_STAGE_LAYOUT=1") + set_tests_properties(d3d12_root_layout_legacy PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_GRAPHICS_STAGE_LAYOUT=0") # Calls a bundle may not make, Close of the bundle and of its parent, against the host runtime and WARP. add_executable(d3d12_bundle_forbidden_test test/d3d12_bundle_forbidden_test.cpp) target_link_libraries(d3d12_bundle_forbidden_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) @@ -3147,7 +3242,7 @@ if(TARGET Vulkan::Headers) DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/ms_draw.mesh COMMENT "Compiling the mesh test shader ms_draw.mesh" VERBATIM) - add_executable(d3d12_mesh_test test/d3d12_mesh_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_MS} + add_executable(d3d12_mesh_test test/d3d12_mesh_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_TEST_MS} ${LEONIDA_TEST_PS} ${LEONIDA_TEST_VS_FULLSCREEN}) target_link_libraries(d3d12_mesh_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_mesh_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX @@ -3215,7 +3310,7 @@ if(TARGET Vulkan::Headers) VERBATIM) list(APPEND LEONIDA_SG_INDEXES ${output}) endforeach() - add_executable(d3d12_subgroup_test test/d3d12_subgroup_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_SG_INDEXES}) + add_executable(d3d12_subgroup_test test/d3d12_subgroup_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_SG_INDEXES}) target_link_libraries(d3d12_subgroup_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_subgroup_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_TEST_SUBGROUP_SHADERS="${LEONIDA_SG_DIR}") diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index a1aa3ccc55..a77b0824a6 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -206,6 +206,15 @@ class GraphicsCommandList final const std::vector>& tables() const { return tables_; } // The pipeline states and root signatures the recording names (it holds a reference to each until Reset). const std::vector& pinned() const { return held_; } + bool needs_all_sampled_views() const { + if (directly_indexed_) return true; + for (const auto& command : list_.commands()) { + if (std::holds_alternative(command)) return true; + if (tables_.empty() && (std::holds_alternative(command) || + std::holds_alternative(command))) return true; + } + return false; + } UINT front_stencil_ref() const { return front_stencil_ref_; } UINT back_stencil_ref() const { return back_stencil_ref_; } D3D12_GPU_VIRTUAL_ADDRESS cbv_srv_uav_base() const { return cbv_srv_uav_base_; } @@ -241,6 +250,7 @@ class GraphicsCommandList final invalid_ = false; calls_.clear(); tables_.clear(); + directly_indexed_ = false; release_held(); // what the old recording used: it was replayed at ExecuteCommandLists reset_state(state); // Reset returns every list state to its default if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) set_initial_pipeline(state); // reset_state holds it @@ -506,19 +516,30 @@ class GraphicsCommandList final for (UINT i = 0; i < count; ++i) { const auto& b = barriers[i]; switch (b.Type) { - case D3D12_RESOURCE_BARRIER_TYPE_TRANSITION: - check(list_.transition({resource_id(b.Transition.pResource), b.Transition.Subresource, - static_cast(b.Transition.StateBefore), - static_cast(b.Transition.StateAfter)}, - static_cast(b.Flags))); + case D3D12_RESOURCE_BARRIER_TYPE_TRANSITION: { + const auto& t = b.Transition; + const auto logical = resource_id(t.pResource); + const bool was_storage = (t.StateBefore & D3D12_RESOURCE_STATE_UNORDERED_ACCESS) != 0; + const bool storage = (t.StateAfter & D3D12_RESOURCE_STATE_UNORDERED_ACCESS) != 0; + const auto pair = (was_storage || storage) ? xbox_depth_storage(t.pResource) : XboxDepthStorage{}; + auto before = t.StateBefore; + if (pair.colour && was_storage != storage && !(b.Flags & D3D12_RESOURCE_BARRIER_FLAG_BEGIN_ONLY)) { + check(copy_depth_storage(logical, pair, storage, {t.Subresource})); + before = D3D12_RESOURCE_STATE_COPY_DEST; + } + check(list_.transition({pair.colour && storage ? pair.colour : logical, t.Subresource, + u(before), u(t.StateAfter)}, u(b.Flags))); break; + } case D3D12_RESOURCE_BARRIER_TYPE_ALIASING: check(!b.Flags && list_.aliasing_barrier({resource_id(b.Aliasing.pResourceBefore), resource_id(b.Aliasing.pResourceAfter)})); break; - case D3D12_RESOURCE_BARRIER_TYPE_UAV: - check(!b.Flags && list_.uav_barrier({resource_id(b.UAV.pResource)})); + case D3D12_RESOURCE_BARRIER_TYPE_UAV: { + const auto pair = xbox_depth_storage(b.UAV.pResource); + check(!b.Flags && list_.uav_barrier({pair.colour ? pair.colour : resource_id(b.UAV.pResource)})); break; + } default: check(false); } @@ -546,12 +567,25 @@ class GraphicsCommandList final case D3D12_BARRIER_TYPE_TEXTURE: { const auto& b = group[g].pTextureBarriers[i]; const auto& r = b.Subresources; - check(list_.barrier(leonida::TextureBarrier{ + leonida::TextureBarrier barrier{ u(b.SyncBefore), u(b.SyncAfter), u(b.AccessBefore), u(b.AccessAfter), u(b.LayoutBefore), u(b.LayoutAfter), resource_id(b.pResource), {r.IndexOrFirstMipLevel, r.NumMipLevels, r.FirstArraySlice, r.NumArraySlices, r.FirstPlane, - r.NumPlanes}, - u(b.Flags)})); + r.NumPlanes}, u(b.Flags)}; + const bool was_storage = storage_access(b.LayoutBefore, b.AccessBefore); + const bool storage = storage_access(b.LayoutAfter, b.AccessAfter); + const auto pair = (was_storage || storage) ? xbox_depth_storage(b.pResource) : XboxDepthStorage{}; + if (pair.colour) { + if (was_storage != storage && b.SyncAfter != D3D12_BARRIER_SYNC_SPLIT && + b.LayoutBefore != D3D12_BARRIER_LAYOUT_UNDEFINED && !(b.Flags & D3D12_TEXTURE_BARRIER_FLAG_DISCARD)) { + check(copy_depth_storage(barrier.resource, pair, storage, barrier.range)); + barrier.sync_before = leonida::d3d12_sync::copy; + barrier.access_before = leonida::d3d12_access::copy_dest; + barrier.layout_before = leonida::d3d12_layout::copy_dest; + } + if (storage) barrier.resource = pair.colour; + } + check(list_.barrier(barrier)); break; } default: @@ -984,9 +1018,47 @@ class GraphicsCommandList final check(list_.copy_acceleration_structure({dest, source, static_cast(mode)})); } + bool xbox_label(const leonida::label::Write& op) { return list_.write_gpu_label(op); } static GraphicsCommandList* from(IUnknown* object) { return Child::from(object); } private: + static bool storage_access(D3D12_BARRIER_LAYOUT layout, D3D12_BARRIER_ACCESS access) { + return (access & D3D12_BARRIER_ACCESS_UNORDERED_ACCESS) || + layout == D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS || + layout == D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_UNORDERED_ACCESS || + layout == D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_UNORDERED_ACCESS; + } + + bool copy_depth_storage(leonida::ResourceId depth, XboxDepthStorage pair, bool to_storage, + const leonida::BarrierSubresourceRange& r) { + namespace access = leonida::d3d12_access; + namespace sync = leonida::d3d12_sync; + const auto from = to_storage ? depth : pair.colour, to = to_storage ? pair.colour : depth; + // The two images can be in GENERAL for bindless use. Order prior depth writes, unordered writes and + // readers of the destination even when Vulkan does not need a layout transition. + if (!list_.barrier(leonida::GlobalBarrier{sync::all, sync::copy, + access::depth_stencil_write | access::depth_stencil_read | access::unordered_access | + access::shader_resource | access::copy_source | access::copy_dest, + access::copy_source | access::copy_dest})) return false; + if (!r.mip_count && r.index_or_first_mip == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES) + return list_.copy_resource({to, from}); + const auto one = [&](UINT subresource) { + leonida::CopyTexture copy{}; + copy.src.resource = from; + copy.dst.resource = to; + copy.src.subresource = copy.dst.subresource = subresource; + return list_.copy_texture(copy); + }; + if (!r.mip_count) return r.index_or_first_mip < pair.mips * pair.layers && one(r.index_or_first_mip); + if (r.first_plane || r.plane_count != 1 || !r.layer_count || + r.first_layer >= pair.layers || r.layer_count > pair.layers - r.first_layer || + r.index_or_first_mip >= pair.mips || r.mip_count > pair.mips - r.index_or_first_mip) return false; + for (UINT layer = r.first_layer; layer < r.first_layer + r.layer_count; ++layer) + for (UINT mip = r.index_or_first_mip; mip < r.index_or_first_mip + r.mip_count; ++mip) + if (!one(layer * pair.mips + mip)) return false; + return true; + } + static bool valid_postbuild_info_type(D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_TYPE type) { switch (type) { case D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_COMPACTED_SIZE: @@ -1136,12 +1208,24 @@ class GraphicsCommandList final if (g::is_image(words)) { g::Image image{}; if (!g::decode(words, image)) return false; + out.resource = uav_image_resource(resource, image.address); + if (!out.resource) return false; const bool volume = image.type == g::ImageType::image_3d; + const auto pair = xbox_depth_storage(resource); + if (pair.colour) out.resource = pair.colour; + if (g::partial_volume_uav(words, image)) { + // Transfer clears operate on a whole 3D mip, not a storage image view. Refuse instead of + // overwriting slices outside the UAV; a sliced clear needs a separate replay path. + stub("ClearUnorderedAccessView of a partial 3D mip"); + return false; + } out.buffer = false; out.format = std::uint32_t(descriptor_format(image.format, image.swizzle)); out.mip = image.first_mip; out.first_layer = volume ? 0 : image.first_layer; // a 3D view clears every slice of its mip out.layer_count = volume ? 1 : image.layer_count; + out.exact_clear_format = volume || image.type == g::ImageType::image_1d || + image.type == g::ImageType::image_1d_array; return out.format != VK_FORMAT_UNDEFINED; } g::BufferWords buffer_words{}; @@ -1191,6 +1275,7 @@ class GraphicsCommandList final if (layout && layout == state.layout) return; hold(signature); // state.layout points into it state.layout = layout; + if (layout && (layout->flags & D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED)) directly_indexed_ = true; state.data = {}; // CreateRootSignature accepted it for the other bind point only (its log line says why). if (layout && !(is_compute(state) ? layout->compute_ok : layout->graphics_ok)) { @@ -1261,13 +1346,16 @@ class GraphicsCommandList final // of the layer's heaps: kept, and its buffer V#s are rewritten the same way before each submission. if (type == rt::rootsig::ParamType::Descriptor) va = leonida::title_va_aliases().resolve(va, kRootViewBytes, leonida::TitleVaAliases::root_view); - else if (va && p->table_descriptors && (tables_.empty() || tables_.back().first != va)) - tables_.push_back({va, p->table_descriptors}); + else if (va && p->table_descriptors) { + if (!tables_.empty() && tables_.back().first == va) + tables_.back().second = std::max(tables_.back().second, p->table_descriptors); + else + tables_.emplace_back(va, p->table_descriptors); + } const std::uint32_t first = first_dword(state, *p); write(state, first, std::uint32_t(va)); - // In the compute layout a descriptor table is one dword, the 32-bit VA of its first descriptor (the heaps - // live below 4 GiB); a root view keeps both halves. The graphics layout gives every address two dwords. - if (!((is_compute(state) || local_graphics_stage_layout()) && type == rt::rootsig::ParamType::Table)) + // Stage-packed tables occupy one dword. Legacy tables and root views occupy two. + if (type != rt::rootsig::ParamType::Table || !(is_compute(state) || state.layout->graphics_compact_tables)) write(state, first + 1, std::uint32_t(va >> 32)); } @@ -1290,6 +1378,7 @@ class GraphicsCommandList final leonida::IndexBufferView index_{}; // SetGraphicsRootDescriptorTable / SetComputeRootDescriptorTable: VA, CBV/SRV/UAV slots the signature declares std::vector> tables_; + bool directly_indexed_ = false; // The span a root view may read: D3D12's largest constant buffer (4096 x 16 bytes). static constexpr std::uint64_t kRootViewBytes = 65536; leonida::Viewport viewport_{}; @@ -1675,6 +1764,11 @@ class CommandQueue final recorded.push_back(&list->commands()); graphics.push_back(list); } + if (!context_.publish_cpu_textures()) { + last_result_=leonida::ReplayResult::unresolved_resource; + d3d12_trace::record(method,"failed"); + return; + } // Buffer V#s the title wrote into a bound table itself may name its own memory: rewritten to a GPU copy's // console VA before the copies are refreshed for this submission (src/title_va_alias.h). { @@ -1684,12 +1778,40 @@ class CommandQueue final tables[table] = std::max(tables[table], descriptors); if (!tables.empty()) { const auto start = std::chrono::steady_clock::now(); - for (const auto& [table, descriptors] : tables) leonida::title_va_aliases().scan_table(table, descriptors); + for (const auto& [table, descriptors] : tables) { + context_.scan_table(table, descriptors); + if (!context_.prepare_sample_table(table, descriptors)) { + last_result_ = leonida::ReplayResult::unresolved_resource; + d3d12_trace::record(method, "failed"); + return; + } + } leonida::title_va_aliases().note_scan(std::uint64_t( std::chrono::duration_cast(std::chrono::steady_clock::now() - start) .count())); } } + for (const auto* list : graphics) { + for (const auto& command : list->commands().commands()) { + leonida::ResourceId resource = 0; + if (const auto* b=std::get_if(&command)) { + if (b->after & (D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE|D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE)) + resource=b->resource; + } else if (const auto* b=std::get_if(&command)) { + if (b->access_after & D3D12_BARRIER_ACCESS_SHADER_RESOURCE) resource=b->resource; + } + if (resource && !context_.prepare_sample_table(resource,0)) { + last_result_=leonida::ReplayResult::unresolved_resource; + d3d12_trace::record(method,"failed"); + return; + } + } + if (list->needs_all_sampled_views() && !context_.prepare_sample_table(0,0)) { + last_result_ = leonida::ReplayResult::unresolved_resource; + d3d12_trace::record(method,"failed"); + return; + } + } last_result_ = queue_.execute(recorded, [&graphics] { return pin_lists(graphics); }); d3d12_trace::record(method, last_result_ == leonida::ReplayResult::success ? "ok" : "failed"); if (last_result_ != leonida::ReplayResult::success) @@ -1980,6 +2102,11 @@ class CommandQueue final } // namespace +bool record_gpu_label(ID3D12GraphicsCommandList* list,const leonida::label::Write& write) { + auto* own=GraphicsCommandList::from(list); + return own && own->xbox_label(write); +} + HRESULT create_command_queue(leonida::VulkanContext& context, VkQueue queue, std::uint32_t queue_family, const D3D12_COMMAND_QUEUE_DESC& desc, REFIID riid, void** out, IUnknown* device, const QueueClock& clock, std::shared_ptr queue_lease) { diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 2811ed1f3d..33f8ac5497 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -5,7 +5,7 @@ // interfaces as far as is known; docs/d3d12_vulkan.md section 3.1 lists what is still unverified. // // Contracts with the rest of the layer (the device proxy that will hand these objects out): -// - an ID3D12Resource's leonida::ResourceId is its pointer value; the device registers it with the VulkanContext; +// - a resource's ID is its backing pointer value (identical Xbox depth placements share storage and layouts); // - so is an ID3D12QueryHeap's leonida::QueryHeapId, registered with its VkQueryPool; // - the CPU handle of an RTV or DSV points at a leonida::TargetView in the device's descriptor heap. #pragma once @@ -17,6 +17,7 @@ #include #include +#include "d3d12_xs_device.h" #include "../src/gfx10_descriptors.h" #include "../src/vulkan_backend.h" @@ -35,7 +36,9 @@ class VulkanPresenter; struct PresentPlanes; } +namespace leonida::label { struct Write; } namespace rt::d3d12 { +bool record_gpu_label(ID3D12GraphicsCommandList* list, const leonida::label::Write& write); // How a queue answers GetClockCalibration. With `calibrated` (vkGetCalibratedTimestampsKHR or its EXT alias, on a // device whose time domains include DEVICE and QUERY_PERFORMANCE_COUNTER) both clocks are read in one call. Without @@ -72,6 +75,14 @@ std::shared_ptr tile_heap(ID3D12Heap* heap, c bool image, std::uint32_t memory_types); bool is_sparse_image(ID3D12Resource* resource); +// Colour image used for unordered accesses to an Xbox single-plane depth surface. +struct XboxDepthStorage { + leonida::ResourceId colour = 0; + UINT mips = 0; + UINT layers = 0; +}; +XboxDepthStorage xbox_depth_storage(ID3D12Resource* resource); + // The Vulkan objects a D3D12 device runs on. Vulkan 1.3 with dynamicRendering, synchronization2, timelineSemaphore // and (when separate_depth_stencil_layouts is set) separateDepthStencilLayouts enabled. struct VulkanDeviceInfo { @@ -137,6 +148,9 @@ struct VulkanDeviceInfo { // Optional device features the caller enabled. Without occlusionQueryPrecise, D3D12_QUERY_TYPE_OCCLUSION counts // are only zero or non-zero; without pipelineStatisticsQuery, pipeline-statistics query heaps are refused. bool occlusion_query_precise = false; + bool first_use_backend_pipelines = false; + bool prepare_on_bind = false; + bool cold_graphics_compile = false; // Driver supports a cache-only create and reports when compilation is pending. bool pipeline_statistics_query = false; bool presentation = false; // VK_KHR_surface + VK_KHR_win32_surface on the instance, VK_KHR_swapchain on the device // VK_KHR_swapchain_maintenance1 (or VK_EXT_swapchain_maintenance1) and its swapchainMaintenance1 feature are @@ -161,6 +175,7 @@ struct VulkanDeviceInfo { // VK_KHR_maintenance5, enabled where its VK_FORMAT_A8_UNORM_KHR can be sampled and is a colour attachment the GPU // can blend: A8_UNORM render targets are then stored in that format (other A8_UNORM textures stay R8_UNORM). bool a8_render_target = false; + bool maintenance10 = false; // VK_KHR_maintenance10 enabled: query depth/stencil copy support per format // The instance enabled VK_EXT_debug_utils: SetMarker/BeginEvent/EndEvent become debug labels. Otherwise they // do nothing. bool debug_utils = false; @@ -171,6 +186,10 @@ struct VulkanDeviceInfo { // Optional VK_KHR_acceleration_structure + VK_KHR_deferred_host_operations + VK_KHR_ray_query are enabled: // GetRaytracingAccelerationStructurePrebuildInfo and BuildRaytracingAccelerationStructure (BLAS + TLAS) work. bool ray_tracing = false; + // robustImageAccess is enabled on `device`, so typed 1D-family and 3D UAV loads are range checked. + bool robust_image_access = false; + // VK_EXT_image_sliced_view_of_3d (imageSlicedViewOf3D) is also enabled for partial 3D UAVs. + bool sliced_3d_uav = false; // BuildRaytracingAccelerationStructure writes the console's XDXR BVH4 records into the destination buffer // (src/xdxr_build.h), the layout the game's translated traversal shaders read, instead of building a // VkAccelerationStructureKHR; needs buffer_device_address and the GPU address arena. The standalone device sets it @@ -236,6 +255,8 @@ HRESULT create_console_descriptor_heap(ID3D12Device* device, const D3D12_DESCRIP // The VkImage behind a texture created by such a device, or VK_NULL_HANDLE. For tests and the swapchain. VkImage vulkan_image(ID3D12Resource* resource); +// Resolves the resource that a UAV clear writes. Xbox depth/stencil UAVs name one of two color images by T#. +leonida::ResourceId uav_image_resource(ID3D12Resource* resource, std::uint64_t address); // The VkBuffer behind a buffer created by such a device, or VK_NULL_HANDLE. For tests. VkBuffer vulkan_buffer(ID3D12Resource* resource); // What a device from create_vulkan_device* was created with (enabled features included), or null. For tests. @@ -248,7 +269,7 @@ bool device_supports_ray_tracing(ID3D12Device* device); // what the GPU reads. A buffer description only; E_NOTIMPL on a device that is not the Vulkan layer, without the // extension, or for a texture. HRESULT create_buffer_at_host_address(ID3D12Device* device, void* address, const D3D12_RESOURCE_DESC& desc, - std::uint32_t layout, REFIID riid, void** out); + std::uint32_t layout, REFIID riid, void** out, const D3D12_CLEAR_VALUE* clear = nullptr); // The VkAccelerationStructureKHR registered for `va` on `device`, or VK_NULL_HANDLE. For tests. VkAccelerationStructureKHR vulkan_acceleration_structure(ID3D12Device* device, D3D12_GPU_VIRTUAL_ADDRESS va); @@ -402,12 +423,13 @@ struct RootArgumentLayout { std::uint32_t user_offset; // graphics: first dword; unused for a parameter with no dwords std::uint32_t constant_count; // constants only std::uint32_t compute_offset = rt::rootsig::kNoSgpr; // compute: first user SGPR - // A table: the CBV/SRV/UAV slots its ranges declare (an unbounded range counts as 1024), for the scan of - // title-written V#s before a submission (src/title_va_alias.h). 0: a sampler table, or not a table. + // Declared span for submission-time heap refresh. Views are capped at 1024 slots and samplers at the + // shader-visible sampler heap limit. Zero for a parameter without a table. std::uint32_t table_descriptors = 0; }; std::vector parameters; std::uint32_t flags = 0; // D3D12_ROOT_SIGNATURE_FLAGS from the serialized blob + bool graphics_compact_tables = false; // the selected graphics layout uses one dword per table bool graphics_ok = true; bool compute_ok = true; }; @@ -452,7 +474,7 @@ bool front_back_stencil_ref(ID3D12GraphicsCommandList8* list, UINT& front, UINT& bool recorded_commands(ID3D12GraphicsCommandList* list, std::vector& commands); inline leonida::ResourceId resource_id(const ID3D12Resource* resource) { - return reinterpret_cast(resource); + return reinterpret_cast(rt::d3d12_xs::texture_backing(resource)); } // A query heap's ID in the command-list IR and the VulkanContext: its pointer value, as for resources. diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 1a9f1d6e48..efa29df0c4 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -7,6 +7,7 @@ #ifndef VK_USE_PLATFORM_WIN32_KHR #define VK_USE_PLATFORM_WIN32_KHR #endif +#include "../src/vulkan_graphics_shader_modules.h" #include "d3d12_com.h" #include "d3d12_feature_compat.h" @@ -14,10 +15,12 @@ #include "d3d12_com_object.h" #include "d3d12_trace.h" #include "d3d12_xs_device.h" +#include "d3d12_xs_native_pso.h" #include "dxgi_com.h" #include "../src/arena_size.h" #include "../src/gfx10_descriptors.h" #include "../src/depth24_fragment.h" +#include "../src/rgba4_fragment.h" #include "../src/rect_list_geometry.h" #include "../src/uav_clear.h" #include "../src/vulkan_bindless.h" @@ -29,6 +32,7 @@ #include "../src/pipeline_cache_store.h" #include "../src/conservative_raster.h" #include "../src/resource_detile.h" +#include "../src/console_texture_layout.h" #include "../src/shader_library.h" #include "../src/spirv_f16_halves.h" #include "../src/spirv_stores.h" @@ -43,6 +47,7 @@ #endif #include +#include #include #include #include @@ -57,6 +62,7 @@ #include #include #include +#include #include #include #include @@ -111,20 +117,22 @@ std::uint64_t vsharp_address(std::uint64_t va, std::uint64_t bytes, return to; } -// The CBV/SRV/UAV slots a descriptor table declares: the end of its furthest range (D3D12 appends a range at -// D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND), an unbounded range counted as 1024. 0 for a sampler table or no table. -std::uint32_t table_view_descriptors(const rt::rootsig::RootParameter& param) { - if (param.type != rt::rootsig::ParamType::Table) return 0; - constexpr std::uint32_t kUnbounded = 1024; +// The furthest range end is the span to refresh at submission. Sampler ranges use their full hardware +// heap limit. Buffer-view translation retains its existing per-table budget. +constexpr std::uint32_t kViewScanLimit = 1024; +std::uint32_t table_descriptor_count(const rt::rootsig::RootParameter& param) { + if (param.type != rt::rootsig::ParamType::Table || param.ranges.empty()) return 0; + const std::uint32_t limit = param.ranges.front().range_type == D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER + ? D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE : UINT_MAX; std::uint64_t next = 0, end = 0; for (const auto& range : param.ranges) { const std::uint64_t start = range.offset_in_table == D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND ? next - : range.offset_in_table; - const std::uint64_t count = range.num_descriptors == UINT_MAX ? kUnbounded : range.num_descriptors; + : range.offset_in_table; + const std::uint64_t count = range.num_descriptors == UINT_MAX ? limit : range.num_descriptors; next = start + count; - if (range.range_type != D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER) end = std::max(end, next); + end = std::max(end, next); } - return std::uint32_t(std::min(end, kUnbounded)); + return std::uint32_t(std::min(end, limit)); } // memcpy that a page fault ends instead of killing the process: the title may decommit a page between the @@ -433,6 +441,11 @@ constexpr VkFormat kA8UnormFormat = VK_FORMAT_A8_UNORM_KHR; constexpr VkFormat kA8UnormFormat = VK_FORMAT_UNDEFINED; #endif +// Xbox DXGI values published by Microsoft's DirectXTex (DirectXTexP.h). +constexpr auto xbox_d16s8=static_cast(118); +constexpr auto xbox_d16_plane=static_cast(119); +constexpr auto xbox_s8_plane=static_cast(120); + struct Format { VkFormat format = VK_FORMAT_UNDEFINED; VkImageAspectFlags aspects = 0; @@ -450,6 +463,8 @@ struct Format { VkFormat uint_backed = VK_FORMAT_UNDEFINED; // A 96-bit R32G32B32 format, held in the R32G32B32A32 image `format` names (ResourceBinding::rgb96). bool rgb96 = false; + bool xbox_depth16_stencil8 = false; + bool rgba4_render_fallback = false; }; // 96-bit textures are always RGBA32 images, even where the GPU has an RGB32 one (most have none with optimal @@ -564,6 +579,9 @@ Format vulkan_format(DXGI_FORMAT format, bool depth) { case DXGI_FORMAT_BC7_UNORM_SRGB: return {VK_FORMAT_BC7_SRGB_BLOCK, color}; case DXGI_FORMAT_D32_FLOAT: return {VK_FORMAT_D32_SFLOAT, d}; case DXGI_FORMAT_D16_UNORM: return {VK_FORMAT_D16_UNORM, d}; + case xbox_d16s8: return {VK_FORMAT_D16_UNORM_S8_UINT, ds}; + case xbox_d16_plane: return {VK_FORMAT_D16_UNORM_S8_UINT, d}; + case xbox_s8_plane: return {VK_FORMAT_D16_UNORM_S8_UINT, VK_IMAGE_ASPECT_STENCIL_BIT}; case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: return {VK_FORMAT_D32_SFLOAT_S8_UINT, ds}; case DXGI_FORMAT_D24_UNORM_S8_UINT: return {VK_FORMAT_D24_UNORM_S8_UINT, ds}; case DXGI_FORMAT_R32_TYPELESS: @@ -763,16 +781,20 @@ std::filesystem::path shader_directory_from_file(const std::filesystem::path& co } // What a device's children need from it, kept apart from the COM class so children can hold a plain pointer. +class Resource; struct DeviceState { + std::mutex mapped_texture_mutex; + std::set mapped_textures; + std::atomic map_count{}; + bool publish_mapped_textures(); + std::mutex title_image_mutex; + std::multimap title_images; VulkanDeviceInfo info; std::vector families; template void share(CreateInfo& create) const { - if (families.size() < 2) return; - create.sharingMode = VK_SHARING_MODE_CONCURRENT; - create.queueFamilyIndexCount = std::uint32_t(families.size()); - create.pQueueFamilyIndices = families.data(); + leonida::share_across_queue_families(create, families); } std::unique_ptr context; VkPhysicalDeviceMemoryProperties memory{}; @@ -967,29 +989,51 @@ struct DeviceState { return true; } - // The shader-visible CBV/SRV/UAV heaps (arena offset -> end), for the scan of bound tables before a submission. - std::mutex cbv_heap_mutex; - std::map cbv_heaps; - static constexpr VkDeviceSize kTableScanDescriptors = 1024; // per table and submission + struct ShaderVisibleHeap { + VkDeviceSize end; + D3D12_DESCRIPTOR_HEAP_TYPE type; + }; + std::mutex visible_heap_mutex; + std::map visible_heaps; + std::map cpu_view_heaps; + bool known_view_heap(std::uintptr_t addr) { + std::lock_guard lock(visible_heap_mutex); + const auto mapped = reinterpret_cast(arena.mapped); + if (mapped && addr >= mapped && addr - mapped < arena.size) { + const auto off = addr-mapped; + auto visible = visible_heaps.upper_bound(off); + if (visible != visible_heaps.begin()) { + --visible; + if (visible->second.type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV && off < visible->second.end && + (off-visible->first)%kDescriptorSize==0) return true; + } + } + auto it = cpu_view_heaps.upper_bound(addr); + if (it == cpu_view_heaps.begin()) return false; + --it; + return addr < it->second && (addr-it->first) % kDescriptorSize == 0; + } // The buffer V#s of the table at `table_va` whose base is in the title's own memory get the address of a copy, // written in place: the title wrote them itself (or copied them), so no Create*View saw them. Images (T#s) and // null slots are skipped; so is a V# already in the arena, so a rewritten one is left alone next time. void scan_title_table(std::uint64_t table_va, std::uint32_t descriptors) { VkDeviceSize end = 0; + bool sampler = false; { - std::lock_guard lock(cbv_heap_mutex); - auto it = cbv_heaps.upper_bound(table_va); - if (it == cbv_heaps.begin()) return; + std::lock_guard lock(visible_heap_mutex); + auto it = visible_heaps.upper_bound(table_va); + if (it == visible_heaps.begin()) return; --it; - if (table_va >= it->second) return; - end = std::min( - it->second, table_va + VkDeviceSize(std::min(descriptors, kTableScanDescriptors)) * - kDescriptorSize); + const auto& heap = it->second; + if (table_va >= heap.end || (table_va - it->first) % kDescriptorSize != 0) return; + sampler = heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER; + const auto slots = sampler ? descriptors : std::min(descriptors, kViewScanLimit); + end = table_va + std::min(heap.end - table_va, VkDeviceSize(slots) * kDescriptorSize); } auto& aliases = leonida::title_va_aliases(); - // Slots the title wrote in its own backing of this heap, if it gave the heap one. aliases.pull_descriptors(arena.mapped + table_va, std::size_t(end - table_va)); + if (sampler) return; // S# words describe sampling state. They have no buffer address to translate. for (VkDeviceSize at = table_va; at + 16 <= end; at += kDescriptorSize) { auto* w = reinterpret_cast(arena.mapped + at); const std::uint32_t w0 = w[0], w1 = w[1], w2 = w[2], w3 = w[3]; @@ -1136,6 +1180,9 @@ struct DeviceState { std::mutex library_mutex; bool library_tried = false; leonida::ShaderLibrary shader_library; + leonida::GraphicsShaderModules graphics_modules; + + rt::d3d12_xs::NativeGraphicsPipelines native_graphics; const leonida::ShaderLibrary* library() { std::lock_guard lock(library_mutex); @@ -1166,6 +1213,12 @@ struct DeviceState { return shader_library.loaded() ? &shader_library : nullptr; } + VkFormat depth_backing(VkFormat logical) const { + if(logical!=VK_FORMAT_D16_UNORM_S8_UINT)return logical; + for(const auto candidate : {VK_FORMAT_D16_UNORM_S8_UINT,VK_FORMAT_D32_SFLOAT_S8_UINT,VK_FORMAT_D24_UNORM_S8_UINT}) + if(depth_usable(candidate))return candidate; + return VK_FORMAT_UNDEFINED; + } bool depth_usable(VkFormat format) const { VkFormatProperties properties{}; format_properties(info.physical, format, &properties); @@ -1239,6 +1292,14 @@ struct DeviceState { return S_OK; } + VkFormatFeatureFlags2 optimal_features(VkFormat format) const { + if (!format_properties2) return 0; + VkFormatProperties3 features{VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_3}; + VkFormatProperties2 properties{VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2, &features}; + format_properties2(info.physical, format, &properties); + return features.optimalTilingFeatures; + } + // D3D12_OPTIONS1's wave facts, from the physical device: which subgroup operations exist and what wave sizes it // can run. Zeros and false when the device cannot be asked, which the query then reports as unsupported. // Read once: std::call_once makes a concurrent first caller wait until the facts are complete. @@ -1398,6 +1459,16 @@ struct DeviceState { Format format = texture_storage_format(desc.Format, desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL); if (desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D && (format.aspects & VK_IMAGE_ASPECT_DEPTH_BIT)) return {}; + if(desc.Format==DXGI_FORMAT_B4G4R4A4_UNORM && (desc.Flags&D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) && + !color_attachment_usable(format.format)) { + if(!color_attachment_usable(VK_FORMAT_R8G8B8A8_UNORM))return {}; + format.format=VK_FORMAT_R8G8B8A8_UNORM;format.rgba4_render_fallback=true; + return format; + } + if(format.format==VK_FORMAT_D16_UNORM_S8_UINT) { + format.xbox_depth16_stencil8=true;format.format=depth_backing(format.format); + return format; + } format.d24 = format.format == VK_FORMAT_D24_UNORM_S8_UINT; // native or not: clears are quantised if (format.format == VK_FORMAT_D24_UNORM_S8_UINT && !depth_usable(format.format)) { log_once("D24_UNORM_S8_UINT unavailable, using D32_SFLOAT_S8_UINT; format", desc.Format); @@ -1510,19 +1581,49 @@ struct DeviceState { const std::uint64_t slot_handle = (static_cast(entry.dimension) << 32) | static_cast(entry.index); context->defer_destroy(leonida::DeferredDeletionQueue::Kind::bindless_slot, slot_handle); - context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_view, entry.sampled); + if (entry.sampled) context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_view, entry.sampled); if (entry.storage) context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_view, entry.storage); } + struct PendingSample { + Resource* owner = nullptr; + leonida::gfx10::Image image{}; + VkFormat view_format{}, channels_format{}; + }; + std::mutex pending_view_mutex; + std::map pending_samples; + std::atomic pending_sample_count{}; + bool materialize_sample(const leonida::DescriptorKey& key); + bool materialize_table(std::uint64_t address,std::uint32_t slots); + void remember_sample(const leonida::DescriptorKey& key, const PendingSample& sample) { + std::lock_guard lock(pending_view_mutex); + if (pending_samples.try_emplace(key,sample).second) { + ++pending_sample_count; + } + } + void retire_samples(Resource* owner) { + std::lock_guard lock(pending_view_mutex); + const auto removed=std::erase_if(pending_samples,[&](const auto& p){return p.second.owner==owner;}); + pending_sample_count -= static_cast(removed); + } + + struct VolumeSlices { + UINT first = 0; + UINT count = 0; // 0: no restriction (ordinary view of the whole mip) + }; + // Gives the T# `words` a view in set 0 and an entry in the hash table, unless it has them. `storage`: shaders // write through it too (an unordered-access view), so it also goes into the storage arrays, which are // shorter. False when set 0 cannot show the image; the descriptor then finds the fallback at index 0. bool bind_image(const leonida::gfx10::ImageWords& words, const leonida::gfx10::Image& image, VkImage vk_image, - VkFormat image_format, VkImageAspectFlags aspects, bool storage, - bool allow_channel_cast = false, VkFormat uint_backed = VK_FORMAT_UNDEFINED) { + VkFormat view_format, VkFormat channels_format, VkFormat storage_format, + VkImageAspectFlags aspects, bool sampled, bool storage, VolumeSlices slices) { namespace g = leonida::gfx10; std::lock_guard lock(descriptor_mutex); - if (!bindless) return false; + if (!bindless) { + if (storage) log_once("unordered-access view needs the Vulkan bindless set; type", int(image.type)); + return false; + } const auto existing = image_entries.find(words); if (existing != image_entries.end() && (existing->second.storage || !storage)) return true; @@ -1533,6 +1634,7 @@ struct DeviceState { case g::ImageType::cube: dimension = leonida::ImageDimension::dim_2d_array; break; case g::ImageType::image_3d: dimension = leonida::ImageDimension::dim_3d; break; case g::ImageType::image_1d: dimension = leonida::ImageDimension::dim_1d; break; + case g::ImageType::image_1d_array: dimension = leonida::ImageDimension::dim_1d_array; break; case g::ImageType::image_2d_msaa: dimension = leonida::ImageDimension::dim_2d_ms; break; case g::ImageType::image_2d_msaa_array: dimension = leonida::ImageDimension::dim_2d_ms_array; break; default: @@ -1541,41 +1643,31 @@ struct DeviceState { } const bool depth_or_stencil = (aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) != 0; if (storage && depth_or_stencil) { - log_once("storage view not supported for depth-stencil image format:", int(image_format)); + log_once("storage view not supported for depth-stencil image format:", int(view_format)); return false; } - // A T# of 8_UINT on a depth-stencil image is a view of its stencil plane (image_descriptor, D3D-75). Vulkan - // views it in the image's own format with the stencil aspect, and returns the value in R, as a T# whose - // format is 8_UINT reads it from X. - const bool stencil = (aspects & VK_IMAGE_ASPECT_STENCIL_BIT) && image.format == g::stencil_format; - const VkFormat logical_format = uint_backed ? uint_backed : image_format; - VkFormat view_format = - stencil ? image_format : g::vulkan_view_format(logical_format, image.format, allow_channel_cast); - VkFormat channels_format = view_format; // whose channels the T#'s swizzle selects from - if (view_format == VK_FORMAT_UNDEFINED) { // a 96-bit texture's T# names RGB32; its image is RGBA32 - view_format = rgb96_view_format(image_format, image.format); - channels_format = rgb96_named_format(view_format); - } if (view_format == VK_FORMAT_UNDEFINED || (depth_or_stencil && !g::is_depth_stencil_format(view_format))) { log_once("no Vulkan view format for the GFX10 format of a view:", int(image.format)); return false; } + // A T# of 8_UINT on a depth-stencil image is a view of its stencil plane (image_descriptor, D3D-75). Vulkan + // views it in the image's own format with the stencil aspect, and returns the value in R, as a T# whose + // format is 8_UINT reads it from X. + const bool stencil = (aspects & VK_IMAGE_ASPECT_STENCIL_BIT) && image.format == g::stencil_format; const unsigned sampled_class = g::multisampled(image.type) ? numeric_class(view_format) : 0; if (g::multisampled(image.type) && !bindless->supports_ms_class(sampled_class)) { log_once("set 0 has no multisample binding for this numeric class:", int(sampled_class)); return false; } auto& vk = context->vk; + VkImageViewUsageCreateInfo view_usage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO}; + view_usage.usage = VK_IMAGE_USAGE_SAMPLED_BIT; VkImageViewCreateInfo view_info{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; + view_info.pNext = &view_usage; view_info.image = vk_image; view_info.viewType = g::vulkan_view_type(image.type); view_info.format = view_format; - VkImageViewUsageCreateInfo sampled_usage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO}; - if (uint_backed) { - sampled_usage.usage = VK_IMAGE_USAGE_SAMPLED_BIT; - view_info.pNext = &sampled_usage; - } auto swizzle = image.swizzle; VkImageViewMinLodCreateInfoEXT clamp{VK_STRUCTURE_TYPE_IMAGE_VIEW_MIN_LOD_CREATE_INFO_EXT}; const bool supports_lod_clamp = image.type == g::ImageType::image_1d || image.type == g::ImageType::image_2d || @@ -1593,8 +1685,7 @@ struct DeviceState { log_once("SRV requires VK_EXT_image_view_min_lod; first mip", int(image.first_mip)); return false; } - clamp.pNext = view_info.pNext; - view_info.pNext = &clamp; + view_usage.pNext = &clamp; } } view_info.components = g::vulkan_swizzle(swizzle, channels_format); @@ -1605,20 +1696,31 @@ struct DeviceState { : VK_IMAGE_ASPECT_COLOR_BIT), image.first_mip, image.mip_count, image.first_layer, image.layer_count}; ImageEntry entry{dimension, 0, VK_NULL_HANDLE, VK_NULL_HANDLE, image.address}; - if (vk.vkCreateImageView(info.device, &view_info, nullptr, &entry.sampled) != VK_SUCCESS) return false; + if (sampled) { + const VkResult result = vk.vkCreateImageView(info.device, &view_info, nullptr, &entry.sampled); + if (result != VK_SUCCESS) { + log_once("sampled image view creation failed:", result); + return false; + } + } leonida::StorageViews views{}; if (storage) { VkImageViewCreateInfo storage_info = view_info; storage_info.components = {}; + storage_info.format = storage_format; VkImageViewUsageCreateInfo storage_usage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO}; - const VkFormat storage_format = uint_backed ? image_format : view_format; - if (uint_backed) { - storage_info.format = storage_format; - storage_usage.usage = VK_IMAGE_USAGE_STORAGE_BIT; - storage_info.pNext = &storage_usage; - } - if (vk.vkCreateImageView(info.device, &storage_info, nullptr, &entry.storage) != VK_SUCCESS) { - vk.vkDestroyImageView(info.device, entry.sampled, nullptr); + storage_usage.usage = VK_IMAGE_USAGE_STORAGE_BIT; + VkImageViewSlicedCreateInfoEXT sliced{VK_STRUCTURE_TYPE_IMAGE_VIEW_SLICED_CREATE_INFO_EXT}; + if (slices.count) { + sliced.sliceOffset = slices.first; + sliced.sliceCount = slices.count; + storage_usage.pNext = &sliced; + } + storage_info.pNext = &storage_usage; + const VkResult result = vk.vkCreateImageView(info.device, &storage_info, nullptr, &entry.storage); + if (result != VK_SUCCESS) { + log_once("storage image view creation failed:", result); + if (entry.sampled) vk.vkDestroyImageView(info.device, entry.sampled, nullptr); return false; } const int numeric = numeric_class(storage_format); @@ -1629,7 +1731,7 @@ struct DeviceState { entry.index = bindless->add_image(dimension, entry.sampled, VK_IMAGE_LAYOUT_GENERAL, views, sampled_class); if (!entry.index) { log_once("a bindless image array is full; dimension", int(dimension)); - vk.vkDestroyImageView(info.device, entry.sampled, nullptr); + if (entry.sampled) vk.vkDestroyImageView(info.device, entry.sampled, nullptr); if (entry.storage) vk.vkDestroyImageView(info.device, entry.storage, nullptr); return false; } @@ -1777,6 +1879,11 @@ struct DeviceState { // line, when it cannot. Committed and placed textures share it so both refuse the same formats for the same reason. Format texture_format(const DeviceState& device, const D3D12_RESOURCE_DESC& desc) { Format format = vulkan_format(desc.Format, desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL); + if(format.format==VK_FORMAT_D16_UNORM_S8_UINT) {format.xbox_depth16_stencil8=true;format.format=device.depth_backing(format.format);return format;} + if(desc.Format==DXGI_FORMAT_B4G4R4A4_UNORM && (desc.Flags&D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) && !device.color_attachment_usable(format.format)) { + if(!device.color_attachment_usable(VK_FORMAT_R8G8B8A8_UNORM))return {}; + format.format=VK_FORMAT_R8G8B8A8_UNORM;format.rgba4_render_fallback=true; + } if (format.format == VK_FORMAT_D24_UNORM_S8_UINT && !device.depth_usable(format.format)) { log_once("D24_UNORM_S8_UINT unavailable, using D32_SFLOAT_S8_UINT; format", desc.Format); format.format = VK_FORMAT_D32_SFLOAT_S8_UINT; @@ -1793,7 +1900,7 @@ Format texture_format(const DeviceState& device, const D3D12_RESOURCE_DESC& desc // no-op. An A8 render target's VK_FORMAT_A8_UNORM_KHR image (Format::a8_as_alpha) is in a class of its own: no // other format can be a view format of it, so any other castable format is refused here, before Vulkan. HRESULT castable_view_formats(const Format& format, DXGI_FORMAT resource_format, UINT32 count, - const DXGI_FORMAT* castable, std::vector& out) { + const DXGI_FORMAT* castable, std::vector& out, bool depth_uav_planes = false) { if (!count || !castable) return S_OK; const bool depth = (format.aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) != 0; const leonida::BlockFormat own = leonida::block_format(format.format, format.aspects); @@ -1803,6 +1910,19 @@ HRESULT castable_view_formats(const Format& format, DXGI_FORMAT resource_format, log_once("castable format of an A8_UNORM render target not supported (only A8_UNORM is):", castable[i]); return E_INVALIDARG; } + if (depth_uav_planes) { + // Attachment and sampled views use the original depth image's VkFormat. Each typed UAV + // already has its own image; putting its colour format on the depth image is invalid. + const DXGI_FORMAT view = castable[i]; + const bool valid = format.format == VK_FORMAT_D16_UNORM + ? view == DXGI_FORMAT_R16_TYPELESS || view == DXGI_FORMAT_D16_UNORM || + view == DXGI_FORMAT_R16_UNORM || view == DXGI_FORMAT_R16_UINT + : view == DXGI_FORMAT_R32G8X24_TYPELESS || view == DXGI_FORMAT_D32_FLOAT_S8X24_UINT || + view == DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS || view == DXGI_FORMAT_X32_TYPELESS_G8X24_UINT || + view == DXGI_FORMAT_R32_FLOAT || view == DXGI_FORMAT_R8_UINT; + if (!valid) return E_INVALIDARG; + continue; + } const Format cast = vulkan_format(castable[i], depth); if (cast.format == VK_FORMAT_UNDEFINED) { log_once("castable format not supported yet:", castable[i]); @@ -1825,6 +1945,7 @@ HRESULT castable_view_formats(const Format& format, DXGI_FORMAT resource_format, // The typeless format a DXGI format can be cast within, or the format itself when it has no such family. DXGI_FORMAT format_family(DXGI_FORMAT format) { + if (format==xbox_d16s8 || format==xbox_d16_plane || format==xbox_s8_plane) return xbox_d16s8; const int f = int(format); const auto in = [f](int first, int last) { return f >= first && f <= last; }; if (in(1, 4)) return DXGI_FORMAT_R32G32B32A32_TYPELESS; @@ -1856,6 +1977,7 @@ DXGI_FORMAT format_family(DXGI_FORMAT format) { // included) and nothing else. bool depth_stencil_family(DXGI_FORMAT format) { const DXGI_FORMAT family = format_family(format); + if (family==xbox_d16s8) return true; return family == DXGI_FORMAT_R32_TYPELESS || family == DXGI_FORMAT_R16_TYPELESS || family == DXGI_FORMAT_R24G8_TYPELESS || family == DXGI_FORMAT_R32G8X24_TYPELESS; } @@ -2022,8 +2144,9 @@ const char* committed_resource_refusal(const D3D12_HEAP_PROPERTIES& heap, D3D12_ } if (desc.Dimension < D3D12_RESOURCE_DIMENSION_TEXTURE1D || desc.Dimension > D3D12_RESOURCE_DIMENSION_TEXTURE3D) return "resource dimension"; - if ((rt && ds) || (ds && uav) || ((flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) && !ds)) + if ((rt && ds) || (ds && uav) || ((flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) && !ds)) { return "resource flag combination"; + } if (ds && !depth_stencil_family(desc.Format)) return "depth-stencil format"; if (rt && !render_target_family(desc.Format)) return "render-target format"; const UINT samples = desc.SampleDesc.Count; @@ -2111,20 +2234,30 @@ class DescriptorHeap final in_arena_ = true; cpu_ = device.arena.mapped + arena_offset_; std::memset(cpu_, 0, std::size_t(bytes)); - if (desc.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) { - std::lock_guard lock(device.cbv_heap_mutex); - device.cbv_heaps[arena_offset_] = arena_offset_ + bytes; + if (desc.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV || desc.Type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) { + std::lock_guard lock(device.visible_heap_mutex); + device.visible_heaps[arena_offset_] = {arena_offset_ + bytes, desc.Type}; } } else { storage_.reset(new std::byte[std::size_t(bytes)]()); cpu_ = reinterpret_cast(storage_.get()); } + if (cpu_ && !(desc_.Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) && desc_.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) { + std::lock_guard lock(device_.visible_heap_mutex); + const auto begin = reinterpret_cast(cpu_); + device_.cpu_view_heaps[begin] = begin + bytes; + registered_cpu_views_ = true; + } } ~DescriptorHeap() override { - if (in_arena_ && desc_.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) { - std::lock_guard lock(device_.cbv_heap_mutex); - device_.cbv_heaps.erase(arena_offset_); + if (registered_cpu_views_) { + std::lock_guard lock(device_.visible_heap_mutex); + device_.cpu_view_heaps.erase(reinterpret_cast(cpu_)); + } + if (in_arena_) { + std::lock_guard lock(device_.visible_heap_mutex); + device_.visible_heaps.erase(arena_offset_); } if (in_arena_) device_.arena_release(arena_offset_, VkDeviceSize(desc_.NumDescriptors) * kDescriptorSize, DeviceState::arena_descriptor_heap); @@ -2148,6 +2281,11 @@ class DescriptorHeap final return {in_arena_ ? UINT64(arena_offset_) : 0}; } + bool owns_mapped_span(SIZE_T start, SIZE_T bytes) const { + return in_arena_ && start == reinterpret_cast(cpu_) && + bytes == SIZE_T(desc_.NumDescriptors) * kDescriptorSize; + } + const D3D12_DESCRIPTOR_HEAP_DESC& raw_desc() const { return desc_; } D3D12_GPU_VIRTUAL_ADDRESS gpu_base() const { if (console_addressed_) return static_cast(console_address_); @@ -2157,6 +2295,7 @@ class DescriptorHeap final private: DeviceState& device_; D3D12_DESCRIPTOR_HEAP_DESC desc_; + bool registered_cpu_views_ = false; std::unique_ptr storage_; std::uint8_t* cpu_ = nullptr; VkDeviceSize arena_offset_ = 0; @@ -2166,11 +2305,29 @@ class DescriptorHeap final bool console_addressed_ = false; }; +// Only Xbox depth resources have an alternate storage image. Barriers for other COM objects +// can look it up without dereferencing the pointer or calling into another implementation. +std::mutex depth_storage_mutex; +std::map depth_storage_images; +std::atomic depth_storage_count{0}; + +constexpr bool xbox_depth_storage_desc(const D3D12_RESOURCE_DESC& desc) { + const unsigned usages = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + return (unsigned(desc.Flags) & ~unsigned(D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)) == usages && + (desc.Format == DXGI_FORMAT_R16_TYPELESS || desc.Format == DXGI_FORMAT_R32_TYPELESS) && + desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc.SampleDesc.Count == 1 && + desc.Layout == D3D12_TEXTURE_LAYOUT_UNKNOWN; +} +D3D12_RESOURCE_DESC depth_storage_part(D3D12_RESOURCE_DESC desc, bool colour) { + desc.Flags = colour ? D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS : + D3D12_RESOURCE_FLAGS(unsigned(desc.Flags) & ~unsigned(D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)); + return desc; +} + class Resource final : public Child { public: - // {9b3e5f12-7c48-4d0e-a6b1-2f8d4c7e9a35} - static constexpr GUID kTag{0x9b3e5f12, 0x7c48, 0x4d0e, {0xa6, 0xb1, 0x2f, 0x8d, 0x4c, 0x7e, 0x9a, 0x35}}; + static constexpr GUID kTag = rt::d3d12_xs::kVulkanResourceTag; Resource(DeviceState& device, const D3D12_RESOURCE_DESC& desc, const D3D12_HEAP_PROPERTIES& heap, D3D12_HEAP_FLAGS heap_flags) @@ -2182,7 +2339,34 @@ class Resource final D3D12_HEAP_FLAGS heap_flags, VkDeviceSize placed_va) : device_(device), desc_(desc), heap_(heap), heap_flags_(heap_flags), placed_(true), va_(placed_va) {} + void adopt_depth_storage(Resource* colour) { + storage_ = colour; + std::lock_guard lock(depth_storage_mutex); + depth_storage_images.emplace(this, XboxDepthStorage{colour->id(), desc_.MipLevels, desc_.DepthOrArraySize}); + ++depth_storage_count; + } + const Resource* storage_image() const { return storage_; } + ~Resource() override { + { + std::lock_guard guard(device_.mapped_texture_mutex); + if (device_.mapped_textures.erase(this)) --device_.map_count; + } + if (deferred_memory_) device_.retire_samples(this); + if (title_image_registered_) { + std::lock_guard lock(device_.title_image_mutex); + auto [begin,end] = device_.title_images.equal_range(va_); + for (auto it = begin; it != end; ++it) + if (it->second == this) { device_.title_images.erase(it); break; } + } + if (storage_) { + { + std::lock_guard lock(depth_storage_mutex); + depth_storage_images.erase(this); + --depth_storage_count; + } + storage_->Release(); + } if (aliased_) leonida::title_va_aliases().remove(va_, title_alias_); if (accel_) { device_.context->unregister_acceleration_structure(gpu_va_); @@ -2214,9 +2398,29 @@ class Resource final leonida::ResourceId id() const { return resource_id(this); } VkImage image() const { return image_; } + bool ensure_texture_bound() { + if (!deferred_memory_ || deferred_bound_.load(std::memory_order_acquire)) return true; + std::lock_guard lock(bind_mutex_); + if (deferred_bound_.load(std::memory_order_relaxed)) return true; + VkMemoryPropertyFlags flags{}; + const auto data = device_.allocate(image_need_, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &flags); + if (!data) return false; + auto& vk = device_.context->vk; + if (vk.vkBindImageMemory(device_.info.device, image_, data, 0) != VK_SUCCESS) { + vk.vkFreeMemory(device_.info.device, data, nullptr); + return false; + } + memory_ = data; + memory_flags_ = flags; + deferred_bound_.store(true, std::memory_order_release); + return true; + } + VkImage bound_image() { return ensure_texture_bound() ? image_ : VK_NULL_HANDLE; } + bool deferrable_sample() const { return deferred_memory_; } bool sparse_image() const { return sparse_image_; } VkBuffer buffer() const { return buffer_; } const D3D12_RESOURCE_DESC& desc() const { return desc_; } + bool rgba4_render_backing() const {return desc_.Format==DXGI_FORMAT_B4G4R4A4_UNORM && format_==VK_FORMAT_R8G8B8A8_UNORM;} VkFormat format() const { return format_; } // of the image bool has_view_format_list() const { return !view_formats_.empty(); } bool allows_view_format(VkFormat format) const { @@ -2237,6 +2441,9 @@ class Resource final VkImageAspectFlags aspects() const { return aspects_; } bool rgb96() const { return rgb96_; } // a 96-bit texture in an RGBA32 image std::uint64_t image_address() const { return image_address_; } // what a T# names the texture by + const Resource* depth_stencil_uav(UINT plane) const { + return plane < storage_planes_.size() ? storage_planes_[plane].get() : nullptr; + } VkMemoryPropertyFlags memory_flags() const { return memory_flags_; } // of the memory type behind it const DeviceState& device_state() const { return device_; } @@ -2504,6 +2711,17 @@ class Resource final if (!address || !desc_.Width || desc_.Width > ~UINT64(0) - D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT) return E_INVALIDARG; const auto* pages = static_cast(address); + const auto base = reinterpret_cast(address); + if (desc_.Width > UINTPTR_MAX - base) return E_INVALIDARG; + // A CPU-data shadow represents committed contents. With demand-paged XMem the placement + // provider commits its own registered pages before entering the backend. + for (std::uintptr_t cursor = base; cursor < base + desc_.Width;) { + MEMORY_BASIC_INFORMATION region{}; + if (!VirtualQuery(reinterpret_cast(cursor), ®ion, sizeof(region)) || + region.State != MEM_COMMIT || (region.Protect & (PAGE_NOACCESS | PAGE_GUARD)) || + !(region.Protect & (PAGE_READONLY | PAGE_READWRITE | PAGE_WRITECOPY))) return E_NOTIMPL; + cursor = reinterpret_cast(region.BaseAddress) + region.RegionSize; + } // The shadow is a range of the GPU address arena when it fits there (docs/d3d12_vulkan.md section 3.3). // The title's VA is a user-mode Windows address far above 4 GiB, past the arena, so a shader's heap_base + VA would miss // any buffer of the layer's; the root views and V#s the layer writes for that VA name the arena offset @@ -2683,12 +2901,20 @@ class Resource final return S_OK; } - HRESULT create_texture(const Format& format, const std::vector& castable = {}) { + HRESULT create_texture(const Format& format, const std::vector& castable = {}, bool defer = false) { auto& vk = device_.context->vk; const bool volume = desc_.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; const UINT depth = volume ? desc_.DepthOrArraySize : 1; const bool one_d = desc_.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D; - if (desc_.MipLevels == 0) desc_.MipLevels = full_mips(desc_.Width, desc_.Height, depth); + const UINT16 mips = full_mips(desc_.Width, desc_.Height, depth); + if (desc_.MipLevels == 0) desc_.MipLevels = mips; + if ((volume || one_d) && (desc_.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { + const UINT extent_limit = volume ? D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION : D3D12_REQ_TEXTURE1D_U_DIMENSION; + const UINT slice_limit = volume ? extent_limit : D3D12_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION; + if (!desc_.Width || desc_.Width > extent_limit || !desc_.Height || desc_.Height > extent_limit || + !desc_.DepthOrArraySize || desc_.DepthOrArraySize > slice_limit || desc_.MipLevels > mips) + return E_INVALIDARG; + } TextureCreateInfo create(desc_, format, device_.color_attachment_usable(format.format)); VkImageCreateInfo& info = create.info; if (!castable.empty()) { @@ -2737,11 +2963,23 @@ class Resource final } VkMemoryRequirements requirements{}; vk.vkGetImageMemoryRequirements(device_.info.device, image_, &requirements); - memory_ = device_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &memory_flags_); - if (!memory_ || vk.vkBindImageMemory(device_.info.device, image_, memory_, 0) != VK_SUCCESS) - return E_OUTOFMEMORY; - leonida::ResourceBinding binding{}; + if (defer && !host_transfer_) { + deferred_memory_ = true; + image_need_ = requirements; + binding.residency_owner = this; + binding.ensure_residency = [](void* object) { + auto* r=static_cast(object); + const bool ready=r->ensure_texture_bound(); + if (ready) r->gpu_referenced_.store(true,std::memory_order_release); + return ready; + }; + } else { + memory_ = device_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &memory_flags_); + if (!memory_ || vk.vkBindImageMemory(device_.info.device, image_, memory_, 0) != VK_SUCCESS) + return E_OUTOFMEMORY; + } + binding.image = image_; binding.typeless = format.typeless && format.aspects == VK_IMAGE_ASPECT_COLOR_BIT; // views name their format binding.castable_view_formats = !view_formats_.empty(); // a castable list made the image mutable @@ -2749,6 +2987,8 @@ class Resource final binding.rgb96 = format.rgb96; binding.depth24_as_float = format.d24_as_float; binding.depth24 = format.d24; + binding.xbox_depth16_stencil8=format.xbox_depth16_stencil8; + binding.rgba4_render_fallback=format.rgba4_render_fallback; binding.format = format.format; binding.aspects = format.aspects; binding.width = std::uint32_t(desc_.Width); @@ -2784,10 +3024,65 @@ class Resource final return S_OK; } + // The Xbox proxy calls this before publishing an allocated depth texture. Each storage plane owns a + // regular color image with its own GFX10 address, so a UAV cannot replace the original SRV in set 0. + HRESULT enable_depth_stencil_uav(D3D12_HEAP_FLAGS storage_heap_flags) { + const bool narrow_stencil = desc_.Format == xbox_d16s8; + const bool depth16 = desc_.Format == DXGI_FORMAT_R16_TYPELESS || narrow_stencil; + if (!image_ || (!depth16 && desc_.Format != DXGI_FORMAT_R32G8X24_TYPELESS) || + !(desc_.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) || + desc_.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc_.MipLevels != 1 || + !desc_.DepthOrArraySize || desc_.SampleDesc.Count != 1) + return E_INVALIDARG; + if (storage_planes_[0]) return S_OK; + try { + decltype(storage_planes_) planes; + D3D12_RESOURCE_DESC plane_desc = desc_; + plane_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + // D16 copies through a buffer as raw UNORM bits. R16_UINT lets an Xbox UAV read/write those bits. + const bool widened = narrow_stencil && format_ != VK_FORMAT_D16_UNORM_S8_UINT; + std::unique_ptr conversion; + if (widened) { + const auto blit = VK_FORMAT_FEATURE_2_BLIT_SRC_BIT | VK_FORMAT_FEATURE_2_BLIT_DST_BIT; + if (format_ != VK_FORMAT_D32_SFLOAT_S8_UINT || (device_.optimal_features(VK_FORMAT_R16_UNORM) & blit) != blit || + (device_.optimal_features(VK_FORMAT_R32_SFLOAT) & blit) != blit) return E_NOTIMPL; + auto intermediate = plane_desc; + intermediate.Format = DXGI_FORMAT_R32_FLOAT; + intermediate.Flags = D3D12_RESOURCE_FLAG_NONE; + conversion = std::make_unique(device_, intermediate, heap_, D3D12_HEAP_FLAG_NONE); + const HRESULT hr = conversion->create_texture(device_.texture_format(intermediate)); + if (FAILED(hr)) return hr; + } + const auto depth_format = widened ? DXGI_FORMAT_R16_TYPELESS : depth16 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_FLOAT; + const DXGI_FORMAT formats[] = {depth_format, DXGI_FORMAT_R8_UINT}; + const UINT plane_count = depth16 && !narrow_stencil ? 1 : 2; + for (UINT plane = 0; plane < plane_count; ++plane) { + plane_desc.Format = formats[plane]; + planes[plane] = std::make_unique(device_, plane_desc, heap_, storage_heap_flags); + const HRESULT hr = planes[plane]->create_texture(device_.texture_format(plane_desc)); + if (FAILED(hr)) return hr; + } + // Replacing the binding preserves the tracked layout of the original depth/stencil image. + auto binding = binding_; + binding.depth_uav = planes[0]->id(); + binding.depth_conversion = conversion ? conversion->id() : 0; + binding.stencil_uav = planes[1] ? planes[1]->id() : 0; + device_.context->add_resource(id(), binding); + binding_ = binding; + storage_planes_ = std::move(planes); + depth_conversion_ = std::move(conversion); + heap_flags_ |= storage_heap_flags; // GetHeapProperties describes the caller's entire logical texture. + } catch (const std::bad_alloc&) { + return E_OUTOFMEMORY; + } + return S_OK; + } + // D3D12 reports the placement alignment of a description that left it 0: 64 KiB, or 4 MiB for a multisampled // texture. One the description asked for is kept. Measured on the PC runtime and WARP (d3d12_resource_desc_test). D3D12_RESOURCE_DESC STDMETHODCALLTYPE GetDesc() override { D3D12_RESOURCE_DESC desc = desc_; + if (storage_ || storage_planes_[0]) desc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; if (!desc.Alignment) { desc.Alignment = (desc.SampleDesc.Count > 1 && !is_tiled_layout(desc.Layout)) ? D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT @@ -2795,6 +3090,7 @@ class Resource final } return desc; } + bool belongs_to(const DeviceState& device) const { return &device_ == &device; } // Both sparse resources and the committed fallback report the reserved layout and have no heap of their own. void make_reserved(D3D12_TEXTURE_LAYOUT layout) { @@ -2811,11 +3107,43 @@ class Resource final // address (instance descriptors and builds hand it to the driver). A texture the title placed at its own address // through Xbox slot 133 reports that title address, as the console does: a title uses it as the CPU pointer it // clears the texture through (docs/d3d12_vulkan.md 3.3). Any other texture answers 0, as on D3D12. - D3D12_GPU_VIRTUAL_ADDRESS STDMETHODCALLTYPE GetGPUVirtualAddress() override { return accel_ ? gpu_va_ : va_; } + D3D12_GPU_VIRTUAL_ADDRESS STDMETHODCALLTYPE GetGPUVirtualAddress() override { + const auto result = accel_ ? gpu_va_ : va_; + return result; + } // The title's own address for a texture Xbox slot 133 placed. The image is still the committed fallback, so its // pixels do not alias the title's pages yet; the address is what GetGPUVirtualAddress answers (XCL PR #168's // behavior, measured on a retail title). - void set_title_address(D3D12_GPU_VIRTUAL_ADDRESS address) { va_ = address; } + void set_title_address(D3D12_GPU_VIRTUAL_ADDRESS address) { + if (!image_ || !address || title_image_registered_) return; + std::lock_guard lock(device_.title_image_mutex); + va_ = address; + device_.title_images.emplace(va_, this); + title_image_registered_ = true; + } + // No descriptors have been built for a newly materialized raw surface. + void set_raw_image_address(std::uint64_t address) { image_address_ = address; } + + void use_texture_lease(void* data, std::size_t size, UINT layout) { + if (!image_ || !data) return; + const auto addr = reinterpret_cast(data); + if (va_ && va_ != addr) return; + if ((layout == 1 || layout == 0x100) && desc_.Dimension==D3D12_RESOURCE_DIMENSION_TEXTURE2D) { + // Placement callbacks get a title VA; pin_mapped_data checks its live XMem section on Map. + title_linear_ = true; + title_linear_limit_ = size ? size : SIZE_MAX; + } + if (!size || va_) return; + std::uint64_t lo = 0, hi = 0; + const bool tracked = leonida::title_va_aliases().title_memory(addr, lo, hi) && size <= hi - addr; + MEMORY_BASIC_INFORMATION page{}; + const bool writable = VirtualQuery(data, &page, sizeof(page)) && page.State == MEM_COMMIT && + !(page.Protect & (PAGE_NOACCESS | PAGE_GUARD)) && + ((page.Protect & 0xffu) == PAGE_READWRITE || (page.Protect & 0xffu) == PAGE_WRITECOPY); + if (tracked && writable) { + set_title_address(addr); + } + } // // The node masks read back as the one node of a single adapter (0 becomes 1), and the heap flags as the runtime @@ -2853,6 +3181,10 @@ class Resource final // no pointer to give (its layout is the driver's), so D3D12 only lets it be mapped with a null pointer, before // WriteToSubresource/ReadFromSubresource. HRESULT STDMETHODCALLTYPE Map(UINT subresource, const D3D12_RANGE* read, void** data) override { + if (title_linear_ && data && image_) { + *data = nullptr; + return map_title_texture(subresource, read, data); + } if (image_) { VkImageSubresourceRange range{}; return !data && cpu_visible() && subresource != leonida::all_subresources && @@ -2865,7 +3197,24 @@ class Resource final if (data) *data = mapped_; return S_OK; } - void STDMETHODCALLTYPE Unmap(UINT, const D3D12_RANGE*) override {} + void STDMETHODCALLTYPE Unmap(UINT sub, const D3D12_RANGE* written) override { + if (!title_linear_) return; + std::lock_guard lock(title_map_mutex_); + const auto it=title_maps_.find(sub); + if(it==title_maps_.end()) return; + if ((!written || written->End>written->Begin) && (!written || written->End<=it->second.bytes)) + if(!upload_title_map(sub,it->second)) std::fprintf(stderr,"[rt] d3d12: texture upload on Unmap failed, format %u\n",unsigned(desc_.Format)); + if (!--it->second.refs) title_maps_.erase(it); + if (title_maps_.empty()) { + std::lock_guard guard(device_.mapped_texture_mutex); + if(device_.mapped_textures.erase(this)) --device_.map_count; + } + } + bool publish_cpu_writes() { + std::lock_guard lock(title_map_mutex_); + for(auto& [sub,map]:title_maps_) if(!upload_title_map(sub,map)) return false; + return true; + } // CPU copies into and out of a texture subresource. D3D12 completes them before returning and leaves it to // the application to keep the GPU off the subresource meanwhile, so a blocking copy is the whole contract. @@ -2879,6 +3228,83 @@ class Resource final } private: + struct TitleMap { + std::shared_ptr data; + std::uintptr_t address{}; + UINT row{},bytes{},refs{}; + std::string fingerprint; + bool shared_pages = false; + }; + static std::string fingerprint(const TitleMap& map) { + std::string out; + for(std::size_t at=0;at(1u<<20,map.bytes-at)}); + return out; + } + bool upload_title_map(UINT sub, TitleMap& map) { + if (map.shared_pages) { + auto current=rt::d3d12_xs::pin_texture_pages(reinterpret_cast(map.address),map.bytes); + if (!current || current.get()!=map.data.get()) return false; + } + auto hash=fingerprint(map); + if(hash==map.fingerprint) return true; + if(FAILED(cpu_copy(true,sub,nullptr,map.data.get(),map.row,map.bytes))) return false; + map.fingerprint=std::move(hash); + return true; + } + HRESULT map_title_texture(UINT sub, const D3D12_RANGE* read, void** out) { + if (!va_ || desc_.SampleDesc.Count!=1 || aspects_!=VK_IMAGE_ASPECT_COLOR_BIT || binding_.rgba4_render_fallback || + binding_.rgb96 || sub>=UINT(desc_.MipLevels)*desc_.DepthOrArraySize) return E_INVALIDARG; + std::lock_guard lock(title_map_mutex_); + if (auto it=title_maps_.find(sub);it!=title_maps_.end()) { + if(read && read->End>read->Begin && read->End>it->second.bytes) return E_INVALIDARG; + ++it->second.refs;*out=reinterpret_cast(it->second.address);return S_OK; + } + namespace ct=leonida::console_texture; + ct::TextureDesc d{};d.format=unsigned(desc_.Format);d.width=UINT(desc_.Width);d.height=desc_.Height; + d.depth_or_array=desc_.DepthOrArraySize;d.mips=desc_.MipLevels;d.swizzle=ct::kLinear; + const auto shape=ct::Texture::make(d); + if(!shape || shape->planes.size()!=1) return E_INVALIDARG; + const auto& layout=shape->planes[0].layout; + const UINT mip=sub%desc_.MipLevels,slice=sub/desc_.MipLevels; + const auto& level=layout.mips[mip]; + const std::uint64_t row=std::uint64_t(level.pitch)*layout.desc.element_bytes, size=row*level.height; + std::uint64_t offset{}; + if(layout.offset(mip,0,0,slice,offset)!=ct::Error::ok || !size || size>UINT_MAX || offset>title_linear_limit_ || + size>title_linear_limit_-offset || offset>UINTPTR_MAX-va_ || size>UINTPTR_MAX-va_-offset || + (read && read->End>read->Begin && read->End>size)) return E_INVALIDARG; + const auto title_address=std::uintptr_t(va_+offset); + auto pinned=rt::d3d12_xs::pin_texture_pages(reinterpret_cast(title_address),std::size_t(size)); + const bool shared=bool(pinned); + if (shared) previously_pinned_ = true; + else if (previously_pinned_) return E_INVALIDARG; + else { + // A console GPU VA need not name CPU memory on the PC. Map the live Vulkan image by + // staging it through our own allocation. The supplied VA is never dereferenced here. + try { pinned = std::shared_ptr(new std::uint8_t[std::size_t(size)]{},std::default_delete()); } + catch(const std::bad_alloc&) { return E_OUTOFMEMORY; } + } + const auto address=shared ? title_address : reinterpret_cast(pinned.get()); + TitleMap map{std::move(pinned),address,UINT(row),UINT(size),1,{},shared}; + if ((!read || read->End>read->Begin) && (!shared || gpu_referenced_.load(std::memory_order_acquire))) { + const HRESULT hr=cpu_copy(false,sub,nullptr,map.data.get(),map.row,map.bytes); + if(FAILED(hr)) return hr; + map.fingerprint=fingerprint(map); + } + title_maps_.emplace(sub,std::move(map)); + { + std::lock_guard guard(device_.mapped_texture_mutex); + if(device_.mapped_textures.insert(this).second) ++device_.map_count; + } + *out=reinterpret_cast(address); + return S_OK; + } + bool title_linear_ = false; + bool previously_pinned_ = false; + std::uint64_t title_linear_limit_ = 0; + std::atomic gpu_referenced_{false}; + std::mutex title_map_mutex_; + std::map title_maps_; // One subresource region in copy units: rows of texels, or of 4x4 blocks for block-compressed formats. struct Region { VkImageSubresourceLayers layers; @@ -3103,8 +3529,14 @@ class Resource final DeviceState& device_; D3D12_RESOURCE_DESC desc_; + Resource* storage_ = nullptr; + bool title_image_registered_ = false; D3D12_HEAP_PROPERTIES heap_; D3D12_HEAP_FLAGS heap_flags_; + VkMemoryRequirements image_need_{}; + bool deferred_memory_ = false; + std::atomic deferred_bound_{false}; + std::mutex bind_mutex_; VkImage image_ = VK_NULL_HANDLE; VkBuffer buffer_ = VK_NULL_HANDLE; VkDeviceMemory memory_ = VK_NULL_HANDLE; @@ -3129,6 +3561,8 @@ class Resource final bool sparse_image_ = false; bool placed_ = false; leonida::ResourceBinding binding_{}; // a texture's, as registered with the context + std::unique_ptr depth_conversion_; + std::array, 2> storage_planes_; // Xbox depth/stencil UAV, by plane bool host_transfer_ = false; // created with VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT D3D12_GPU_VIRTUAL_ADDRESS va_ = 0; // a buffer's console VA, or a slot-133 texture's title address VkDeviceSize arena_offset_ = 0; @@ -3288,6 +3722,83 @@ bool equal_semantic(const std::string& a, const char* b) { // A heap (section 3.3): a range of the GPU address arena, as large as the game asked for, so a placed buffer can // name any 64 KiB-aligned offset in it. Textures placed in it still get their own VkDeviceMemory; the offset is only // their key, which keeps optimal-tiling images out of the arena's memory type. +bool DeviceState::publish_mapped_textures() { + if(!map_count.load(std::memory_order_acquire)) return true; + std::vector pending; + { + std::lock_guard lock(mapped_texture_mutex); + for(auto* r:mapped_textures) if(r->try_add_ref()) pending.push_back(r); + } + bool ok=true; + for(auto* r:pending) { if(!r->publish_cpu_writes()) ok=false; r->Release(); } + return ok; +} +bool DeviceState::materialize_sample(const leonida::DescriptorKey& key) { + if (!pending_sample_count.load(std::memory_order_acquire)) return true; + PendingSample sample{}; + { + std::lock_guard lock(pending_view_mutex); + const auto it = pending_samples.find(key); + if (it == pending_samples.end()) return true; + sample = it->second; + if (!sample.owner->try_add_ref()) return false; + } + const auto image = sample.owner->bound_image(); + const bool ok = image && bind_image(key, sample.image, image, sample.view_format, sample.channels_format, + sample.view_format, sample.owner->aspects(), true, false, {}); + if (ok) { + context->note_shader_image(sample.owner->id()); + std::lock_guard lock(pending_view_mutex); + const auto it=pending_samples.find(key); + if (it!=pending_samples.end() && it->second.owner==sample.owner) { + pending_samples.erase(it); + --pending_sample_count; + } + } + sample.owner->Release(); + return ok; +} + +bool DeviceState::materialize_table(std::uint64_t address, std::uint32_t slots) { + if (!pending_sample_count.load(std::memory_order_acquire)) return true; + if (!slots && address) { + std::vector keys; + { std::lock_guard lock(pending_view_mutex); + for (const auto& [key,view]:pending_samples) + if (view.owner->id() == address) keys.push_back(key); } + for (const auto& key:keys) if (!materialize_sample(key)) return false; + return true; + } + std::uint64_t end = 0; + if (slots) { + std::lock_guard lock(visible_heap_mutex); + auto it = visible_heaps.upper_bound(address); + if (it != visible_heaps.begin()) { + --it; + if (address < it->second.end && (address-it->first)%kDescriptorSize==0) { + if(it->second.type==D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) return true; + end = address + std::min(it->second.end-address, std::uint64_t(slots)*kDescriptorSize); + } + } + } + if (!end) { + // Directly indexed and unrecognized heaps have no trustworthy table extent. + std::vector all; + {std::lock_guard lock(pending_view_mutex);for(const auto& [key,v]:pending_samples) all.push_back(key);} + for(const auto& key:all) if(!materialize_sample(key)) return false; + return true; + } + const auto refreshed = std::min(end-address, std::uint64_t(kViewScanLimit)*kDescriptorSize); + if (end-address>refreshed) + leonida::title_va_aliases().pull_descriptors(arena.mapped+address+refreshed,std::size_t(end-address-refreshed)); + for (auto at=address; at { public: @@ -3816,7 +4327,7 @@ class PipelineState final if (graphics_.pipeline) vk.vkDestroyPipeline(dev, graphics_.pipeline, nullptr); for (const auto& [unbound, built] : variants_) vk.vkDestroyPipeline(dev, built, nullptr); if (graphics_.layout) vk.vkDestroyPipelineLayout(dev, graphics_.layout, nullptr); - for (VkShaderModule module : modules_) vk.vkDestroyShaderModule(dev, module, nullptr); + modules_.clear(); if (code_bytes_) device_.arena_release(code_base_, code_bytes_, DeviceState::arena_shader); } @@ -3845,11 +4356,26 @@ class PipelineState final subgroup_requests_.push_back(request); } - std::uintptr_t id() const { return reinterpret_cast(static_cast(this)); } + std::uintptr_t id() const { + return native_owner_ ? native_owner_->id() : reinterpret_cast(static_cast(this)); + } + void share_native_graphics(std::shared_ptr owner) { native_owner_ = std::move(owner); } + bool ensure_native_source(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& pc, D3D12_SHADER_BYTECODE mesh, + std::span containers) { + std::call_once(native_source_once_,[&]{ + if(rt::d3d12_xs::find_pso_record(this)){native_source_ready_=true;return;} + rt::d3d12_xs::native_pipeline_detail::Stream source; + rt::d3d12_xs::native_pipeline_detail::build_stream(pc,mesh,source); + auto record=rt::d3d12_xs::PsoStreamRecord::capture(source.desc(),containers); + native_source_ready_=record && rt::d3d12_xs::attach_pso_record(this,std::move(record)); + }); + return native_source_ready_; + } void set_cache_key(leonida::cached_pso::Key key) { cache_key_ = std::move(key); } // A null pointer is accepted with S_OK, as by the PC runtime (measured on an RTX 3060 and WARP). HRESULT STDMETHODCALLTYPE GetCachedBlob(ID3DBlob** blob) override { + if (native_owner_) return native_owner_->GetCachedBlob(blob); if (!blob) return S_OK; *blob = new CachedBlob(leonida::cached_pso::encode(device_.pso_identity, cache_key_)); return S_OK; @@ -3879,9 +4405,25 @@ class PipelineState final return S_OK; } - bool compute() const { return registered_ && !is_graphics_; } - bool graphics() const { return registered_ && is_graphics_; } - const std::vector& subgroup_requests() const { return subgroup_requests_; } + void set_pending_stream(bool compute) { pending_stream_kind_=compute?2:1; } + bool resolve_type(bool graphics) { + if(native_owner_)return native_owner_->resolve_type(graphics); + if(pending_stream_kind_) { + if(pending_stream_kind_!=(graphics?1u:2u))return false; + std::call_once(resolve_stream_once_,[&]{ + const auto* record=rt::d3d12_xs::find_pso_record(this); + PipelineStream stream{}; + HRESULT hr=record?parse_pipeline_stream(record->desc(),stream):E_INVALIDARG; + if(SUCCEEDED(hr))hr=stream.has_cs?create_compute(stream.compute):create_graphics(stream.graphics,&stream.ms,&stream.as); + }); + } + return registered_ && (is_graphics_==graphics); + } + bool compute() const { return pending_stream_kind_==2 || (registered_ && !is_graphics_); } + bool graphics() const { return native_owner_ ? native_owner_->graphics() : pending_stream_kind_==1 || (registered_ && is_graphics_); } + const std::vector& subgroup_requests() const { + return native_owner_ ? native_owner_->subgroup_requests() : subgroup_requests_; + } // A VS (+ GS) (+ PS) pipeline for dynamic rendering. Vertex input comes from the input layout matched to the // VS's input signature by semantic name and index: location = the element's register, the translator's rule @@ -4016,6 +4558,14 @@ class PipelineState final // stage_infos.size() indexes the recipe's per-stage required-size structs: one for every table entry. static_assert(std::size(stages) <= std::size(decltype(recipe_.required_sizes){}), "Recipe::required_sizes needs an entry per graphics stage"); + unsigned packed_color_mask=0; + for(unsigned i=0;i stage_infos; // Chained from stage_infos, which the recipe keeps for variants built at draw time: so they live in the recipe. @@ -4027,7 +4577,9 @@ class PipelineState final const bool d24_as_float = desc.DSVFormat != DXGI_FORMAT_UNKNOWN && vulkan_format(desc.DSVFormat, true).format == VK_FORMAT_D24_UNORM_S8_UINT && !device_.depth_usable(VK_FORMAT_D24_UNORM_S8_UINT); - bool depth24_fragment = d24_as_float && desc.DepthStencilState.DepthEnable; + const bool packed16_fallback=desc.DSVFormat==xbox_d16s8 && device_.depth_backing(VK_FORMAT_D16_UNORM_S8_UINT)!=VK_FORMAT_D16_UNORM_S8_UINT; + if(packed16_fallback && samples>1 && desc.DepthStencilState.DepthEnable) return E_NOTIMPL; + bool depth24_fragment = (d24_as_float || packed16_fallback) && desc.DepthStencilState.DepthEnable; if (depth24_fragment && samples > 1) { log_once("D24 depth stored as D32 keeps float depth bias and precision on multisampled targets; samples", int(samples)); @@ -4035,7 +4587,7 @@ class PipelineState final } const leonida::Depth24Bias depth24_bias{desc.RasterizerState.DepthBias, desc.RasterizerState.SlopeScaledDepthBias, - desc.RasterizerState.DepthBiasClamp}; + desc.RasterizerState.DepthBiasClamp,packed16_fallback?65535.0f:16777215.0f}; for (Stage& stage : stages) { if (!stage.code.pShaderBytecode || !stage.code.BytecodeLength) continue; // no PS: depth only stage.fssm = leonida::fssm_program( @@ -4082,6 +4634,7 @@ class PipelineState final code_stage = &stage; } stage.words = library->spirv(*stage.entry); + if(stage.bit==VK_SHADER_STAGE_FRAGMENT_BIT && packed_color_mask && !leonida::rgba4::quantize(stage.words,packed_color_mask)) return E_INVALIDARG; if (stage.words.empty()) return E_FAIL; const auto inner = leonida::conservative_raster::inner_coverage_requirements(stage.words); if (!inner.valid) return E_INVALIDARG; @@ -4142,12 +4695,11 @@ class PipelineState final stage.words = std::move(patched); } } - VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - module_info.codeSize = stage.words.size() * 4; - module_info.pCode = stage.words.data(); - VkShaderModule module = VK_NULL_HANDLE; - if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) return E_FAIL; - modules_.push_back(module); + const VkShaderModule module = shader_module(stage.words); + if (!module) return E_FAIL; + if (stage.bit == VK_SHADER_STAGE_VERTEX_BIT && !geometry && device_.info.features.geometryShader && + topology_type == D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) + rectangle_vertex_ = modules_.back(); VkPipelineShaderStageCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; info.stage = stage.bit; info.module = module; @@ -4163,12 +4715,8 @@ class PipelineState final vs_stage.entry->name.c_str(), why.c_str()); return E_NOTIMPL; } - VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - module_info.codeSize = words.size() * 4; - module_info.pCode = words.data(); - VkShaderModule module = VK_NULL_HANDLE; - if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) return E_FAIL; - modules_.push_back(module); + const VkShaderModule module = shader_module(words); + if (!module) return E_FAIL; VkPipelineShaderStageCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; info.stage = VK_SHADER_STAGE_GEOMETRY_BIT; info.module = module; @@ -4177,13 +4725,8 @@ class PipelineState final } if (depth24_fragment && !ps_stage.entry) { // no pixel shader: a built-in one writes the depth const std::vector words = leonida::depth24_depth_only_fragment(depth24_bias); - VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - module_info.codeSize = words.size() * 4; - module_info.pCode = words.data(); - VkShaderModule module = VK_NULL_HANDLE; - if (words.empty() || vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) - return E_FAIL; - modules_.push_back(module); + const VkShaderModule module = shader_module(words); + if (!module) return E_FAIL; VkPipelineShaderStageCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; info.stage = VK_SHADER_STAGE_FRAGMENT_BIT; info.module = module; @@ -4392,6 +4935,8 @@ class PipelineState final graphics_.color_formats[i] = desc.RTVFormats[i] == DXGI_FORMAT_A8_UNORM && device_.info.a8_render_target ? kA8UnormFormat : vulkan_format(desc.RTVFormats[i], false).format; + if(desc.RTVFormats[i]==DXGI_FORMAT_B4G4R4A4_UNORM && !device_.color_attachment_usable(graphics_.color_formats[i])) + graphics_.color_formats[i]=VK_FORMAT_R8G8B8A8_UNORM; if (graphics_.color_formats[i] == VK_FORMAT_UNDEFINED) { log_once("render-target format not supported yet:", desc.RTVFormats[i]); return E_INVALIDARG; @@ -4401,7 +4946,7 @@ class PipelineState final Format f = vulkan_format(desc.DSVFormat, true); if (f.format == VK_FORMAT_D24_UNORM_S8_UINT && !device_.depth_usable(f.format)) f.format = VK_FORMAT_D32_SFLOAT_S8_UINT; // as CreateCommittedResource does - graphics_.depth_format = f.format; + graphics_.depth_format = device_.depth_backing(f.format); graphics_.depth_aspects = f.aspects; } if (samples > 1) { @@ -4474,6 +5019,7 @@ class PipelineState final // Kept for variants: a draw that leaves a slot unbound needs this pipeline with that format undefined. graphics_.mesh = mesh; + graphics_.base_rectangle_stage = rect_list; recipe_.mesh = mesh; recipe_.stages = std::move(stage_infos); recipe_.attributes = std::move(attributes); @@ -4488,8 +5034,17 @@ class PipelineState final recipe_.depth = depth; recipe_.blends = std::move(blends); recipe_.blend = blend; - graphics_.pipeline = build(0); - if (!graphics_.pipeline) return E_FAIL; + VkResult compile_status=VK_SUCCESS; + const bool cache_only=device_.info.cold_graphics_compile; + if(device_.info.first_use_backend_pipelines) { + graphics_.pending_base_compile=true; + } else { + graphics_.pipeline=build(0,cache_only?VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT:0,&compile_status); + if(!graphics_.pipeline) { + if(!cache_only || compile_status!=VK_PIPELINE_COMPILE_REQUIRED)return E_FAIL; + graphics_.pending_base_compile=true; + } + } graphics_.variant = [this](std::uint32_t unbound) { return variant(unbound); }; if (code_stage) { @@ -4601,22 +5156,38 @@ class PipelineState final VkPipelineShaderStageRequiredSubgroupSizeCreateInfo required_size{}; subgroup_size_for(*entry, required_size, pipeline_info.stage); pipeline_info.layout = pipeline_.layout; - const VkPipelineCache cache = device_.pipeline_cache(); - const bool checkpoint = cache && startup_cache_checkpoints_enabled(); - const ULONGLONG started = checkpoint ? GetTickCount64() : 0; - if (vk.vkCreateComputePipelines(dev, cache, 1, &pipeline_info, nullptr, &pipeline_.pipeline) != VK_SUCCESS) - return E_FAIL; - if (checkpoint && GetTickCount64() - started >= 500) { - const std::unique_lock lock(device_.startup_cache_checkpoint_mutex, std::try_to_lock); - if (lock.owns_lock()) { - try { - save_session_pipeline_cache(vk, dev, cache); - } catch (const std::exception& error) { - std::fprintf(stderr, "[rt] d3d12: pipeline cache checkpoint failed (%s)\n", error.what()); + if(device_.info.first_use_backend_pipelines && (!pipeline_info.stage.pNext || pipeline_info.stage.pNext==&required_size)) { + const bool has_subgroup=pipeline_info.stage.pNext!=nullptr; + pipeline_info.stage.pNext=nullptr; + pipeline_.materialize=[this,pipeline_info,required_size,has_subgroup]() -> VkPipeline { + std::lock_guard lock(compute_compile_mutex_); + if(pipeline_.pipeline)return pipeline_.pipeline; + auto info=pipeline_info; + auto size=required_size;if(has_subgroup)info.stage.pNext=&size; + VkPipeline live=VK_NULL_HANDLE; + const auto result=device_.context->vk.vkCreateComputePipelines(device_.info.device,device_.pipeline_cache(),1,&info,nullptr,&live); + if(result!=VK_SUCCESS){if(live)device_.context->vk.vkDestroyPipeline(device_.info.device,live,nullptr);return VK_NULL_HANDLE;} + pipeline_.pipeline = live; + return live; + }; + } else { + const VkPipelineCache cache = device_.pipeline_cache(); + const bool checkpoint = cache && startup_cache_checkpoints_enabled(); + const ULONGLONG started = checkpoint ? GetTickCount64() : 0; + if (vk.vkCreateComputePipelines(dev, cache, 1, &pipeline_info, nullptr, &pipeline_.pipeline) != VK_SUCCESS) + return E_FAIL; + if (checkpoint && GetTickCount64() - started >= 500) { + const std::unique_lock lock(device_.startup_cache_checkpoint_mutex, std::try_to_lock); + if (lock.owns_lock()) { + try { + save_session_pipeline_cache(vk, dev, cache); + } catch (const std::exception& error) { + std::fprintf(stderr, "[rt] d3d12: pipeline cache checkpoint failed (%s)\n", error.what()); + } } } - } + } // The code base: shaders read constant tables embedded in their own program through s_getpc_b64. The // translator's code offsets are into the bytes the key hashes (the FSSM blob, or the kind-6 program). const std::vector& code = program.bytes; @@ -4652,7 +5223,7 @@ class PipelineState final }; // The graphics pipeline with the formats of the `unbound` slots (leonida::GraphicsPipeline::variant) undefined. - VkPipeline build(std::uint32_t unbound) const { + VkPipeline build(std::uint32_t unbound, VkPipelineCreateFlags flags=0, VkResult* status=nullptr) { // The stride state is last: a pipeline without vertex bindings (a full-screen pass that builds its vertices // from SV_VertexID) leaves it out, since no vkCmdBindVertexBuffers2 would ever set it // (VUID-vkCmdDraw-pStrides-04913). @@ -4718,8 +5289,29 @@ class PipelineState final } VkGraphicsPipelineCreateInfo info{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &rendering}; - info.stageCount = std::uint32_t(r.stages.size()); - info.pStages = r.stages.data(); + std::vector rectangle_stages; + if (unbound & leonida::GraphicsPipeline::rectangle_stage) { + if (!rectangle_vertex_) return VK_NULL_HANDLE; + if (!rectangle_module_) { + std::string why; + const auto words = leonida::rect_list_geometry(rectangle_vertex_->words, why); + if (words.empty()) { + std::fprintf(stderr, "[rt] d3d12: cannot draw rectangle list: %s\n", why.c_str()); + return VK_NULL_HANDLE; + } + rectangle_module_ = shader_module(words); + if (!rectangle_module_) return VK_NULL_HANDLE; + } + rectangle_stages = r.stages; + VkPipelineShaderStageCreateInfo geometry{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; + geometry.stage = VK_SHADER_STAGE_GEOMETRY_BIT; + geometry.module = rectangle_module_; + geometry.pName = "main"; + rectangle_stages.push_back(geometry); + } + const auto& stages = rectangle_stages.empty() ? r.stages : rectangle_stages; + info.stageCount = std::uint32_t(stages.size()); + info.pStages = stages.data(); info.pVertexInputState = r.mesh ? nullptr : &vertex_input; // ignored with a mesh stage; null for clarity info.pInputAssemblyState = r.mesh ? nullptr : &r.assembly; info.pViewportState = &viewport; @@ -4728,11 +5320,15 @@ class PipelineState final info.pDepthStencilState = &r.depth; info.pColorBlendState = &blend; info.pDynamicState = &dynamic; + info.flags=flags; info.layout = graphics_.layout; VkPipeline pipeline = VK_NULL_HANDLE; - if (device_.context->vk.vkCreateGraphicsPipelines(device_.info.device, device_.pipeline_cache(), 1, - &info, nullptr, &pipeline) != VK_SUCCESS) + const auto result=device_.context->vk.vkCreateGraphicsPipelines(device_.info.device,device_.pipeline_cache(),1,&info,nullptr,&pipeline); + if(status)*status=result; + if(result!=VK_SUCCESS) { + if(pipeline)device_.context->vk.vkDestroyPipeline(device_.info.device,pipeline,nullptr); return VK_NULL_HANDLE; + } return pipeline; } @@ -4756,12 +5352,28 @@ class PipelineState final std::mutex variants_mutex_; std::map variants_; VkShaderModule module_ = VK_NULL_HANDLE; - std::vector modules_; + std::mutex compute_compile_mutex_; + std::vector modules_; + leonida::GraphicsShaderModules::Reference rectangle_vertex_; + VkShaderModule rectangle_module_ = VK_NULL_HANDLE; + VkShaderModule shader_module(std::span words) { + auto& vk=device_.context->vk; + auto object = device_.graphics_modules.acquire(device_.info.device, vk.vkCreateShaderModule, + vk.vkDestroyShaderModule, words); + if(!object)return VK_NULL_HANDLE; + const auto h=object->handle;modules_.push_back(std::move(object)); + return h; + } VkDeviceSize code_base_ = 0; VkDeviceSize code_bytes_ = 0; bool registered_ = false; bool is_graphics_ = false; std::vector subgroup_requests_; // one per stage, in creation order + unsigned pending_stream_kind_=0; + std::once_flag resolve_stream_once_; + std::once_flag native_source_once_; + bool native_source_ready_ = false; + std::shared_ptr native_owner_; leonida::cached_pso::Key cache_key_; }; @@ -4789,6 +5401,31 @@ struct TextureView { float min_lod = 0.0f; }; +// The existing mutable Vulkan formats come from these DXGI typeless families. A typed resource cannot be +// reinterpreted by the 1D/3D UAV path; equal texel sizes alone don't make a cast legal. +bool uav_format_compatible(DXGI_FORMAT resource, DXGI_FORMAT view) { + if (view == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB || view == DXGI_FORMAT_B8G8R8A8_UNORM_SRGB) return false; + if (resource == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB) return view == DXGI_FORMAT_R8G8B8A8_UNORM; + if (resource == DXGI_FORMAT_B8G8R8A8_UNORM_SRGB) return view == DXGI_FORMAT_B8G8R8A8_UNORM; + if (resource == view) return true; + switch (resource) { + case DXGI_FORMAT_R32G32B32A32_TYPELESS: + return view >= DXGI_FORMAT_R32G32B32A32_FLOAT && view <= DXGI_FORMAT_R32G32B32A32_SINT; + case DXGI_FORMAT_R16G16B16A16_TYPELESS: + return view >= DXGI_FORMAT_R16G16B16A16_FLOAT && view <= DXGI_FORMAT_R16G16B16A16_SINT; + case DXGI_FORMAT_R32G32_TYPELESS: return view >= DXGI_FORMAT_R32G32_FLOAT && view <= DXGI_FORMAT_R32G32_SINT; + case DXGI_FORMAT_R10G10B10A2_TYPELESS: return view == DXGI_FORMAT_R10G10B10A2_UNORM || + view == DXGI_FORMAT_R10G10B10A2_UINT; + case DXGI_FORMAT_R8G8B8A8_TYPELESS: return view >= DXGI_FORMAT_R8G8B8A8_UNORM && view <= DXGI_FORMAT_R8G8B8A8_SINT; + case DXGI_FORMAT_R16G16_TYPELESS: return view >= DXGI_FORMAT_R16G16_FLOAT && view <= DXGI_FORMAT_R16G16_SINT; + case DXGI_FORMAT_R8G8_TYPELESS: return view >= DXGI_FORMAT_R8G8_UNORM && view <= DXGI_FORMAT_R8G8_SINT; + case DXGI_FORMAT_R32_TYPELESS: return view >= DXGI_FORMAT_R32_FLOAT && view <= DXGI_FORMAT_R32_SINT; + case DXGI_FORMAT_R16_TYPELESS: return view >= DXGI_FORMAT_R16_FLOAT && view <= DXGI_FORMAT_R16_SINT; + case DXGI_FORMAT_B8G8R8A8_TYPELESS: return view == DXGI_FORMAT_B8G8R8A8_UNORM; + default: return false; + } +} + // In-memory pipeline library (docs/d3d12_vulkan.md sections 3.6 and 4). D3D12 cached blobs are driver-specific // and ignored across runs; Serialize writes a versioned header so CreatePipelineLibrary recognizes our own blobs. // As on the host runtime (d3d12_pipeline_library_host_test), a foreign, truncated or corrupt blob is E_INVALIDARG; @@ -5214,9 +5851,14 @@ class ShaderCacheSession final // The T# of a view: what the shader gets to know about it, in the structure the console's shaders read. // False (with a log) for a view set 0 cannot show yet. -bool image_descriptor(const Resource& resource, const TextureView& view, leonida::gfx10::Image& out) { +bool image_descriptor(const Resource& resource, const TextureView& view, bool storage, leonida::gfx10::Image& out, + VkFormat& view_format, DeviceState::VolumeSlices& slices) { namespace g = leonida::gfx10; const D3D12_RESOURCE_DESC& desc = resource.desc(); + if (storage && (resource.aspects() & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT))) { + log_once("storage view not supported for depth-stencil texture:", int(desc.Format)); + return false; + } // Plane 1 of a depth-stencil texture is its stencil, viewed as X24_TYPELESS_G8_UINT (D24S8) or // X32_TYPELESS_G8X24_UINT (D32S8): eight unsigned bits in G, as D3D12 returns them. The T# is 8_UINT, the // format of the console's separate stencil surface, and bind_image views the stencil aspect for it. @@ -5228,6 +5870,7 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida // Each stencil view format belongs to its own DXGI family only, as in D3D12: the family is the texture's DXGI // format, not the Vulkan format behind it (a D24 texture may be D32_SFLOAT_S8_UINT underneath). const bool stencil_format_fits = + (view.format==xbox_s8_plane && desc.Format==xbox_d16s8) || (view.format == DXGI_FORMAT_X24_TYPELESS_G8_UINT && (desc.Format == DXGI_FORMAT_R24G8_TYPELESS || desc.Format == DXGI_FORMAT_D24_UNORM_S8_UINT)) || (view.format == DXGI_FORMAT_X32_TYPELESS_G8X24_UINT && @@ -5236,13 +5879,15 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida log_once("a stencil-plane view needs its texture family's stencil view format; format", int(view.format)); return false; } - const bool volume = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; - const bool msaa = g::multisampled(view.type); + const bool volume = view.type == g::ImageType::image_3d; const bool line = view.type == g::ImageType::image_1d; - const auto dimension = line ? D3D12_RESOURCE_DIMENSION_TEXTURE1D : - view.type == g::ImageType::image_3d ? D3D12_RESOURCE_DIMENSION_TEXTURE3D : - D3D12_RESOURCE_DIMENSION_TEXTURE2D; - if (desc.Dimension != dimension || (line && view.layer_count != 1) || msaa != (desc.SampleDesc.Count > 1)) { + const bool line_array = view.type == g::ImageType::image_1d_array; + const bool one_d = line || line_array; + const bool msaa = g::multisampled(view.type); + const auto dimension = volume ? D3D12_RESOURCE_DIMENSION_TEXTURE3D + : one_d ? D3D12_RESOURCE_DIMENSION_TEXTURE1D : D3D12_RESOURCE_DIMENSION_TEXTURE2D; + if (desc.Dimension != dimension || (msaa ? desc.SampleDesc.Count <= 1 : desc.SampleDesc.Count != 1) || + (storage ? msaa : line_array) || (line && view.layer_count != 1)) { log_once("view type incompatible with texture dimension or sample count; view type", int(view.type)); return false; } @@ -5262,7 +5907,7 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida } const VkFormat resource_format = resource.uint_backed() ? resource.uint_backed() : resource.format(); VkFormat named = resource_format; - if (volume) { + if (volume && !storage) { const bool compatible = vulkan_format(desc.Format, false).typeless ? desc.Format == DXGI_FORMAT_R8G8B8A8_TYPELESS && (view.format == DXGI_FORMAT_R8G8B8A8_UNORM || view.format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB) @@ -5280,6 +5925,7 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida const bool depth_plane = (resource.aspects() & VK_IMAGE_ASPECT_DEPTH_BIT) && !stencil; if (depth_plane) { const bool depth_format_fits = + (desc.Format == xbox_d16s8 && (view.format == DXGI_FORMAT_UNKNOWN || view.format == xbox_d16_plane)) || (desc.Format == DXGI_FORMAT_D16_UNORM && (view.format == DXGI_FORMAT_UNKNOWN || view.format == DXGI_FORMAT_R16_UNORM)) || (desc.Format == DXGI_FORMAT_R16_TYPELESS && view.format == DXGI_FORMAT_R16_UNORM) || @@ -5297,7 +5943,16 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida return false; } } - if (view.format != DXGI_FORMAT_UNKNOWN && !stencil && !depth_plane) { + const bool new_uav = storage && (volume || one_d); + if (new_uav) { + const DXGI_FORMAT dxgi = view.format == DXGI_FORMAT_UNKNOWN ? desc.Format : view.format; + const Format format = texture_storage_format(dxgi, false); + if (format.typeless || format.aspects != VK_IMAGE_ASPECT_COLOR_BIT || !uav_format_compatible(desc.Format, dxgi)) { + log_once("unordered-access view format is not compatible with the resource:", dxgi); + return false; + } + named = format.format; + } else if (view.format != DXGI_FORMAT_UNKNOWN && !stencil && !depth_plane) { if ((view.format == DXGI_FORMAT_A8_UNORM) != (desc.Format == DXGI_FORMAT_A8_UNORM)) { log_once("incompatible typed A8 view format:", int(view.format)); return false; @@ -5320,8 +5975,8 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida } } // A 96-bit texture takes views of its own family only (and a four-channel texture none of it), and only the - // TYPELESS one is cast between FLOAT, UINT and SINT. Its T# names the three-channel format: the swizzle below - // then reads alpha as one, and bind_image views the RGBA32 image accordingly. + // TYPELESS one is cast between FLOAT, UINT and SINT. Its T# names the three-channel format (alpha reads as + // one), but the format list and Vulkan view use the RGBA32 format that backs it. const bool rgb96 = resource.rgb96(); if (!stencil && !depth_plane) { const bool view_rgb96 = view.format != DXGI_FORMAT_UNKNOWN ? vulkan_format(view.format, false).rgb96 : rgb96; @@ -5330,31 +5985,45 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida log_once("view format outside the texture's 96-bit family:", int(view.format)); return false; } - if (rgb96) named = rgb96_named_format(named); } if (named == VK_FORMAT_UNDEFINED || !resource.allows_view_format(named)) { log_once("view format not in the resource's castable list:", int(view.format)); return false; } - const std::uint32_t code = stencil ? g::stencil_format : g::format_from_vulkan(named); - VkFormat view_format = VK_FORMAT_UNDEFINED; + const std::uint32_t code = stencil ? g::stencil_format + : g::format_from_vulkan(rgb96 ? rgb96_named_format(named) : named); + view_format = VK_FORMAT_UNDEFINED; if (stencil) { view_format = resource.format(); - } else if (code && rgb96) { - view_format = named; + } else if (code && (new_uav || rgb96)) { + view_format = rgb96 ? rgb96_view_format(resource.format(), code) : named; } else if (code) { view_format = g::vulkan_view_format(resource_format, code, resource.has_view_format_list()); } - if (view_format == VK_FORMAT_UNDEFINED) { + if (!storage && resource.rgba4_render_backing() && (view.format == DXGI_FORMAT_B4G4R4A4_UNORM || view.format == DXGI_FORMAT_UNKNOWN)) + view_format = resource.format(); + if (view_format == VK_FORMAT_UNDEFINED || !resource.allows_view_format(view_format)) { log_once("view format not supported for this texture:", int(view.format)); return false; } - const UINT layers = volume ? 1 : desc.DepthOrArraySize; - if (view.first_mip >= desc.MipLevels || view.first_layer >= layers) { + if (view.first_mip >= desc.MipLevels) { + log_once("view starts past the texture's mips; first mip", int(view.first_mip)); + return false; + } + // SRVs address an entire volume; only a UAV descriptor can specify a W range within its mip. + const UINT layers = volume ? (storage ? std::max(1u, UINT(desc.DepthOrArraySize) >> view.first_mip) : 1u) + : desc.DepthOrArraySize; + if (view.first_layer >= layers) { log_once("view starts past the texture's mips or layers; first mip", int(view.first_mip)); return false; } - if (msaa && view.layer_count != UINT_MAX && view.layer_count > UINT(desc.DepthOrArraySize) - view.first_layer) { + const UINT remaining = layers - view.first_layer; + const UINT layer_count = view.layer_count == ~0u ? remaining : view.layer_count; + if (new_uav && (!layer_count || layer_count > remaining)) { + log_once("unordered-access view slice count is outside the selected mip:", int(view.layer_count)); + return false; + } + if (msaa && layer_count > remaining) { log_once("multisample shader view ends past the texture array; layers", int(view.layer_count)); return false; } @@ -5368,8 +6037,13 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida out.samples = desc.SampleDesc.Count; out.first_mip = view.first_mip; out.mip_count = std::min(view.mip_count, desc.MipLevels - view.first_mip); - out.first_layer = view.first_layer; - out.layer_count = std::min(view.layer_count, layers - view.first_layer); + if (volume) { + if (storage && (view.first_layer != 0 || layer_count != layers)) + slices = {view.first_layer, layer_count}; + } else { + out.first_layer = view.first_layer; + out.layer_count = std::min(layer_count, remaining); + } if (view.type == g::ImageType::cube) out.layer_count -= out.layer_count % 6; // whole cubes out.resource_mips = desc.MipLevels; out.min_lod = view.min_lod; @@ -5387,7 +6061,8 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida // order, so then the view's own format places the channels. Depth images keep their own format's channels. const bool other_order = view.format != DXGI_FORMAT_UNKNOWN && !stencil && !depth_plane && !rgb96 && named != view_format && !g::is_depth_stencil_format(view_format); - g::Swizzle channels = g::format_swizzle(other_order ? named : view_format); + const VkFormat channels_format = rgb96 ? rgb96_named_format(view_format) : other_order ? named : view_format; + g::Swizzle channels = g::format_swizzle(channels_format); if (stencil) channels = {g::select_zero, g::select_x, g::select_zero, g::select_one}; else if (desc.Format == DXGI_FORMAT_A8_UNORM) channels = {g::select_zero, g::select_zero, g::select_zero, g::select_x}; else if (alpha_unused(view.format != DXGI_FORMAT_UNKNOWN ? view.format : desc.Format)) channels[3] = g::select_one; @@ -5576,6 +6251,8 @@ class Device final info.get_instance_proc(info.instance, "vkGetDeviceProcAddr")); state_.format_properties = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceFormatProperties")); + state_.format_properties2 = reinterpret_cast( + info.get_instance_proc(info.instance, "vkGetPhysicalDeviceFormatProperties2")); state_.image_format_properties = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceImageFormatProperties")); state_.image_format_properties2 = reinterpret_cast( @@ -5678,14 +6355,44 @@ class Device final if (getenv_s(&length, text, "LEONIDA_TITLE_WINDOWS_MB") == 0 && length > 1) state_.title_window_cap = std::strtoull(text, nullptr, 10) << 20; } - leonida::title_va_aliases().set_hooks( + leonida::title_va_aliases().set_resolver( &state_, [](void* device, std::uint64_t va, std::uint64_t bytes, std::uint64_t& out) { return static_cast(device)->resolve_title_memory(va, bytes, out); - }, - [](void* device, std::uint64_t table, std::uint32_t descriptors) { - static_cast(device)->scan_title_table(table, descriptors); }); + state_.context->set_cpu_texture_publisher([this]{return state_.publish_mapped_textures();}); + state_.context->set_sample_table_resolver([this](std::uint64_t address, std::uint32_t slots) { + return state_.materialize_table(address, slots); + }); + state_.context->set_table_scanner([this](std::uint64_t table, std::uint32_t descriptors) { + state_.scan_title_table(table, descriptors); + }); + state_.context->set_graphics_family(info.queue_family); +#ifdef VK_KHR_MAINTENANCE_10_EXTENSION_NAME + if (info.maintenance10 && info.physical) { + const auto get_props = reinterpret_cast( + info.get_instance_proc(info.instance, "vkGetPhysicalDeviceFormatProperties2")); + if (get_props) { + const auto aspects = [&](VkFormat format) { + VkFormatProperties3 props{VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_3}; + VkFormatProperties2 query{VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2, &props}; + get_props(info.physical, format, &query); + VkImageAspectFlags mask = 0; + if (props.optimalTilingFeatures & VK_FORMAT_FEATURE_2_DEPTH_COPY_ON_COMPUTE_QUEUE_BIT_KHR) + mask |= VK_IMAGE_ASPECT_DEPTH_BIT; + if (props.optimalTilingFeatures & VK_FORMAT_FEATURE_2_STENCIL_COPY_ON_COMPUTE_QUEUE_BIT_KHR) + mask |= VK_IMAGE_ASPECT_STENCIL_BIT; + return mask; + }; + state_.context->set_compute_copy_aspects( + [d16 = aspects(VK_FORMAT_D16_UNORM), ds = aspects(VK_FORMAT_D32_SFLOAT_S8_UINT)](VkFormat format) { + if (format == VK_FORMAT_D16_UNORM) return d16; + if (format == VK_FORMAT_D32_SFLOAT_S8_UINT) return ds; + return VkImageAspectFlags{}; + }); + } + } +#endif if (info.physical && state_.format_properties) { state_.context->set_color_attachment_format( [physical = info.physical, get_props = state_.format_properties](VkFormat format) { @@ -5723,7 +6430,7 @@ class Device final // Depth <-> colour copies are staged through scratch buffers (vulkan_scratch.h), on every GPU. state_.context->enable_copy_scratch(get_device, [this](const VkMemoryRequirements& requirements) { return state_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); - }); + }, state_.families); if (info.buffer_device_address && info.physical && info.get_instance_proc) { if (const auto get_props = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties"))) { @@ -5875,7 +6582,8 @@ class Device final "sampler heap (%u of %u besides the fallback): its limits or " "vkGetDescriptorSetLayoutSupport allow no more\n", features.counts[b::sampler_binding] - 1, unsigned(D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE)); - state_.bindless = std::make_unique(get_device, state_.info.device, state_.memory, features); + state_.bindless = std::make_unique(get_device, state_.info.device, state_.memory, features, + state_.families); if (!state_.bindless->ok() || !state_.context->vk.vkCreateSampler) { state_.bindless.reset(); return false; @@ -6033,49 +6741,43 @@ class Device final state_.context->set_heap_base(arena.address); state_.context->set_zero_page(arena.buffer, 0, kZeroPage); state_.context->set_quad_indices(arena.buffer, kZeroPage, kQuadIndexCount); - // Vertex and index views that name the title's own CPU memory are copied into a ring carved from the - // arena at replay (not fence-tracked: the ring is large against a frame's few KiB of immediate geometry). - state_.context->set_title_memory( - [st = &state_](std::uint64_t va, std::uint64_t size, VkBuffer& buffer, VkDeviceSize& offset) { - static constexpr VkDeviceSize kRing = 16ull << 20; - static std::mutex mutex; - static VkDeviceSize ring_base = 0, ring_next = 0; - static bool tried = false, logged = false; - if (!va || !size || size > kRing / 4 || !st->arena.mapped) return false; - // The whole range must be committed, readable host memory. - for (std::uint64_t at = va; at < va + size;) { - MEMORY_BASIC_INFORMATION info{}; - if (!VirtualQuery(reinterpret_cast(at), &info, sizeof(info))) return false; - if (info.State != MEM_COMMIT || (info.Protect & (PAGE_NOACCESS | PAGE_GUARD)) || !info.Protect) - return false; - at = reinterpret_cast(info.BaseAddress) + info.RegionSize; - } - std::lock_guard lock(mutex); - if (!tried) { - tried = true; - if (!st->arena_allocate(kRing, 256, ring_base, DeviceState::arena_shader)) ring_base = 0; - } - if (!ring_base) return false; - const VkDeviceSize aligned = (size + 255) & ~VkDeviceSize(255); - if (ring_next + aligned > kRing) ring_next = 0; - std::memcpy(st->arena.mapped + ring_base + ring_next, reinterpret_cast(va), - std::size_t(size)); - buffer = st->arena.buffer; - offset = ring_base + ring_next; - ring_next += aligned; - if (!logged) { - logged = true; - std::fprintf(stderr, "[rt] d3d12: vertex/index views in title memory are copied into a " - "%llu MiB ring (first: %llu bytes)\n", - static_cast(kRing >> 20), static_cast(size)); - } - return true; - }); + // Copy only registered title data. Each immutable upload stays alive in the queue command slot + // until that submission's timeline value completes; a large indexed frame cannot wrap over itself. + state_.context->set_geometry_provider([st=&state_](std::uint64_t va,std::uint64_t bytes, + leonida::VulkanContext::GeometryUpload& result) { + if (!va || !bytes || bytes>UINTPTR_MAX-va || !st->arena.mapped || bytes>st->arena.size) return false; + std::uint64_t lo{},hi{}; + if (!leonida::title_va_aliases().title_memory(va,lo,hi) || bytes>hi-va) { + return false; + } + for(std::uint64_t at=va;at(at),®ion,sizeof(region)) || region.State!=MEM_COMMIT || + (region.Protect & (PAGE_NOACCESS|PAGE_GUARD)) || + !(region.Protect & (PAGE_READONLY|PAGE_READWRITE|PAGE_WRITECOPY))) return false; + at=reinterpret_cast(region.BaseAddress)+region.RegionSize; + } + struct Lease { + DeviceState* state{}; + VkDeviceSize offset{},bytes{}; + ~Lease(){if(bytes)state->arena_release(offset,bytes,DeviceState::arena_buffer);} + }; + auto lease=std::make_shared(); + if (!st->arena_allocate(bytes,256,lease->offset,DeviceState::arena_buffer)) return false; + lease->state=st;lease->bytes=bytes; + SIZE_T copied{}; + if (!ReadProcessMemory(GetCurrentProcess(),reinterpret_cast(va),st->arena.mapped+lease->offset, + SIZE_T(bytes),&copied) || copied!=bytes) return false; + result={va,bytes,st->arena.buffer,lease->offset,std::move(lease)}; + return true; + }); return true; } ~Device() override { - leonida::title_va_aliases().clear_hooks(&state_); + raw_images_.clear(); + leonida::label::completions().stop(state_.info.device); + leonida::title_va_aliases().clear_resolver(&state_); { std::lock_guard lock(state_.title_window_mutex); for (const auto& window : state_.title_windows) @@ -6125,6 +6827,100 @@ class Device final leonida::VulkanContext& context() { return *state_.context; } const leonida::BindlessSet* bindless() const { return state_.bindless.get(); } const DeviceState& state() const { return state_; } + HRESULT create_native_graphics(const leonida::native_pso::GraphicsDesc& desc, REFIID iid, void** out) { + const auto* shaders = state_.library(); + if (!shaders) return E_NOTIMPL; + return state_.native_graphics.create(shaders->directory(), desc, out, [&](const auto& pc, const auto& mesh, const auto& containers) { + return shared_native_graphics(pc, mesh, containers, iid, out); + }); + } + // A fresh public PSO has its own COM identity, private data and name. Equal native descriptions can + // hold one compiled backend PSO while either public object lives. The device only holds weak references. + HRESULT prepare_console_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& source, REFIID iid, void** out, + std::unique_ptr record) { + if (!out)return E_POINTER;*out=nullptr; + PipelineStream stream{}; + if(const auto hr=parse_pipeline_stream(source,stream);FAILED(hr))return hr; + const auto* library=state_.library();if(!library)return E_FAIL; + const auto verify=[&](const char* name,const D3D12_SHADER_BYTECODE& code) { + if(!code.BytecodeLength)return true; + if(!code.pShaderBytecode)return false; + const std::span bytes{static_cast(code.pShaderBytecode),code.BytecodeLength}; + const std::string identity=std::string(name)+leonida::sha256_hex(bytes); + {std::lock_guard lock(verified_program_mutex_);if(verified_programs_.count(identity))return true;} + auto program=leonida::compute_program(bytes); + if(program.bytes.empty())return false; + bool ambiguous=false; + const auto candidates=library->program_candidates(name,program,&ambiguous); + if(candidates.empty() || ambiguous)return false; + {std::lock_guard lock(verified_program_mutex_);verified_programs_.insert(identity);} + return true; + }; + if(stream.has_cs) { + if(!stream.compute.CS.BytecodeLength || !verify("cs",stream.compute.CS))return E_INVALIDARG; + } else { + const auto& g=stream.graphics; + if(stream.as.BytecodeLength || g.HS.BytecodeLength || g.DS.BytecodeLength)return E_NOTIMPL; + if((bool(g.VS.BytecodeLength)==bool(stream.ms.BytecodeLength)) || g.NumRenderTargets>8 || + !verify("vs",g.VS)||!verify("gs",g.GS)||!verify("ms",stream.ms)||!verify("ps",g.PS))return E_INVALIDARG; + } + if(!record) record=rt::d3d12_xs::PsoStreamRecord::capture(source); + if(!record)return E_INVALIDARG; + auto* pipeline=new PipelineState(state_); + pipeline->attach_device(identity()); + pipeline->set_cache_key(stream.has_cs?pipeline_key(stream.compute):pipeline_key(stream.graphics)); + if(!rt::d3d12_xs::attach_pso_record(pipeline,std::move(record))){pipeline->Release();return E_OUTOFMEMORY;} + pipeline->set_pending_stream(stream.has_cs); + return hand_out(pipeline,iid,out); + } + HRESULT shared_native_graphics(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& pc, D3D12_SHADER_BYTECODE mesh, + std::span containers, + REFIID iid, void** out) { + auto key = pipeline_key(pc); + if (mesh.BytecodeLength) + key += leonida::sha256_hex({static_cast(mesh.pShaderBytecode), mesh.BytecodeLength}); + std::shared_ptr compiled; + { + std::lock_guard lock(native_pipeline_mutex_); + const auto found = native_pipelines_.find(key); + if (found != native_pipelines_.end()) compiled = found->second.lock(); + } + if (!compiled) { + ID3D12PipelineState* raw = nullptr; + HRESULT hr; + if(state_.info.prepare_on_bind) { + rt::d3d12_xs::native_pipeline_detail::Stream native; + rt::d3d12_xs::native_pipeline_detail::build_stream(pc,mesh,native); + const auto source=native.desc(); + auto record=rt::d3d12_xs::PsoStreamRecord::capture(source,containers); + hr=record?prepare_console_stream(source,__uuidof(ID3D12PipelineState),reinterpret_cast(&raw),std::move(record)):E_INVALIDARG; + } else { + hr = mesh.BytecodeLength + ? rt::d3d12_xs::native_pipeline_detail::create_mesh(this, pc, mesh, __uuidof(ID3D12PipelineState), + reinterpret_cast(&raw)) + : CreateGraphicsPipelineState(&pc, IID_PPV_ARGS(&raw)); + } + if (FAILED(hr)) return hr; + if (!raw) return E_FAIL; + auto* owner = PipelineState::from(raw); + if (!owner) { raw->Release(); return E_NOINTERFACE; } + compiled = std::shared_ptr(owner, [](PipelineState* p) { p->Release(); }); + std::lock_guard lock(native_pipeline_mutex_); + if (native_pipelines_.size() >= 16384) native_pipelines_.clear(); + auto& cached = native_pipelines_[key]; + if (auto concurrent = cached.lock()) compiled = std::move(concurrent); + else cached = compiled; + } + if(!compiled->ensure_native_source(pc,mesh,containers)) return E_FAIL; + auto* view = new PipelineState(state_); + view->attach_device(identity()); + if(!rt::d3d12_xs::share_pso_record(compiled.get(),view)) { + view->Release(); + return E_OUTOFMEMORY; + } + view->share_native_graphics(std::move(compiled)); + return hand_out(view, iid, out); + } IUnknown* holder() { return identity(); } // Console-extended CreateDescriptorHeap (Xbox slot 14): a heap at the title's console address. The proxy's // handler (set_console_descriptor_heap_handler) calls this; a normal PC create never does. @@ -6159,6 +6955,148 @@ class Device final return ok ? found : nullptr; } + class RawTileReader { + public: + RawTileReader(std::uint64_t address, std::size_t size) + : address_(address), size_(size), cache_(std::min(size, block_size * slots)) { + tags_.fill(SIZE_MAX); + } + bool copy(std::size_t offset, std::uint8_t* to, std::size_t bytes) { + if (offset > size_ || bytes > size_ - offset) return false; + while (bytes) { + const auto block = offset / block_size; + const auto slot = block % slots; + const auto base = block * block_size; + const auto available = std::min(block_size, size_ - base); + auto* window = cache_.data() + slot * block_size; + if (tags_[slot] != block) { + SIZE_T copied{}; + if (!ReadProcessMemory(GetCurrentProcess(),reinterpret_cast(address_+base), + window,available,&copied) || copied!=available) return false; + tags_[slot]=block; + } + const auto n=std::min(bytes,available-(offset-base)); + std::memcpy(to,window+offset-base,n); + offset+=n;to+=n;bytes-=n; + } + return true; + } + private: + static constexpr std::size_t block_size = 64 * 1024, slots = 8; + std::uint64_t address_; + std::size_t size_; + std::vector cache_; + std::array tags_; + }; + + bool raw_texture_view(const D3D12_RESOURCE_DESC& raw, const D3D12_SHADER_RESOURCE_VIEW_DESC& view, + std::uint64_t address, D3D12_CPU_DESCRIPTOR_HANDLE destination) { + namespace ct = leonida::console_texture; + if (!address || !destination.ptr || (address & 255) || raw.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) + return false; + Resource* placed = nullptr; + { + std::lock_guard lock(state_.title_image_mutex); + auto [begin, end] = state_.title_images.equal_range(address); + for (auto it = begin; it != end; ++it) { + const auto& shape = it->second->desc(); + if (raw.Width == shape.Width && raw.Height == shape.Height && raw.Format == shape.Format && + raw.DepthOrArraySize == shape.DepthOrArraySize && raw.MipLevels == shape.MipLevels && + raw.SampleDesc.Count == shape.SampleDesc.Count && it->second->try_add_ref()) { + placed = it->second; + break; + } + } + } + if (placed) { + CreateShaderResourceView(placed, &view, destination); + placed->Release(); + return true; + } + // Raw sampled surfaces have no COM owner. Only consume the full span of a retained title allocation + // and a layout the console texture computer can actually untile. + if (view.ViewDimension != D3D12_SRV_DIMENSION_TEXTURE2D || raw.DepthOrArraySize != 1 || + raw.MipLevels != 1 || raw.SampleDesc.Count != 1 || (unsigned(raw.Flags) & 0x0f) || + raw.Width > ct::kMaxExtent || raw.Height > ct::kMaxExtent || + (view.Format != raw.Format && view.Format != DXGI_FORMAT_UNKNOWN)) return false; + const UINT mode = unsigned(raw.Layout); + if (mode != 0 && mode != 1 && (mode & ~255u) != 256u) return false; + const UINT swizzle = mode == 0 ? ct::kSw4kbS : mode == 1 ? ct::kLinear : mode & 255u; + ct::TextureDesc d{}; + d.width = static_cast(raw.Width); d.height = raw.Height; d.format = unsigned(raw.Format); + d.swizzle = swizzle; + const auto texture = ct::Texture::make(d); + if (!texture || texture->planes.size() != 1 || !texture->planes[0].layout.addressable()) return false; + const auto fmt = ct::format(d.format); + if (!fmt || fmt->stencil) return false; + const auto& level = texture->planes[0].layout; + const auto& mip = level.mips[0]; + const std::size_t row = std::size_t(mip.width) * fmt->bytes, bytes = row * mip.height; + std::uint64_t lo = 0, hi = 0; + if (!bytes || row > UINT_MAX || bytes > UINT_MAX || texture->size > SIZE_MAX || + !leonida::title_va_aliases().title_memory(address, lo, hi) || texture->size > hi - address) return false; + // Bound CPU and transfer scratch per upload. The full title surface can be hundreds of + // megabytes; the title already owns its source, and the copy on the GPU is the one sampled. + RawTileReader source(address,static_cast(texture->size)); + constexpr std::size_t stripe_bytes = 2 * 1024 * 1024; + const UINT max_rows = static_cast(std::min(mip.height, std::max(1,stripe_bytes/row))); + std::vector linear(row*max_rows); + std::vector columns; + if (swizzle != ct::kLinear) { + std::uint64_t origin{}; + if (level.offset(0,0,0,0,origin)!=ct::Error::ok) return false; + columns.resize(mip.width); + for (UINT x=0; x(state_, clean, heap, D3D12_HEAP_FLAG_NONE); + const Format backing = state_.texture_format(clean); + if (backing.format == VK_FORMAT_UNDEFINED || backing.typeless || FAILED(resource->create_texture(backing))) { + raw_images_.erase(key); + return false; + } + resource->set_raw_image_address(address); + cached.resource = std::move(resource); + } + const UINT stripes = (mip.height + max_rows - 1) / max_rows; + cached.fingerprints.resize(stripes); + for (UINT first=0, strip=0; firstbytes,fmt->bytes)) return false; + } + } + const std::span content(linear.data(),used); + const auto digest = leonida::sha256_hex(content); + if (cached.fingerprints[strip] == digest) continue; + const UINT bottom = std::min(raw.Height,(first+rows)*fmt->block); + const D3D12_BOX box{0,first*fmt->block,0,UINT(raw.Width),bottom,1}; + const HRESULT hr = cached.resource->WriteToSubresource(0,&box,linear.data(),UINT(row),UINT(used)); + if (FAILED(hr)) return false; + cached.fingerprints[strip] = digest; + } + CreateShaderResourceView(cached.resource.get(), &view, destination); + return true; + } + UINT STDMETHODCALLTYPE GetNodeCount() override { return 1; } // The Vulkan physical device's LUID, which is the DXGI adapter's on Windows. Zero (logged) when the driver has @@ -6666,31 +7604,31 @@ class Device final std::fprintf(stderr, "[rt] d3d12: root signature not understood: %s\n", parsed.error.c_str()); return E_INVALIDARG; } - // Two layouts, one per bind point (RootArgumentLayout): graphics keeps pack(), compute takes the console - // layout pack_stage() measured (D3D-448). The signature is refused only when neither can place it. + // Select the graphics layout once. A stage layout that spills falls back to the default packing. const rt::rootsig::PackResult packed = rt::rootsig::pack(parsed.sig); + RootArgumentLayout layout; + rt::rootsig::StagePackResult local_stage; + if (local_graphics_stage_layout()) { + local_stage = rt::rootsig::pack_stage(parsed.sig, rt::rootsig::Stage::Vertex); + layout.graphics_compact_tables = local_stage.ok; + static std::atomic said{0}; + if (said.fetch_add(1) < 3) + std::fprintf(stderr, "[rt] d3d12: local: graphics root arguments in the console stage layout (from s%u): %s\n", + local_stage.base, local_stage.ok ? "ok" : local_stage.error.c_str()); + } const rt::rootsig::StagePackResult compute = rt::rootsig::pack_stage(parsed.sig, rt::rootsig::Stage::Compute); - if (!packed.ok && !compute.ok) { + layout.graphics_ok = layout.graphics_compact_tables || packed.ok; + layout.compute_ok = compute.ok; + layout.flags = parsed.sig.flags; + if (!layout.graphics_ok && !compute.ok) { std::fprintf(stderr, "[rt] d3d12: root signature refused: %s (compute: %s)\n", packed.error.c_str(), compute.error.c_str()); return E_INVALIDARG; } - if (!packed.ok) + if (!layout.graphics_ok) std::fprintf(stderr, "[rt] d3d12: root signature usable for compute only: %s\n", packed.error.c_str()); if (!compute.ok) std::fprintf(stderr, "[rt] d3d12: root signature usable for graphics only: %s\n", compute.error.c_str()); - RootArgumentLayout layout; - layout.flags = parsed.sig.flags; - layout.graphics_ok = packed.ok; - layout.compute_ok = compute.ok; - const rt::rootsig::StagePackResult local_stage = rt::rootsig::pack_stage(parsed.sig, rt::rootsig::Stage::Vertex); - const bool local_stage_layout = local_graphics_stage_layout() && local_stage.ok; - if (local_graphics_stage_layout()) { - static std::atomic said{0}; - if (said.fetch_add(1) < 3) - std::fprintf(stderr, "[rt] d3d12: local: graphics root arguments in the console stage layout (from s%u): %s\n", - local_stage.base, local_stage.ok ? "ok" : local_stage.error.c_str()); - } for (std::size_t i = 0; i < parsed.sig.params.size(); ++i) { std::uint32_t first = UINT32_MAX; for (std::uint32_t d = 0; packed.ok && d < packed.dword_count; ++d) @@ -6698,10 +7636,10 @@ class Device final first = d; break; } - if (local_stage_layout) first = local_stage.first_sgpr[i]; + if (layout.graphics_compact_tables) first = local_stage.first_sgpr[i]; layout.parameters.push_back({parsed.sig.params[i].type, first, parsed.sig.params[i].num_values, compute.ok ? compute.first_sgpr[i] : rt::rootsig::kNoSgpr, - table_view_descriptors(parsed.sig.params[i])}); + table_descriptor_count(parsed.sig.params[i])}); } register_static_samplers(parsed.sig); auto* signature = new RootSignature( @@ -6908,6 +7846,8 @@ class Device final if (!r || !r->a8_as_alpha() || rd.Format != DXGI_FORMAT_A8_UNORM || !plain_2d || (desc && desc->Format != DXGI_FORMAT_UNKNOWN && desc->Format != DXGI_FORMAT_A8_UNORM)) view = {}; + } else if (r && rd.Format==DXGI_FORMAT_B4G4R4A4_UNORM && r->format()==VK_FORMAT_R8G8B8A8_UNORM) { + if(!desc || desc->Format==DXGI_FORMAT_UNKNOWN || desc->Format==rd.Format) view.format=leonida::ColorViewFormat::resource; } else if (r && r->uint_backed() == VK_FORMAT_A1R5G5B5_UNORM_PACK16) { // An R16_UINT-backed B5G5R5A1 UAV texture (Format::uint_backed) renders through an A1R5G5B5 view, in // its own format only. @@ -7058,16 +7998,23 @@ class Device final // A null description, zero address, or zero size leaves the whole slot zeroed (null V#: reads return 0). void STDMETHODCALLTYPE CreateConstantBufferView(const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE destination) override { + write_constant_buffer_view(desc,destination,false); + } + void write_constant_buffer_view(const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE destination, + bool vector_rows) { d3d12_trace::record("ID3D12Device::CreateConstantBufferView"); if (!destination.ptr) return; std::memset(reinterpret_cast(destination.ptr), 0, kDescriptorSize); if (!desc || !desc->BufferLocation || !desc->SizeInBytes) return; leonida::gfx10::Buffer buffer{}; buffer.address = desc->BufferLocation; - buffer.stride = 0; - buffer.num_records = desc->SizeInBytes; + const bool indexed = vector_rows && desc->SizeInBytes % 16 == 0; + // A vector ALU fetch selects a 16-byte constant register with IDXEN. Scalar SMEM + // still sees the very same byte extent, NUM_RECORDS * STRIDE. + buffer.stride = indexed ? 16u : 0u; + buffer.num_records = indexed ? desc->SizeInBytes / 16u : desc->SizeInBytes; buffer.format = leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT); - buffer.oob_select = leonida::gfx10::OobSelect::raw; + buffer.oob_select = indexed ? leonida::gfx10::OobSelect::structured_with_offset : leonida::gfx10::OobSelect::raw; buffer.address = vsharp_address(buffer.address, desc->SizeInBytes); const leonida::gfx10::BufferWords words = leonida::gfx10::encode(buffer); std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); @@ -7240,7 +8187,7 @@ class Device final return; } } - write_image_descriptor(*r, view, destination, false); + write_image_descriptor(*r, view, destination, ImageViewUse::sampled); } // An unordered-access view of a buffer is a V# in the slot (docs section 3.4): the shader loads those four dwords @@ -7342,60 +8289,99 @@ class Device final if (!destination.ptr) return; std::memset(reinterpret_cast(destination.ptr), 0, kDescriptorSize); const Resource* r = Resource::from(resource); - if (!r) { + if (!r || !r->belongs_to(state_)) { if (resource) stub("ID3D12Device::CreateUnorderedAccessView(resource from another device)"); return; } + if (r->storage_image()) r = r->storage_image(); if (!r->image()) return write_buffer_uav(resource, counter, desc, destination); if (counter) { log_once("unordered-access view of a texture with a counter resource; dimension", int(r->desc().Dimension)); return; } - if (!(r->desc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { + const bool depth_uav = r->depth_stencil_uav(0) != nullptr; + if (!depth_uav && !(r->desc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { log_once("unordered-access view of a texture created without ALLOW_UNORDERED_ACCESS; flags", int(r->desc().Flags)); return; } TextureView view{}; view.mip_count = 1; + namespace g = leonida::gfx10; if (!desc) { - const bool array = r->desc().DepthOrArraySize > 1; - if (r->desc().Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D && !array) { - view.type = leonida::gfx10::ImageType::image_1d; - view.layer_count = 1; - } else if (array) - view.type = leonida::gfx10::ImageType::image_2d_array; + const auto& shape = r->desc(); + if (shape.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D) + view.type = g::ImageType::image_3d; + else if (shape.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D) { + view.type = shape.DepthOrArraySize > 1 ? g::ImageType::image_1d_array : g::ImageType::image_1d; + if (view.type == g::ImageType::image_1d) view.layer_count = 1; + } else if (shape.DepthOrArraySize > 1) + view.type = g::ImageType::image_2d_array; } else { view.format = desc->Format; switch (desc->ViewDimension) { case D3D12_UAV_DIMENSION_TEXTURE1D: - view.type = leonida::gfx10::ImageType::image_1d; + view.type = g::ImageType::image_1d; view.first_mip = desc->Texture1D.MipSlice; view.layer_count = 1; break; + case D3D12_UAV_DIMENSION_TEXTURE1DARRAY: + view.type = g::ImageType::image_1d_array; + view.first_mip = desc->Texture1DArray.MipSlice; + view.first_layer = desc->Texture1DArray.FirstArraySlice; + view.layer_count = desc->Texture1DArray.ArraySize; + break; case D3D12_UAV_DIMENSION_TEXTURE2D: view.first_mip = desc->Texture2D.MipSlice; view.layer_count = 1; view.plane = desc->Texture2D.PlaneSlice; break; case D3D12_UAV_DIMENSION_TEXTURE2DARRAY: - view.type = leonida::gfx10::ImageType::image_2d_array; + view.type = g::ImageType::image_2d_array; view.first_mip = desc->Texture2DArray.MipSlice; view.first_layer = desc->Texture2DArray.FirstArraySlice; view.layer_count = desc->Texture2DArray.ArraySize; view.plane = desc->Texture2DArray.PlaneSlice; break; + case D3D12_UAV_DIMENSION_TEXTURE3D: + view.type = g::ImageType::image_3d; + view.first_mip = desc->Texture3D.MipSlice; + view.first_layer = desc->Texture3D.FirstWSlice; + view.layer_count = desc->Texture3D.WSize; + break; default: log_once("unordered-access view dimension not supported:", desc->ViewDimension); return; } } + if (depth_uav) { + const UINT layers = r->desc().DepthOrArraySize; + if (!desc || !(desc->ViewDimension == D3D12_UAV_DIMENSION_TEXTURE2DARRAY || + (desc->ViewDimension == D3D12_UAV_DIMENSION_TEXTURE2D && layers == 1)) || + view.first_mip || !view.layer_count || view.first_layer >= layers || + (view.layer_count != UINT_MAX && view.layer_count > layers - view.first_layer)) { + log_once("Xbox depth-stencil UAV requires a valid mip-zero 2D or array view; dimension", + desc ? int(desc->ViewDimension) : 0); + return; + } + const Resource* storage = r->depth_stencil_uav(view.plane); + const bool raw_narrow = storage && r->desc().Format == xbox_d16s8 && view.plane == 0 && + (view.format == DXGI_FORMAT_R16_UINT || + (storage->desc().Format == DXGI_FORMAT_R16_TYPELESS && view.format == DXGI_FORMAT_R16_UNORM)); + if (!storage || (!raw_narrow && view.format != storage->desc().Format)) { + log_once("unsupported Xbox depth-stencil UAV plane or format; format", int(view.format)); + return; + } + view.plane = 0; // The chosen shadow is a single-plane colour image with the same array layers. + write_image_descriptor(*storage, view, destination, ImageViewUse::depth_stencil_uav); + return; + } // B8G8R8X8 has no typed UAV, so no format of its family gives an unordered-access view. if (alpha_unused(r->desc().Format) || alpha_unused(view.format)) { log_once("unordered-access view of a B8G8R8X8 format; format", int(view.format)); return; } - write_image_descriptor(*r, view, destination, true); + write_image_descriptor(*r, view, destination, ImageViewUse::storage); state_.context->note_shader_image(r->id()); } @@ -7646,15 +8632,23 @@ class Device final if (texture_mip_region(*desc)) return d3d12_trace::result(method, E_INVALIDARG); // A count with a null array is no list (as on the PC runtime). The layer reports relaxed format casting, so // a real list is passed through; only buffers are refused. - const D3D12_RESOURCE_DESC base = resource_desc(*desc); + D3D12_RESOURCE_DESC base = resource_desc(*desc); if (const char* why = barrier_layout_refusal(base, layout)) { log_once((std::string(method) + " refused (" + why + "), layout").c_str(), int(layout)); return d3d12_trace::result(method, E_INVALIDARG); } + // The Xbox slot-127 bridge forwards the logical texture to Device10. Validate its layout above, + // then allocate the depth attachment and enable the typed storage planes before returning it. + std::optional storage_heap_flags; + if (xbox_depth_uav(base)) { + storage_heap_flags = heap_flags & D3D12_HEAP_FLAG_ALLOW_SHADER_ATOMICS; + heap_flags &= ~*storage_heap_flags; + base.Flags &= ~D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + } // D3D12_BARRIER_LAYOUT has no acceleration-structure value; an AS buffer's state comes through the // legacy CreateCommittedResource path. Buffers here start COMMON, as before. return create_committed_validated(method, heap, heap_flags, &base, D3D12_RESOURCE_STATE_COMMON, clear, - castable_count, castable, riid, out); + castable_count, castable, riid, out, storage_heap_flags); } // Device9. The creator ID only groups queues for tools; one creator is as good as another here. @@ -7797,7 +8791,7 @@ class Device final } HRESULT create_at_host_address(void* address, const D3D12_RESOURCE_DESC& desc, std::uint32_t layout, REFIID riid, - void** out) { + void** out, const D3D12_CLEAR_VALUE* clear) { constexpr auto method = "Xbox CreatePlacedResourceX (device slot 133)"; if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) { // A texture is not placed on the title's pages yet: it gets an ordinary committed DEFAULT texture of the @@ -7815,11 +8809,13 @@ class Device final // uses it moves it to that command's layout (vulkan_replay.h, initialize), as for every texture here. const D3D12_HEAP_PROPERTIES fallback{D3D12_HEAP_TYPE_DEFAULT}; const D3D12_RESOURCE_STATES initial = state_for_barrier_layout(layout); - HRESULT hr = create_committed_validated(nullptr, &fallback, D3D12_HEAP_FLAG_NONE, &desc, initial, nullptr, - 0, nullptr, riid, out); + const bool defer = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && + !(desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL); + HRESULT hr = create_committed_validated(nullptr, &fallback, D3D12_HEAP_FLAG_NONE, &desc, initial, clear, + 0, nullptr, riid, out, std::nullopt, defer); if (FAILED(hr) && initial != D3D12_RESOURCE_STATE_COMMON) hr = create_committed_validated(nullptr, &fallback, D3D12_HEAP_FLAG_NONE, &desc, - D3D12_RESOURCE_STATE_COMMON, nullptr, 0, nullptr, riid, out); + D3D12_RESOURCE_STATE_COMMON, clear, 0, nullptr, riid, out, std::nullopt, defer); if (SUCCEEDED(hr) && out && *out) { // The console answers the texture's GetGPUVirtualAddress with the title's address; without it a // title that clears the texture through that pointer writes at address 0 (XCL measured this on a @@ -7865,7 +8861,8 @@ class Device final int(shadow)); const D3D12_HEAP_PROPERTIES fallback{D3D12_HEAP_TYPE_DEFAULT}; return d3d12_trace::result(method, create_committed(&fallback, D3D12_HEAP_FLAG_NONE, &desc, - D3D12_RESOURCE_STATE_COMMON, 0, nullptr, riid, out)); + D3D12_RESOURCE_STATE_COMMON, 0, nullptr, riid, out, + std::nullopt)); } return d3d12_trace::result(method, hand_out(resource, riid, out)); } @@ -8167,7 +9164,7 @@ class Device final : D3D12_TEXTURE_DATA_PITCH_ALIGNMENT)); offset = align(offset, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT); DXGI_FORMAT footprint_format = desc->Format; - if (planes == 2) footprint_format = plane ? DXGI_FORMAT_R8_TYPELESS : DXGI_FORMAT_R32_TYPELESS; + if (planes == 2) footprint_format = plane ? DXGI_FORMAT_R8_TYPELESS : (desc->Format==xbox_d16s8?DXGI_FORMAT_R16_TYPELESS:DXGI_FORMAT_R32_TYPELESS); const UINT slices = std::max(1u, depth >> (mip & 31)); if (layouts) layouts[i] = {base + offset, @@ -8497,6 +9494,9 @@ class Device final auto* info = static_cast(data); // Plane count describes the DXGI layout even when the backend cannot create the texture. switch (info->Format) { + case xbox_d16s8: + case xbox_d16_plane: + case xbox_s8_plane: case DXGI_FORMAT_R32G8X24_TYPELESS: case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS: @@ -8534,7 +9534,7 @@ class Device final // formats P208/V208/V408 (130-132), and from 192 up; 189-191 are the sampler-feedback formats and // A4B4G4R4. UNKNOWN is a buffer format (raw and structured buffers). const UINT format_value = static_cast(fs->Format); - if (format_value > static_cast(DXGI_FORMAT_B4G4R4A4_UNORM) && + if (format_value > static_cast(DXGI_FORMAT_B4G4R4A4_UNORM) && !(format_value>=118 && format_value<=120) && (format_value < 189 || format_value > 191)) return d3d12_trace::result(method, E_FAIL); if (fs->Format == DXGI_FORMAT_UNKNOWN) { @@ -8545,14 +9545,15 @@ class Device final // R24G8/R32G8X24 and D24S8/D32S8 textures) have no image of their own, so the lookups below find nothing. // The host reports them as sampled 2D and cube textures with mips, the depth plane also filtered and // compared. Left out, as for the depth formats themselves: 1D, and multisample loads. - const bool depth_plane = fs->Format == DXGI_FORMAT_R24_UNORM_X8_TYPELESS || + const bool depth_plane = fs->Format == xbox_d16_plane || fs->Format == DXGI_FORMAT_R24_UNORM_X8_TYPELESS || fs->Format == DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS; - if (depth_plane || fs->Format == DXGI_FORMAT_X24_TYPELESS_G8_UINT || + if (depth_plane || fs->Format == xbox_s8_plane || fs->Format == DXGI_FORMAT_X24_TYPELESS_G8_UINT || fs->Format == DXGI_FORMAT_X32_TYPELESS_G8X24_UINT) { const bool d24 = fs->Format == DXGI_FORMAT_R24_UNORM_X8_TYPELESS || fs->Format == DXGI_FORMAT_X24_TYPELESS_G8_UINT; VkFormat family = vulkan_format(d24 ? DXGI_FORMAT_D24_UNORM_S8_UINT : DXGI_FORMAT_D32_FLOAT_S8X24_UINT, true).format; + if(fs->Format==xbox_d16_plane || fs->Format==xbox_s8_plane)family=state_.depth_backing(VK_FORMAT_D16_UNORM_S8_UINT); if (family == VK_FORMAT_D24_UNORM_S8_UINT && !state_.depth_usable(family)) family = VK_FORMAT_D32_SFLOAT_S8_UINT; VkFormatProperties props{}; @@ -8573,6 +9574,7 @@ class Device final // Report what creation makes: a D24 texture on a GPU without Vulkan D24 (AMD) is a D32_SFLOAT_S8_UINT // image (texture_format), so its features are D32S8's. Asking D24 itself gave Support1 = 0 there, // although CreateCommittedResource(ALLOW_DEPTH_STENCIL) succeeds. + vk_fmt=state_.depth_backing(vk_fmt); if (vk_fmt == VK_FORMAT_D24_UNORM_S8_UINT && !state_.depth_usable(vk_fmt)) vk_fmt = VK_FORMAT_D32_SFLOAT_S8_UINT; if (vk_fmt == VK_FORMAT_UNDEFINED || !state_.format_properties) { @@ -8652,7 +9654,7 @@ class Device final } if (optimal & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) { s1 |= D3D12_FORMAT_SUPPORT1_RENDER_TARGET; - // A D3D12 multisample resolve needs the same image usages as texture_create_info(): colour + // A D3D12 multisample resolve needs the same image usages as TextureCreateInfo: colour // attachment plus transfer source/destination (and the ordinary sampled usage). VkImageFormatProperties image_properties{}; const VkImageUsageFlags usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | @@ -8670,6 +9672,8 @@ class Device final s1 |= D3D12_FORMAT_SUPPORT1_MULTISAMPLE_LOAD; } } + if(fs->Format==DXGI_FORMAT_B4G4R4A4_UNORM && !(optimal&VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) && + state_.color_attachment_usable(VK_FORMAT_R8G8B8A8_UNORM))s1|=D3D12_FORMAT_SUPPORT1_RENDER_TARGET; if (optimal & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT) { s1 |= D3D12_FORMAT_SUPPORT1_BLENDABLE; } @@ -8781,7 +9785,7 @@ class Device final // output untouched; a known format clears it before the sample count is checked. const UINT format_id = UINT(levels->Format); if (levels->Format == DXGI_FORMAT_R1_UNORM || - !(format_id <= DXGI_FORMAT_B4G4R4A4_UNORM || + !(format_id <= DXGI_FORMAT_B4G4R4A4_UNORM || (format_id>=118 && format_id<=120) || (format_id >= DXGI_FORMAT_SAMPLER_FEEDBACK_MIN_MIP_OPAQUE && format_id <= DXGI_FORMAT_A4B4G4R4_UNORM))) return d3d12_trace::result(method, E_FAIL); @@ -8963,6 +9967,10 @@ class Device final return value > UINT64_MAX - (to - 1) ? UINT64_MAX / to * to : (value + to - 1) / to * to; } + bool xbox_depth_uav(const D3D12_RESOURCE_DESC& desc) const { + return rt::d3d12_xs::depth_uav_description(desc) && rt::d3d12_xs::is_device_proxy(outer_); + } + // Lays `count` resources out one after another; `each` (optional) gets every resource's offset, size and // alignment. As on the PC runtime, the total is rounded up to the largest alignment (1 for no resources) and // saturates near 2^64 rather than wrapping. @@ -8972,7 +9980,13 @@ class Device final D3D12_RESOURCE_ALLOCATION_INFO total{0, 1}; bool failed = count && !descs; for (UINT i = 0; i < count; ++i) { - const D3D12_RESOURCE_ALLOCATION_INFO one = failed ? kInvalidAllocation : allocation(get(i)); + D3D12_RESOURCE_ALLOCATION_INFO one = kInvalidAllocation; + if (!failed) { + auto desc = get(i); + // The boot stack charges XMem for the guest placement; storage planes are private to Vulkan. + if (xbox_depth_uav(desc)) desc.Flags &= ~D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + one = allocation(desc); + } failed = failed || one.SizeInBytes == UINT64_MAX; if (failed) { if (each) each[i] = {UINT64_MAX, one.Alignment, UINT64_MAX}; @@ -8989,6 +10003,12 @@ class Device final // One resource's size and alignment, or kInvalidAllocation for a description D3D12 (or this device) rejects. D3D12_RESOURCE_ALLOCATION_INFO allocation(const D3D12_RESOURCE_DESC& desc) const { + if (xbox_depth_storage_desc(desc) && outer_ && rt::d3d12_xs::is_device_proxy(outer_)) { + const auto depth = allocation(depth_storage_part(desc, false)); + const auto colour = allocation(depth_storage_part(desc, true)); + if (depth.SizeInBytes == UINT64_MAX || colour.SizeInBytes == UINT64_MAX) return kInvalidAllocation; + return {std::max(depth.SizeInBytes, colour.SizeInBytes), std::max(depth.Alignment, colour.Alignment)}; + } constexpr UINT64 align_4k = D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT, align_64k = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT, align_msaa_64k = D3D12_SMALL_MSAA_RESOURCE_PLACEMENT_ALIGNMENT, @@ -9138,18 +10158,87 @@ class Device final return std::min(fallback, align_up(total, alignment)); } + enum class ImageViewUse { sampled, storage, depth_stencil_uav }; + // Writes the view's T# into the slot and makes sure set 0 and the hash table know it. A view that cannot be // shown leaves the slot a null descriptor. void write_image_descriptor(const Resource& resource, const TextureView& view, - D3D12_CPU_DESCRIPTOR_HANDLE destination, bool storage) { - leonida::gfx10::Image image{}; - if (!image_descriptor(resource, view, image)) return; - const leonida::gfx10::ImageWords words = leonida::gfx10::encode(image); - const bool registered = state_.bind_image(words, image, resource.image(), resource.format(), - resource.aspects(), storage, resource.has_view_format_list(), - resource.uint_backed()); - if (registered && resource.sparse_image()) state_.context->note_shader_image(resource.id()); - if (leonida::gfx10::multisampled(image.type) && !registered) return; + D3D12_CPU_DESCRIPTOR_HANDLE destination, ImageViewUse use) { + const bool storage = use != ImageViewUse::sampled; + const bool storage_plane = use == ImageViewUse::depth_stencil_uav; + namespace g = leonida::gfx10; + g::Image image{}; + VkFormat view_format{}; + DeviceState::VolumeSlices slices{}; + if (!image_descriptor(resource, view, storage, image, view_format, slices)) { + return; + } + const bool sampled = view.type != g::ImageType::image_1d_array && + !(resource.desc().Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE); + const bool new_uav = storage && (view.type == g::ImageType::image_3d || view.type == g::ImageType::image_1d || + view.type == g::ImageType::image_1d_array); + const bool packed_storage = storage && resource.desc().Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP && resource.uint_backed(); + const VkFormat storage_format = storage && resource.uint_backed() ? resource.format() : view_format; + if (storage) { + if (!state_.storage_usable(storage_format)) { + log_once("texture view format does not support storage images:", storage_format); + return; + } + if (new_uav && state_.info.robust_image_access) { + if (sampled && !state_.sampled_usable(view_format)) { + log_once("texture view format does not support sampled access:", view_format); + return; + } + // All three dimensions use Unknown-format storage writes and can use Unknown-format reads + // (image_load glc, or any image_load on a 1D array). Check the actual storage view's format. + // Packed RGB9E5 only exposes formatted raw R32_UINT storage, so it does not need these bits. + if (!packed_storage) { + constexpr auto required = VK_FORMAT_FEATURE_2_STORAGE_READ_WITHOUT_FORMAT_BIT | + VK_FORMAT_FEATURE_2_STORAGE_WRITE_WITHOUT_FORMAT_BIT; + if ((state_.optimal_features(storage_format) & required) != required) { + log_once("texture view format lacks the required formatless storage image access:", storage_format); + return; + } + } + } + } + if (slices.count && !(state_.info.sliced_3d_uav && state_.info.robust_image_access)) { + log_once("partial Texture3D UAV requires imageSlicedViewOf3D and robustImageAccess; mip", view.first_mip); + return; + } + g::ImageWords words = g::encode(image); + if (storage && view.type == g::ImageType::image_3d) { + words[4] |= g::volume_uav_flag; + const UINT mip_depth = std::max(1u, image.depth >> image.first_mip); + words[7] = g::volume_uav_word(slices.first, slices.count ? slices.count : mip_depth); + } + if (new_uav && packed_storage) { + words[4] |= g::volume_uav_flag; + if (view.type != g::ImageType::image_3d) words[7] = g::volume_uav_word(0, 1); + words[7] |= g::packed_uav_flag; + log_once("packed RGB9E5 UAV: translated storage operations are not implemented; type", int(view.type)); + } + const VkFormat channels_format = resource.rgba4_render_backing() ? VK_FORMAT_A4R4G4B4_UNORM_PACK16 : + (resource.rgb96() ? rgb96_named_format(view_format) : view_format); + if (new_uav && !state_.info.robust_image_access) { + log_once("shader access to 1D and 3D UAVs requires robustImageAccess; type", int(view.type)); + } else { + const bool known_heap = state_.known_view_heap(destination.ptr); + if (!storage && resource.deferrable_sample() && state_.info.prepare_on_bind && known_heap && + !g::multisampled(image.type)) { + state_.remember_sample(words,{const_cast(&resource),image,view_format,channels_format}); + std::memcpy(reinterpret_cast(destination.ptr),words.data(),sizeof(words)); + return; + } + const auto bound = const_cast(resource).bound_image(); + if (!bound) { log_once("unable to make a placed shader image resident; format", int(resource.desc().Format)); return; } + const bool registered = state_.bind_image(words, image, bound, view_format, + channels_format, storage_format, resource.aspects(), + sampled, storage, slices); + if (registered && (resource.sparse_image() || storage_plane)) state_.context->note_shader_image(resource.id()); + if (!registered && (g::multisampled(image.type) || storage_plane)) return; + } + // The CPU UAV used by ClearUnorderedAccessView is independent of set 0. std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); } @@ -9158,10 +10247,29 @@ class Device final HRESULT create_committed_validated(const char* method, const D3D12_HEAP_PROPERTIES* heap, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, - UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out) { + UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out, + std::optional storage_heap_flags = std::nullopt, + bool defer_placed_memory = false) { const auto finish = [&](HRESULT hr) { return method ? d3d12_trace::result(method, hr) : hr; }; if (out) *out = nullptr; if (!heap || !desc) return finish(E_INVALIDARG); + if (xbox_depth_storage_desc(*desc) && outer_ && rt::d3d12_xs::is_device_proxy(outer_) && + heap->Type == D3D12_HEAP_TYPE_DEFAULT && (!castable_count || !castable)) { + const auto depth_desc = depth_storage_part(*desc, false), colour_desc = depth_storage_part(*desc, true); + const bool initial_uav = state == D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + ID3D12Resource *depth = nullptr, *colour = nullptr; + HRESULT hr = create_committed_validated(nullptr, heap, heap_flags, &depth_desc, + initial_uav ? D3D12_RESOURCE_STATE_COMMON : state, clear, 0, nullptr, IID_PPV_ARGS(&depth)); + if (FAILED(hr)) return finish(hr); + hr = create_committed_validated(nullptr, heap, heap_flags, &colour_desc, + initial_uav ? state : D3D12_RESOURCE_STATE_COMMON, nullptr, 0, nullptr, IID_PPV_ARGS(&colour)); + if (SUCCEEDED(hr)) { + Resource::from(depth)->adopt_depth_storage(Resource::from(colour)); + hr = out ? depth->QueryInterface(riid, out) : S_FALSE; + } + depth->Release(); + return finish(hr); + } if (const char* why = committed_resource_refusal(*heap, heap_flags, *desc, state, clear, acceleration_structures(), state_.uma)) { log_once((std::string(method ? method : "CreateCommittedResource") + " refused (" + why + "), dimension") @@ -9180,7 +10288,8 @@ class Device final int(desc->Dimension)); return finish(E_INVALIDARG); } - return finish(create_committed(heap, heap_flags, desc, state, castable_count, castable, riid, out)); + return finish(create_committed(heap, heap_flags, desc, state, castable_count, castable, riid, out, + storage_heap_flags, defer_placed_memory)); } // Shared by CreateCommittedResource, CreateCommittedResource3 and CreateReservedResource*. A castable-format list @@ -9189,7 +10298,8 @@ class Device final // runtime. HRESULT create_committed(const D3D12_HEAP_PROPERTIES* heap, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES initial_state, - UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out) { + UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out, + std::optional storage_heap_flags, bool defer_placed_memory = false) { if (out) *out = nullptr; if (!heap || !desc) return E_INVALIDARG; if (castable_count && castable && desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { @@ -9233,9 +10343,10 @@ class Device final hr = E_INVALIDARG; } else { std::vector cast_formats; - hr = castable_view_formats(format, desc->Format, castable_count, castable, cast_formats); - if (SUCCEEDED(hr)) hr = resource->create_texture(format, cast_formats); + hr = castable_view_formats(format, desc->Format, castable_count, castable, cast_formats, storage_heap_flags.has_value()); + if (SUCCEEDED(hr)) hr = resource->create_texture(format, cast_formats, defer_placed_memory); if (SUCCEEDED(hr)) resource->keep_castable_formats(castable_count, castable); + if (SUCCEEDED(hr) && storage_heap_flags) hr = resource->enable_depth_stencil_uav(*storage_heap_flags); } } if (FAILED(hr)) { @@ -9417,8 +10528,6 @@ class Device final const VkDevice dev = state_.info.device; const auto properties2 = reinterpret_cast( state_.info.get_instance_proc(state_.info.instance, "vkGetPhysicalDeviceProperties2")); - state_.format_properties2 = reinterpret_cast( - state_.info.get_instance_proc(state_.info.instance, "vkGetPhysicalDeviceFormatProperties2")); const auto to_image = reinterpret_cast(get_device(dev, "vkCopyMemoryToImageEXT")); const auto to_memory = reinterpret_cast(get_device(dev, "vkCopyImageToMemoryEXT")); const auto transition = @@ -9471,7 +10580,18 @@ class Device final std::vector queue_users_; std::vector compute_users_; std::vector copy_users_; + std::mutex verified_program_mutex_; + std::unordered_set verified_programs_; + std::mutex native_pipeline_mutex_; + std::unordered_map> native_pipelines_; DeviceState state_; + struct RawImage { + std::unique_ptr resource; + std::vector fingerprints; + }; + std::mutex raw_image_mutex_; + using RawKey = std::tuple; + std::map raw_images_; std::atomic removed_{false}; OwnedRuntime owned_; IUnknown* outer_ = nullptr; // the Xbox-ABI proxy, which owns a reference to this device @@ -9496,14 +10616,39 @@ std::shared_ptr tile_heap(ID3D12Heap* heap, c return object ? object->tiles(context, image, memory_types) : nullptr; } +XboxDepthStorage xbox_depth_storage(ID3D12Resource* resource) { + if (!resource || !depth_storage_count.load(std::memory_order_acquire)) return {}; + std::lock_guard lock(depth_storage_mutex); + const auto it = depth_storage_images.find(resource); + return it == depth_storage_images.end() ? XboxDepthStorage{} : it->second; +} + bool is_sparse_image(ID3D12Resource* resource) { const auto* object = Resource::from(resource); return object && object->sparse_image(); } +static HRESULT enable_depth_stencil_uav(ID3D12Resource* resource, D3D12_HEAP_FLAGS storage_heap_flags) { + Resource* r = Resource::from(resource); + return r ? r->enable_depth_stencil_uav(storage_heap_flags) : E_INVALIDARG; +} + +leonida::ResourceId uav_image_resource(ID3D12Resource* resource, std::uint64_t address) { + const Resource* r = Resource::from(resource); + if (!r || !r->depth_stencil_uav(0)) return resource_id(resource); + for (UINT plane = 0; plane < 2; ++plane) { + const Resource* storage = r->depth_stencil_uav(plane); + if (storage && storage->image_address() == address) return storage->id(); + } + return 0; +} + void set_device_outer(ID3D12Device* device, IUnknown* outer) { Device* d = Device::from(device); if (!d) return; + const auto& label_info=d->state().info; + leonida::label::completions().initialize(label_info.device,reinterpret_cast(label_info.get_instance_proc(label_info.instance,"vkGetDeviceProcAddr"))); + // A caller passes what create_device_proxy returned, which is the proxy's DXGI pointer when the title asked // for IDXGIDevice1: the device's outer identity is the proxy itself either way. if (void* proxy = rt::d3d12_xs::device_proxy_primary(outer)) outer = static_cast(proxy); @@ -9521,6 +10666,48 @@ void set_device_outer(ID3D12Device* device, IUnknown* outer) { // out this layer's adapter, the one create_dxgi_factory enumerates, so a title on the Vulkan device never gets // a host DXGI object from it. if (!rt::d3d12_xs::is_device_proxy(outer)) return; + rt::d3d12_xs::set_constant_view_provider(outer, [](ID3D12Device* real, const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc, + D3D12_CPU_DESCRIPTOR_HANDLE target) { + auto* device=Device::from(real); + if (!device) return false; + device->write_constant_buffer_view(desc,target,true); + return true; + }); + rt::d3d12_xs::set_raw_texture_view_provider(outer, [](ID3D12Device* real, const D3D12_RESOURCE_DESC& desc, + const D3D12_SHADER_RESOURCE_VIEW_DESC& view, std::uint64_t va, D3D12_CPU_DESCRIPTOR_HANDLE out) { + auto* device = Device::from(real); + try { + return device && device->raw_texture_view(desc, view, va, out); + } catch (const std::bad_alloc&) { + return false; + } + }); + rt::d3d12_xs::set_texture_lease_provider(outer, [](IUnknown* object, void* data, std::size_t bytes, UINT layout) { + if (auto* resource = Resource::from(object)) resource->use_texture_lease(data, bytes, layout); + }); + rt::d3d12_xs::set_descriptor_mapping_provider(outer, [](ID3D12DescriptorHeap* heap, SIZE_T start, SIZE_T bytes) { + const auto* object = DescriptorHeap::from(heap); + return object && object->owns_mapped_span(start, bytes); + }); + if(d->state().info.prepare_on_bind) { + rt::d3d12_xs::set_native_stream_factory(outer,[](ID3D12Device* real,const D3D12_PIPELINE_STATE_STREAM_DESC& desc,REFIID iid,void** out,std::unique_ptr record){ + return Device::from(real)->prepare_console_stream(desc,iid,out,std::move(record)); + }); + } + rt::d3d12_xs::set_device_native_graphics_factory(outer, [](ID3D12Device* real, const leonida::native_pso::GraphicsDesc& desc, + REFIID iid, void** out) { + return Device::from(real)->create_native_graphics(desc, iid, out); + }); + rt::d3d12_xs::set_depth_stencil_uav_provider(outer, &enable_depth_stencil_uav, + [](const D3D12_RESOURCE_DESC& native, std::uint32_t layout, const D3D12_CLEAR_VALUE* clear) { + auto logical = native; + logical.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + if (barrier_layout_refusal(logical, static_cast(layout))) return false; + D3D12_HEAP_PROPERTIES heap{}; + heap.Type = D3D12_HEAP_TYPE_DEFAULT; + return !committed_resource_refusal(heap, D3D12_HEAP_FLAG_NONE, native, D3D12_RESOURCE_STATE_COMMON, + clear, false, false); + }); rt::d3d12_xs::set_device_adapter_provider(outer, [](ID3D12Device* real, REFIID riid, void** out) { IDXGIFactory1* factory = nullptr; HRESULT hr = create_dxgi_factory(real, __uuidof(IDXGIFactory1), reinterpret_cast(&factory)); @@ -9541,13 +10728,13 @@ const RootArgumentLayout* root_signature_layout(ID3D12RootSignature* signature) } std::uintptr_t compute_pipeline_id(ID3D12PipelineState* pipeline) { - const PipelineState* p = PipelineState::from(pipeline); - return p && p->compute() ? p->id() : 0; + auto* p=PipelineState::from(pipeline); + return p && p->resolve_type(false) ? p->id() : 0; } std::uintptr_t graphics_pipeline_id(ID3D12PipelineState* pipeline) { - const PipelineState* p = PipelineState::from(pipeline); - return p && p->graphics() ? p->id() : 0; + auto* p=PipelineState::from(pipeline); + return p && p->resolve_type(true) ? p->id() : 0; } const std::vector* pipeline_subgroup_requests(ID3D12PipelineState* pipeline) { @@ -9568,7 +10755,7 @@ IUnknown* descriptor_heap_info(ID3D12DescriptorHeap* heap, D3D12_DESCRIPTOR_HEAP VkImage vulkan_image(ID3D12Resource* resource) { const Resource* r = Resource::from(resource); - return r ? r->image() : VK_NULL_HANDLE; + return r ? const_cast(r)->bound_image() : VK_NULL_HANDLE; } VkMemoryPropertyFlags vulkan_memory_flags(ID3D12Resource* resource) { @@ -9589,13 +10776,13 @@ const VulkanDeviceInfo* vulkan_device_info(ID3D12Device* device) { } HRESULT create_buffer_at_host_address(ID3D12Device* device, void* address, const D3D12_RESOURCE_DESC& desc, - std::uint32_t layout, REFIID riid, void** out) { + std::uint32_t layout, REFIID riid, void** out, const D3D12_CLEAR_VALUE* clear) { if (out) *out = nullptr; if (!device || !out) return E_POINTER; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); auto* d = Device::from(real ? real : device); if (!d) return E_NOTIMPL; - return d->create_at_host_address(address, desc, layout, riid, out); + return d->create_at_host_address(address, desc, layout, riid, out, clear); } bool device_supports_ray_tracing(ID3D12Device* device) { @@ -10234,10 +11421,24 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin // Subgroup size control: a pipeline stage asks for the size its shader was translated for (src/subgroup_size.h). leonida::query_subgroup_size_caps(vkGetPhysicalDeviceProperties2, info.physical, v13.subgroup_size_control, v13.compute_full_subgroups, info.subgroup); + const char* compile_mode = std::getenv("LEONIDA_PIPELINE_COMPILE"); + const auto mode = compile_mode ? std::string_view(compile_mode) : std::string_view{}; + v13.enable_pipeline_cache_control = mode == "cache-only" && v13.core && v13.pipeline_cache_control; + info.cold_graphics_compile = v13.enable_pipeline_cache_control; + info.prepare_on_bind = mode == "on-demand"; + info.first_use_backend_pipelines = info.prepare_on_bind || mode == "first-use"; + void* v13_chain = v13.enable(ext_chain); + // D3D-78 uses the core robustness and format-feature flags. Leave the Vulkan 1.2 extension path unchanged. + if (v13.core) { + VkPhysicalDeviceVulkan13Features supported{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; + VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &supported}; + vkGetPhysicalDeviceFeatures2(info.physical, &query); + info.robust_image_access = supported.robustImageAccess == VK_TRUE; + static_cast(v13_chain)->robustImageAccess = supported.robustImageAccess; + } // Translated vertex shaders read BaseVertex / BaseInstance (SPIR-V DrawParameters) to give v0 / v3 the // hardware's zero-based vertex and instance ids (docs/design.md, Inputs and outputs). - VkPhysicalDeviceVulkan11Features enable11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, - v13.enable(ext_chain)}; + VkPhysicalDeviceVulkan11Features enable11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, v13_chain}; enable11.shaderDrawParameters = chosen_draw_params ? VK_TRUE : VK_FALSE; if (!chosen_draw_params) std::fprintf(stderr, "[rt] d3d12: the GPU has no shaderDrawParameters\n"); VkPhysicalDeviceVulkan12Features enable12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &enable11}; @@ -10406,12 +11607,25 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin std::fprintf(stderr, "[rt] d3d12: no VK_EXT_host_image_copy; CPU texture copies use a staging submit\n"); } - // The pixel-shader extensions translated shaders can declare (VulkanDeviceInfo::fragment_shader_barycentric and - // the two after it). Each is queried, and enabled with its feature where the GPU has it. const auto has_device_extension = [&](const char* name) { return std::any_of(extensions.begin(), extensions.end(), [&](const auto& e) { return std::strcmp(e.extensionName, name) == 0; }); }; + const char* sliced_name = VK_EXT_IMAGE_SLICED_VIEW_OF_3D_EXTENSION_NAME; + VkPhysicalDeviceImageSlicedViewOf3DFeaturesEXT sliced{ + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_SLICED_VIEW_OF_3D_FEATURES_EXT}; + if (info.robust_image_access && has_device_extension(sliced_name)) { + VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &sliced}; + vkGetPhysicalDeviceFeatures2(info.physical, &query); + info.sliced_3d_uav = sliced.imageSlicedViewOf3D == VK_TRUE; + if (info.sliced_3d_uav) { + sliced.pNext = *v13.next(); + *v13.next() = &sliced; + } + } + + // The pixel-shader extensions translated shaders can declare (VulkanDeviceInfo::fragment_shader_barycentric and + // the two after it). Each is queried, and enabled with its feature where the GPU has it. VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR barycentric{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR}; if (has_device_extension(VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME)) { @@ -10470,6 +11684,19 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin } #endif +#ifdef VK_KHR_MAINTENANCE_10_EXTENSION_NAME + VkPhysicalDeviceMaintenance10FeaturesKHR maintenance10{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_10_FEATURES_KHR}; + // Vulkan 1.3 makes the 64-bit optimal tiling format features used by this path core. + if (v13.core && has_device_extension(VK_KHR_MAINTENANCE_10_EXTENSION_NAME)) { + VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &maintenance10}; + vkGetPhysicalDeviceFeatures2(info.physical, &query); + info.maintenance10 = maintenance10.maintenance10 == VK_TRUE; + if (info.maintenance10) { + maintenance10.pNext = *v13.next(); + *v13.next() = &maintenance10; + } + } +#endif #ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME // VK_KHR_shader_fma: OpFmaKHR is a single-rounding multiply-add in SPIR-V (GLSL.std.450 Fma may round twice). // Translated shaders built with `rdna2spirv.py --fma khr` need it (index capability FMAKHR, feature @@ -10508,16 +11735,17 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin enable.depthClamp = chosen_features.depthClamp; enable.geometryShader = chosen_features.geometryShader; // translated geometry shaders (195 in the corpus) // What translated shaders declare (the index's `features`): 64-bit integers in most of the corpus (25,803 of - // 26,503 entries), doubles, 16-bit integers, clip and cull distances in a few vertex shaders, image stores - // without a format (StorageImageWriteWithoutFormat), gather offsets (ImageGatherExtended) and LOD-clamped samples - // (MinLod), and the layer or viewport a vertex shader writes (above, in Vulkan 1.2). Enabled where the GPU has - // them; without one, vkCreateShaderModule reports the capability (VUID-...-pCode-08740). + // 26,503 entries), doubles, 16-bit integers, clip and cull distances in a few vertex shaders, formatless image + // reads and writes, gather offsets (ImageGatherExtended), LOD-clamped samples (MinLod), and the layer or viewport + // a vertex shader writes (above, in Vulkan 1.2). Enabled where the GPU has them; without one, vkCreateShaderModule + // reports the capability (VUID-...-pCode-08740). enable.shaderInt64 = chosen_features.shaderInt64; enable.shaderFloat64 = chosen_features.shaderFloat64; enable.shaderInt16 = chosen_features.shaderInt16; enable.shaderClipDistance = chosen_features.shaderClipDistance; enable.shaderCullDistance = chosen_features.shaderCullDistance; enable.shaderStorageImageWriteWithoutFormat = chosen_features.shaderStorageImageWriteWithoutFormat; + enable.shaderStorageImageExtendedFormats = chosen_features.shaderStorageImageExtendedFormats; enable.shaderStorageImageReadWithoutFormat = chosen_features.shaderStorageImageReadWithoutFormat; enable.shaderImageGatherExtended = chosen_features.shaderImageGatherExtended; enable.shaderResourceMinLod = chosen_features.shaderResourceMinLod; @@ -10614,6 +11842,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin if (info.vertex_attribute_divisor) device_extensions.push_back(divisor_extension); if (info.conditional_rendering) device_extensions.push_back(conditional_extension); if (info.host_image_copy) device_extensions.push_back(host_image_copy_name); + if (info.sliced_3d_uav) device_extensions.push_back(sliced_name); if (info.fragment_shader_barycentric) device_extensions.push_back(VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME); if (info.fragment_shader_interlock) device_extensions.push_back(VK_EXT_FRAGMENT_SHADER_INTERLOCK_EXTENSION_NAME); @@ -10623,6 +11852,9 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin #ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME if (info.a8_render_target) device_extensions.push_back(VK_KHR_MAINTENANCE_5_EXTENSION_NAME); #endif +#ifdef VK_KHR_MAINTENANCE_10_EXTENSION_NAME + if (info.maintenance10) device_extensions.push_back(VK_KHR_MAINTENANCE_10_EXTENSION_NAME); +#endif #ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME if (info.shader_fma) device_extensions.push_back(VK_KHR_SHADER_FMA_EXTENSION_NAME); #endif diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 9bfa5ea7f4..02a03b07b7 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -27,7 +27,13 @@ #include "../src/title_va_alias.h" #include "title_window.h" #include "d3d12_xs_device.h" +#ifdef LEONIDA_VULKAN_DEVICE +#include "present_window.h" +#endif +#include "d3d12_xs_placed_depth.h" #include "d3d12_trace.h" +#include "../src/native_pso.h" +#include "d3d12_xs_pso_stream.h" #include "d3d12_xs_alloc_size.h" #include "d3d12_xs_desc_clean.h" #include "../src/frame_pacer.h" @@ -67,8 +73,7 @@ namespace rt::d3d12_xs { namespace { -// The retail title calls device slots well past ID3D12Device14 (slot 133 at least); every slot past the PC device's -// vtable goes through the generic thunk and is refused with E_NOTIMPL, so the table must outlast the highest one. +// The retail title calls beyond ID3D12Device14. Cover the measured slots and refuse unknown ones in the thunk. constexpr unsigned kMaxSlots = 192; static_assert(kMaxSlots > 133, "the proxy table must cover the slots the retail title calls (up to 133)"); static_assert(kMaxSlots > 83, "the proxy table must cover ID3D12Device14 (83 slots)"); @@ -99,7 +104,16 @@ struct DeviceProxy { // The device's IDXGIDevice1 (see "IDXGIDevice1 on the device" below): a title's IDXGIDevice1* points here. void** dxgi_vtable; DxgiAdapterProvider adapter_provider; + DescriptorMappingProvider descriptor_mapping = nullptr; + NativeGraphicsFactory native_graphics = nullptr; + NativeStreamFactory prepare_stream = nullptr; + TextureLeaseProvider texture_lease_provider = nullptr; + RawTextureViewProvider raw_texture_view = nullptr; + ConsoleConstantView constant_view = nullptr; ResourceByVaProvider resource_provider; // slot 70: a buffer by console VA; null leaves slot 70 on the null view + DepthStencilUavProvider depth_stencil_uav_provider = nullptr; + ValidateDepthPlacement validate_depth_placement = nullptr; + PlacedDepthTextures placed_depth_textures; std::atomic gpu_thread_priority; std::atomic max_frame_latency; // The first-frame subset of SetFrameIntervalX/ScheduleFrameEventX/WaitFrameEventX. Tokens were never measured; @@ -108,6 +122,8 @@ struct DeviceProxy { std::atomic frame_interval_us{0}; std::atomic frame_latency{1}; std::atomic frame_event_scheduled{false}; + std::atomic frame_event_offset_us{0}; + std::mutex presentation_mutex; std::shared_ptr frame_tokens = std::make_shared(); }; @@ -135,6 +151,8 @@ struct DescriptorRange { SIZE_T custom_start; SIZE_T custom_end; // exclusive SIZE_T real_start; + SIZE_T stride; + bool mapped; const DeviceProxy* device; const HeapProxy* heap; }; @@ -162,12 +180,13 @@ DescriptorHeapBackingFree g_heap_free = nullptr; bool g_heap_alloc_explicit = false; bool register_descriptor_range(const DeviceProxy* device, const HeapProxy* heap, SIZE_T custom_start, - SIZE_T byte_size, SIZE_T real_start) { + SIZE_T byte_size, SIZE_T real_start, SIZE_T stride) { if (custom_start == 0 || byte_size == 0 || custom_start > (std::numeric_limits::max)() - byte_size) return false; + const bool mapped = device->descriptor_mapping && device->descriptor_mapping(heap->real, real_start, byte_size); try { std::lock_guard lock(descriptor_range_mutex()); - descriptor_ranges().push_back({custom_start, custom_start + byte_size, real_start, device, heap}); + descriptor_ranges().push_back({custom_start, custom_start + byte_size, real_start, stride, mapped, device, heap}); g_custom_range_count.store(descriptor_ranges().size(), std::memory_order_release); return true; } catch (const std::bad_alloc&) { @@ -236,17 +255,58 @@ bool local_accessible(std::uint64_t address, std::uint64_t bytes, bool write) { void local_write_through(const DeviceProxy* device, D3D12_CPU_DESCRIPTOR_HANDLE custom, SIZE_T count) { if (!local_desc_mirror() || !custom.ptr || !count) return; - const D3D12_CPU_DESCRIPTOR_HANDLE real = translate_cpu_handle(device, custom); - if (real.ptr == custom.ptr) return; - if (!local_accessible(real.ptr, count * kLocalDescriptorBytes, false) || - !local_accessible(custom.ptr, count * kLocalDescriptorBytes, true)) + if (!g_custom_range_count.load(std::memory_order_acquire)) return; + std::lock_guard lock(descriptor_range_mutex()); + const auto& ranges = descriptor_ranges(); + for (auto it = ranges.rbegin(); it != ranges.rend(); ++it) { + if (it->device != device || custom.ptr < it->custom_start || custom.ptr >= it->custom_end) continue; + const SIZE_T offset = custom.ptr - it->custom_start; + if (!it->stride || offset % it->stride || count > (it->custom_end - custom.ptr) / it->stride) return; + const SIZE_T bytes = count * it->stride; + if (offset > (std::numeric_limits::max)() - it->real_start) return; + const SIZE_T real = it->real_start + offset; + // On Wine, VirtualQuery can report a live vkMapMemory span as MEM_FREE. + if (real == custom.ptr || (!it->mapped && !local_accessible(real, bytes, false)) || + !local_accessible(custom.ptr, bytes, true)) return; + std::memcpy(reinterpret_cast(custom.ptr), reinterpret_cast(real), bytes); + static std::atomic said{false}; + if (!said.exchange(true)) + std::fprintf(stderr, "[rt] d3d12_xs: local: descriptors written for a title-backed heap are also stored at the " + "title's address\n"); return; - std::memcpy(reinterpret_cast(custom.ptr), reinterpret_cast(real.ptr), - count * kLocalDescriptorBytes); - static std::atomic said{false}; - if (!said.exchange(true)) - std::fprintf(stderr, "[rt] d3d12_xs: local: descriptors written for a title-backed heap are also stored at the " - "title's address\n"); + } +} + +// Caller holds descriptor_range_mutex, keeping the backing alive for the complete copy. +std::uint64_t copy_title_slots(std::uint8_t* dest, SIZE_T source, SIZE_T bytes) { + const SIZE_T slots = bytes / kLocalDescriptorBytes; + if (!local_accessible(source, bytes, false)) return 0; + std::uint64_t copied = 0; + for (SIZE_T i = 0; i < slots; ++i) { + const SIZE_T at = i * kLocalDescriptorBytes; + const auto* from = reinterpret_cast(source + at); + if (!(from[0] | from[1] | from[2] | from[3])) continue; // keep slots populated only in the real heap + std::memcpy(dest + at, from, kLocalDescriptorBytes); + ++copied; + } + return copied; +} + +// The queue already bounds this scan by the root signature and real heap. Resolve the CPU address again at +// submission so a list can be recorded once and see successive writes to its title-backed descriptors. +std::uint64_t pull_title_descriptors(void*, std::uint8_t* real, std::size_t bytes) { + if (!local_desc_mirror() || !bytes || !g_custom_range_count.load(std::memory_order_acquire)) return 0; + const auto addr = reinterpret_cast(real); + std::lock_guard lock(descriptor_range_mutex()); + for (const DescriptorRange& range : descriptor_ranges()) { + const SIZE_T size = range.custom_end - range.custom_start; + if (addr < range.real_start || addr - range.real_start >= size) continue; + const SIZE_T offset = addr - range.real_start; + if (offset % kLocalDescriptorBytes) return 0; + // real is the queue's live vkMapMemory destination. Wine can report it as free to VirtualQuery. + return copy_title_slots(real, range.custom_start + offset, std::min(bytes, size - offset)); + } + return 0; } D3D12_GPU_DESCRIPTOR_HANDLE local_real_gpu_start(const HeapProxy* heap); @@ -261,17 +321,10 @@ void local_mirror_table(const DeviceProxy* device, std::uint64_t gpu_handle) { if (!gpu_start || gpu_handle < gpu_start || gpu_handle >= gpu_start + bytes) continue; const std::uint64_t offset = (gpu_handle - gpu_start) / kLocalDescriptorBytes * kLocalDescriptorBytes; const std::uint64_t slots = (std::min)(kLocalMirrorSlots, (bytes - offset) / kLocalDescriptorBytes); - if (!local_accessible(range.custom_start + offset, slots * kLocalDescriptorBytes, false) || - !local_accessible(range.real_start + offset, slots * kLocalDescriptorBytes, true)) - return; - std::uint64_t copied = 0; - for (std::uint64_t i = 0; i < slots; ++i) { - const auto* from = reinterpret_cast(range.custom_start + offset + i * kLocalDescriptorBytes); - if (!(from[0] | from[1] | from[2] | from[3])) continue; // nothing the title wrote: keep the real slot - std::memcpy(reinterpret_cast(range.real_start + offset + i * kLocalDescriptorBytes), from, - kLocalDescriptorBytes); - ++copied; - } + const SIZE_T copy_bytes = slots * kLocalDescriptorBytes; + if (!local_accessible(range.real_start + offset, copy_bytes, true)) return; + const auto copied = copy_title_slots(reinterpret_cast(range.real_start + offset), + range.custom_start + offset, copy_bytes); static std::atomic said{0}; if (said.fetch_add(1) < 4) std::fprintf(stderr, "[rt] d3d12_xs: local: table at heap offset 0x%llx: %llu of %llu slots taken from the " @@ -350,6 +403,7 @@ const char* slot_name(unsigned slot) { case 48: return "Xbox CreateCommandQueueX (32-byte desc) -> queue proxy"; case 50: return "EnqueueMakeResident (proxies unwrapped)"; case 56: return "GetResourceAllocationInfo1 (C or PC form)"; + case 57: return "Xbox native graphics pipeline / PC lifetime tracker"; case 61: return "Xbox CreateSamplerX -> PC CreateSampler"; case 62: return "Xbox CreateComputePipelineState"; case 67: return "Xbox DeserializeComputePipelineStateX"; @@ -828,7 +882,7 @@ void** get_heap_vtable() { HRESULT create_heap_proxy(ID3D12DescriptorHeap* real, DeviceProxy* device, REFIID riid, void** out, SIZE_T custom_cpu_start = 0, SIZE_T custom_byte_size = 0, SIZE_T real_cpu_start = 0, - DescriptorHeapBackingFree custom_free = nullptr) { + DescriptorHeapBackingFree custom_free = nullptr, SIZE_T stride = 0) { if (!real || !device) return E_POINTER; if (!out) return E_POINTER; *out = nullptr; @@ -847,7 +901,7 @@ HRESULT create_heap_proxy(ID3D12DescriptorHeap* real, DeviceProxy* device, REFII proxy_add_ref(device); // the heap keeps its Xbox-ABI device alive for GetDevice if (custom_cpu_start != 0 && - !register_descriptor_range(device, proxy, custom_cpu_start, custom_byte_size, real_cpu_start)) { + !register_descriptor_range(device, proxy, custom_cpu_start, custom_byte_size, real_cpu_start, stride)) { delete proxy; proxy_release(device); return E_OUTOFMEMORY; @@ -1388,9 +1442,7 @@ LONG CALLBACK table_overrun_handler(EXCEPTION_POINTERS* info) { #ifdef LEONIDA_VULKAN_DEVICE struct PresentState { - ~PresentState() { - if (window) DestroyWindow(window); // the presentation and its window die with the device proxy - } + rt::d3d12_xs::PresentWindow owner; HWND window = nullptr; std::unique_ptr xbox; bool tried = false; // creation is attempted once; a null xbox means this device cannot present @@ -1400,29 +1452,16 @@ void destroy_present_state(void* present_state) { delete static_cast(present_state); } -LRESULT CALLBACK present_window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { - return DefWindowProcW(window, message, wparam, lparam); -} - // Lazily builds the window, presenter and XboxPresentation a console PresentX needs, once per device. Returns the // state even when `xbox` stays null (no presentation support): the failure is logged once, not retried. PresentState* present_state_for(DeviceProxy* device) { + std::lock_guard lock(device->presentation_mutex); if (auto* state = static_cast(device->present_state)) return state; auto* state = new (std::nothrow) PresentState; if (!state) return nullptr; device->present_state = state; state->tried = true; - WNDCLASSW window_class{}; - window_class.lpfnWndProc = present_window_proc; - window_class.hInstance = GetModuleHandleW(nullptr); - window_class.lpszClassName = L"LeonidaPresentX"; - if (!RegisterClassW(&window_class) && GetLastError() != ERROR_CLASS_ALREADY_EXISTS) { - std::fprintf(stderr, "[rt] d3d12_xs: PresentX window class failed (error %lu)\n", GetLastError()); - return state; - } - state->window = CreateWindowExW(0, window_class.lpszClassName, L"Leonida", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, - CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, nullptr, nullptr, - window_class.hInstance, nullptr); + state->window = state->owner.create(); if (!state->window) { std::fprintf(stderr, "[rt] d3d12_xs: PresentX window failed (error %lu)\n", GetLastError()); return state; @@ -1440,7 +1479,7 @@ PresentState* present_state_for(DeviceProxy* device) { } } else { target = state->window; - ShowWindow(target, SW_SHOWNOACTIVATE); + ShowWindowAsync(target, SW_SHOWNOACTIVATE); } auto presenter = rt::d3d12::create_window_presenter(device->real, target); if (!presenter) { @@ -1449,9 +1488,29 @@ PresentState* present_state_for(DeviceProxy* device) { } // The device's token source: the title takes its frame tokens from device slot 80 (#7685). state->xbox = std::make_unique(std::move(presenter), nullptr, device->frame_tokens); + // The title registers its interval and origin event before the first PresentX builds this. + if (const std::uint32_t interval = device->frame_interval_us.load(std::memory_order_relaxed); interval && std::getenv("LEONIDA_FRAME_PACING")) { + const HRESULT set = state->xbox->SetFrameIntervalX(nullptr, interval, + device->frame_latency.load(std::memory_order_relaxed), 0); + const HRESULT armed = device->frame_event_scheduled.load(std::memory_order_relaxed) + ? state->xbox->ScheduleFrameEventX( + rt::d3d12::xbox_frame_event_origin, + device->frame_event_offset_us.load(std::memory_order_relaxed), 0) + : S_FALSE; + std::fprintf(stderr, "[rt] d3d12_xs: frame interval %u us replayed (0x%08lx), origin event (0x%08lx)\n", + interval, static_cast(set), static_cast(armed)); + } std::fprintf(stderr, "[rt] d3d12_xs: PresentX ready (window %p)\n", static_cast(state->window)); return state; } +rt::d3d12::XboxPresentation* device_presentation(DeviceProxy* device) { + static const bool enabled=[] {const auto* p=std::getenv("LEONIDA_FRAME_PACING");return p && *p=='1';}(); + if(!enabled)return nullptr; + std::lock_guard lock(device->presentation_mutex); + const auto* state=static_cast(device->present_state); + return state ? state->xbox.get() : nullptr; +} + std::uint64_t queue_present_x(ChildProxy* self, std::uint64_t plane_count, std::uint64_t planes, std::uint64_t params) { @@ -2118,6 +2177,18 @@ std::uint64_t WINAPI list_slot(ListProxy* self, std::uint64_t a1, std::uint64_t note_list_slot(Slot, a1, a2, a3, a4, self->device->console_layout.load(std::memory_order_relaxed)); constexpr unsigned pc = console_to_pc_list_slot(Slot); if constexpr (pc == kListNotForwarded) { +#ifdef LEONIDA_VULKAN_DEVICE + if constexpr (Slot == 71 || Slot == 72) { + if (leonida::label::enabled()) { + const unsigned width = Slot == 71 ? 4u : 8u; + const unsigned clock = Slot == 72 ? ((a4 & 1) ? 1u : ((a4 & 2) ? 2u : 0u)) : 0u; + auto target = leonida::label::memory().capture(a1, width); + if (target.owner.lock()) + rt::d3d12::record_gpu_label(reinterpret_cast(self->real), + {std::move(target), a2, clock}); + } + } +#endif if constexpr (Slot == kConsoleAllocateUpload) { return upload_alloc(self->device, a1, a2); // (size, alignment); the comment at UploadChunk } @@ -2414,20 +2485,26 @@ HRESULT proxy_create_command_queue_xbox(DeviceProxy* self, const std::uint32_t* // 60 Hz), and latency is the allowed frames in flight. S_OK even for 0: a boot must not abort here, and nothing paces. HRESULT proxy_set_frame_interval_x(DeviceProxy* self, std::uint64_t output, std::uint64_t interval_us, std::uint64_t latency, std::uint64_t flags) { - (void)output; - (void)flags; self->frame_interval_us.store(static_cast(interval_us), std::memory_order_relaxed); self->frame_latency.store(static_cast(latency ? latency : 1), std::memory_order_relaxed); +#ifdef LEONIDA_VULKAN_DEVICE + if (auto* presentation = device_presentation(self)) + return presentation->SetFrameIntervalX(reinterpret_cast(output), static_cast(interval_us), + static_cast(latency), static_cast(flags)); +#endif return S_OK; } // Xbox device slot 79 (public HLE): ScheduleFrameEventX(event, offset_us, pEvent, flags); our pacer has only the origin. HRESULT proxy_schedule_frame_event_x(DeviceProxy* self, std::uint64_t event, std::uint64_t offset_us, std::uint64_t flags) { - (void)event; - (void)offset_us; - (void)flags; + self->frame_event_offset_us.store(static_cast(offset_us), std::memory_order_relaxed); self->frame_event_scheduled.store(true, std::memory_order_relaxed); +#ifdef LEONIDA_VULKAN_DEVICE + if (auto* presentation = device_presentation(self)) + return presentation->ScheduleFrameEventX(static_cast(event), static_cast(offset_us), + static_cast(flags)); +#endif return S_OK; } @@ -2436,12 +2513,14 @@ HRESULT proxy_schedule_frame_event_x(DeviceProxy* self, std::uint64_t event, std // a zero wait cannot stall the title. A null token pointer is E_POINTER, as a _Out_ parameter. HRESULT proxy_wait_frame_event_x(DeviceProxy* self, std::uint64_t event, std::uint64_t timeout_ms, std::uint64_t flags, std::uint64_t token_word) { - (void)event; - (void)timeout_ms; - (void)flags; auto* token = reinterpret_cast(token_word); if (!token) return E_POINTER; - *token = self->frame_tokens->issue(); +#ifdef LEONIDA_VULKAN_DEVICE + if (auto* presentation = device_presentation(self)) + return presentation->WaitFrameEventX(static_cast(event), static_cast(timeout_ms), + static_cast(flags), token); +#endif + *token=self->frame_tokens->issue(); return S_OK; } @@ -2501,6 +2580,44 @@ struct RawSrvShape { D3D12_GPU_VIRTUAL_ADDRESS va; }; +static bool readable_range(const void* ptr, std::size_t bytes) { + if (!ptr || !bytes) return false; + const auto* p = static_cast(ptr); + std::size_t remaining = bytes; + while (remaining) { + MEMORY_BASIC_INFORMATION mbi{}; + if (!VirtualQuery(p, &mbi, sizeof(mbi)) || mbi.State != MEM_COMMIT) return false; + const DWORD protect = mbi.Protect & 0xffu; + if (protect == PAGE_NOACCESS || (mbi.Protect & PAGE_GUARD) || protect == PAGE_EXECUTE) return false; + const auto base = reinterpret_cast(mbi.BaseAddress); + const auto addr = reinterpret_cast(p); + const std::size_t avail = static_cast(base + mbi.RegionSize - addr); + if (avail >= remaining) return true; + remaining -= avail; + p += avail; + } + return true; +} + +HRESULT proxy_create_native_graphics(DeviceProxy* self, const void* raw, REFIID riid, void** out) { + namespace np = leonida::native_pso; + if (!out) return E_POINTER; + *out = nullptr; + if (!self->native_graphics) return E_NOTIMPL; + if (!readable_range(raw, sizeof(np::GraphicsDesc))) return E_INVALIDARG; + np::GraphicsDesc desc{}; + std::memcpy(&desc, raw, sizeof(desc)); + const auto readable_pair = [](const np::Pair& pair) { + const auto state = np::pair_state(pair); + return state == np::PairState::absent || + (state == np::PairState::present && readable_range(pair.data, static_cast(pair.size))); + }; + if (!readable_pair(desc.state_b)) return E_INVALIDARG; + for (const auto& stage : desc.stages) + if (!readable_pair(stage.records)) return E_INVALIDARG; + return self->native_graphics(self->real, desc, riid, out); +} + bool readable(std::uint64_t address, std::size_t bytes) { MEMORY_BASIC_INFORMATION info{}; if (!address || !VirtualQuery(reinterpret_cast(address), &info, sizeof(info))) return false; @@ -2553,10 +2670,16 @@ void proxy_create_srv_from_raw_x(DeviceProxy* self, std::uint64_t texture_words, ~LocalWriteThrough() { local_write_through(self, D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(custom)}, 1); } } local_write_back{self, destination}; // The console hands a CPU descriptor handle in the title's heap memory; #7021 translates it to the real heap's. - destination = translate_cpu_handle(self, D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(destination)}).ptr; + const D3D12_CPU_DESCRIPTOR_HANDLE title_slot{static_cast(destination)}; + destination = translate_cpu_handle(self, title_slot).ptr; RawSrvShape shape{}; const char* why = parse_raw_srv(texture_words, view_desc, shape); + if (shape.resource.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && self->raw_texture_view && shape.va && + self->raw_texture_view(self->real, shape.resource, shape.view, shape.va, {static_cast(destination)})) { + local_write_through(self, title_slot, 1); + return; + } if (why || !self->resource_provider) { log_slot70_null_once(why ? why : "no resource provider", texture_words, view_desc); write_null_srv(self, destination); @@ -2746,6 +2869,7 @@ HRESULT proxy_create_descriptor_heap(DeviceProxy* self, const D3D12_DESCRIPTOR_H SIZE_T custom_cpu_start = 0; SIZE_T custom_byte_size = 0; SIZE_T real_cpu_start = 0; + SIZE_T stride = 0; DescriptorHeapBackingAlloc alloc_fn = nullptr; DescriptorHeapBackingFree free_fn = nullptr; { @@ -2763,6 +2887,7 @@ HRESULT proxy_create_descriptor_heap(DeviceProxy* self, const D3D12_DESCRIPTOR_H if (addr <= (std::numeric_limits::max)() - byte_size) { custom_cpu_start = addr; custom_byte_size = byte_size; + stride = inc; real_cpu_start = raw_heap_get_cpu_handle(heap, *reinterpret_cast(heap)).ptr; } else if (free_fn) { free_fn(backing, kXmemDescriptorHeapAttributes); @@ -2772,7 +2897,7 @@ HRESULT proxy_create_descriptor_heap(DeviceProxy* self, const D3D12_DESCRIPTOR_H } hr = create_heap_proxy(heap, self, *riid, out, custom_cpu_start, custom_byte_size, real_cpu_start, - custom_cpu_start ? free_fn : nullptr); + custom_cpu_start ? free_fn : nullptr, stride); if (FAILED(hr)) { heap->Release(); if (custom_cpu_start && free_fn) @@ -2787,7 +2912,9 @@ HRESULT proxy_create_descriptor_heap(DeviceProxy* self, const D3D12_DESCRIPTOR_H void proxy_create_cbv(DeviceProxy* self, const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE dest) { note_slot(17); - self->real->CreateConstantBufferView(desc, translate_cpu_handle(self, dest)); + const auto target = translate_cpu_handle(self,dest); + if (!self->constant_view || !self->constant_view(self->real,desc,target)) + self->real->CreateConstantBufferView(desc,target); local_write_through(self, dest, 1); } @@ -3104,7 +3231,7 @@ class TitleMemoryLease final : public IUnknown { // `created` is the object a slot 76/127 creation returned (any interface of the resource). Nothing happens without // installed hooks, for a size the PC device refuses, or when the hooks return null; creation never fails here. -void lease_title_resource_memory(DeviceProxy* self, void* created, const D3D12_RESOURCE_DESC& clean_desc) { +void lease_title_resource_memory(DeviceProxy* self, void* created, const D3D12_RESOURCE_DESC& clean_desc, UINT layout) { if (!created) return; DescriptorHeapBackingAlloc alloc_fn = nullptr; DescriptorHeapBackingFree free_fn = nullptr; @@ -3128,7 +3255,9 @@ void lease_title_resource_memory(DeviceProxy* self, void* created, const D3D12_R free_fn(memory, kXmemCommittedResourceAttributes); return; } - object->SetPrivateDataInterface(kTitleMemoryLeaseGuid, lease); // the resource's reference + const HRESULT kept = object->SetPrivateDataInterface(kTitleMemoryLeaseGuid, lease); + if (SUCCEEDED(kept) && self->texture_lease_provider && clean_desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) + self->texture_lease_provider(static_cast(created), memory, static_cast(size), layout); object->Release(); lease->Release(); // ours; from here the resource's reference is the only one static std::atomic logged{false}; @@ -3139,6 +3268,53 @@ void lease_title_resource_memory(DeviceProxy* self, void* created, const D3D12_R static_cast(size)); } +bool supports_depth_uav(const DeviceProxy* self, const D3D12_RESOURCE_DESC& desc) { + return self->depth_stencil_uav_provider && depth_uav_description(desc); +} + +D3D12_RESOURCE_DESC depth_image_desc(D3D12_RESOURCE_DESC desc) { + // Keep desktop resource flags up to RTAS and USE_TIGHT_ALIGNMENT. Xbox stores additional flags above them. + desc.Flags = static_cast((UINT(desc.Flags) & 0x5ffu) & + ~UINT(D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)); + desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + return desc; +} + +D3D12_RESOURCE_STATES depth_image_state(D3D12_RESOURCE_STATES requested) { + return requested == D3D12_RESOURCE_STATE_UNORDERED_ACCESS ? D3D12_RESOURCE_STATE_COMMON : requested; +} + +HRESULT create_depth_uav_backing(DeviceProxy* self, const D3D12_HEAP_PROPERTIES* props, D3D12_HEAP_FLAGS flags, + const D3D12_RESOURCE_DESC& native, D3D12_RESOURCE_STATES initial, + const D3D12_CLEAR_VALUE* clear, ID3D12Resource** out) { + // The logical Xbox texture has a UAV. Its writable planes take ALLOW_SHADER_ATOMICS, which the PC + // rejects on the depth-only attachment. Upload/readback heaps cannot hold a UAV on either API. + if (props && (props->Type == D3D12_HEAP_TYPE_UPLOAD || props->Type == D3D12_HEAP_TYPE_READBACK)) + return E_INVALIDARG; + const auto storage_flags = flags & D3D12_HEAP_FLAG_ALLOW_SHADER_ATOMICS; + HRESULT hr = self->real->CreateCommittedResource(props, flags & ~storage_flags, &native, initial, clear, + IID_PPV_ARGS(out)); + if (FAILED(hr)) return hr; + hr = self->depth_stencil_uav_provider(*out, storage_flags); + if (FAILED(hr)) { + (*out)->Release(); + *out = nullptr; + } + return hr; +} + +HRESULT proxy_create_placed_depth(DeviceProxy* self, UINT64 address, const D3D12_RESOURCE_DESC& desc, + std::uint32_t layout, const D3D12_CLEAR_VALUE* clear, REFIID riid, void** out) { + const auto native = depth_image_desc(desc); + if (!self->validate_depth_placement(native, layout, clear)) return E_INVALIDARG; + const auto alloc = self->real->GetResourceAllocationInfo(0, 1, &native); + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + return self->placed_depth_textures.create(address, native, alloc, clear, desc.Layout == D3D12_TEXTURE_LAYOUT_UNKNOWN, riid, out, [&](ID3D12Resource** backing) { + return create_depth_uav_backing(self, &heap, D3D12_HEAP_FLAG_NONE, native, D3D12_RESOURCE_STATE_COMMON, + clear, backing); + }); +} + HRESULT proxy_create_resource(DeviceProxy* self, const D3D12_HEAP_PROPERTIES* heap_properties, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC* xbox_desc, D3D12_RESOURCE_STATES initial_state, const D3D12_CLEAR_VALUE* clear_value, @@ -3167,9 +3343,19 @@ HRESULT proxy_create_resource(DeviceProxy* self, const D3D12_HEAP_PROPERTIES* he "[rt] d3d12_xs: slot 76 resource: dimension=%d xbox layout=0x%x -> PC layout=0x%x\n", static_cast(pc_desc.Dimension), xbox_layout, static_cast(pc_desc.Layout)); } + if (supports_depth_uav(self, *xbox_desc)) { + ID3D12Resource* resource = nullptr; + HRESULT hr = create_depth_uav_backing(self, heap_properties, heap_flags, depth_image_desc(pc_desc), + depth_image_state(initial_state), clear_value, &resource); + if (FAILED(hr)) return hr; + hr = resource->QueryInterface(*riid, out); + if (SUCCEEDED(hr)) lease_title_resource_memory(self, *out, pc_desc, unsigned(xbox_desc->Layout)); + resource->Release(); + return hr; + } const HRESULT hr = self->real->CreateCommittedResource(heap_properties, heap_flags, &pc_desc, initial_state, clear_value, *riid, out); - if (SUCCEEDED(hr)) lease_title_resource_memory(self, *out, pc_desc); + if (SUCCEEDED(hr)) lease_title_resource_memory(self, *out, pc_desc, unsigned(xbox_desc->Layout)); return hr; } @@ -3261,7 +3447,7 @@ HRESULT proxy_create_committed_resource3_x(DeviceProxy* self, std::uint64_t heap plain.SampleDesc = pc_desc.SampleDesc; plain.Layout = pc_desc.Layout; plain.Flags = pc_desc.Flags; - lease_title_resource_memory(self, *out, plain); + lease_title_resource_memory(self, *out, plain, xbox_layout); } return hr; } @@ -3404,14 +3590,85 @@ std::uint64_t proxy_slot74(std::uint64_t a1, std::uint64_t a2, std::uint64_t a3) } // Xbox slot 86: CreatePipelineState(desc, riid, out), forwarded to PC ID3D12Device2::CreatePipelineState (PC slot 47). +void keep_pso_stream(IUnknown* pso, const D3D12_PIPELINE_STATE_STREAM_DESC& desc) { + ID3D12Object* object = nullptr; + if (FAILED(pso->QueryInterface(__uuidof(ID3D12Object), reinterpret_cast(&object))) || !object) return; + auto record = PsoStreamRecord::capture(desc); + static std::atomic logged{false}; + if (!record || !attach_pso_record(object, std::move(record))) { + if (!logged.exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, "[rt] d3d12_xs: a pipeline state stream is not kept for derivation (unmodelled subobject or allocation failure); slot 55 refuses that PSO as a base\n"); + } + object->Release(); +} + +// The PC CreatePipelineState (PC slot 47) that slots 86 and 55 share: on success the stream is kept on the PSO. +HRESULT create_pso_from_stream(DeviceProxy* self, const D3D12_PIPELINE_STATE_STREAM_DESC* desc, const IID* riid, + void** out, std::unique_ptr derived = {}) { + if (!riid) return E_POINTER; + if(self->prepare_stream && desc && out && IsEqualIID(*riid,__uuidof(ID3D12PipelineState))) + return self->prepare_stream(self->real,*desc,*riid,out,std::move(derived)); + + // Through the queried ID3D12Device2 (#8517): supporting an interface does not make its pointer or vtable the + // base device's. + ID3D12Device2* device2 = nullptr; + const HRESULT query = self->real->QueryInterface(__uuidof(ID3D12Device2), reinterpret_cast(&device2)); + if (FAILED(query) || !device2) return FAILED(query) ? query : E_NOINTERFACE; + const HRESULT hr = device2->CreatePipelineState(desc, *riid, out); + device2->Release(); + if (SUCCEEDED(hr) && out && *out && desc) { + if (!derived) { + keep_pso_stream(static_cast(*out), *desc); + } else { + auto* pipeline = static_cast(*out); + if (!attach_pso_record(pipeline, std::move(derived))) { + pipeline->Release(); + *out = nullptr; + return E_OUTOFMEMORY; + } + } + } + return hr; +} + HRESULT proxy_create_pipeline_state(DeviceProxy* self, const D3D12_PIPELINE_STATE_STREAM_DESC* desc, const IID* riid, void** out) { note_slot(86); if (out) *out = nullptr; if (self->slot_count <= 47) return refuse_beyond_device(86, self->slot_count); // predates ID3D12Device2 - if (!riid) return E_POINTER; - using Fn = HRESULT(WINAPI*)(ID3D12Device*, const D3D12_PIPELINE_STATE_STREAM_DESC*, const IID*, void**); - return reinterpret_cast(self->real_vtable[47])(self->real, desc, riid, out); + return create_pso_from_stream(self,desc,riid,out); +} + +HRESULT refuse_derived(unsigned reason, const char* why, HRESULT hr) { + static std::atomic logged[4]{}; + if (!logged[reason].exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, "[rt] d3d12_xs: derived pipeline state (device slot 55) refused: %s\n", why); + return hr; +} + +// Xbox slot 55: CreateDerivedPipelineState(pBasePSO, n, pRecords, riid, ppv). The base must be a PSO that slot 86 or +// slot 55 created with a kept stream; n is 1..4 records of 0x14c bytes (d3d12_xs_pso_stream.h). The patched stream +// goes through the slot 86 path. Every refusal leaves *ppv null and returns a failure, never a fake success. +HRESULT proxy_create_derived_pso(DeviceProxy* self, ID3D12PipelineState* base, std::uint32_t count, + const unsigned char* records, const IID* riid, void** out) { + note_slot(55); + if (out) *out = nullptr; + if (self->slot_count <= 47) return refuse_beyond_device(55, self->slot_count); // predates ID3D12Device2 + if (!out || !riid || !records) return E_POINTER; + if (!count || count>kDerivedMaxRecords) return E_INVALIDARG; + if (!readable_range(records, std::size_t(count)*kDerivedRecordSize)) return E_INVALIDARG; + const PsoStreamRecord* base_record = base ? find_pso_record(base) : nullptr; + if (!base_record) return refuse_derived(0, "base PSO has no kept stream", E_FAIL); + std::vector patched; + switch (derive_stream(*base_record, records, count, patched)) { + case DeriveStatus::ok: break; + case DeriveStatus::unknown_tag: return refuse_derived(1, "record tag not known", E_INVALIDARG); + case DeriveStatus::missing_state: return refuse_derived(2, "base has no subobject for a record", E_INVALIDARG); + case DeriveStatus::malformed: return refuse_derived(3, "record count or base stream malformed", E_INVALIDARG); + } + auto record = PsoStreamRecord::derived(*base_record, std::move(patched)); + const auto desc = record->desc(); + return create_pso_from_stream(self, &desc, riid, out, std::move(record)); } // Xbox slot 101: CreateStateObject(desc, riid, out), forwarded to PC ID3D12Device5::CreateStateObject (PC slot 62, @@ -3491,25 +3748,27 @@ std::uint64_t proxy_get_resource_allocation_info2(DeviceProxy* self, std::uint64 return reinterpret_cast(ret); } -// Device slot 133 is the console's CreatePlacedResourceX: (va, desc, state, clear, riid, out), measured on the retail +// Device slot 133 is the console's CreatePlacedResourceX: (va, desc, layout, clear, riid, out), measured on the retail // executable (docs/retail_boot_chain.md, section 3.4). `va` is the start of a physical-page range the title has just -// mapped, `desc` a 56-byte description with Xbox bits above the PC resource flags and an Xbox layout word, and -// `state` is 0xFFFFFFFF, which is no PC state. The resource is a buffer on those pages, made by the handler the -// device behind the proxy registered (set_placed_at_va_handler), with the PC flags kept and the layout made -// ROW_MAJOR, as slot 76 does. +// mapped. `desc` has an Xbox texture layout word and flags above the PC resource flags. The separate initial +// barrier layout is passed through to the applicable provider, including 0xFFFFFFFF (UNDEFINED). std::atomic g_placed_at_va{nullptr}; std::atomic g_placed_at_va_pages{nullptr}; +std::atomic g_pin_texture_pages{nullptr}; std::atomic g_console_descriptor_heap{nullptr}; HRESULT proxy_create_placed_resource_x(DeviceProxy* self, void* va, const D3D12_RESOURCE_DESC* xbox_desc, - std::uint32_t state, const IID* riid, void** out) { + std::uint32_t layout, const D3D12_CLEAR_VALUE* clear, const IID* riid, void** out) { note_slot(133); if (out) *out = nullptr; - // Without a handler (a PC device behind the proxy, or none registered) the slot refuses like any slot past the - // PC vtable, whatever its arguments. + // An unhandled slot past the PC vtable is refused before inspecting any of its arguments. const PlacedAtVaHandler handler = g_placed_at_va.load(std::memory_order_acquire); - if (!handler) return E_NOTIMPL; + const bool can_place_depth = self->depth_stencil_uav_provider && self->validate_depth_placement; + if (!handler && !can_place_depth) return E_NOTIMPL; if (!out || !xbox_desc || !riid) return E_POINTER; + if (can_place_depth && depth_uav_description(*xbox_desc)) + return proxy_create_placed_depth(self, reinterpret_cast(va), *xbox_desc, layout, clear, *riid, out); + if (!handler) return E_NOTIMPL; // An integer mask: a D3D12_RESOURCE_FLAGS constant past the SDK's last enumerator is not a constant expression // for clang-cl with SDK 10.0.26100 (found in review). The cast is applied to the masked value at run time. // The PC flags up to RAYTRACING_ACCELERATION_STRUCTURE (0x100) and USE_TIGHT_ALIGNMENT (0x400); 0x200 is @@ -3526,9 +3785,9 @@ HRESULT proxy_create_placed_resource_x(DeviceProxy* self, void* va, const D3D12_ if (!logged.exchange(true, std::memory_order_relaxed)) { std::fprintf(stderr, "[rt] d3d12_xs: slot 133 CreatePlacedResourceX: va=%p dimension=%d width=%llu xbox flags=0x%x " - "state=0x%x -> a buffer on the title's pages\n", + "layout=0x%x\n", va, static_cast(pc_desc.Dimension), static_cast(pc_desc.Width), - xbox_flags, state); + xbox_flags, layout); } // The buffer's pages are committed before the handler walks them (set_placed_at_va_pages_hook). const PlacedAtVaPagesHook pages = g_placed_at_va_pages.load(std::memory_order_acquire); @@ -3540,7 +3799,8 @@ HRESULT proxy_create_placed_resource_x(DeviceProxy* self, void* va, const D3D12_ va, static_cast(pc_desc.Width), GetLastError()); } } - return handler(self->real, va, pc_desc, state, *riid, out); + const bool clearable = pc_desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL); + return handler(self->real, va, pc_desc, layout, *riid, out, clearable ? clear : nullptr); } template @@ -3641,10 +3901,26 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64 self, reinterpret_cast(a1), reinterpret_cast(a2), reinterpret_cast(a3))); } else if constexpr (Slot == 133) { - return hr_to_u64(proxy_create_placed_resource_x( - self, a1, reinterpret_cast(a2), static_cast(a3), - reinterpret_cast(a4), reinterpret_cast(a5), - reinterpret_cast(a6))); + const auto* desc = reinterpret_cast(a2); + const auto* iid = reinterpret_cast(a5); + auto** out = reinterpret_cast(a6); + // The live Vulkan backend owns the resource on the title's pages. Keep the PC fallback + // for backends with no placement provider and retain the six-argument Xbox ABI. + const bool depth = self->depth_stencil_uav_provider && self->validate_depth_placement && desc && + depth_uav_description(*desc); + const bool generic = g_placed_at_va.load(std::memory_order_acquire) && desc && + (desc->Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || !self->raw_texture_view); + const HRESULT hr = depth || generic + ? proxy_create_placed_resource_x(self, reinterpret_cast(a1), desc, static_cast(a3), + reinterpret_cast(a4), iid, out) + : proxy_create_placed_resource_x(self, a1, desc, static_cast(a3), + reinterpret_cast(a4), iid, out); + if (SUCCEEDED(hr) && desc) { + if (a1 && out && *out && self->texture_lease_provider && desc->Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && + (unsigned(desc->Layout)==1u || unsigned(desc->Layout)==0x100u)) + self->texture_lease_provider(static_cast(*out),reinterpret_cast(a1),0,unsigned(desc->Layout)); + } + return hr_to_u64(hr); } else if constexpr (Slot == kCreateCommittedResource3X) { return hr_to_u64(proxy_create_committed_resource3_x(self, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10)); } else if constexpr (Slot == 70) { @@ -3680,6 +3956,25 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64 static_cast(a2), static_cast(static_cast(a3)))); } note_slot(Slot); + if constexpr (Slot == 55) { + const auto* iid=reinterpret_cast(a4); + if(readable_range(iid,sizeof(IID)) && IsEqualIID(*iid,__uuidof(ID3D12PipelineState))) { + HRESULT hr; + try { hr=proxy_create_derived_pso(self,reinterpret_cast(a1), + static_cast(a2),reinterpret_cast(a3),iid,reinterpret_cast(a5)); } catch(const std::bad_alloc&) { hr=E_OUTOFMEMORY; } + return hr_to_u64(d3d12_trace::result("XboxID3D12Device::CreateDerivedPipelineState",hr)); + } + } + if constexpr (Slot == 57) { + const auto* iid = reinterpret_cast(a2); + if (!readable_range(iid, sizeof(IID))) return hr_to_u64(E_POINTER); + // The title requests a PSO here. Other interfaces retain their ordinary forwarding path. + if (IsEqualIID(*iid, __uuidof(ID3D12PipelineState))) { + const HRESULT hr = proxy_create_native_graphics(self, reinterpret_cast(a1), *iid, + reinterpret_cast(a3)); + return hr_to_u64(d3d12_trace::result("XboxID3D12Device::CreateNativeGraphicsPipelineState", hr)); + } + } // Xbox device slots, before the PC vtable is indexed: the public HLE's 78/79/80 would otherwise reach // CreateReservedResource2/CreateSampler2 or fall past an 80-slot table, and 48/73 would reach unrelated PC // methods. The check is before the slot-count refusal because slot 80 is outside a PC ID3D12Device11 table. @@ -3912,6 +4207,8 @@ HRESULT create_device_proxy(ID3D12Device* real, REFIID riid, void** out, bool co delete proxy; return hr; } + // The source consults the process-wide heap registry; it holds no pointer to this device. + leonida::title_va_aliases().set_descriptor_source(nullptr, pull_title_descriptors); if (!d3d12_trace::enabled()) std::fprintf(stderr, "[rt] d3d12_xs: device proxy %p wraps PC device %p (%u PC vtable slots)\n", static_cast(proxy), static_cast(real), slot_count); @@ -3945,6 +4242,19 @@ bool set_device_adapter_provider(void* device, DxgiAdapterProvider provider) { return true; } +void set_constant_view_provider(void* device, ConsoleConstantView provider) { + if (auto* proxy=static_cast(device_proxy_primary(device))) proxy->constant_view=provider; +} +void set_raw_texture_view_provider(void* device, RawTextureViewProvider provider) { + if (auto* proxy = static_cast(device_proxy_primary(device))) proxy->raw_texture_view = provider; +} +void set_texture_lease_provider(void* device, TextureLeaseProvider provider) { + if (is_device_proxy(device)) static_cast(device)->texture_lease_provider = provider; +} +void set_descriptor_mapping_provider(void* device, DescriptorMappingProvider provider) { + if (auto* proxy = static_cast(device_proxy_primary(device))) proxy->descriptor_mapping = provider; +} + bool set_device_resource_provider(void* device, ResourceByVaProvider provider) { auto* proxy = static_cast(device_proxy_primary(device)); if (!proxy) { @@ -3956,6 +4266,21 @@ bool set_device_resource_provider(void* device, ResourceByVaProvider provider) { return true; } +void set_native_stream_factory(void* device, NativeStreamFactory factory) { + if (auto* proxy=static_cast(device_proxy_primary(device)))proxy->prepare_stream=factory; +} +void set_device_native_graphics_factory(void* device, NativeGraphicsFactory factory) { + if (auto* proxy = static_cast(device_proxy_primary(device))) proxy->native_graphics = factory; +} + +bool set_depth_stencil_uav_provider(void* device, DepthStencilUavProvider provider, ValidateDepthPlacement validate) { + auto* proxy = static_cast(device_proxy_primary(device)); + if (!proxy) return false; + proxy->depth_stencil_uav_provider = provider; + proxy->validate_depth_placement = validate; + return true; +} + bool is_heap_proxy(const void* heap) { return heap && *reinterpret_cast(heap) == reinterpret_cast(get_heap_vtable()); } @@ -3993,6 +4318,12 @@ void set_placed_at_va_handler(PlacedAtVaHandler handler) { g_placed_at_va.store(handler, std::memory_order_release); } +void set_texture_page_provider(PinnedTexturePages hook) { g_pin_texture_pages.store(hook,std::memory_order_release); } +std::shared_ptr pin_texture_pages(const void* address, std::size_t size) { + const auto hook=g_pin_texture_pages.load(std::memory_order_acquire); + return hook ? hook(address,size) : std::shared_ptr{}; +} + void set_placed_at_va_pages_hook(PlacedAtVaPagesHook hook) { g_placed_at_va_pages.store(hook, std::memory_order_release); } @@ -4015,7 +4346,7 @@ std::shared_ptr device_frame_tokens(const void* devic bool device_slot_overridden(unsigned slot) { if (slot <= 2 || slot == 8 || slot == 9 || slot == 12 || slot == 14 || (slot >= 17 && slot <= 24) || slot == 25 || slot == 26 || slot == 31 || slot == 32 || - slot == 34 || slot == 35 || slot == 36 || slot == 45 || slot == 46 || slot == 50 || slot == 56 || slot == 62 || + slot == 34 || slot == 35 || slot == 36 || slot == 45 || slot == 46 || slot == 50 || slot == 56 || slot == 57 || slot == 62 || slot == 67 || slot == 70 || slot == 75 || slot == 76 || slot == kCreateCommittedResource3X || slot == 133 || slot == 41 || slot == 61 || slot == 74 || slot == 86 || slot == 101 || slot == 108) return true; const XboxDeviceSlotRoutes& routes = xbox_device_slot_routes(); diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index f5cbc76585..611c967c50 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -107,6 +107,7 @@ #include +#include #include #include #include @@ -115,6 +116,8 @@ namespace leonida { class FrameTokenSource; } +namespace leonida::native_pso { struct GraphicsDesc; } + namespace rt::d3d12_xs { // Wraps `real` and returns the requested device interface through `out`. Takes ownership of one reference to @@ -142,6 +145,13 @@ bool is_device_proxy(const void* device); using DxgiAdapterProvider = HRESULT (*)(ID3D12Device* real, REFIID riid, void** out); // `device` is the proxy or its DXGI pointer. False, with a line on stderr, when it is neither: nothing is set then. bool set_device_adapter_provider(void* device, DxgiAdapterProvider provider); +// The Vulkan backend installs its own graphics PSO factory on its outer Xbox device. +class PsoStreamRecord; +using NativeStreamFactory = HRESULT (*)(ID3D12Device*, const D3D12_PIPELINE_STATE_STREAM_DESC&, REFIID, void**, + std::unique_ptr); +void set_native_stream_factory(void* device, NativeStreamFactory factory); +using NativeGraphicsFactory = HRESULT (*)(ID3D12Device*, const leonida::native_pso::GraphicsDesc&, REFIID, void**); +void set_device_native_graphics_factory(void* device, NativeGraphicsFactory factory); // Finds the buffer resource that holds a console GPU virtual address, for device slot 70. `real` is the device behind // the proxy; `bytes` is how many bytes from `va` the caller wants, so a resource that holds all of them is preferred // over a shorter alias. Returns the resource with a reference added (the proxy releases it), or null when no resource holds @@ -151,6 +161,46 @@ using ResourceByVaProvider = ID3D12Resource* (*)(ID3D12Device* real, std::uint64 // `device` is the proxy or its DXGI pointer. False, with a line on stderr, when it is neither. Without a provider slot // 70 writes only the null view. bool set_device_resource_provider(void* device, ResourceByVaProvider provider); +using TextureLeaseProvider = void (*)(IUnknown* resource, void* pages, std::size_t size, UINT layout); +void set_texture_lease_provider(void* device, TextureLeaseProvider provider); +using RawTextureViewProvider = bool (*)(ID3D12Device*, const D3D12_RESOURCE_DESC&, const D3D12_SHADER_RESOURCE_VIEW_DESC&, + std::uint64_t, D3D12_CPU_DESCRIPTOR_HANDLE); +void set_raw_texture_view_provider(void* device, RawTextureViewProvider provider); +using ConsoleConstantView = bool (*)(ID3D12Device*, const D3D12_CONSTANT_BUFFER_VIEW_DESC*, D3D12_CPU_DESCRIPTOR_HANDLE); +void set_constant_view_provider(void* device, ConsoleConstantView provider); +// Installed by the Vulkan backend before handing the device to callers. Reports whether the exact +// CPU span belongs to the heap's live mapped allocation. PC descriptor handles may be opaque. +using DescriptorMappingProvider = bool (*)(ID3D12DescriptorHeap* heap, SIZE_T start, SIZE_T bytes); +void set_descriptor_mapping_provider(void* device, DescriptorMappingProvider provider); +// Called before publishing an Xbox resource when the backend can implement its depth/stencil UAV views. +using DepthStencilUavProvider = HRESULT (*)(ID3D12Resource* resource, D3D12_HEAP_FLAGS storage_heap_flags); +inline bool depth_uav_description(const D3D12_RESOURCE_DESC& desc) { + constexpr auto flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + return (desc.Flags & flags) == flags && desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && + (desc.Format == DXGI_FORMAT_R32G8X24_TYPELESS || desc.Format == DXGI_FORMAT_R16_TYPELESS || + desc.Format == static_cast(118)) && + desc.DepthOrArraySize && desc.MipLevels == 1 && desc.SampleDesc.Count == 1; +} +using ValidateDepthPlacement = bool (*)(const D3D12_RESOURCE_DESC& native, std::uint32_t layout, + const D3D12_CLEAR_VALUE* clear); +bool set_depth_stencil_uav_provider(void* device, DepthStencilUavProvider provider, + ValidateDepthPlacement validate_placement = nullptr); + +// The Vulkan implementation uses this private interface to look up an image for view creation. +inline constexpr GUID kVulkanResourceTag{0x9b3e5f12, 0x7c48, 0x4d0e, {0xa6, 0xb1, 0x2f, 0x8d, 0x4c, 0x7e, 0x9a, 0x35}}; + +// Identically placed Xbox depth textures have distinct COM identities but refer to one GPU image and layout. +// Only these wrappers carry a backing pointer. Every other resource retains its ordinary pointer-valued IR ID. +struct PlacedDepthInterface : ID3D12Resource { + ID3D12Resource* backing = nullptr; +}; +inline std::atomic placed_depth_vtable{nullptr}; +inline const ID3D12Resource* texture_backing(const ID3D12Resource* resource) { + const void* vtable = placed_depth_vtable.load(std::memory_order_acquire); + if (resource && vtable && *reinterpret_cast(resource) == vtable) + return static_cast(resource)->backing; + return resource; +} // The device proxy an IDXGIDevice pointer handed out by one belongs to, or null. void* device_proxy_from_dxgi_device(void* dxgi_device); // The device proxy itself, given the proxy or its DXGI pointer; null for anything else. @@ -185,14 +235,13 @@ ID3D12Device* device_proxy_real_device(const void* device); // this file that is handed a title's object, like the XboxBvhBuilder shim's command lists. IUnknown* real_object_behind_proxy(const void* object); std::shared_ptr device_frame_tokens(const void* device); -// Device slot 133 (the console's CreatePlacedResourceX) makes a buffer on the title's pages at `va`. The proxy does -// not create it itself: the device behind it does, through this handler, which the Vulkan layer registers -// (rt::d3d12::create_buffer_at_host_address). With none registered, or a PC device behind the proxy, the slot -// answers E_NOTIMPL. +// Device slot 133 (the console's CreatePlacedResourceX) routes supported depth UAVs to the proxy's depth provider. +// Other resources use this handler, registered by the Vulkan layer (rt::d3d12::create_buffer_at_host_address). +// It creates buffers on the title's pages at `va`. With no applicable provider the slot answers E_NOTIMPL. // `layout` is the title's third argument, a D3D12_BARRIER_LAYOUT (0xFFFFFFFF = UNDEFINED), measured on a retail // boot: 0x6 SHADER_RESOURCE, 0x3 UNORDERED_ACCESS, as PC CreatePlacedResource2 takes it. using PlacedAtVaHandler = HRESULT (*)(ID3D12Device* real, void* va, const D3D12_RESOURCE_DESC& desc, - std::uint32_t layout, REFIID riid, void** out); + std::uint32_t layout, REFIID riid, void** out, const D3D12_CLEAR_VALUE* clear); void set_placed_at_va_handler(PlacedAtVaHandler handler); // Called by slot 133 for a buffer, before the handler, with the buffer's range [va, va + width). gta6rt registers @@ -202,6 +251,9 @@ void set_placed_at_va_handler(PlacedAtVaHandler handler); // called. With none registered nothing is done. using PlacedAtVaPagesHook = bool (*)(const void* va, std::size_t bytes); void set_placed_at_va_pages_hook(PlacedAtVaPagesHook hook); +using PinnedTexturePages = std::shared_ptr (*)(const void*, std::size_t); +void set_texture_page_provider(PinnedTexturePages hook); +std::shared_ptr pin_texture_pages(const void* address, std::size_t size); // Device slot 14's console-extended CreateDescriptorHeap: the description is the PC 16-byte shape followed by a // console VA and a size (issue #313). The proxy does not create the heap itself: the device behind it registers this diff --git a/runtime/shims/d3d12_xs_native_pso.h b/runtime/shims/d3d12_xs_native_pso.h new file mode 100644 index 0000000000..fce79ea8c4 --- /dev/null +++ b/runtime/shims/d3d12_xs_native_pso.h @@ -0,0 +1,234 @@ +#pragma once + +// Xbox native graphics pipeline state, adapted from enx/leonida's slot-57 implementation. +// The state and stage resolution are in native_pso.h. All stage bytecode handed to D3D12 +// comes from the user's carved DXBC containers and is translated by the normal Vulkan PSO path. +#include "../src/native_pso.h" +#include "d3d12_xs_pso_stream.h" +#include "../src/shader_library.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rt::d3d12_xs { +namespace native_pipeline_detail { +namespace np = leonida::native_pso; + +inline void fill_fixed_state(const np::FixedState& s, D3D12_GRAPHICS_PIPELINE_STATE_DESC& pc) { + for (auto& rt : pc.BlendState.RenderTarget) rt.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + pc.SampleMask = s.sample_mask ? s.sample_mask : UINT_MAX; + pc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pc.RasterizerState.DepthClipEnable = TRUE; + pc.DSVFormat = static_cast(s.dsv_format); + pc.DepthStencilState.DepthEnable = pc.DSVFormat != DXGI_FORMAT_UNKNOWN; + pc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; + pc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS; + pc.PrimitiveTopologyType = s.topology_type ? static_cast(s.topology_type) + : D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + pc.NumRenderTargets = s.rt_count; + for (unsigned i = 0; i < s.rt_count; ++i) pc.RTVFormats[i] = static_cast(s.rtv_formats[i]); + pc.SampleDesc.Count = s.sample_count; +} + +template +struct alignas(void*) Subobject { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type = T; + P value{}; +}; + +struct MeshStream { + Subobject root; + Subobject ms; + Subobject ps; + Subobject blend; + Subobject sample_mask; + Subobject raster; + Subobject depth; + Subobject rtvs; + Subobject dsv; + Subobject sample; +}; + +inline HRESULT create_mesh(ID3D12Device* real, const D3D12_GRAPHICS_PIPELINE_STATE_DESC& pc, + D3D12_SHADER_BYTECODE ms, const IID& riid, void** out) { + ID3D12Device2* device2 = nullptr; + if (FAILED(real->QueryInterface(__uuidof(ID3D12Device2), reinterpret_cast(&device2))) || !device2) + return E_NOTIMPL; + MeshStream s; + s.root.value = pc.pRootSignature; + s.ms.value = ms; + s.ps.value = pc.PS; + s.blend.value = pc.BlendState; + s.sample_mask.value = pc.SampleMask; + s.raster.value = pc.RasterizerState; + s.depth.value = pc.DepthStencilState; + s.rtvs.value.NumRenderTargets = pc.NumRenderTargets; + for (unsigned i = 0; i < 8; ++i) s.rtvs.value.RTFormats[i] = pc.RTVFormats[i]; + s.dsv.value = pc.DSVFormat; + s.sample.value = pc.SampleDesc; + const D3D12_PIPELINE_STATE_STREAM_DESC stream{sizeof(s), &s}; + const HRESULT hr = device2->CreatePipelineState(&stream, riid, out); + device2->Release(); + return hr; +} + +// A pipeline state stream: each subobject is a type word, then its payload at its own alignment, padded to 8 bytes +// (d3dx12's alignas(void*) subobjects). +class Stream { +public: + template + void add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type, const P& payload) { + const std::size_t at = size_; + const std::size_t offset = (at + sizeof(type) + alignof(P) - 1) & ~(alignof(P) - 1); + size_ = (offset + sizeof(P) + 7) & ~std::size_t(7); + words_.resize(size_ / 8); + auto* bytes = reinterpret_cast(words_.data()); + std::memcpy(bytes + at, &type, sizeof(type)); + std::memcpy(bytes + offset, &payload, sizeof(P)); + } + D3D12_PIPELINE_STATE_STREAM_DESC desc() { return {size_, words_.data()}; } + +private: + std::vector words_; + std::size_t size_ = 0; +}; + +// The stream of a graphics description; an MS stage makes a mesh pipeline (no input layout or topology). +inline void build_stream(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& pc, D3D12_SHADER_BYTECODE ms, Stream& s) { + s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, pc.pRootSignature); + const bool mesh = ms.pShaderBytecode != nullptr; + if (mesh) s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, ms); + if (pc.VS.pShaderBytecode) s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, pc.VS); + if (pc.GS.pShaderBytecode) s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS, pc.GS); + if (pc.PS.pShaderBytecode) s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, pc.PS); + s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, pc.BlendState); + s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, pc.SampleMask); + s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, pc.RasterizerState); + s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, pc.DepthStencilState); + if (!mesh) { + s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, pc.InputLayout); + s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, pc.PrimitiveTopologyType); + } + D3D12_RT_FORMAT_ARRAY rtvs{}; + rtvs.NumRenderTargets = pc.NumRenderTargets; + for (unsigned i = 0; i < 8; ++i) rtvs.RTFormats[i] = pc.RTVFormats[i]; + s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, rtvs); + s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, pc.DSVFormat); + s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, pc.SampleDesc); +} + + +} // namespace native_pipeline_detail + +// One instance per Vulkan device. The catalog is immutable once loaded; repeated pipeline +// descriptions can share the source containers without sharing mutable COM pipeline objects. +class NativeGraphicsPipelines { +public: + template + HRESULT create(const std::filesystem::path& folder, const leonida::native_pso::GraphicsDesc& desc, + void** out, Create&& create_pipeline) { + using namespace native_pipeline_detail; + *out = nullptr; + try { + std::call_once(load_, [&] { + std::ifstream file(folder / L"native_hashes.txt", std::ios::binary); + if (!file) { + std::fprintf(stderr, "[rt] d3d12_xs: slot 57 needs native_hashes.txt from the shaders stage\n"); + return; + } + const std::string text{std::istreambuf_iterator(file), std::istreambuf_iterator()}; + std::string error; + if (!catalog_.parse(text, &error)) std::fprintf(stderr, "[rt] d3d12_xs: slot 57: %s\n", error.c_str()); + }); + const auto plan = np::plan(desc, catalog_); + if (plan.status == np::PlanStatus::malformed) return E_INVALIDARG; + if (plan.status != np::PlanStatus::ok) return E_NOTIMPL; + + D3D12_GRAPHICS_PIPELINE_STATE_DESC pc{}; + pc.pRootSignature = static_cast(const_cast(desc.root_signature)); + fill_fixed_state(plan.state, pc); + std::vector elements; + for (const auto& e : plan.state.elements) { + elements.push_back({e.name.c_str(), e.semantic_index, static_cast(e.format), e.input_slot, + e.aligned_byte_offset, static_cast(e.classification), + e.step_rate}); + } + pc.InputLayout = {elements.data(), static_cast(elements.size())}; + + std::array code; + D3D12_SHADER_BYTECODE mesh{}; + for (const auto& stage : plan.stages) { + auto& bytes = code[stage.block]; + bytes = container(folder, *stage.shader); + if (!bytes) return E_INVALIDARG; + const D3D12_SHADER_BYTECODE view{bytes->data(), bytes->size()}; + if (stage.shader->stage == "vs") pc.VS = view; + else if (stage.shader->stage == "ps") pc.PS = view; + else if (stage.shader->stage == "gs") pc.GS = view; + else mesh = view; // plan() admits only VS/PS/GS or MS/PS. + } + return create_pipeline(pc, mesh, code); + } catch (const std::bad_alloc&) { + return E_OUTOFMEMORY; + } catch (const std::exception&) { + return E_INVALIDARG; + } + } + +private: + using Container = std::shared_ptr>; + Container container(const std::filesystem::path& folder, const leonida::native_pso::ShaderRef& ref) { + { + std::lock_guard lock(mutex_); + if (const auto it = containers_.find(ref.digest); it != containers_.end()) return it->second; + } + // A catalog names files inside the shader workspace. Checking only its components lets a + // reader with access to the two shader directories work without opening their ancestors. + if (ref.path.find_first_of("\\:\r\n\t") != std::string::npos || ref.path.find('\0') != std::string::npos) + return {}; + const auto path = std::filesystem::u8path(ref.path); + if (path.has_root_path() || path.extension() != ".dxbc") return {}; + const auto workspace = folder.parent_path(); + const auto resolved = (folder / path).lexically_normal(); + const auto relative = resolved.lexically_relative(workspace); + if (relative.empty() || *relative.begin() == "..") return {}; + auto component = workspace; + for (const auto& part : relative) { + component /= part; + const DWORD attrs = GetFileAttributesW(component.c_str()); + if (attrs == INVALID_FILE_ATTRIBUTES || (attrs & FILE_ATTRIBUTE_REPARSE_POINT)) return {}; + } + std::ifstream in(resolved, std::ios::binary | std::ios::ate); + const std::streamoff size = in ? static_cast(in.tellg()) : 0; + if (size <= 0 || size > (64 << 20)) return {}; + auto result = std::make_shared>(static_cast(size)); + in.seekg(0); + if (!in.read(reinterpret_cast(result->data()), size)) return {}; + const auto hash = leonida::dxbc_part(*result, "HASH"); + if (hash.size() < 20 || std::memcmp(hash.data() + 4, ref.digest.data(), ref.digest.size())) return {}; + std::lock_guard lock(mutex_); + if (const auto it = containers_.find(ref.digest); it != containers_.end()) return it->second; + constexpr std::size_t budget = std::size_t{256} << 20; + if (result->size() <= budget - cached_bytes_) { + containers_.emplace(ref.digest, result); + cached_bytes_ += result->size(); + } + return result; + } + + std::once_flag load_; + leonida::native_pso::HashMap catalog_; + std::mutex mutex_; + std::map containers_; + std::size_t cached_bytes_ = 0; +}; + +} // namespace rt::d3d12_xs diff --git a/runtime/shims/d3d12_xs_placed_depth.h b/runtime/shims/d3d12_xs_placed_depth.h new file mode 100644 index 0000000000..73bc28eb7a --- /dev/null +++ b/runtime/shims/d3d12_xs_placed_depth.h @@ -0,0 +1,134 @@ +// GPU backing for slot-133 depth/UAV textures, keyed by the Xbox placement range on one device. +#pragma once + +#include "d3d12_com_object.h" +#include "d3d12_xs_device.h" + +#include +#include +#include +#include +#include +#include + +namespace rt::d3d12_xs { + +class PlacedDepthTexture final + : public d3d12::Object { +public: + static constexpr GUID kTag{0x64472a85, 0x967d, 0x46bc, {0x96, 0xaf, 0x68, 0x1f, 0x50, 0x35, 0x64, 0x71}}; + + PlacedDepthTexture(std::shared_ptr owner, UINT64 address) + : owner_(std::move(owner)), address_(address) { + backing = owner_.get(); + placed_depth_vtable.store(*reinterpret_cast(this), std::memory_order_release); + } + + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void** out) override { + if (iid == kVulkanResourceTag) return backing->QueryInterface(iid, out); + return Object::QueryInterface(iid, out); + } + HRESULT STDMETHODCALLTYPE GetDevice(REFIID iid, void** out) override { return backing->GetDevice(iid, out); } + D3D12_RESOURCE_DESC STDMETHODCALLTYPE GetDesc() override { return backing->GetDesc(); } + D3D12_GPU_VIRTUAL_ADDRESS STDMETHODCALLTYPE GetGPUVirtualAddress() override { return address_; } + HRESULT STDMETHODCALLTYPE GetHeapProperties(D3D12_HEAP_PROPERTIES* props, D3D12_HEAP_FLAGS* flags) override { + return backing->GetHeapProperties(props, flags); + } + HRESULT STDMETHODCALLTYPE Map(UINT index, const D3D12_RANGE* read, void** data) override { + return backing->Map(index, read, data); + } + void STDMETHODCALLTYPE Unmap(UINT index, const D3D12_RANGE* written) override { backing->Unmap(index, written); } + HRESULT STDMETHODCALLTYPE WriteToSubresource(UINT index, const D3D12_BOX* box, const void* data, + UINT row_pitch, UINT depth_pitch) override { + return backing->WriteToSubresource(index, box, data, row_pitch, depth_pitch); + } + HRESULT STDMETHODCALLTYPE ReadFromSubresource(void* data, UINT row_pitch, UINT depth_pitch, + UINT index, const D3D12_BOX* box) override { + return backing->ReadFromSubresource(data, row_pitch, depth_pitch, index, box); + } + +private: + std::shared_ptr owner_; + UINT64 address_; +}; + +class PlacedDepthTextures { +public: + // The initial barrier layout and optimized clear are checked for each caller before looking up an alias. + // Reusing a live compatible placement retains both the attachment image and its writable plane images. + template + HRESULT create(UINT64 address, const D3D12_RESOURCE_DESC& desc, D3D12_RESOURCE_ALLOCATION_INFO allocation, + const D3D12_CLEAR_VALUE* clear, bool opaque_layout, REFIID iid, void** out, Create create_backing) { + if (!address || !allocation.Alignment || address % allocation.Alignment || !allocation.SizeInBytes || + allocation.SizeInBytes > UINT64_MAX - address) + return E_INVALIDARG; + const UINT64 end = address + allocation.SizeInBytes; + // Placed RT/DS textures can inherit contents only when their optimized clear values also match. + // Compare the defined fields. D3D12_CLEAR_VALUE has union padding, and D16 has no stencil plane. + std::optional optimized; + if (clear) optimized = OptimizedClear{clear->Format, std::bit_cast(clear->DepthStencil.Depth), + desc.Format == DXGI_FORMAT_R16_TYPELESS ? UINT8(0) : clear->DepthStencil.Stencil}; + std::shared_ptr owner; + try { + { + std::lock_guard lock(mutex_); + // Weak ownership avoids keeping GPU images or the device alive just because an address was used. + std::erase_if(ranges_, [](const auto& entry) { return entry.second.backing.expired(); }); + // At the same offset two differently shaped opaque depth targets may alternate after + // an aliasing barrier and reinitialization. The API promises data inheritance only for + // identical descriptions and optimized clears. Keep that matching backing alive even + // when another shape is also registered at this address. + const auto limit = ranges_.lower_bound(end); + for (auto it = ranges_.begin(); it != limit; ++it) { + const auto& range = it->second; + if (range.end <= address) continue; + if (it->first != address) return E_NOTIMPL; + const bool same_shape = compatible(desc, range.desc); + if (range.end == end && same_shape && range.optimized == optimized) { + if (auto live = range.backing.lock()) owner = std::move(live); + } else if (!opaque_layout || !range.opaque_layout || same_shape) { + return E_NOTIMPL; + } + } + if (!owner) { + ID3D12Resource* resource = nullptr; + const HRESULT hr = create_backing(&resource); + if (FAILED(hr)) return hr; + owner = {resource, [](ID3D12Resource* r) { r->Release(); }}; + ranges_.emplace(address, Range{end, desc, optimized, owner, opaque_layout}); + } + } + auto* alias = new PlacedDepthTexture(std::move(owner), address); + return d3d12::hand_out(alias, iid, out); + } catch (const std::bad_alloc&) { + return E_OUTOFMEMORY; + } + } + +private: + // Dimension, mip/sample counts and layout are fixed by the slot handler. The effective alignment and byte + // interval have already been validated. All remaining usage and image geometry must match for data inheritance. + static bool compatible(const D3D12_RESOURCE_DESC& a, const D3D12_RESOURCE_DESC& b) { + return a.Format == b.Format && a.Width == b.Width && a.Height == b.Height && + a.DepthOrArraySize == b.DepthOrArraySize && a.SampleDesc.Quality == b.SampleDesc.Quality && + a.Flags == b.Flags; + } + struct OptimizedClear { + DXGI_FORMAT format; + UINT depth_bits; + UINT8 stencil; + bool operator==(const OptimizedClear&) const = default; + }; + struct Range { + UINT64 end; + D3D12_RESOURCE_DESC desc; + std::optional optimized; + std::weak_ptr backing; + bool opaque_layout; + }; + std::mutex mutex_; + std::multimap ranges_; +}; + +} // namespace rt::d3d12_xs diff --git a/runtime/shims/d3d12_xs_pso_stream.cpp b/runtime/shims/d3d12_xs_pso_stream.cpp new file mode 100644 index 0000000000..fa2941ef50 --- /dev/null +++ b/runtime/shims/d3d12_xs_pso_stream.cpp @@ -0,0 +1,340 @@ +#include "d3d12_xs_pso_stream.h" + +#include +#include + +namespace rt::d3d12_xs { +namespace { + +// Tag 5 and the DEPTH_STENCIL offsets of its two stencil mask bytes (StencilReadMask, StencilWriteMask). +constexpr std::uint32_t kStencilMaskTag = 5; +constexpr std::size_t kStencilReadMaskOffset = 0x10; +constexpr std::size_t kStencilWriteMaskOffset = 0x11; + +// Streams beyond this are refused: a title's PSO stream is a few kilobytes. +constexpr std::size_t kMaxStreamBytes = 64 * 1024; + +// Private-data GUIDs (random, fixed for this shim). The record pointer is found by GetPrivateData; the owner is an +// IUnknown the object releases when it is destroyed, which frees the record with it. +constexpr GUID kRecordPointerGuid{0x3c1f9a2e, 0x5b7d, 0x4e08, {0x8f, 0x12, 0x6a, 0x4d, 0x9c, 0x2b, 0x71, 0xe3}}; +constexpr GUID kRecordOwnerGuid{0x9e4b2d17, 0x0a6c, 0x4f35, {0xb1, 0x8d, 0x23, 0x7e, 0x5f, 0xc9, 0x40, 0x6a}}; + +struct Layout { + std::size_t size; + std::size_t align; +}; + +// Size and alignment of each subobject payload this module walks (the SDK's D3D12_PIPELINE_STATE_SUBOBJECT_TYPE). +// VIEW_INSTANCING and unknown types are not modelled: a stream with one is not captured. +bool layout_of(unsigned type, Layout& out) { + switch (type) { + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE: out = {8, 8}; return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_HS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS: + out = {sizeof(D3D12_SHADER_BYTECODE), 8}; + return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT: out = {sizeof(D3D12_STREAM_OUTPUT_DESC), 8}; return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND: out = {sizeof(D3D12_BLEND_DESC), 4}; return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK: out = {4, 4}; return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER: out = {sizeof(D3D12_RASTERIZER_DESC), 4}; return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL: out = {sizeof(D3D12_DEPTH_STENCIL_DESC), 4}; return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT: out = {sizeof(D3D12_INPUT_LAYOUT_DESC), 8}; return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS: + out = {4, 4}; + return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS: + out = {sizeof(D3D12_RT_FORMAT_ARRAY), 4}; + return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC: out = {sizeof(DXGI_SAMPLE_DESC), 4}; return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO: out = {sizeof(D3D12_CACHED_PIPELINE_STATE), 8}; return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1: out = {sizeof(D3D12_DEPTH_STENCIL_DESC1), 4}; return true; + default: return false; + } +} + +std::size_t align_up(std::size_t value, std::size_t align) { return (value + align - 1) / align * align; } + +struct Subobject { + unsigned type; + std::size_t payload; // offset of the payload in the stream + std::size_t size; +}; + +// Walks a stream laid out as the console does: u32 type, payload at its natural alignment, next entry 8-aligned +// (the measured console offsets: BLEND payload +0x8c, DEPTH_STENCIL1 entry at +0x210). False when a type is unknown +// or the entries do not end exactly at `size`. +bool walk(const unsigned char* stream, std::size_t size, std::vector& out) { + out.clear(); + std::size_t off = 0; + while (off < size) { + if (size - off < 4) return false; + unsigned type; + std::memcpy(&type, stream + off, 4); + Layout layout{}; + if (!layout_of(type, layout)) return false; + const std::size_t payload = align_up(off + 4, layout.align); + if (payload > size || layout.size > size - payload) return false; + out.push_back({type, payload, layout.size}); + off = align_up(payload + layout.size, 8); + } + return off == size; +} + +// Copies `count` bytes into a new owned blob and returns its address (stable: the blob's buffer does not move). +const unsigned char* own_blob(std::vector>& blobs, const void* bytes, std::size_t count) { + const auto* src = static_cast(bytes); + blobs.emplace_back(src, src + count); + return blobs.back().data(); +} + +// Holds a PsoStreamRecord as an IUnknown: the object keeps one reference, the creation code drops its own. +class RecordOwner final : public IUnknown { +public: + explicit RecordOwner(std::unique_ptr record) : record_(std::move(record)) {} + + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { + if (!out) return E_POINTER; + if (riid == __uuidof(IUnknown)) { + *out = static_cast(this); + AddRef(); + return S_OK; + } + *out = nullptr; + return E_NOINTERFACE; + } + ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } + ULONG STDMETHODCALLTYPE Release() override { + const ULONG left = --refs_; + if (left == 0) delete this; + return left; + } + PsoStreamRecord* record() { return record_.get(); } + +private: + ~RecordOwner() = default; + std::atomic refs_{1}; + std::unique_ptr record_; +}; + +// A record's target: the subobject it patches, a fallback subobject type (0 for none), and the payload bytes it carries. +struct Target { + unsigned primary_type; + unsigned fallback_type; + std::size_t bytes; +}; + +bool target_of_tag(std::uint32_t tag, Target& out) { + switch (tag) { + case 0: // D3D12_DEPTH_STENCIL_DESC: DEPTH_STENCIL, or the prefix of DEPTH_STENCIL1 + out = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, + sizeof(D3D12_DEPTH_STENCIL_DESC)}; + return true; + case 1: // D3D12_RASTERIZER_DESC + out = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, 0, sizeof(D3D12_RASTERIZER_DESC)}; + return true; + case 2: // D3D12_BLEND_DESC + out = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, 0, sizeof(D3D12_BLEND_DESC)}; + return true; + case 3: // sample mask (UINT) + out = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, 0, sizeof(UINT)}; + return true; + default: return false; + } +} + +const Subobject* find_subobject(const std::vector& subs, const Target& target); + +// Tag 5: the two stencil mask bytes of the record overwrite the base's DEPTH_STENCIL (or DEPTH_STENCIL1) masks; the +// rest of the record's zeros are not applied. False when the base has no depth-stencil subobject. +bool overlay_stencil_masks(const std::vector& subs, const unsigned char* record, + std::vector& out) { + const Target depth{D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, 0}; + const Subobject* sub = find_subobject(subs, depth); + if (!sub) return false; + for (std::size_t field : {kStencilReadMaskOffset, kStencilWriteMaskOffset}) + out[sub->payload + field] = record[kDerivedRecordPayload + field]; + return true; +} + +const Subobject* find_subobject(const std::vector& subs, const Target& target) { + for (const Subobject& sub : subs) + if (sub.type == target.primary_type) return ⊂ + if (target.fallback_type) + for (const Subobject& sub : subs) + if (sub.type == target.fallback_type) return ⊂ + return nullptr; +} + +} // namespace + +PsoStreamRecord::Payloads::~Payloads() { + for (ID3D12RootSignature* root : roots) + if (root) root->Release(); +} + +std::unique_ptr PsoStreamRecord::capture(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, std::span shaders) { + if (!desc.pPipelineStateSubobjectStream || desc.SizeInBytes == 0 || desc.SizeInBytes > kMaxStreamBytes) + return nullptr; + const auto* source = static_cast(desc.pPipelineStateSubobjectStream); + std::vector subs; + if (!walk(source, desc.SizeInBytes, subs)) return nullptr; + + std::unique_ptr record(new PsoStreamRecord()); + record->payloads_ = std::make_shared(); + for (const auto& shader : shaders) if (shader) record->payloads_->shaders.push_back(shader); + record->bytes_.assign(source, source + desc.SizeInBytes); + for (const Subobject& sub : subs) { + if (!record->copy_pointed_data(sub.type, sub.payload)) return nullptr; + } + return record; +} + +// Replaces the pointers in one subobject's payload with copies of what they point to. +// The derived overrides touch value subobjects only. Shader bytes, semantic names and root +// signature references have the lifetime of the shared payload even after releasing the base PSO. +std::unique_ptr PsoStreamRecord::derived(const PsoStreamRecord& base, std::vector stream) { + std::unique_ptr record(new PsoStreamRecord()); + record->bytes_ = std::move(stream); + record->payloads_ = base.payloads_; + return record; +} + +bool PsoStreamRecord::copy_pointed_data(std::size_t type, std::size_t payload_offset) { + unsigned char* payload = bytes_.data() + payload_offset; + switch (type) { + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE: { + ID3D12RootSignature* root = nullptr; + std::memcpy(&root, payload, sizeof(root)); + if (root) { + payloads_->roots.push_back(root); + root->AddRef(); + } + return true; + } + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_HS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS: { + D3D12_SHADER_BYTECODE code{}; + std::memcpy(&code, payload, sizeof(code)); + if (code.pShaderBytecode && code.BytecodeLength) { + for (const auto& shader : payloads_->shaders) + if (shader->data() == code.pShaderBytecode && shader->size() == code.BytecodeLength) return true; + code.pShaderBytecode = own_blob(payloads_->blobs, code.pShaderBytecode, code.BytecodeLength); + std::memcpy(payload, &code, sizeof(code)); + } + return true; + } + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT: { + D3D12_STREAM_OUTPUT_DESC so{}; + std::memcpy(&so, payload, sizeof(so)); + if (so.pSODeclaration && so.NumEntries) + so.pSODeclaration = reinterpret_cast( + own_blob(payloads_->blobs, so.pSODeclaration, so.NumEntries * sizeof(D3D12_SO_DECLARATION_ENTRY))); + if (so.pBufferStrides && so.NumStrides) + so.pBufferStrides = reinterpret_cast( + own_blob(payloads_->blobs, so.pBufferStrides, so.NumStrides * sizeof(UINT))); + std::memcpy(payload, &so, sizeof(so)); + return true; + } + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT: { + D3D12_INPUT_LAYOUT_DESC layout{}; + std::memcpy(&layout, payload, sizeof(layout)); + if (!layout.pInputElementDescs || !layout.NumElements) return true; + const std::size_t bytes = layout.NumElements * sizeof(D3D12_INPUT_ELEMENT_DESC); + auto* elements = reinterpret_cast( + const_cast(own_blob(payloads_->blobs, layout.pInputElementDescs, bytes))); + for (UINT i = 0; i < layout.NumElements; ++i) { + if (!elements[i].SemanticName) continue; + const std::size_t len = std::strlen(elements[i].SemanticName) + 1; + elements[i].SemanticName = + reinterpret_cast(own_blob(payloads_->blobs, elements[i].SemanticName, len)); + } + layout.pInputElementDescs = elements; + std::memcpy(payload, &layout, sizeof(layout)); + return true; + } + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO: { + D3D12_CACHED_PIPELINE_STATE cached{}; + std::memcpy(&cached, payload, sizeof(cached)); + if (cached.pCachedBlob && cached.CachedBlobSizeInBytes) { + cached.pCachedBlob = own_blob(payloads_->blobs, cached.pCachedBlob, cached.CachedBlobSizeInBytes); + std::memcpy(payload, &cached, sizeof(cached)); + } + return true; + } + default: return true; // no pointers in this payload + } +} + +DeriveStatus derive_stream(const PsoStreamRecord& base, const unsigned char* records, unsigned count, + std::vector& out) { + if (!records || count == 0 || count > kDerivedMaxRecords) return DeriveStatus::malformed; + out = base.bytes(); + std::vector subs; + if (!walk(out.data(), out.size(), subs)) return DeriveStatus::malformed; + + for (unsigned i = 0; i < count; ++i) { + const unsigned char* record = records + i * kDerivedRecordSize; + std::uint32_t tag; + std::memcpy(&tag, record, sizeof(tag)); + if (tag == kStencilMaskTag) { + if (!overlay_stencil_masks(subs, record, out)) return DeriveStatus::missing_state; + continue; + } + Target target{}; + if (!target_of_tag(tag, target)) return DeriveStatus::unknown_tag; + const Subobject* sub = find_subobject(subs, target); + if (!sub) return DeriveStatus::missing_state; + std::memcpy(out.data() + sub->payload, record + kDerivedRecordPayload, target.bytes); + } + return DeriveStatus::ok; +} + +bool attach_pso_record(ID3D12Object* object, std::unique_ptr record) { + if (!object || !record) return false; + RecordOwner* owner = new RecordOwner(std::move(record)); // one reference: ours + if (FAILED(object->SetPrivateDataInterface(kRecordOwnerGuid, owner))) { + owner->Release(); + return false; + } + // The object holds its own reference now; drop ours. The pointer below is for lookups only. + owner->Release(); + RecordOwner* pointer = owner; + return SUCCEEDED(object->SetPrivateData(kRecordPointerGuid, sizeof(pointer), &pointer)); +} + +bool share_pso_record(ID3D12Object* source, ID3D12Object* target) { + UINT size=sizeof(RecordOwner*); + RecordOwner* owner=nullptr; + if(!source || !target || FAILED(source->GetPrivateData(kRecordPointerGuid,&size,&owner)) || + size!=sizeof(owner) || !owner) return false; + if(FAILED(target->SetPrivateDataInterface(kRecordOwnerGuid,owner))) return false; + return SUCCEEDED(target->SetPrivateData(kRecordPointerGuid,sizeof(owner),&owner)); +} + +const PsoStreamRecord* find_pso_record(ID3D12Object* object) { + if (!object) return nullptr; + UINT size = sizeof(RecordOwner*); + RecordOwner* owner = nullptr; + if (FAILED(object->GetPrivateData(kRecordPointerGuid, &size, &owner)) || size != sizeof(RecordOwner*) || !owner) + return nullptr; + return owner->record(); +} + +} // namespace rt::d3d12_xs diff --git a/runtime/shims/d3d12_xs_pso_stream.h b/runtime/shims/d3d12_xs_pso_stream.h new file mode 100644 index 0000000000..7a299989f1 --- /dev/null +++ b/runtime/shims/d3d12_xs_pso_stream.h @@ -0,0 +1,85 @@ +// Xbox derived pipeline states (device slot 55) over PC pipeline state streams. +// +// Slot 86 creates a PSO from a D3D12_PIPELINE_STATE_STREAM_DESC. The proxy keeps a deep copy of that stream on the +// PSO it returns (ID3D12Object private data, so the copy is freed with the PSO). Slot 55 takes a base PSO and up to +// three state records; it patches a copy of the base stream and creates the new PSO through the same path. +// +// Record layout (TomBox's create_derived_pso_x, GPL-3.0): 0x14c bytes, a u32 tag, then the state payload at +4. +// tag 0: D3D12_DEPTH_STENCIL_DESC (0x34) -> the DEPTH_STENCIL or DEPTH_STENCIL1 subobject (first 0x34 bytes) +// tag 1: D3D12_RASTERIZER_DESC (0x2c) +// tag 2: D3D12_BLEND_DESC (0x148) +// tag 3: sample mask (u32) +// tag 5: the StencilReadMask and StencilWriteMask bytes (payload +0x10, +0x11) overwrite those two bytes of the base's +// DEPTH_STENCIL / DEPTH_STENCIL1; the title writes no other byte of it (read from the retail build's record writes) +// Any other tag is refused: its meaning is not known. +#pragma once + +#include + +#include +#include +#include +#include +#include + +namespace rt::d3d12_xs { + +inline constexpr std::size_t kDerivedRecordSize = 0x14c; +inline constexpr std::size_t kDerivedRecordPayload = 4; +// The console passes the count of records it built: raster, depth-stencil, the tag-5 record and blend can all be +// present, so the count reaches 4 (measured from the title's record writes, see the notes in docs/d3d12_vulkan.md). +inline constexpr unsigned kDerivedMaxRecords = 4; + +// An owned deep copy of one pipeline state stream. The root signature references are held until destruction; shader +// bytecode, stream-output and input-layout arrays and strings, and cached blobs are copied, and their pointers in the +// copy point at the copies. +class PsoStreamRecord { +public: + // Null when the stream is malformed, holds a subobject type this module does not walk, or is too large. + using ShaderData = std::shared_ptr>; + static std::unique_ptr capture(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, + std::span shaders = {}); + static std::unique_ptr derived(const PsoStreamRecord& base, std::vector stream); + ~PsoStreamRecord() = default; + PsoStreamRecord(const PsoStreamRecord&) = delete; + PsoStreamRecord& operator=(const PsoStreamRecord&) = delete; + + // The stream bytes. Its pointers refer to this record's copies, so the record must outlive any use of the desc. + const std::vector& bytes() const { return bytes_; } + // The PC runtime reads the stream and never writes it; the const_cast only meets the desc's void* member. + D3D12_PIPELINE_STATE_STREAM_DESC desc() const { + D3D12_PIPELINE_STATE_STREAM_DESC d{}; + d.SizeInBytes = bytes_.size(); + d.pPipelineStateSubobjectStream = const_cast(bytes_.data()); + return d; + } + +private: + PsoStreamRecord() = default; + bool copy_pointed_data(std::size_t type, std::size_t payload_offset); + + std::vector bytes_; + struct Payloads { + std::vector> blobs; + std::vector shaders; + std::vector roots; + ~Payloads(); + }; + std::shared_ptr payloads_; + +}; + +enum class DeriveStatus { ok, unknown_tag, missing_state, malformed }; + +// Writes the base stream with `count` records applied (count 1..kDerivedMaxRecords; `records` holds count records). +// The result's pointers still refer to the base record's copies. +DeriveStatus derive_stream(const PsoStreamRecord& base, const unsigned char* records, unsigned count, + std::vector& out); + +// Keeps `record` on `object` (lifetime follows the object) and finds it again. attach returns false on failure, and +// then the record is dropped. find returns null when no record was attached to that object. +bool attach_pso_record(ID3D12Object* object, std::unique_ptr record); +bool share_pso_record(ID3D12Object* source, ID3D12Object* target); +const PsoStreamRecord* find_pso_record(ID3D12Object* object); + +} // namespace rt::d3d12_xs diff --git a/runtime/shims/dstorage.cpp b/runtime/shims/dstorage.cpp index 81abaea3d9..37270beebd 100644 --- a/runtime/shims/dstorage.cpp +++ b/runtime/shims/dstorage.cpp @@ -280,7 +280,9 @@ class StatusArray final : public IDStorageStatusArrayX { uint32_t capacity() const { return capacity_; } void set_pending(uint32_t index) { entries_[index].store(E_PENDING, std::memory_order_release); } - void complete(uint32_t index, HRESULT hr) { entries_[index].store(hr, std::memory_order_release); } + void complete(uint32_t index, HRESULT hr) { + entries_[index].store(hr,std::memory_order_release); + } std::atomic& refs() { return refs_; } private: @@ -409,6 +411,19 @@ bool guarded_move(void* destination, const void* source, size_t size) { } } +// Reads one byte of every 4 KiB page of the range from user mode. Title memory that xmem maps from physical pages is +// committed by a vectored handler on first touch; a kernel write (ReadFile) raises no user-mode fault and fails with +// ERROR_NOACCESS instead. No C++ objects here: the function has __try. +void touch_pages(void* buffer, size_t size) { + const uintptr_t start = reinterpret_cast(buffer); + for (uintptr_t page = start & ~uintptr_t{0xfff}; page < start + size; page += 0x1000) { + __try { + (void)*reinterpret_cast(page < start ? start : page); + } __except (EXCEPTION_EXECUTE_HANDLER) { + } + } +} + HRESULT read_error(DWORD error) { switch (error) { case ERROR_NOACCESS: @@ -432,7 +447,16 @@ HRESULT read_file_range(HANDLE handle, uint64_t offset, void* destination, uint3 at.Offset = static_cast(position); at.OffsetHigh = static_cast(position >> 32); DWORD got = 0; - if (!ReadFile(handle, out + done, size - done, &got, &at)) return read_error(GetLastError()); + if (!ReadFile(handle, out + done, size - done, &got, &at)) { + const DWORD error = GetLastError(); + if (error != ERROR_NOACCESS) return read_error(error); + // Destination pages not committed yet (see touch_pages): commit them from user mode and read again once. + touch_pages(out + done, size - done); + at = OVERLAPPED{}; + at.Offset = static_cast(position); + at.OffsetHigh = static_cast(position >> 32); + if (!ReadFile(handle, out + done, size - done, &got, &at)) return read_error(GetLastError()); + } if (got == 0) return E_DSTORAGE_END_OF_FILE; // the file shrank since the size check done += got; } diff --git a/runtime/shims/file_system.cpp b/runtime/shims/file_system.cpp index 720c106f34..75f5e98103 100644 --- a/runtime/shims/file_system.cpp +++ b/runtime/shims/file_system.cpp @@ -701,6 +701,41 @@ void note_open_failure(const char* api, LPCWSTR name, DWORD error, const void* c rt::startup_trace::quote(rt::startup_trace::where(reinterpret_cast(caller)))); } +// Reads one byte of every 4 KiB page of [buffer, buffer + size) from user mode, so that pages committed on first +// touch (xmem's physical-page views: a reserve-only section committed by its vectored handler) are committed before +// the kernel writes into them. A page that is not valid at all is left for the caller's ReadFile to refuse. No C++ +// objects here: the function has __try. +bool touch_pages(void* buffer, DWORD size) { + auto* p = static_cast(buffer); + const uintptr_t first = reinterpret_cast(buffer) & ~uintptr_t{0xfff}; + const uintptr_t end = reinterpret_cast(buffer) + size; + bool all = true; + for (uintptr_t page = first; page < end; page += 0x1000) { + const uintptr_t at = page < reinterpret_cast(p) ? reinterpret_cast(p) : page; + __try { + (void)*reinterpret_cast(at); + } __except (EXCEPTION_EXECUTE_HANDLER) { + all = false; + } + } + return all; +} + +// ReadFile with one retry for a destination the kernel cannot write yet. The retail title reads into title memory +// that xmem maps from physical pages committed on first touch; the kernel's write raises no user-mode fault, so +// ReadFile fails with ERROR_NOACCESS (998), and the title's read loop sleeps 1 ms and retries forever (measured on +// 1.0.2.1, native Windows). Touching the pages from user mode commits them; the read is then retried once. +BOOL WINAPI read_file(HANDLE file, LPVOID buffer, DWORD size, LPDWORD read, LPOVERLAPPED overlapped) { + if (ReadFile(file, buffer, size, read, overlapped)) return TRUE; + if (GetLastError() != ERROR_NOACCESS || !buffer || !size) return FALSE; + static std::atomic logged{false}; + if (!logged.exchange(true)) + std::fprintf(stderr, "[rt] fs: ReadFile into uncommitted title memory (ERROR_NOACCESS): committing the " + "destination pages and retrying (logged once)\n"); + touch_pages(buffer, size); + return ReadFile(file, buffer, size, read, overlapped); +} + HANDLE WINAPI create_file_w(LPCWSTR name, DWORD access, DWORD share, LPSECURITY_ATTRIBUTES attributes, DWORD disposition, DWORD flags, HANDLE template_file) { if (!name) { @@ -1405,6 +1440,7 @@ using namespace rt::fs; {dll, "CreateFileA", reinterpret_cast(&create_file_a)}, \ {dll, "CreateFileW", reinterpret_cast(&create_file_w)}, \ {dll, "CreateFile2", reinterpret_cast(&create_file2)}, \ + {dll, "ReadFile", reinterpret_cast(&read_file)}, \ {dll, "FindFirstFileA", reinterpret_cast(&find_first_file_a)}, \ {dll, "FindFirstFileW", reinterpret_cast(&find_first_file_w)}, \ {dll, "FindFirstFileExA", reinterpret_cast(&find_first_file_ex_a)}, \ diff --git a/runtime/shims/present_window.h b/runtime/shims/present_window.h new file mode 100644 index 0000000000..1f03f58fcc --- /dev/null +++ b/runtime/shims/present_window.h @@ -0,0 +1,72 @@ +#pragma once + +#include +#include +#include +#include + +// The thread that owns an HWND must continue dispatching window messages while another +// thread creates pipelines or waits for the GPU. A stop event also wakes an idle window. +namespace rt::d3d12_xs { +class PresentWindow { +public: + PresentWindow() = default; + PresentWindow(const PresentWindow&) = delete; + PresentWindow& operator=(const PresentWindow&) = delete; + ~PresentWindow() { + if (stop_) SetEvent(stop_); + if (owner_.joinable()) owner_.join(); + if (stop_) CloseHandle(stop_); + } + + HWND create() { + if (stop_) return nullptr; + stop_ = CreateEventW(nullptr, TRUE, FALSE, nullptr); + if (!stop_) return nullptr; + try { + std::promise> ready; + auto result = ready.get_future(); + owner_ = std::thread([stop = stop_, ready = std::move(ready)]() mutable { + WNDCLASSW cls{}; + cls.lpfnWndProc = &procedure; + cls.hInstance = GetModuleHandleW(nullptr); + cls.lpszClassName = L"LeonidaPresentX"; + HWND window = nullptr; + if (RegisterClassW(&cls) || GetLastError() == ERROR_CLASS_ALREADY_EXISTS) + window = CreateWindowExW(0, cls.lpszClassName, L"Leonida", WS_OVERLAPPEDWINDOW, + CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, + nullptr, nullptr, cls.hInstance, nullptr); + ready.set_value({window, window ? ERROR_SUCCESS : GetLastError()}); + if (!window) return; + while (MsgWaitForMultipleObjectsEx(1, &stop, INFINITE, QS_ALLINPUT, MWMO_INPUTAVAILABLE) == + WAIT_OBJECT_0 + 1) { + MSG msg; + while (WaitForSingleObject(stop, 0) == WAIT_TIMEOUT && PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) { + if (msg.message == WM_QUIT) return; + TranslateMessage(&msg); + DispatchMessageW(&msg); + } + } + if (IsWindow(window)) DestroyWindow(window); + }); + const auto [window, error] = result.get(); + if (!window) SetLastError(error); + return window; + } catch (const std::exception&) { + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + return nullptr; + } + } + +private: + static LRESULT CALLBACK procedure(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { + if (message == WM_DESTROY) { + PostQuitMessage(0); + return 0; + } + return DefWindowProcW(window, message, wparam, lparam); + } + HANDLE stop_ = nullptr; + std::thread owner_; +}; +} // namespace rt::d3d12_xs diff --git a/runtime/shims/xg_xs.cpp b/runtime/shims/xg_xs.cpp index b45fbf689a..751305c85b 100644 --- a/runtime/shims/xg_xs.cpp +++ b/runtime/shims/xg_xs.cpp @@ -1,4 +1,6 @@ -// xg_xs.dll: the console's texture layout library. The game executable (1.0.2.1) imports two functions from it. +// xg_xs.dll: the console's texture layout library. Titles ask it which swizzle mode a texture should use, how large it +// is, where each mip and slice lies, and to copy linear data into tiled memory and back. The game executable +// (1.0.2.1) imports two functions from it. // // Measured from the call sites in the executable, read statically (shapes and checks only): // HRESULT XGSuggestSwizzleMode(const desc*, 0, uint32_t* mode) @@ -7,86 +9,498 @@ // known, writes itself as 0x100 | mode. The HRESULT is only passed back up; no caller branches on it. // HRESULT XGCreateTextureComputer(const desc*, computer** out) // 4 call sites. Two test the HRESULT and take their failure path when it is negative; two ignore it and call -// through *out at once. On the computer the callers use vtable slot 1 after they are done (3 sites, read as -// Release; no site calls slot 0, read as AddRef, nor QueryInterface), slot 2 with one out pointer to a large -// stack structure (2 sites), slot 8 with six arguments in a loop over subresources (1 site) and slot 10 with -// seven arguments (1 site). No site reads the return value of slots 2, 8 or 10. +// through *out at once. On the computer the callers use vtable slot 1 after they are done (3 sites), slot 2 with +// one out pointer to a large stack structure (2 sites), slot 8 with six arguments in a loop over subresources +// (1 site) and slot 10 with seven arguments (1 site). // -// The runtime has no model of the console's resource layout (runtime/src/gfx10_tiling.h covers two swizzle modes of -// one 2D level, without mips or the layout structure slot 2 fills), so nothing here computes a layout: -// - XGSuggestSwizzleMode returns E_NOTIMPL and writes nothing, so the field keeps the 0 the caller put there. -// - XGCreateTextureComputer returns E_NOTIMPL, but still stores a computer in *out. The two checking callers then -// fail cleanly; the two that do not check would otherwise call through a null pointer. COM says *out is null on -// failure; this breaks that on purpose, because the measured callers need it. -// - Slot 0 and slot 1 count nothing (the computer is one static object). Every other slot, up to kSlots, prints its -// index and caller once and returns E_NOTIMPL without writing its arguments, so a caller's own zero-filled outputs -// stay zero and a stack structure the caller did not fill stays as it was. -// Hypothesis, not measured: slots 0 and 1 being AddRef and Release; the meaning of slots 2, 8 and 10; that callers -// reach no slot above kSlots - 1 (the computer is also stored in an object at one site and may be called later). +// The computer's methods, their arguments and the layout structure slot 2 fills are taken from Marvisak/VIctory +// (GPL-3.0), crates/victory-hle/src/modules/xg.rs at commit d2a4bae1f, which serves the same title: 0 AddRef, +// 1 Release, 2 the layout, 6 an element's byte offset, 8 a copy into and 9 a copy out of a subresource, 10 the 64 KiB +// tiling. They match the slots measured above. The layouts come from runtime/src/console_texture_layout.h, ported +// from the same project. +// +// Kept from the measured callers: a description this shim cannot lay out still gets a computer in *out (with a +// negative HRESULT), because two callers use *out without checking the HRESULT. That computer answers every slot +// with E_NOTIMPL and writes nothing. COM says *out is null on failure; this breaks that on purpose. +// +// Not modelled: compression metadata planes (HTILE, CMASK, FMASK, DCC), addressing and copies for the pipe/bank XOR +// modes (_X, _T) and MSAA (they need the GPU's pipe configuration; the host renders those targets), and the slots no +// caller reaches (size, alignment, mip offset, element coordinate, view descriptor), which log once and return +// E_NOTIMPL. #include #include +#include #include #include +#include #include #include +#include +#include +#include +#include #include +#include "../src/console_texture_layout.h" #include "shims.h" namespace { +namespace ct = leonida::console_texture; + constexpr HRESULT kNotImpl = static_cast(rt::shims::kENotImpl); +constexpr HRESULT kInvalidArg = static_cast(0x80070057u); +constexpr HRESULT kFail = static_cast(0x80004005u); constexpr size_t kSlots = 32; -// Prints once per entry point; `slot` is the vtable index for a computer method, or -1 for an export. -void warn_once(std::atomic& warned, const char* what, int slot, const void* caller) { +// D3D12_RESOURCE_DESC, whose layout field carries 0x100 | swizzle mode on the console (1 row major, 0 "pick one"). +struct ResourceDesc { + uint32_t dimension; + uint64_t alignment; + uint64_t width; + uint32_t height; + uint16_t depth_or_array; + uint16_t mips; + uint32_t format; + uint32_t samples; + uint32_t quality; + uint32_t layout; + uint32_t flags; +}; +static_assert(sizeof(ResourceDesc) == 0x38); + +constexpr uint32_t kSwizzled = 0x100; +constexpr uint32_t kRowMajor = 1; +constexpr uint32_t kAllowRenderTarget = 1; +constexpr uint32_t kAllowDepthStencil = 2; +constexpr uint32_t kTexture1d = 2, kTexture2d = 3, kTexture3d = 4; + +// The layout structure slot 2 fills. Offsets 0x00, 0x08, 0x10 and 0x1c of a mip are the ones the title reads; the +// rest follow the library's older public shape (VIctory's reading). +constexpr size_t kMips = 15; +struct MipOut { + uint64_t size; + uint64_t offset; + uint64_t slice_size; + uint32_t pitch_texels; + uint32_t pitch_bytes; + uint32_t alignment; + uint32_t padded[3]; // width, height in elements, depth or array size + uint32_t elements[2]; + uint32_t texels[2]; + uint32_t depth_or_array; + uint32_t samples; + uint32_t swizzle; + uint64_t bank_rotation[2]; + uint32_t slice_depth; + uint32_t in_tail; + uint32_t tail_position; // where a tail mip starts in elements: x bits 0-10, y 11-21 +}; +struct PlaneOut { + uint32_t usage; // 1 data, 7 depth, 8 stencil (metadata planes are not made) + uint64_t size; + uint64_t slice_size; + uint64_t offset; + uint64_t alignment; + uint32_t element_bytes; + uint32_t standard_mips; + uint32_t tail_mips; + MipOut mips[kMips]; +}; +struct LayoutOut { + uint64_t size; + uint64_t alignment; + uint32_t mips; + uint32_t planes; + PlaneOut plane[4]; + uint32_t dimension; +}; +static_assert(sizeof(MipOut) == 0x70); +static_assert(sizeof(PlaneOut) == 0x6c8); +static_assert(sizeof(LayoutOut) == 0x1b40); + +struct PackedMips { + uint8_t standard; + uint8_t packed; + uint32_t tiles; + uint32_t start; +}; +struct SubresourceTiling { + uint32_t width; + uint16_t height; + uint16_t depth; + uint32_t start; +}; +constexpr uint64_t kTile = 64u << 10; + +// Prints once per call site kind; `slot` is the vtable index for a computer method, or -1 for an export. +void warn_once(std::atomic& warned, const char* what, int slot, const void* caller, const char* why) { if (warned.exchange(true, std::memory_order_relaxed)) return; char name[64]; if (slot < 0) std::snprintf(name, sizeof(name), "%s", what); else std::snprintf(name, sizeof(name), "%s%d", what, slot); - std::fprintf(stderr, "[rt] xg_xs: %s: no console texture layout on the PC; E_NOTIMPL (caller %s, logged once)\n", - name, rt::shims::module_offset(reinterpret_cast(caller)).c_str()); + std::fprintf(stderr, "[rt] xg_xs: %s: %s (caller %s, logged once)\n", name, why, + rt::shims::module_offset(reinterpret_cast(caller)).c_str()); +} + +// The mode the console's library picks for a description: linear for 1D, the XOR render and depth modes for targets, +// else 4 KiB standard. VIctory's reading of the library's older optimal-mode function (any size, 2D, 3D and cubes +// alike); revisit if streamed textures come out scrambled. +uint32_t suggested(const ResourceDesc& d) { + if (d.dimension == kTexture1d) return ct::kLinear; + if (d.flags & kAllowDepthStencil) return ct::kSw64kbZX; + if (d.flags & kAllowRenderTarget) return ct::kSw64kbRX; + return ct::kSw4kbS; } -ULONG __stdcall computer_add_ref(void*) { return 1; } -ULONG __stdcall computer_release(void*) { return 1; } +std::optional texture_of(const ResourceDesc& d) { + ct::TextureDesc t; + switch (d.dimension) { + case kTexture1d: t.dimension = ct::Dimension::tex1d; break; + case kTexture2d: t.dimension = ct::Dimension::tex2d; break; + case kTexture3d: t.dimension = ct::Dimension::tex3d; break; + default: return std::nullopt; + } + if (d.layout == 0) t.swizzle = suggested(d); + else if (d.layout == kRowMajor) t.swizzle = ct::kLinear; + else if ((d.layout & ~0xffu) == kSwizzled) t.swizzle = d.layout & 0xffu; + else return std::nullopt; + if (d.width > std::numeric_limits::max()) return std::nullopt; + t.width = static_cast(d.width); + t.height = d.height; + t.depth_or_array = d.depth_or_array; + t.mips = d.mips; + t.format = d.format; + t.samples = d.samples ? d.samples : 1; + auto texture = ct::Texture::make(t); + // The layout structure has room for 15 mips. + if (!texture || texture->planes[0].layout.mips.size() > kMips) return std::nullopt; + return texture; +} + +// ---- The computer that cannot lay its description out: every slot E_NOTIMPL, nothing written. ---- + +ULONG __stdcall stub_add_ref(void*) { return 1; } +ULONG __stdcall stub_release(void*) { return 1; } template -HRESULT __stdcall computer_slot(void*) { +HRESULT __stdcall stub_slot(void*) { static std::atomic warned{false}; - warn_once(warned, "texture computer slot ", static_cast(Slot), _ReturnAddress()); + warn_once(warned, "texture computer slot ", static_cast(Slot), _ReturnAddress(), + "no layout for this description; E_NOTIMPL"); return kNotImpl; } template -constexpr auto make_vtable(std::index_sequence) { +constexpr auto make_stub_vtable(std::index_sequence) { return std::array{ - (Slot == 0 ? reinterpret_cast(&computer_add_ref) - : Slot == 1 ? reinterpret_cast(&computer_release) - : reinterpret_cast(&computer_slot))...}; + (Slot == 0 ? reinterpret_cast(&stub_add_ref) + : Slot == 1 ? reinterpret_cast(&stub_release) + : reinterpret_cast(&stub_slot))...}; } +const auto kStubVtable = make_stub_vtable(std::make_index_sequence{}); +struct StubComputer { + const void* const* vtable; +}; +StubComputer g_stub{kStubVtable.data()}; + +// ---- The computer with a layout. ---- -const auto kVtable = make_vtable(std::make_index_sequence{}); struct Computer { const void* const* vtable; + std::atomic refs{1}; + ResourceDesc desc{}; + uint32_t mips = 0; + ct::Texture texture; }; -Computer g_computer{kVtable.data()}; -HRESULT __stdcall XGCreateTextureComputer(const void* /*desc*/, void** out) { - static std::atomic warned{false}; - warn_once(warned, "XGCreateTextureComputer", -1, _ReturnAddress()); - if (!out) return E_POINTER; - *out = &g_computer; // see the top of the file: two measured callers use *out without checking the HRESULT - return kNotImpl; +ULONG __stdcall add_ref(Computer* c) { return c->refs.fetch_add(1, std::memory_order_relaxed) + 1; } + +ULONG __stdcall release(Computer* c) { + const ULONG left = c->refs.fetch_sub(1, std::memory_order_acq_rel) - 1; + if (left == 0) delete c; + return left; +} + +// The mode a tail mip is reported in: the 256-byte one of its kind (3 for the render kind, which GFX10 lacks), the +// depth mode itself. +uint32_t tail_swizzle(uint32_t s) { + switch (s) { + case 2: case 6: case 10: case 18: case 22: case 26: return ct::kSw256bD; + case 23: case 27: return 3; + case 24: return s; + default: return ct::kSw256bS; + } +} + +MipOut mip_out(const ResourceDesc& desc, const ct::Layout& l, size_t i) { + const ct::Mip& m = l.mips[i]; + const uint64_t bpe = l.desc.element_bytes; + const uint32_t block = l.desc.block; + const bool three_d = desc.dimension == kTexture3d; + const uint32_t array = desc.depth_or_array ? desc.depth_or_array : 1u; + MipOut out{}; + out.pitch_texels = m.pitch * block; + out.pitch_bytes = m.pitch * l.desc.element_bytes; + out.padded[0] = m.pitch; + out.padded[1] = m.rows; + out.padded[2] = three_d ? m.depth_pitch : array; + out.elements[0] = m.width; + out.elements[1] = m.height; + const uint64_t w = desc.width >> i; + out.texels[0] = w ? static_cast(w) : 1u; + out.texels[1] = (desc.height >> i) ? (desc.height >> i) : 1u; + out.depth_or_array = three_d ? m.depth : array; + out.samples = l.desc.samples; + out.slice_depth = l.block[2]; + const uint64_t slice = uint64_t{m.pitch} * m.rows * bpe; + const uint64_t depth = three_d ? m.depth_pitch : 1u; + if (!m.tail) { + out.offset = m.offset; + out.slice_size = slice * l.desc.samples; + out.size = out.slice_size * depth; + out.alignment = static_cast(l.alignment); + out.swizzle = l.desc.swizzle; + } else { + out.in_tail = 1; + out.alignment = 256; + out.swizzle = tail_swizzle(l.desc.swizzle); + if (l.thick) { // a 3D tail mip is placed by position, not by offset + out.slice_size = l.alignment / l.block[2]; + out.tail_position = m.tail->x | (m.tail->y << 11); + } else { + out.offset = m.tail->offset; + out.slice_size = slice; + } + out.size = out.slice_size * depth; + } + return out; } -HRESULT __stdcall XGSuggestSwizzleMode(const void* /*desc*/, uint32_t /*flags*/, uint32_t* /*mode*/) { +HRESULT __stdcall layout(Computer* c, LayoutOut* out) { + if (!out) return kInvalidArg; + std::memset(out, 0, sizeof(*out)); + out->size = c->texture.size; + out->alignment = c->texture.alignment; + out->mips = c->mips; + out->planes = static_cast(c->texture.planes.size()); + out->dimension = c->desc.dimension; + // The library calls a depth plane "depth" only beside stencil or without mips. + const bool depth = (c->desc.flags & kAllowDepthStencil) && (c->texture.planes.size() > 1 || c->mips == 1); + for (size_t p = 0; p < c->texture.planes.size() && p < 4; ++p) { + const ct::Plane& src = c->texture.planes[p]; + const ct::Layout& l = src.layout; + PlaneOut& plane = out->plane[p]; + plane.usage = src.stencil ? 8u : depth ? 7u : 1u; + plane.size = l.size; + plane.slice_size = l.slice_size; + plane.offset = src.offset; + plane.alignment = l.alignment; + plane.element_bytes = l.desc.element_bytes; + plane.standard_mips = l.first_tail_mip; + plane.tail_mips = c->mips - l.first_tail_mip; + for (size_t i = 0; i < l.mips.size() && i < kMips; ++i) plane.mips[i] = mip_out(c->desc, l, i); + } + return S_OK; +} + +// The plane, its mip and array slice for a subresource index, and the tiled bytes and the linear bytes a copy touches. +struct CopyArgs { + const ct::Plane* plane; + uint32_t mip, slice; + size_t tiled, linear; +}; + +std::optional copy_args(const Computer* c, uint32_t plane, uint32_t subresource, uint32_t row, + uint32_t depth) { + if (plane >= c->texture.planes.size() || c->mips == 0) return std::nullopt; + const ct::Plane& p = c->texture.planes[plane]; + const ct::Layout& l = p.layout; + const uint32_t mip = subresource % c->mips, slice = subresource / c->mips; + if (mip >= l.mips.size()) return std::nullopt; + const ct::Mip& m = l.mips[mip]; + const uint64_t bytes = uint64_t{m.width} * l.desc.element_bytes; + const uint64_t depths = l.subresource_depth(mip); + // Every factor is at most 2^32, so each product fits in 64 bits; the sum is checked against size_t below. + const uint64_t linear = (depths - 1) * depth + uint64_t{m.height - 1} * row + bytes; + const uint64_t tiled = p.offset + l.size; + if (linear > std::numeric_limits::max() || tiled > std::numeric_limits::max()) + return std::nullopt; + return CopyArgs{&p, mip, slice, static_cast(tiled), static_cast(linear)}; +} + +HRESULT result(ct::Error e) { + switch (e) { + case ct::Error::ok: return S_OK; + case ct::Error::unsupported: return kNotImpl; + default: return kInvalidArg; + } +} + +void warn_copy(const Computer* c, const char* what, uint32_t subresource, ct::Error e) { + static std::atomic warned{0}; + if (warned.fetch_add(1, std::memory_order_relaxed) >= 8) return; + std::fprintf(stderr, + "[rt] xg_xs: %s subresource %u failed (%s): dim=%u %llux%u depth/array=%u mips=%u format=%u " + "layout=0x%x\n", + what, subresource, + e == ct::Error::unsupported ? "addressing not modelled" : e == ct::Error::too_small ? "too small" + : "invalid", + c->desc.dimension, static_cast(c->desc.width), c->desc.height, + c->desc.depth_or_array, c->desc.mips, c->desc.format, c->desc.layout); +} + +// (tiled base, plane, subresource, linear, row pitch, depth pitch). +HRESULT __stdcall copy_into(Computer* c, uint8_t* tiled, uint32_t plane, uint32_t subresource, const uint8_t* linear, + uint32_t row, uint32_t depth) { + const auto a = copy_args(c, plane, subresource, row, depth); + if (!a || !tiled || !linear) return kInvalidArg; + const size_t offset = static_cast(a->plane->offset); + const ct::Error e = a->plane->layout.tile(tiled + offset, a->tiled - offset, a->mip, a->slice, linear, a->linear, + row, depth); + if (e != ct::Error::ok) warn_copy(c, "copy into", subresource, e); + return result(e); +} + +// (linear, plane, subresource, sample, tiled base, row pitch, depth pitch). +HRESULT __stdcall copy_from(Computer* c, uint8_t* linear, uint32_t plane, uint32_t subresource, uint32_t /*sample*/, + const uint8_t* tiled, uint32_t row, uint32_t depth) { + const auto a = copy_args(c, plane, subresource, row, depth); + if (!a || !tiled || !linear) return kInvalidArg; + const size_t offset = static_cast(a->plane->offset); + const ct::Error e = a->plane->layout.detile(tiled + offset, a->tiled - offset, a->mip, a->slice, linear, a->linear, + row, depth); + if (e != ct::Error::ok) warn_copy(c, "copy out of", subresource, e); + return result(e); +} + +// (total tiles, packed mips, tile shape in texels, in: room / out: count, first, subresource tilings), in 64 KiB +// tiles of plane 0, for 2D 64 KiB modes only (others fail, as on the console). The mip tail is the packed part, tile 0 +// of each slice; tilings list the standard mips of every slice in turn. With a tail the console's library lists two +// slices at most and zeroes all but the first (VIctory's reading; the title reads slice 0 only). +HRESULT __stdcall tiling(Computer* c, uint32_t* tiles, PackedMips* packed, uint32_t* shape, uint32_t* count, + uint32_t first, SubresourceTiling* out) { + const ct::Layout& l = c->texture.planes[0].layout; + if (l.alignment != kTile) return kFail; + if (l.thick) return kNotImpl; + const uint32_t standard = l.first_tail_mip; + const bool tail = standard < c->mips; + const uint64_t tail_tiles = standard == 0 ? l.slice_size / kTile + : tail ? l.mips[standard - 1].offset / kTile + : 0; + const uint32_t block = l.desc.block; + if (tiles) *tiles = static_cast(l.size / kTile); + if (packed) { + packed->standard = static_cast(standard); + packed->packed = static_cast(c->mips - standard); + packed->tiles = static_cast(tail_tiles); + packed->start = 0; + } + if (shape) { + shape[0] = l.block[0] * block; + shape[1] = l.block[1] * block; + shape[2] = l.block[2]; + } + if (count) { + const uint32_t slices = tail ? std::min(l.slices, 2u) : l.slices; + const uint64_t total = uint64_t{standard} * slices; + const uint32_t wanted = + static_cast(std::min(total > first ? total - first : 0, *count)); + for (uint32_t i = 0; i < wanted && out; ++i) { + const uint32_t slice = (first + i) / standard, mip = (first + i) % standard; + const ct::Mip& m = l.mips[mip]; + SubresourceTiling entry{}; + if (!(tail && slice > 0)) { + entry.width = m.pitch / l.block[0]; + entry.height = static_cast(m.rows / l.block[1]); + entry.depth = 1; + entry.start = static_cast((uint64_t{slice} * l.slice_size + m.offset) / kTile); + } + out[i] = entry; + } + *count = out ? wanted : 0; + } + return S_OK; +} + +// (plane, mip, x, y, z or slice, sample, bit position): an element's byte offset from the texture's start, 0 if +// outside. VIctory measured the title reading texels of a 128x4 4KB_S texture on the CPU through it. +uint64_t __stdcall element_offset(Computer* c, uint32_t plane, uint32_t mip, uint64_t x, uint32_t y, uint32_t z, + uint32_t /*sample*/, uint32_t* bit) { + if (bit) *bit = 0; + if (plane >= c->texture.planes.size()) return 0; + const ct::Plane& p = c->texture.planes[plane]; + const uint32_t x32 = x > std::numeric_limits::max() ? std::numeric_limits::max() + : static_cast(x); + uint64_t at = 0; + if (p.layout.offset(mip, x32, y, z, at) != ct::Error::ok) return 0; + return p.offset + at; +} + +template +HRESULT __stdcall unused_slot(Computer*) { static std::atomic warned{false}; - warn_once(warned, "XGSuggestSwizzleMode", -1, _ReturnAddress()); + warn_once(warned, "texture computer slot ", static_cast(Slot), _ReturnAddress(), + "method not implemented; E_NOTIMPL"); return kNotImpl; } +template +constexpr auto make_vtable(std::index_sequence) { + return std::array{ + (Slot == 0 ? reinterpret_cast(&add_ref) + : Slot == 1 ? reinterpret_cast(&release) + : Slot == 2 ? reinterpret_cast(&layout) + : Slot == 6 ? reinterpret_cast(&element_offset) + : Slot == 8 ? reinterpret_cast(©_into) + : Slot == 9 ? reinterpret_cast(©_from) + : Slot == 10 ? reinterpret_cast(&tiling) + : reinterpret_cast(&unused_slot))...}; +} +const auto kVtable = make_vtable(std::make_index_sequence{}); + +HRESULT __stdcall XGCreateTextureComputer(const ResourceDesc* desc, void** out) { + if (!out) return E_POINTER; + std::optional texture; + if (desc) texture = texture_of(*desc); + if (!texture) { + static std::atomic warned{0}; + if (warned.fetch_add(1, std::memory_order_relaxed) < 8) { + if (desc) + std::fprintf(stderr, + "[rt] xg_xs: XGCreateTextureComputer: no layout for dim=%u %llux%u depth/array=%u " + "mips=%u format=%u samples=%u layout=0x%x flags=0x%x (caller %s)\n", + desc->dimension, static_cast(desc->width), desc->height, + desc->depth_or_array, desc->mips, desc->format, desc->samples, desc->layout, + desc->flags, + rt::shims::module_offset(reinterpret_cast(_ReturnAddress())).c_str()); + else + std::fprintf(stderr, "[rt] xg_xs: XGCreateTextureComputer: null description\n"); + } + *out = &g_stub; // see the top of the file: two measured callers use *out without checking the HRESULT + return kInvalidArg; + } + auto* c = new (std::nothrow) Computer; + if (!c) { + *out = &g_stub; + return E_OUTOFMEMORY; + } + c->vtable = kVtable.data(); + c->desc = *desc; + c->mips = static_cast(texture->planes[0].layout.mips.size()); + c->texture = std::move(*texture); + *out = c; + return S_OK; +} + +// (desc, flags, out layout); the title passes flags 0 and puts the result in the description's layout field. +HRESULT __stdcall XGSuggestSwizzleMode(const ResourceDesc* desc, uint32_t /*flags*/, uint32_t* mode) { + if (!desc || !mode) return kInvalidArg; + *mode = kSwizzled | suggested(*desc); + return S_OK; +} + } // namespace SHIM_TABLE(xg_xs, diff --git a/runtime/shims/xgameruntime_offline.cpp b/runtime/shims/xgameruntime_offline.cpp index cc7a91d211..7aa1000351 100644 --- a/runtime/shims/xgameruntime_offline.cpp +++ b/runtime/shims/xgameruntime_offline.cpp @@ -27,6 +27,7 @@ // Slots whose signature the public pages don't give answer with a value that is safe whichever way the caller reads // it: see `client_not_connected` (XGameStreaming) and `offline_failure`. #include +#include #include #include @@ -593,6 +594,36 @@ const GUID kAccessibilityInterfaces[] = { {0xd722b373, 0x8c4d, 0x4692, {0x9e, 0x51, 0xd6, 0xad, 0x9b, 0x37, 0xaa, 0x7d}}, // IXAccessibilityImpl2 }; +// Forward the speech family to the +// operating system's installed runtime. Other offline services keep their existing providers. +struct HostSpeechProvider { + HMODULE module=nullptr; + IUnknown* base=nullptr; + IUnknown* extended=nullptr; + HostSpeechProvider() { + char enabled[4]{}; + if(GetEnvironmentVariableA("LEONIDA_LOCAL_SPEECH",enabled,sizeof(enabled))!=1 || enabled[0]!='1') return; + module=LoadLibraryExW(L"xgameruntime.dll",nullptr,LOAD_LIBRARY_SEARCH_SYSTEM32); + if(!module)return; + using Query=HRESULT (WINAPI*)(const GUID*,REFIID,void**); + auto query=reinterpret_cast(GetProcAddress(module,"QueryApiImpl")); + if(!query)return; + (void)query(&kAccessibilityClass,kAccessibilityInterfaces[0],reinterpret_cast(&base)); + (void)query(&kAccessibilityClass,kAccessibilityInterfaces[1],reinterpret_cast(&extended)); + } + ~HostSpeechProvider(){if(extended)extended->Release();if(base)base->Release();if(module)FreeLibrary(module);} +}; +HostSpeechProvider& host_speech_provider(){static HostSpeechProvider host;return host;} +template +bool call_host_speech(HRESULT& result,Args... args) { + auto& host=host_speech_provider(); + auto* obj=Slot==21?host.extended:host.base; + if(!obj)return false; + using Method=HRESULT (STDMETHODCALLTYPE*)(IUnknown*,Args...); + auto fn=reinterpret_cast((*reinterpret_cast(obj))[Slot]); + result=fn(obj,args...); + return true; +} // 5: HRESULT XHighContrastGetMode(XHighContrastMode* mode): Off, the first enumerator. ASSUMPTION: the signature and // that Off is 0 (GDK reference, not re-checked for this file). HRESULT STDMETHODCALLTYPE accessibility_high_contrast(void*, uint32_t* mode) { @@ -606,34 +637,48 @@ HRESULT STDMETHODCALLTYPE accessibility_captions_set_enabled(void*, bool) { retu // 8: HRESULT XSpeechSynthesizerEnumerateInstalledVoices(callback, void* context): no voice is installed, so the // callback runs zero times. ASSUMPTION: the argument order (GDK reference), only the count (2) was measured. -HRESULT STDMETHODCALLTYPE speech_enumerate_voices(void*, void* callback, void*) { +HRESULT STDMETHODCALLTYPE speech_enumerate_voices(void*, void* callback, void* context) { + HRESULT hr; if(callback && call_host_speech<8>(hr,callback,context))return hr; return callback ? S_OK : E_INVALIDARG; } // 9: HRESULT XSpeechSynthesizerCreate(XSpeechSynthesizerHandle* handle): no synthesizer offline. HRESULT STDMETHODCALLTYPE speech_create(void* self, void** handle) { + if(!handle)return E_POINTER; *handle=nullptr; + HRESULT hr; if(call_host_speech<9>(hr,handle))return hr; if (handle) *handle = nullptr; return offline_failure(self); } // 10-12, 14: a synthesizer or stream handle is the first argument, and none was ever handed out: E_INVALIDARG. -HRESULT STDMETHODCALLTYPE speech_bad_handle(void*) { return E_INVALIDARG; } +template HRESULT STDMETHODCALLTYPE speech_handle_call(void*,void* handle) { + if(!handle)return E_INVALIDARG; + HRESULT hr;return call_host_speech(hr,handle)?hr:E_INVALIDARG; +} +HRESULT STDMETHODCALLTYPE speech_custom_voice(void*,void* handle,const char* voice) { + if(!handle||!voice)return E_INVALIDARG; + HRESULT hr;return call_host_speech<12>(hr,handle,voice)?hr:E_INVALIDARG; +} // 13, 21: HRESULT XSpeechSynthesizerCreateStreamFromText/Ssml(synthesizer, const char* text, // XSpeechSynthesizerStreamHandle* stream) -HRESULT STDMETHODCALLTYPE speech_create_stream(void*, void*, const char*, void** stream) { +template HRESULT STDMETHODCALLTYPE speech_create_stream(void*,void* handle,const char* text,void** stream) { + if(stream)*stream=nullptr; + HRESULT hr;if(handle && text && stream && call_host_speech(hr,handle,text,stream))return hr; if (stream) *stream = nullptr; return E_INVALIDARG; } // 15: HRESULT XSpeechSynthesizerGetStreamDataSize(stream, size_t* size) -HRESULT STDMETHODCALLTYPE speech_stream_size(void*, void*, size_t* size) { +HRESULT STDMETHODCALLTYPE speech_stream_size(void*,void* stream,size_t* size) { + HRESULT hr;if(stream && size && call_host_speech<15>(hr,stream,size))return hr; if (size) *size = 0; return E_INVALIDARG; } // 16: HRESULT XSpeechSynthesizerGetStreamData(stream, size_t size, void* buffer, size_t* used) -HRESULT STDMETHODCALLTYPE speech_stream_data(void*, void*, size_t, void*, size_t* used) { +HRESULT STDMETHODCALLTYPE speech_stream_data(void*,void* stream,size_t capacity,void* buffer,size_t* used) { + HRESULT hr;if(stream && buffer && used && call_host_speech<16>(hr,stream,capacity,buffer,used))return hr; if (used) *used = 0; return E_INVALIDARG; } @@ -654,18 +699,18 @@ const void* const kAccessibilityVtable[] = { FN(accessibility_offline<7>), // 7 XSpeechToTextSendString FN(speech_enumerate_voices), // 8 XSpeechSynthesizerEnumerateInstalledVoices FN(speech_create), // 9 XSpeechSynthesizerCreate - FN(speech_bad_handle), // 10 XSpeechSynthesizerCloseHandle - FN(speech_bad_handle), // 11 XSpeechSynthesizerSetDefaultVoice - FN(speech_bad_handle), // 12 XSpeechSynthesizerSetCustomVoice - FN(speech_create_stream), // 13 XSpeechSynthesizerCreateStreamFromText - FN(speech_bad_handle), // 14 XSpeechSynthesizerCloseStreamHandle + FN(speech_handle_call<10>), // 10 XSpeechSynthesizerCloseHandle + FN(speech_handle_call<11>), // 11 XSpeechSynthesizerSetDefaultVoice + FN(speech_custom_voice), // 12 XSpeechSynthesizerSetCustomVoice + FN(speech_create_stream<13>), // 13 XSpeechSynthesizerCreateStreamFromText + FN(speech_handle_call<14>), // 14 XSpeechSynthesizerCloseStreamHandle FN(speech_stream_size), // 15 XSpeechSynthesizerGetStreamDataSize FN(speech_stream_data), // 16 XSpeechSynthesizerGetStreamData FN(accessibility_offline<17>), // 17 XSpeechToTextBeginHypothesisString FN(accessibility_offline<18>), // 18 XSpeechToTextUpdateHypothesisString FN(accessibility_offline<19>), // 19 XSpeechToTextFinalizeHypothesisString FN(accessibility_offline<20>), // 20 XSpeechToTextCancelHypothesisString - FN(speech_create_stream), // 21 XSpeechSynthesizerCreateStreamFromSsml + FN(speech_create_stream<21>), // 21 XSpeechSynthesizerCreateStreamFromSsml }; static_assert(std::size(kAccessibilityVtable) == 22, "IUnknown + IXAccessibilityImpl's 19 methods"); ClassObject g_accessibility_object{kAccessibilityVtable}; diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp index e8988c0461..52368c2d85 100644 --- a/runtime/shims/xmem.cpp +++ b/runtime/shims/xmem.cpp @@ -14,11 +14,12 @@ // locally at a title's call sites (each function says which). The page functions are built on the Windows placeholder // APIs (VirtualAlloc2, MapViewOfFile3), whose flags the title's own XMemVirtualAlloc calls already use. #include +#include +#include #include #include #include -#include #include #include #include @@ -36,8 +37,9 @@ #include "shims.h" #include "startup_trace.h" -#include "../src/title_va_alias.h" #include "xmem.h" +#include "../src/gpu_label_memory.h" +#include "../src/title_va_alias.h" namespace { @@ -71,13 +73,21 @@ void* allocate_block(size_t size) { return _aligned_malloc(size ? size : 1, kAli // Every block and range the title gets here is recorded as the title's memory (src/title_va_alias.h): a shader // address into it can be given a GPU copy, and an address anywhere else cannot. +void track_label_data(void* p,std::size_t bytes,bool heap) { + if(!p)return; MEMORY_BASIC_INFORMATION info{}; + if(VirtualQuery(p,&info,sizeof(info)) && info.Type==MEM_PRIVATE) + leonida::label::memory().track(reinterpret_cast(p),bytes,reinterpret_cast(info.AllocationBase),heap); +} + void* title_block(size_t size) { void* p = allocate_block(size); leonida::title_va_aliases().add_title_memory(reinterpret_cast(p), size ? size : 1); + track_label_data(p,size?size:1,true); return p; } void free_title_block(void* p) { + if(p)leonida::label::memory().release_heap(reinterpret_cast(p)); if (p) leonida::title_va_aliases().remove_title_memory(reinterpret_cast(p)); _aligned_free(p); } @@ -252,12 +262,45 @@ struct Window { DWORD protect; }; +// A sparse temporary file gives large physical pools real shared pages without reserving their +// total size against the process's pagefile commitment. Views retain the section until the last alias dies. +HANDLE file_backed_section(std::uint64_t bytes) { + wchar_t dir[32768]{}; + const auto len = GetEnvironmentVariableW(L"LEONIDA_XMEM_BACKING_DIR", dir, DWORD(std::size(dir))); + if (!len || len >= std::size(dir)) return nullptr; + const std::filesystem::path parent(dir); + if (!parent.is_absolute()) return nullptr; + static std::atomic sequence{}; + const auto name = L"physical-" + std::to_wstring(GetCurrentProcessId()) + L"-" + + std::to_wstring(GetTickCount64()) + L"-" + std::to_wstring(++sequence) + L".tmp"; + const HANDLE file = CreateFileW((parent / name).c_str(), GENERIC_READ | GENERIC_WRITE | DELETE, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, CREATE_NEW, + FILE_FLAG_DELETE_ON_CLOSE, nullptr); + if (file == INVALID_HANDLE_VALUE) { + return nullptr; + } + DWORD ignored{}; + LARGE_INTEGER size{}; + size.QuadPart = static_cast(bytes); + HANDLE section = nullptr; + if (DeviceIoControl(file, FSCTL_SET_SPARSE, nullptr, 0, nullptr, 0, &ignored, nullptr) && + SetFilePointerEx(file, size, nullptr, FILE_BEGIN) && SetEndOfFile(file)) + section = CreateFileMappingW(file, nullptr, PAGE_READWRITE, size.HighPart, size.LowPart, nullptr); + CloseHandle(file); + return section; +} + struct Section { HANDLE handle; - explicit Section(HANDLE h) : handle(h) {} + void* scratch; + bool file_backed; + Section(HANDLE h, bool use_file) : handle(h), scratch(MapViewOfFile(h, FILE_MAP_WRITE, 0, 0, 0)), file_backed(use_file) {} Section(const Section&) = delete; Section& operator=(const Section&) = delete; - ~Section() { CloseHandle(handle); } + ~Section() { + if (scratch) UnmapViewOfFile(scratch); + CloseHandle(handle); + } }; struct PhysicalPage { @@ -277,16 +320,28 @@ std::map g_windows; // base -> window std::unordered_map g_pages; // page number -> backing std::vector g_free_slots; uint64_t g_next_slot = 1; -// A mapped run: `count` pages of one section at consecutive offsets, mapped as one view at its base. One view per run -// rather than per page: under Wine each view costs a placeholder split and a section map whose time grows with the -// number of views, and the retail title maps about 100,000 pages in one call. -struct View { - uint64_t count; - std::shared_ptr
section; // kept for remapping part of the run after its pages are freed - uint64_t offset; // section offset of the first page - DWORD protect; +struct MappedPage { + uint64_t page; + std::shared_ptr
section; + uint64_t offset; +}; + +std::unordered_map g_mapped; +SRWLOCK g_fault_lock = SRWLOCK_INIT; + +struct FaultLockExclusive { + FaultLockExclusive() { AcquireSRWLockExclusive(&g_fault_lock); } + ~FaultLockExclusive() { ReleaseSRWLockExclusive(&g_fault_lock); } + FaultLockExclusive(const FaultLockExclusive&) = delete; + FaultLockExclusive& operator=(const FaultLockExclusive&) = delete; +}; + +struct FaultLockShared { + FaultLockShared() { AcquireSRWLockShared(&g_fault_lock); } + ~FaultLockShared() { ReleaseSRWLockShared(&g_fault_lock); } + FaultLockShared(const FaultLockShared&) = delete; + FaultLockShared& operator=(const FaultLockShared&) = delete; }; -std::map g_views; // view base -> view // With g_phys_mutex held. A window replaces every window it overlaps: the title released those regions (with // kernel32!VirtualFree, which the shim does not see) before the host could hand the addresses out again. @@ -353,6 +408,7 @@ void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type, // The title's memory (src/title_va_alias.h). Never forgotten: a released range is no longer committed, which // the copy also checks. if (result) leonida::title_va_aliases().add_title_memory(reinterpret_cast(result), size); + if(result)track_label_data(result,size,false); return result; } @@ -460,74 +516,19 @@ void* xmem_virtual_alloc(void* address, SIZE_T size, DWORD allocation_type, ULON return VirtualAlloc(address, size, host_type, host_prot); } -// With g_phys_mutex held. Maps `view` at the 64 KiB-aligned `address`, which holds no mapped page. MEM_REPLACE_PLACEHOLDER -// needs the view to fill one placeholder exactly, and earlier partial unmaps can leave several host placeholders in one -// run, so the run is mapped as one view per placeholder it spans. Views are capped at kMaxViewPages so that unmapping a -// page inside a long run only remaps the rest of one capped view, not the whole run. -constexpr uint64_t kMaxViewPages = 1024; // 64 MiB - -bool map_view(uintptr_t address, const View& view) { - for (uint64_t mapped = 0; mapped < view.count;) { - const uintptr_t base = address + mapped * kPhysicalPageSize; - void* const target = reinterpret_cast(base); - MEMORY_BASIC_INFORMATION info{}; - if (!VirtualQuery(target, &info, sizeof(info)) || info.State != MEM_RESERVE || - info.RegionSize < kPhysicalPageSize) { - SetLastError(ERROR_INVALID_ADDRESS); - return false; - } - const uint64_t available = info.RegionSize / kPhysicalPageSize; - const uint64_t remaining = view.count - mapped; - const uint64_t count = (std::min)({available, remaining, kMaxViewPages}); - const SIZE_T size = static_cast(count * kPhysicalPageSize); - const uint64_t offset = view.offset + mapped * kPhysicalPageSize; - if (!isolate_placeholder(target, size)) return false; - if (!placeholder_api().map_view3(view.section->handle, GetCurrentProcess(), target, offset, size, - MEM_REPLACE_PLACEHOLDER, view.protect, nullptr, 0)) { - return false; - } - g_views.emplace(base, View{count, view.section, offset, view.protect}); - mapped += count; - } - return true; -} - -// With g_phys_mutex held. Unmaps every page in [start, end); the addresses become placeholders again. A view that -// reaches outside the range is unmapped whole, and its pages outside the range are mapped again, so neighbours keep -// their pages. -bool unmap_range(uintptr_t start, uintptr_t end) { - auto it = g_views.upper_bound(start); - if (it != g_views.begin()) { - const auto prev = std::prev(it); - if (prev->first + prev->second.count * kPhysicalPageSize > start) it = prev; - } - while (it != g_views.end() && it->first < end) { - const uintptr_t base = it->first; - const View view = it->second; - const uintptr_t view_end = base + view.count * kPhysicalPageSize; - if (!placeholder_api().unmap_view2(GetCurrentProcess(), reinterpret_cast(base), - MEM_PRESERVE_PLACEHOLDER)) { - return false; - } - it = g_views.erase(it); - if (base < start) { - View left = view; - left.count = (start - base) / kPhysicalPageSize; - if (!map_view(base, left)) return false; - } - if (view_end > end) { - const uint64_t skipped = (end - base) / kPhysicalPageSize; - View right = view; - right.count = view.count - skipped; - right.offset += skipped * kPhysicalPageSize; - return map_view(end, right); // the last view the range touches - } +// With g_phys_mutex held. Unmaps the page at `address` if one is mapped there; the address becomes a placeholder again. +bool unmap_page(uintptr_t address) { + const FaultLockExclusive lock; + const auto it = g_mapped.find(address); + if (it == g_mapped.end()) return true; + if (!placeholder_api().unmap_view2(GetCurrentProcess(), reinterpret_cast(address), + MEM_PRESERVE_PLACEHOLDER)) { + return false; } + g_mapped.erase(it); return true; } -bool unmap_page(uintptr_t address) { return unmap_range(address, address + kPhysicalPageSize); } - // With g_phys_mutex held. Maps physical page `page` (0: unmap) at the 64 KiB-aligned `address`, replacing what was // mapped there. The caller has found the window. bool map_page(uintptr_t address, uint64_t page, DWORD protect) { @@ -538,7 +539,81 @@ bool map_page(uintptr_t address, uint64_t page, DWORD protect) { SetLastError(ERROR_INVALID_PARAMETER); return false; } - return map_view(address, View{1, it->second.section, it->second.offset, protect}); + void* const target = reinterpret_cast(address); + if (!isolate_placeholder(target, kPhysicalPageSize)) return false; + const FaultLockExclusive lock; + void* const view = placeholder_api().map_view3(it->second.section->handle, GetCurrentProcess(), target, + it->second.offset, kPhysicalPageSize, MEM_REPLACE_PLACEHOLDER, + protect, nullptr, 0); + if (!view) return false; + g_mapped[address] = MappedPage{page, it->second.section, it->second.offset}; + return true; +} + +enum class PageCommit { not_ours, committed_before, committed_now, failed }; + +PageCommit commit_mapped_page(uintptr_t address, uintptr_t accessed, DWORD& protect) { + const auto it = g_mapped.find(address); + if (it == g_mapped.end() || !it->second.section->scratch) return PageCommit::not_ours; + MEMORY_BASIC_INFORMATION info{}; + if (!VirtualQuery(reinterpret_cast(accessed), &info, sizeof(info)) || info.Type != MEM_MAPPED) { + return PageCommit::not_ours; + } + if (info.State == MEM_COMMIT) { + protect = info.Protect; + return PageCommit::committed_before; + } + void* const backing = static_cast(it->second.section->scratch) + it->second.offset; + return VirtualAlloc(backing, kPhysicalPageSize, MEM_COMMIT, PAGE_READWRITE) ? PageCommit::committed_now + : PageCommit::failed; +} + +bool access_allowed(DWORD protect, ULONG_PTR access) { + if (protect & PAGE_GUARD) return false; + switch (protect & 0xff) { + case PAGE_EXECUTE_READWRITE: + case PAGE_EXECUTE_WRITECOPY: + return true; + case PAGE_READWRITE: + case PAGE_WRITECOPY: + return access != 8; + case PAGE_EXECUTE_READ: + return access != 1; + case PAGE_READONLY: + return access == 0; + case PAGE_EXECUTE: + return access == 8; + default: + return false; + } +} + +LONG CALLBACK physical_page_fault(EXCEPTION_POINTERS* info) { + thread_local bool busy = false; + const EXCEPTION_RECORD* record = info ? info->ExceptionRecord : nullptr; + if (busy || !record || record->ExceptionCode != EXCEPTION_ACCESS_VIOLATION || record->NumberParameters < 2) { + return EXCEPTION_CONTINUE_SEARCH; + } + busy = true; + const uintptr_t accessed = static_cast(record->ExceptionInformation[1]); + const uintptr_t address = accessed & ~static_cast(kPhysicalPageSize - 1); + DWORD protect = 0; + PageCommit result; + { + const FaultLockShared lock; + result = commit_mapped_page(address, accessed, protect); + } + busy = false; + if (result == PageCommit::committed_now) return EXCEPTION_CONTINUE_EXECUTION; + if (result == PageCommit::committed_before && access_allowed(protect, record->ExceptionInformation[0])) { + return EXCEPTION_CONTINUE_EXECUTION; + } + return EXCEPTION_CONTINUE_SEARCH; +} + +bool install_physical_page_fault_handler() { + static const bool installed = AddVectoredExceptionHandler(1, &physical_page_fault) != nullptr; + return installed; } // Two of the measured windows are reserved PAGE_NOACCESS for the CPU and the GPU alike; pages mapped there are still @@ -576,7 +651,7 @@ void note_physical_attributes(uint64_t attributes, uint64_t count, const void* c // a 32-bit BOOL. After success every caller compares the count with the one it asked for and frees the pages if they // differ, so the count is in/out. // -// Each call is backed by one pagefile-backed section of count * 64 KiB: committed (charged) at once, given physical +// Each call is backed by one pagefile-backed section of count * 64 KiB: committed (charged) on touch, given physical // memory as it is touched, zero-filled. Pages keep their contents while unmapped or mapped elsewhere, and one page can // be mapped at several addresses. ASSUMPTION: the attribute word (memory type, perhaps the page size) is not decoded; // every page is 64 KiB, which all four callers' arithmetic agrees with. @@ -595,14 +670,25 @@ BOOL WINAPI XMemAllocatePhysicalPages(uint64_t attributes, uint64_t* page_count, SetLastError(ERROR_NOT_ENOUGH_MEMORY); return FALSE; } + if (!install_physical_page_fault_handler()) { + *page_count = 0; + SetLastError(ERROR_NOT_SUPPORTED); + return FALSE; + } const uint64_t bytes = count * kPhysicalPageSize; // below 2^37: count is below 2^21 - const HANDLE handle = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE | SEC_COMMIT, + HANDLE handle = file_backed_section(bytes); + const bool use_file = handle != nullptr; + if (!handle) handle = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE | SEC_RESERVE, static_cast(bytes >> 32), static_cast(bytes), nullptr); if (!handle) { *page_count = 0; return FALSE; } - const auto section = std::make_shared
(handle); + const auto section = std::make_shared
(handle, use_file); + if (!section->scratch) { + *page_count = 0; + return FALSE; + } for (uint64_t i = 0; i < count; ++i) { uint64_t slot; if (!g_free_slots.empty()) { @@ -645,9 +731,8 @@ BOOL WINAPI XMemFreePhysicalPages(uint64_t page_count, const uint64_t* page_arra // or null to unmap that many (four calls at shutdown). Callers test the 64-bit result for zero, so it is the address on // success. A page number of 0 in the array unmaps that one page. // -// Consecutive pages of one allocation are mapped as one view (MapViewOfFile3 into a placeholder of their size); a -// page remapped or unmapped later splits its view, and its neighbours stay mapped. The range is unmapped first, so a -// page number that is not a live page fails with the pages before it mapped and the rest of the range unmapped. +// Each page is its own view (MapViewOfFile3 into a 64 KiB placeholder), so any page can be remapped or unmapped later +// without touching its neighbours. A failure part-way leaves the pages before it mapped. void* WINAPI XMemMapPhysicalPages(void* address, uint64_t page_count, const uint64_t* page_array) { const uintptr_t start = reinterpret_cast(address); if (!aligned_page_address(start) || page_count > (std::numeric_limits::max)() / kPhysicalPageSize || @@ -660,36 +745,20 @@ void* WINAPI XMemMapPhysicalPages(void* address, uint64_t page_count, const uint return nullptr; } const std::lock_guard lock(g_phys_mutex); - const uintptr_t end = start + page_count * kPhysicalPageSize; - if (!page_array) return unmap_range(start, end) ? address : nullptr; + if (!page_array) { + for (uint64_t i = 0; i < page_count; ++i) { + if (!unmap_page(start + i * kPhysicalPageSize)) return nullptr; + } + return address; + } const Window* const window = find_window(start, page_count * kPhysicalPageSize); if (!window) { SetLastError(ERROR_INVALID_ADDRESS); return nullptr; } const DWORD protect = view_protect(*window); - if (!unmap_range(start, end)) return nullptr; - for (uint64_t i = 0; i < page_count;) { - if (page_array[i] == 0) { - ++i; - continue; - } - const auto it = g_pages.find(page_array[i]); - if (it == g_pages.end()) { - SetLastError(ERROR_INVALID_PARAMETER); - return nullptr; - } - View view{1, it->second.section, it->second.offset, protect}; - while (i + view.count < page_count) { - const auto next = g_pages.find(page_array[i + view.count]); - if (next == g_pages.end() || next->second.section != view.section || - next->second.offset != view.offset + view.count * kPhysicalPageSize) { - break; - } - ++view.count; - } - if (!map_view(start + i * kPhysicalPageSize, view)) return nullptr; - i += view.count; + for (uint64_t i = 0; i < page_count; ++i) { + if (!map_page(start + i * kPhysicalPageSize, page_array[i], protect)) return nullptr; } return address; } @@ -794,9 +863,26 @@ BOOL WINAPI XMemTransferMemory(uint32_t type, SIZE_T size) { constexpr DWORD kMemGraphics = 0x10000000; constexpr DWORD kMemTitle = 0x40000000; +BOOL WINAPI TitleVirtualFree(LPVOID address,SIZE_T size,DWORD flags) { + DWORD saved=0; + const bool ok=leonida::label::memory().release_pages(reinterpret_cast(address),size,(flags&MEM_RELEASE)!=0,[&]{ + const BOOL r=::VirtualFree(address,size,flags);saved=GetLastError();return !!r; + }); + SetLastError(saved);return ok?TRUE:FALSE; +} +BOOL WINAPI TitleVirtualFreeEx(HANDLE process,LPVOID address,SIZE_T size,DWORD flags) { + if(GetProcessId(process)!=GetCurrentProcessId())return ::VirtualFreeEx(process,address,size,flags); + DWORD saved=0; + const bool ok=leonida::label::memory().release_pages(reinterpret_cast(address),size,(flags&MEM_RELEASE)!=0,[&]{ + const BOOL r=::VirtualFreeEx(process,address,size,flags);saved=GetLastError();return !!r; + }); + SetLastError(saved);return ok?TRUE:FALSE; +} + LPVOID WINAPI TitleVirtualAlloc(LPVOID address, SIZE_T size, DWORD allocation_type, DWORD protect) { LPVOID result = VirtualAlloc(address, size, allocation_type & ~(kMemGraphics | kMemTitle), host_protect(protect)); if (result) leonida::title_va_aliases().add_title_memory(reinterpret_cast(result), size); + if(result)track_label_data(result,size,false); return result; } @@ -804,35 +890,85 @@ LPVOID WINAPI TitleVirtualAlloc(LPVOID address, SIZE_T size, DWORD allocation_ty namespace rt::xmem { -// main's xmem commits physical pages on first touch and exposes these two for code that must see them committed -// (slot 133's import, d3d12_xmem_placed_test). Here a physical page is committed when it is allocated, so there is -// nothing to do: the range only has to be mapped, readable memory, and the page array non-null. -bool commit_physical_range(const void* address, std::size_t size) { +bool commit_physical_range(const void* address, size_t size) { if (size == 0) return true; - const auto* at = static_cast(address); - const auto* const end = at + size; - while (at < end) { - MEMORY_BASIC_INFORMATION info{}; - if (!VirtualQuery(at, &info, sizeof(info)) || info.State != MEM_COMMIT) { - SetLastError(ERROR_INVALID_ADDRESS); - return false; - } - at = static_cast(info.BaseAddress) + info.RegionSize; + const uintptr_t start = reinterpret_cast(address); + if (start > (std::numeric_limits::max)() - (size - 1)) { + SetLastError(ERROR_INVALID_PARAMETER); + return false; + } + const uintptr_t mask = ~static_cast(kPhysicalPageSize - 1); + const uintptr_t first = start & mask; + const uintptr_t pages = (((start + (size - 1)) & mask) - first) / kPhysicalPageSize + 1; + const FaultLockShared lock; + for (uintptr_t i = 0; i < pages; ++i) { + DWORD protect = 0; + const uintptr_t page = first + i * kPhysicalPageSize; + if (commit_mapped_page(page, page, protect) == PageCommit::failed) return false; } return true; } -bool commit_physical_pages(const std::uint64_t* page_array, std::size_t count) { - if (count && !page_array) { +std::shared_ptr pin_mapped_data(const void* address, std::size_t size) { + const auto start = reinterpret_cast(address); + if (!size || !start || size > UINTPTR_MAX - start) return {}; + const auto end = start + size; + const auto first = start & ~std::uintptr_t(kPhysicalPageSize - 1); + const FaultLockShared lock; + const auto base = g_mapped.find(first); + if (base == g_mapped.end() || !base->second.section || !base->second.section->scratch) return {}; + const auto section = base->second.section; + const auto offset = base->second.offset; + for (auto page=first; pagesecond.section != section || it->second.offset != offset+page-first) return {}; + DWORD previous{}; + const auto ready = commit_mapped_page(page, std::max(page,start), previous); + if (ready!=PageCommit::committed_before && ready!=PageCommit::committed_now) return {}; + } + for (auto at=start; at(at), &info, sizeof(info)) || + info.Type!=MEM_MAPPED || info.State!=MEM_COMMIT || (info.Protect & (PAGE_NOACCESS|PAGE_GUARD)) || + ((info.Protect & 255)!=PAGE_READWRITE && (info.Protect & 255)!=PAGE_WRITECOPY)) return {}; + at=reinterpret_cast(info.BaseAddress)+info.RegionSize; + } + return {section,static_cast(section->scratch)+offset+(start-first)}; +} + +bool commit_physical_pages(const uint64_t* page_array, size_t count) { + if (count == 0) return true; + if (!page_array) { SetLastError(ERROR_INVALID_PARAMETER); return false; } + const std::lock_guard lock(g_phys_mutex); + size_t first = 0; + while (first < count) { + const auto it = g_pages.find(page_array[first]); + if (it == g_pages.end() || !it->second.section->scratch) { + SetLastError(ERROR_INVALID_PARAMETER); + return false; + } + size_t last = first + 1; + while (last < count) { + const auto next = g_pages.find(page_array[last]); + if (next == g_pages.end() || next->second.section != it->second.section || + next->second.offset != it->second.offset + (last - first) * kPhysicalPageSize) { + break; + } + ++last; + } + void* const backing = static_cast(it->second.section->scratch) + it->second.offset; + if (!it->second.section->file_backed && !VirtualAlloc(backing, (last - first) * kPhysicalPageSize, MEM_COMMIT, PAGE_READWRITE)) return false; + first = last; + } return true; } -} // namespace rt::xmem +} -#define TITLE_VIRTUAL_ALLOC(dll) {dll, "VirtualAlloc", reinterpret_cast(&TitleVirtualAlloc)} +#define TITLE_VIRTUAL_ALLOC(dll) {dll, "VirtualAlloc", reinterpret_cast(&TitleVirtualAlloc)}, {dll,"VirtualFree",reinterpret_cast(&TitleVirtualFree)}, {dll,"VirtualFreeEx",reinterpret_cast(&TitleVirtualFreeEx)} // The classic libraries and the memory api sets a title's imports name. SHIM_TABLE(title_memory, diff --git a/runtime/shims/xmem.h b/runtime/shims/xmem.h index beef935e65..45c422841a 100644 --- a/runtime/shims/xmem.h +++ b/runtime/shims/xmem.h @@ -2,10 +2,13 @@ #include #include +#include namespace rt::xmem { bool commit_physical_range(const void* address, std::size_t size); +// A lifetime-pinned alias of a contiguous range of the title's writable mapped physical pages. +std::shared_ptr pin_mapped_data(const void* address, std::size_t size); bool commit_physical_pages(const std::uint64_t* page_array, std::size_t count); } diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index 595110f360..3e89e1cff0 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h @@ -1,4 +1,5 @@ #pragma once +#include "gpu_label_memory.h" // The command-list IR (docs/d3d12_vulkan.md section 3.2): what a D3D12 command list records, kept until // ExecuteCommandLists replays it on Vulkan (vulkan_replay.h). This slice covers legacy and enhanced barriers and @@ -517,6 +518,7 @@ struct UavView { std::uint32_t mip; // texture std::uint32_t first_layer; std::uint32_t layer_count; + bool exact_clear_format = false; // newly exposed 1D/3D UAVs: do not clear via a different backing format }; // ClearUnorderedAccessViewUint / ...Float; the resource must be in unordered_access state at execution. values are @@ -657,7 +659,7 @@ struct AccelerationStructurePostbuild { using Command = std::variant; @@ -786,6 +788,11 @@ class CommandList { } // WriteBufferImmediate: D3D12 requires a 4-byte aligned, non-null address and one of the three modes. + bool write_gpu_label(const label::Write& write) { + if(write.target.owner.expired() || write.clock>2) return false; + return append(write); + } + bool write_immediate(const WriteImmediate& write) { if (!write.address || write.address % 4 || write.mode > write_immediate_mode::marker_out) return false; return append(write); diff --git a/runtime/src/console_texture_layout.h b/runtime/src/console_texture_layout.h new file mode 100644 index 0000000000..782d8584ad --- /dev/null +++ b/runtime/src/console_texture_layout.h @@ -0,0 +1,610 @@ +// Texture layouts of the console GPU (RDNA2, GFX10.3): a texture's size and alignment, where each mip and array slice +// starts, the address of each element, and copies between tiled memory and linear rows. Used by the xg_xs.dll shim +// (runtime/shims/xg_xs.cpp), whose texture computer answers the title's layout and copy calls from it. +// +// Ported from Marvisak/VIctory (GPL-3.0), crates/victory-formats/src/texture.rs at commit d2a4bae1f, which follows +// AMD's address library (addrlib) as shipped in Mesa under src/amd/addrlib: block dimensions, mip placement and mip +// tails from gfx10addrlib.cpp and addrlib2.cpp (ComputeSurfaceInfoMacroTiled, ComputeThinBlockDimension, +// GetMipTailDim, GetMaxNumMipsInTail, HwlComputeSurfaceInfoLinear, ComputeSurfaceAddrFromCoordMacroTiled), and the +// 256-byte micro tile patterns in kMicro from gfx10SwizzlePattern.h (the RB+ tables, as on RDNA2). addrlib carries +// this notice: +// +// Copyright (C) 2007-2026 Advanced Micro Devices, Inc. All rights reserved. +// SPDX-License-Identifier: MIT +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated +// documentation files (the "Software"), to deal in the Software without restriction, including without limitation +// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and +// to permit persons to whom the Software is furnished to do so, subject to the following conditions: the above +// copyright notice and this permission notice shall be included in all copies or substantial portions of the +// Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. +// +// Units: an element is a texel, or a 4x4 block of a block-compressed format. Mips of one array slice (or one depth +// slab of a thick 3D texture) are stored together, smallest first: the mip tail (the small mips sharing one block) +// at offset 0, mip 0 last. +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace leonida::console_texture { + +// A swizzle mode, by its hardware number (addrlib's ADDR_SW_* order). +enum : uint32_t { + kLinear = 0, + kSw256bS = 1, + kSw256bD = 2, + kSw4kbS = 5, + kSw4kbD = 6, + kSw64kbS = 9, + kSw64kbD = 10, + kSw64kbST = 17, + kSw64kbDT = 18, + kSw4kbSX = 21, + kSw4kbDX = 22, + kSw4kbRX = 23, + kSw64kbZX = 24, + kSw64kbSX = 25, + kSw64kbDX = 26, + kSw64kbRX = 27, +}; + +// log2 of the block size in bytes (0 for linear); nullopt for modes GFX10 does not have. +inline std::optional block_log2(uint32_t swizzle) { + switch (swizzle) { + case 0: return 0; + case 1: case 2: return 8; + case 5: case 6: case 21: case 22: case 23: return 12; + case 9: case 10: case 17: case 18: case 24: case 25: case 26: case 27: return 16; + default: return std::nullopt; + } +} +inline bool is_standard(uint32_t s) { return s == 1 || s == 5 || s == 9 || s == 17 || s == 21 || s == 25; } +inline bool is_display(uint32_t s) { return s == 2 || s == 6 || s == 10 || s == 18 || s == 22 || s == 26; } +inline bool is_z_order(uint32_t s) { return s == 24; } +// Pipe and bank XOR modes (_T, _X): their addresses depend on the GPU's pipe configuration. +inline bool is_xor(uint32_t s) { return s >= 16; } + +enum class Dimension { tex1d, tex2d, tex3d }; + +enum class Error { + ok, + invalid, // the description makes no texture, or a coordinate or subresource lies outside it + unsupported, // a valid layout whose addressing is not implemented here + too_small, // a buffer is smaller than the layout or the rows need +}; + +// One plane of a texture. +struct Desc { + Dimension dimension = Dimension::tex2d; + uint32_t width = 1, height = 1; // in texels + uint32_t depth = 1; // depth of a 3D texture, else the array size + uint32_t mips = 1; + uint32_t element_bytes = 4; // 1, 2, 4, 8 or 16 + uint32_t block = 1; // texels per element side: 1, or 4 for block compression + uint32_t samples = 1; + uint32_t swizzle = kLinear; +}; + +struct Tail { + uint32_t offset = 0; // byte offset inside the tail block + uint32_t x = 0, y = 0; // element position the mip starts at +}; + +// Where one mip lives inside a slice. +struct Mip { + uint32_t width = 0, height = 0, depth = 0; // size in elements (depth 1 unless the texture is 3D) + uint32_t pitch = 0, rows = 0, depth_pitch = 0; // padded size in elements: whole blocks, or the tail's share + uint64_t offset = 0; // byte offset of its first block in the slice (0 in the tail) + std::optional tail; +}; + +namespace detail { + +constexpr uint32_t div_ceil(uint32_t a, uint32_t b) { return (a + b - 1) / b; } +constexpr uint32_t round_up(uint32_t a, uint32_t b) { return div_ceil(a, b) * b; } + +// Elements along one side of mip `mip`, as data and copies see it: texels halve rounding down (to at least 1), then +// round up to whole elements. +constexpr uint32_t dim(uint32_t texels, uint32_t mip, uint32_t block) { + return div_ceil(std::max(texels >> mip, 1u), block); +} +// Elements along one side of mip `mip` for placement (padding, tail, offsets): addrlib halves mip 0's elements +// rounding up, which can be one more than dim() for odd sizes. +constexpr uint32_t padded_dim(uint32_t texels, uint32_t mip, uint32_t block) { + return div_ceil(div_ceil(std::max(texels, 1u), block), 1u << mip); +} + +// Micro tile (256 bytes) patterns by log2 of the element size: for each address bit, the element coordinate bit it +// takes (x0, y1, z0...), "--" for the bits inside an element. Thin S, thin D, thick S (also the D 3D modes). From +// addrlib's GFX10_SW_256_S_RBPLUS, GFX10_SW_256_D_RBPLUS and GFX10_SW_4K_S3_RBPLUS patterns; the larger blocks add +// bits Y, X (thin) or Y, X, Z (thick) in turn. +inline constexpr const char* kMicro[3][5] = { + {"x0x1x2x3y0y1y2y3", "--x0x1x2y0y1y2x3", "----x0x1y0y1y2x2", "------x0y0y1x1x2", "--------y0y1x0x1"}, + {"x0x1x2y1y0y2x3y3", "--x0x1x2y0y1y2x3", "----x0x1y0y1x2y2", "------x0y0x1x2y1", "--------x0y0x1y1"}, + {"x0x1z0y0z1y1x2z2", "--x0z0y0z1y1x1z2", "----x0y0z0y1x1z1", "------x0z0y0x1z1", "--------z0y0x0z1"}, +}; + +// For each axis, the address bit each coordinate bit lands on. +inline std::array, 3> pattern(int kind, uint32_t element_log2, uint32_t block_log2) { + std::array, 3> axes; + const char* micro = kMicro[kind][element_log2]; + for (uint32_t bit = 0; bit < 8; ++bit) { + const char a = micro[2 * bit]; + const int axis = a == 'x' ? 0 : a == 'y' ? 1 : a == 'z' ? 2 : -1; + if (axis < 0) continue; + const size_t index = static_cast(micro[2 * bit + 1] - '0'); + auto& to = axes[static_cast(axis)]; + if (to.size() <= index) to.resize(index + 1, 0); + to[index] = bit; + } + static constexpr int kThin[2] = {1, 0}; + static constexpr int kThick[3] = {1, 0, 2}; + const int* order = kind == 2 ? kThick : kThin; + const uint32_t n = kind == 2 ? 3u : 2u; + for (uint32_t bit = 8, i = 0; bit < block_log2; ++bit, ++i) axes[static_cast(order[i % n])].push_back(bit); + return axes; +} + +// Byte offsets inside a block for coordinates 0..2^bits of one axis. +inline std::vector spread(const std::vector& bits) { + std::vector out(size_t{1} << bits.size()); + for (uint32_t c = 0; c < out.size(); ++c) { + uint32_t v = 0; + for (size_t i = 0; i < bits.size(); ++i) v |= ((c >> i) & 1u) << bits[i]; + out[c] = v; + } + return out; +} + +} // namespace detail + +constexpr uint32_t kMaxMips = 16; +// The largest width, height and depth (or array size) accepted, in texels. GFX10's image descriptors hold at most +// 16384 texels per side, so no texture the GPU can use is refused. The bound also keeps every size computed below +// within uint64_t (and its uint32_t steps), which unchecked values from a title would otherwise overflow. +constexpr uint32_t kMaxExtent = 1u << 14; + +// 256-byte micro tile dimensions by log2 element size, 2D and 3D. +inline constexpr uint32_t kBlock256_2d[5][2] = {{16, 16}, {16, 8}, {8, 8}, {8, 4}, {4, 4}}; +inline constexpr uint32_t kBlock256_3d[5][3] = {{8, 4, 8}, {4, 4, 8}, {4, 4, 4}, {4, 2, 4}, {2, 2, 4}}; +inline constexpr uint32_t kBlock1k_3d[5][3] = {{16, 8, 8}, {8, 8, 8}, {8, 8, 4}, {8, 4, 4}, {4, 4, 4}}; + +class Layout { +public: + Desc desc; + std::array block{}; // block dimensions in elements (linear: the pitch alignment, 1, 1) + bool thick = false; // 3D blocks span block[2] depth slices (GFX10 3D S and D modes) + // Array slices, depth slabs of block[2] slices (thick), or depth slices (thin and linear 3D). + uint32_t slices = 0; + uint64_t slice_size = 0; // bytes of one slice: its whole mip chain + uint64_t size = 0; + uint64_t alignment = 0; + uint32_t first_tail_mip = 0; // the first mip in the tail; mips.size() without one + std::vector mips; + + static std::optional make(const Desc& d) { + const auto log2 = block_log2(d.swizzle); + if (!log2) return std::nullopt; + const auto in = [](uint32_t v, uint32_t lo, uint32_t hi) { return v >= lo && v <= hi; }; + const bool valid = + in(d.width, 1, kMaxExtent) && in(d.height, 1, kMaxExtent) && in(d.depth, 1, kMaxExtent) && + in(d.mips, 1, kMaxMips) && std::has_single_bit(d.element_bytes) && d.element_bytes <= 16 && + (d.block == 1 || d.block == 4) && std::has_single_bit(d.samples) && d.samples <= 8 && + (d.samples == 1 || (d.dimension == Dimension::tex2d && d.mips == 1)) && + (d.dimension != Dimension::tex1d || d.height == 1) && + (d.dimension != Dimension::tex3d || d.swizzle == 0 || d.swizzle == 5 || d.swizzle == 9 || + d.swizzle == 17 || d.swizzle == 21 || (d.swizzle >= 24 && d.swizzle <= 27)); + if (!valid) return std::nullopt; + return *log2 == 0 ? linear(d) : tiled(d, *log2); + } + + // Whether offset() and the copies work for this layout: linear and the modes without pipe or bank XOR, + // single-sampled. The XOR modes (_X, _T) and MSAA need the GPU's pipe and bank configuration (Series X and S + // differ); titles use them for render targets and depth, which the host renders. + bool addressable() const { return desc.swizzle == kLinear || !pattern_[0].empty(); } + + // Depth slices a subresource of mip `mip` covers: the mip's depth for 3D textures, else 1 (one array slice). + uint32_t subresource_depth(uint32_t mip) const { return mip < mips.size() ? mips[mip].depth : 0; } + + // Byte offset of element (x, y) of mip `mip` in array slice or depth slice `z`. Coordinates must lie inside. + Error offset(uint32_t mip, uint32_t x, uint32_t y, uint32_t z, uint64_t& out) const { + if (mip >= mips.size()) return Error::invalid; + const Mip& m = mips[mip]; + const uint32_t depth = desc.dimension == Dimension::tex3d ? m.depth : slices; + const bool inside = x < m.width && y < m.height && z < depth; + if (!inside) return Error::invalid; + if (!addressable()) return Error::unsupported; + const auto [slice, inner] = split(z); + const uint64_t base = uint64_t{slice} * slice_size + m.offset; + if (desc.swizzle == kLinear) { + out = base + (uint64_t{y} * m.pitch + x) * desc.element_bytes; + return Error::ok; + } + out = base + row(m, y, inner) + column(m, x); + return Error::ok; + } + + // Copies one subresource out of tiled memory (the whole texture, `size` bytes) into linear rows: mip `mip` of + // array slice `slice` (3D: every depth slice of the mip, slice 0). Rows are row_pitch bytes apart, depth slices + // depth_pitch. + Error detile(const uint8_t* tiled, size_t tiled_len, uint32_t mip, uint32_t slice, uint8_t* linear, + size_t linear_len, size_t row_pitch, size_t depth_pitch) const { + return walk(tiled_len, mip, slice, linear_len, row_pitch, depth_pitch, [&](size_t t, size_t l, size_t n) { + std::memcpy(linear + l, tiled + t, n); + }); + } + // The reverse of detile(): linear rows into tiled memory. + Error tile(uint8_t* tiled, size_t tiled_len, uint32_t mip, uint32_t slice, const uint8_t* linear, + size_t linear_len, size_t row_pitch, size_t depth_pitch) const { + return walk(tiled_len, mip, slice, linear_len, row_pitch, depth_pitch, [&](size_t t, size_t l, size_t n) { + std::memcpy(tiled + t, linear + l, n); + }); + } + + // Byte offsets inside a block of each element coordinate bit, per axis; empty for linear and XOR/MSAA modes. + const std::array, 3>& pattern() const { return pattern_; } + +private: + std::array, 3> pattern_; + + // HwlComputeSurfaceInfoLinear: rows aligned to 256 bytes, mips packed smallest first, a 3D texture's depth slices + // each hold the chain. + static Layout linear(const Desc& d) { + using namespace detail; + Layout l; + l.desc = d; + const uint64_t bpe = d.element_bytes; + const uint32_t align = 256 / d.element_bytes; + const bool three_d = d.dimension == Dimension::tex3d; + uint64_t offset = 0; + for (uint32_t i = d.mips; i-- > 0;) { + const uint32_t h = padded_dim(d.height, i, d.block); + const uint32_t pitch = round_up(padded_dim(d.width, i, d.block), align); + Mip m; + m.width = dim(d.width, i, d.block); + m.height = dim(d.height, i, d.block); + m.depth = three_d ? dim(d.depth, i, 1) : 1; + m.pitch = pitch; + m.rows = h; + m.depth_pitch = three_d ? d.depth : 1; + m.offset = offset; + l.mips.push_back(m); + offset += uint64_t{pitch} * h * bpe; + } + std::reverse(l.mips.begin(), l.mips.end()); + l.block = {align, 1, 1}; + l.slices = d.depth; + l.slice_size = offset; + l.size = offset * d.depth; + l.alignment = 256; + l.first_tail_mip = d.mips; + return l; + } + + static Layout tiled(const Desc& d, uint32_t block_log2) { + using namespace detail; + Layout l; + l.desc = d; + const uint32_t element_log2 = static_cast(std::countr_zero(d.element_bytes)); + const uint64_t bpe = d.element_bytes; + const uint64_t block_bytes = uint64_t{1} << block_log2; + const bool thick = d.dimension == Dimension::tex3d && (is_standard(d.swizzle) || is_display(d.swizzle)); + std::array block{}; + if (thick) { // ComputeThickBlockDimension + const uint32_t amp = (block_log2 - 10) / 3, rest = (block_log2 - 10) % 3; + const auto* b = kBlock1k_3d[element_log2]; + block = {b[0] << amp, b[1] << (amp + rest / 2), b[2] << (amp + (rest != 0 ? 1u : 0u))}; + } else { // ComputeThinBlockDimension + const uint32_t samples_log2 = static_cast(std::countr_zero(d.samples)); + const uint32_t elements_log2 = block_log2 - element_log2 - samples_log2; + const bool wide = (samples_log2 & 1) == 0 || (block_log2 & 1) != 0; + const uint32_t w = (elements_log2 + (wide ? 1u : 0u)) / 2; + block = {1u << w, 1u << (elements_log2 - w), 1}; + } + uint32_t slices = round_up(d.depth, block[2]); + const bool three_d = d.dimension == Dimension::tex3d; + // Mip depths placed by a thick layout (thin ones store depth as slices). + const auto mip_depth = [&](uint32_t i) { return thick ? padded_dim(d.depth, i, 1) : 1u; }; + const auto depth_of = [&](uint32_t i) { return three_d ? dim(d.depth, i, 1) : 1u; }; + const auto width = [&](uint32_t i) { return dim(d.width, i, d.block); }; + const auto height = [&](uint32_t i) { return dim(d.height, i, d.block); }; + uint32_t first_tail_mip = d.mips; + uint64_t slice_size = 0; + if (d.mips == 1) { + Mip m; + m.width = width(0); + m.height = height(0); + m.depth = depth_of(0); + m.pitch = round_up(width(0), block[0]); + m.rows = round_up(height(0), block[1]); + m.depth_pitch = three_d ? slices : 1; + l.mips.push_back(m); + slice_size = uint64_t{m.pitch} * m.rows * bpe * d.samples; + } else { + // GetMipTailDim: the largest mip the tail takes. + std::array tail_max = block; + if (thick) { + switch (block_log2 % 3) { + case 0: tail_max[1] >>= 1; break; + case 1: tail_max[0] >>= 1; break; + default: tail_max[2] >>= 1; break; + } + } else { + tail_max[0] >>= 1; + } + // GetMaxNumMipsInTail; 256-byte blocks have no tail (ComputeSurfaceInfoMicroTiled). + const uint32_t effective = thick ? block_log2 - (block_log2 - 8) / 3 : block_log2; + const uint32_t max_in_tail = effective == 8 ? 0 + : (effective >= 9 && effective <= 11) ? 1 + (1u << (effective - 9)) + : effective - 4; + // dsMipmapHtileFix: 8- and 16-bit depth enter the tail as 32-bit. + std::array fixed = tail_max; + if (is_z_order(d.swizzle) && element_log2 <= 1) { + const auto* b = kBlock256_2d[element_log2]; + fixed[0] /= b[0] / kBlock256_2d[2][0]; + fixed[1] /= b[1] / kBlock256_2d[2][1]; + } + std::vector sizes; + for (uint32_t i = 0; i < d.mips; ++i) { + const uint32_t w = padded_dim(d.width, i, d.block), h = padded_dim(d.height, i, d.block); + if (w <= fixed[0] && h <= fixed[1] && d.mips - i <= max_in_tail) { + first_tail_mip = i; + slice_size += block_bytes / block[2]; + break; + } + const uint32_t pitch = round_up(w, block[0]), rows = round_up(h, block[1]); + const uint32_t depth = round_up(mip_depth(i), block[2]); + const uint64_t one = uint64_t{pitch} * rows * bpe; + slice_size += one; + sizes.push_back(one * block[2]); + Mip m; + m.width = width(i); + m.height = height(i); + m.depth = depth_of(i); + m.pitch = pitch; + m.rows = rows; + m.depth_pitch = three_d ? depth : 1; + l.mips.push_back(m); + } + // Standard mips from the smallest up, after the tail block. + uint64_t offset = first_tail_mip < d.mips ? block_bytes : 0; + for (uint32_t i = first_tail_mip; i-- > 0;) { + l.mips[i].offset = offset; + offset += sizes[i]; + } + uint32_t micro[2]; + if (thick) { + micro[0] = kBlock256_3d[element_log2][0]; + micro[1] = kBlock256_3d[element_log2][1]; + } else { + micro[0] = kBlock256_2d[element_log2][0]; + micro[1] = kBlock256_2d[element_log2][1]; + } + uint32_t pitch = tail_max[0], rows = tail_max[1]; + for (uint32_t i = first_tail_mip; i < d.mips; ++i) { + const uint32_t m = max_in_tail - 1 - (i - first_tail_mip); + const uint32_t offset_in_tail = m > 6 ? 16u << m : m << 8; + // Address bits 8.. of the offset, odd ones x, even ones y. + const auto bits = [&](uint32_t from) { + uint32_t v = 0; + for (uint32_t b = 0; b < 6; ++b) v |= ((offset_in_tail >> (from + 2 * b)) & 1u) << b; + return v; + }; + uint32_t x = bits(9), y = bits(8); + if ((block_log2 & 1) != 0) { + std::swap(x, y); + if ((element_log2 & 1) != 0) { + y = (y << 1) | (x & 1); + x >>= 1; + } + } + Mip t; + t.width = width(i); + t.height = height(i); + t.depth = depth_of(i); + t.pitch = pitch; + t.rows = rows; + t.depth_pitch = thick ? round_up(mip_depth(i), kBlock256_3d[element_log2][2]) : 1; + t.offset = 0; + t.tail = Tail{offset_in_tail, x * micro[0], y * micro[1]}; + l.mips.push_back(t); + pitch = std::max(pitch >> 1, micro[0]); + rows = std::max(rows >> 1, micro[1]); + } + } + // Thick layouts store each depth slab's chain together. + const uint64_t slab = thick ? block[2] : 1; + slice_size *= slab; + slices /= block[2]; + if (!is_xor(d.swizzle) && d.samples == 1) { + const int kind = thick ? 2 : (is_display(d.swizzle) ? 1 : 0); + const auto bits = detail::pattern(kind, element_log2, block_log2); + for (size_t a = 0; a < 3; ++a) l.pattern_[a] = detail::spread(bits[a]); + } + l.block = block; + l.thick = thick; + l.slices = slices; + l.slice_size = slice_size; + l.size = slice_size * slices; + l.alignment = block_bytes; + l.first_tail_mip = first_tail_mip; + return l; + } + + // The slice and the depth inside it for z (an array slice or a 3D depth slice). + std::pair split(uint32_t z) const { + return thick ? std::pair{z / block[2], z % block[2]} : std::pair{z, 0u}; + } + + // The part of an address that depends on the row (and depth in a thick block). + uint64_t row(const Mip& m, uint32_t y, uint32_t z) const { + const uint32_t bw = block[0], bh = block[1]; + const int log2 = std::countr_zero(alignment); + // In the tail the pattern of the shifted position gives the mip's offset inside the tail block. + y += m.tail ? m.tail->y : 0; + const uint64_t blocks = uint64_t{y / bh} * (m.pitch / bw); + return (blocks << log2) + (pattern_[1][y % bh] | pattern_[2][z]); + } + + // The part of an address that depends on the column. + uint64_t column(const Mip& m, uint32_t x) const { + const uint32_t bw = block[0]; + x += m.tail ? m.tail->x : 0; + return (uint64_t{x / bw} << std::countr_zero(alignment)) + pattern_[0][x % bw]; + } + + // Visits contiguous runs as (tiled byte offset, linear byte offset, length). + template + Error walk(size_t tiled_len, uint32_t mip, uint32_t slice, size_t linear_len, size_t row_pitch, + size_t depth_pitch, Copy&& copy) const { + if (mip >= mips.size()) return Error::invalid; + const Mip& m = mips[mip]; + const uint32_t depth = m.depth; + uint32_t first = slice; + if (desc.dimension == Dimension::tex3d) { + if (slice != 0) return Error::invalid; + first = 0; + } + if (first >= slices) return Error::invalid; + if (!addressable()) return Error::unsupported; + const size_t n = desc.element_bytes; + const size_t bytes = size_t{m.width} * n; + // need = (depth - 1) * depth_pitch + (height - 1) * row_pitch + bytes, refused on overflow. + const size_t dz = depth - 1u, dy = m.height - 1u; + if ((dz && depth_pitch > SIZE_MAX / dz) || (dy && row_pitch > SIZE_MAX / dy)) return Error::too_small; + const size_t depth_offset = dz * depth_pitch, row_offset = dy * row_pitch; + if (depth_offset > SIZE_MAX - row_offset || depth_offset + row_offset > SIZE_MAX - bytes) + return Error::too_small; + const size_t need = depth_offset + row_offset + bytes; + if (tiled_len < size || linear_len < need || row_pitch < bytes) return Error::too_small; + const bool is_linear = desc.swizzle == kLinear; + // The row and depth contribute one common base to every column, so the same contiguous runs repeat on + // every row, including mip tails. + struct Run { + size_t tiled, linear, len; + }; + std::vector runs; + if (!is_linear) { + size_t first_linear = 0, first_tiled = static_cast(column(m, 0)); + for (uint32_t x = 1; x < m.width; ++x) { + const size_t off = static_cast(column(m, x)); + const size_t at = x * n; + if (off != first_tiled + (at - first_linear)) { + runs.push_back({first_tiled, first_linear, at - first_linear}); + first_tiled = off; + first_linear = at; + } + } + runs.push_back({first_tiled, first_linear, bytes - first_linear}); + } + for (uint32_t z = 0; z < depth; ++z) { + const auto [s, inner] = split(first + z); + const uint64_t base = uint64_t{s} * slice_size + m.offset; + for (uint32_t y = 0; y < m.height; ++y) { + const size_t linear_row = z * depth_pitch + y * row_pitch; + if (is_linear) { + copy(static_cast(base + uint64_t{y} * m.pitch * n), linear_row, bytes); + } else { + const size_t tiled_row = static_cast(base + row(m, y, inner)); + for (const Run& r : runs) copy(tiled_row + r.tiled, linear_row + r.linear, r.len); + } + } + } + return Error::ok; + } +}; + +// What a DXGI format stores per element: bytes, texels per element side (4 for block compression), and whether its +// stencil is a second plane (the GPU keeps depth and stencil apart). nullopt for 96-bit, 1-bit, packed 4:2:2 and +// video formats, which have no layout here. +struct Format { + uint32_t bytes, block; + bool stencil; +}; +inline std::optional format(uint32_t dxgi) { + const auto in = [&](uint32_t lo, uint32_t hi) { return dxgi >= lo && dxgi <= hi; }; + if (in(1, 4)) return Format{16, 1, false}; + if (in(9, 18)) return Format{8, 1, false}; + if (in(19, 22) || in(44, 47)) return Format{4, 1, true}; + if (in(23, 43) || dxgi == 67 || in(87, 93) || dxgi == 116 || dxgi == 117) return Format{4, 1, false}; + if (in(48, 59) || dxgi == 85 || dxgi == 86 || dxgi == 115) return Format{2, 1, false}; + if (in(118, 120)) return Format{2, 1, true}; + if (in(60, 65)) return Format{1, 1, false}; + if (in(70, 72) || in(79, 81)) return Format{8, 4, false}; + if (in(73, 78) || in(82, 84) || in(94, 99)) return Format{16, 4, false}; + return std::nullopt; +} + +// A texture as the console allocates it: a D3D12-style description with a swizzle mode. +struct TextureDesc { + Dimension dimension = Dimension::tex2d; + uint32_t width = 1, height = 1; // in texels + uint32_t depth_or_array = 1; // depth of a 3D texture, else the array size + uint32_t mips = 1; // 0: the full chain + uint32_t format = 0; // DXGI format number + uint32_t samples = 1; + uint32_t swizzle = kLinear; +}; + +struct Plane { + uint64_t offset = 0; // from the start of the texture + bool stencil = false; + Layout layout; +}; + +// Every data plane of a texture (depth, then stencil), placed one after the other. No compression metadata planes +// (HTILE, CMASK, FMASK, DCC): the console adds them to render targets and depth buffers unless the description +// denies them, so those are smaller here than on the console; the host GPU renders them, so nothing reads that +// memory. +struct Texture { + std::vector planes; + uint64_t size = 0; + uint64_t alignment = 0; + + static std::optional make(const TextureDesc& desc) { + const auto f = format(desc.format); + if (!f) return std::nullopt; + const uint32_t depth3d = desc.dimension == Dimension::tex3d ? desc.depth_or_array : 1; + const uint32_t mips = + desc.mips ? desc.mips + : 32u - static_cast(std::countl_zero( + std::max({desc.width, desc.height, depth3d, 1u}))); + const auto plane = [&](uint32_t bytes) { + Desc d; + d.dimension = desc.dimension; + d.width = desc.width; + d.height = desc.height; + d.depth = desc.depth_or_array; + d.mips = mips; + d.element_bytes = bytes; + d.block = f->block; + d.samples = std::max(desc.samples, 1u); + d.swizzle = desc.swizzle; + return d; + }; + Texture t; + auto main = Layout::make(plane(f->bytes)); + if (!main) return std::nullopt; + t.planes.push_back({0, false, std::move(*main)}); + if (f->stencil) { + auto s = Layout::make(plane(1)); + if (!s) return std::nullopt; + const uint64_t a = s->alignment; + const uint64_t offset = (t.planes[0].layout.size + a - 1) / a * a; + t.planes.push_back({offset, true, std::move(*s)}); + } + const Plane& last = t.planes.back(); + t.size = last.offset + last.layout.size; + for (const Plane& p : t.planes) t.alignment = std::max(t.alignment, p.layout.alignment); + return t; + } +}; + +} // namespace leonida::console_texture diff --git a/runtime/src/depth24_fragment.h b/runtime/src/depth24_fragment.h index 10f0dada87..d32f975b26 100644 --- a/runtime/src/depth24_fragment.h +++ b/runtime/src/depth24_fragment.h @@ -37,12 +37,13 @@ struct Depth24Bias { int constant = 0; // D3D12_RASTERIZER_DESC::DepthBias float slope = 0.0f; // SlopeScaledDepthBias float clamp = 0.0f; // DepthBiasClamp: > 0 caps the bias, < 0 floors it, 0 leaves it + float levels = 16777215.0f; bool any() const { return constant != 0 || slope != 0.0f; } }; // D3D's constant term in float: (float)DepthBias * r, with r the float nearest 1 / (2^24 - 1). -inline float depth24_bias_constant(int bias) { - return float(bias) * float(1.0 / 16777215.0); +inline float depth24_bias_constant(int bias, float levels=16777215.0f) { + return float(bias) * float(1.0 / double(levels)); } namespace spirv24 { @@ -141,7 +142,7 @@ class Module { // The edit, on a parsed module. Globals are collected first and spliced in at their section's end. class Patch { public: - Patch(Module& m, std::uint32_t entry) : m_(m), entry_(entry) { + Patch(Module& m, std::uint32_t entry, float levels) : m_(m), entry_(entry), levels_(levels) { // Copies: apply() moves the module's instructions while the code at returns still looks types up. for (const Inst& i : m.insts()) { if (opcode(i) == op_function) break; @@ -185,7 +186,7 @@ class Patch { void prime_quantise() { t_bool(); glsl(); - for (float f : {16777215.0f, 0.0f}) f32(f); + for (float f : {levels_, 0.0f}) f32(f); for (std::uint32_t u : {0x3f800000u, 0xffffffu, 0x7f800000u, 0u, 23u, 1u, 80u}) u32(u); } std::uint32_t f32(float f) { return constant(t_float(), bits(f)); } @@ -248,11 +249,11 @@ class Patch { std::uint32_t quantise(std::vector& code, std::uint32_t z) { const std::uint32_t tf = t_float(), tu = t_uint(), tb = t_bool(); const std::uint32_t b = emit(code, op_bitcast, tu, {z}); - const std::uint32_t product = emit(code, op_f_mul, tf, {z, f32(16777215.0f)}); + const std::uint32_t product = emit(code, op_f_mul, tf, {z, f32(levels_)}); const std::uint32_t rounded = ext(code, tf, glsl_round_even, {product}); // Clamped before the conversion so an out-of-range float never reaches OpConvertFToU (undefined there). const std::uint32_t safe = ext(code, tf, glsl_fmin, {ext(code, tf, glsl_fmax, {rounded, f32(0.0f)}), - f32(16777215.0f)}); + f32(levels_)}); const std::uint32_t code_mid = emit(code, op_convert_f_to_u, tu, {safe}); const std::uint32_t at_least_one = emit(code, op_u_greater_than_equal, tb, {b, u32(0x3f800000u)}); const std::uint32_t code_hi = emit(code, op_select, tu, {at_least_one, u32(0xffffffu), code_mid}); @@ -327,6 +328,7 @@ class Patch { } private: + float levels_; Module& m_; std::uint32_t entry_; std::vector existing_; @@ -369,7 +371,7 @@ inline std::vector depth24_patch_fragment(const std::vector depth24_patch_fragment(const std::vector 0.0f) amount = p.ext(entry_code, tf, glsl_fmin, {amount, p.f32(bias.clamp)}); if (bias.clamp < 0.0f) amount = p.ext(entry_code, tf, glsl_fmax, {amount, p.f32(bias.clamp)}); z = p.emit(entry_code, op_f_add, tf, {z, amount}); diff --git a/runtime/src/frame_pacer.h b/runtime/src/frame_pacer.h index 5de8e9b79d..6e14c60d5d 100644 --- a/runtime/src/frame_pacer.h +++ b/runtime/src/frame_pacer.h @@ -106,6 +106,8 @@ class ManualFrameClock final : public FrameClock { // Provisional definitions of ours: the real constants and layouts of the console API are unmeasured. inline constexpr std::uint32_t frame_event_origin = 0; +// WaitFrameEventX flag 2 with timeout 0 is the retail title's poll for the current token, which it asserts succeeds. +inline constexpr std::uint32_t wait_flag_current_token = 0x2; // Statistics types (bit mask). Interval and render entries are never produced here. inline constexpr std::uint32_t stat_frame_interval = 0x01; inline constexpr std::uint32_t stat_frame_event = 0x02; @@ -216,9 +218,9 @@ class FramePacer { // alone then. invalid_state when nothing is registered, the pacer is suspended, or one of those happens while waiting. std::int32_t wait_frame_event(std::uint32_t event, std::uint32_t timeout_ms, std::uint32_t flags, std::uint64_t* token) { - (void)flags; if (event != frame_event_origin || !token) return pacer_hr::invalid_arg; std::unique_lock lock(mutex_); + if (flags & wait_flag_current_token) return current_token_locked(token); ++waiters_; const std::int32_t result = wait_locked(lock, timeout_ms, token); if (--waiters_ == 0) cv_.notify_all(); @@ -412,6 +414,25 @@ class FramePacer { } } + // Never blocks: a fresh token for the newest passed origin, with no wait for the next origin or the latency. + std::int32_t current_token_locked(std::uint64_t* token) { + if (shutdown_ || suspended_) return pacer_hr::invalid_state; + *token = tokens_->issue(); + if (!interval_set_ || !armed_) return pacer_hr::ok; + const std::uint64_t now = clock_.now_us(); + retire_locked(now); + const std::uint64_t first = epoch_us_ + offset_us_; + const std::int64_t newest = now >= first ? std::int64_t((now - first) / period_us_) : 0; + last_origin_ = std::max(last_origin_, newest); + Record record; + record.token = *token; + record.origin_us = first + std::uint64_t(last_origin_) * period_us_; + record.due_us = record.origin_us - offset_us_ + period_us_; + records_.push_back(record); + if (records_.size() > 64) records_.pop_front(); + return pacer_hr::ok; + } + std::int32_t wait_locked(std::unique_lock& lock, std::uint32_t timeout_ms, std::uint64_t* token) { const std::uint64_t start = clock_.now_us(); const std::uint64_t give_up = timeout_ms == infinite_timeout_ms ? no_deadline diff --git a/runtime/src/gfx10_descriptors.h b/runtime/src/gfx10_descriptors.h index e6fc4df6d4..85ea2edfc2 100644 --- a/runtime/src/gfx10_descriptors.h +++ b/runtime/src/gfx10_descriptors.h @@ -146,6 +146,26 @@ inline ImageWords encode(const Image& image) { // TYPE names an image, so these eight dwords are a T# and not a V# followed by something else. inline constexpr bool is_image(const ImageWords& words) { return detail::get(words[3], 28, 4) >= 8; } +// Synthetic volume UAV metadata distinguishes the storage view from SRVs of the same mip, and distinct W +// ranges from one another. Sampled fetches use it because Vulkan only applies slicing to storage views. +// WORD4[31] is reserved on GFX10/GFX103; hardware uses WORD7 for metadata addresses. DEPTH and BASE_ARRAY +// stay unchanged. D3D12 depth is at most 2048, so count - 1 and offset fit 11 bits. +inline constexpr std::uint32_t volume_uav_flag = 0x80000000; +inline constexpr std::uint32_t volume_uav_tag = 0xD7800000; +inline constexpr std::uint32_t volume_uav_tag_mask = 0xff800000; +// RGB9E5 emulation uses R32_UINT storage, not the logical float format in T# word 1. The same tag marks packed +// 1D-family UAVs (without a W range). No ordinary SRV or raw hardware T# has this synthetic metadata. +inline constexpr std::uint32_t packed_uav_flag = 0x00400000; +inline constexpr std::uint32_t volume_uav_word(std::uint32_t offset, std::uint32_t count) { + return volume_uav_tag | ((count - 1) << 11) | offset; +} +inline constexpr bool partial_volume_uav(const ImageWords& words, const Image& image) { + const auto mip_depth = image.depth >> image.first_mip; + return image.type == ImageType::image_3d && (words[4] & volume_uav_flag) && + (words[7] & volume_uav_tag_mask) == volume_uav_tag && + (words[7] & ~packed_uav_flag) != volume_uav_word(0, mip_depth ? mip_depth : 1u); +} + inline constexpr float image_min_lod(const ImageWords& words) { return float(detail::get(words[1], 8, 12)) / 256.0f; } diff --git a/runtime/src/gpu_label_memory.h b/runtime/src/gpu_label_memory.h new file mode 100644 index 0000000000..890aadf7e1 --- /dev/null +++ b/runtime/src/gpu_label_memory.h @@ -0,0 +1,77 @@ +#pragma once +#include +#include +#include +#include +#include + +namespace leonida::label { +struct Region { + std::uintptr_t begin, end, allocation_base; + bool heap; + std::uint64_t generation=1; +}; +struct Target { + std::weak_ptr owner; + std::uintptr_t address = 0; + unsigned bytes = 0; + std::uint64_t generation=0; +}; +struct Write { + Target target; + std::uint64_t value{}; + unsigned clock{}; // 0: supplied value; 1: GPU timestamp; 2: system timestamp +}; +class Memory { + std::mutex mutex_; + std::map> regions_; +public: + void track(std::uintptr_t base,std::uintptr_t bytes,std::uintptr_t allocation_base,bool heap) { + if (!base || !bytes || !allocation_base || bytes>std::numeric_limits::max()-base) return; + const auto end=base+bytes; + std::lock_guard lock(mutex_); + auto previous=regions_.upper_bound(base); + if (!heap && previous!=regions_.begin()) { + --previous; + const auto& r=*previous->second; + if (!r.heap && r.allocation_base==allocation_base && base>=r.begin && end<=r.end) return; + } + regions_[base]=std::make_shared(Region{base,end,allocation_base,heap}); + } + void release_heap(std::uintptr_t base) { + std::lock_guard lock(mutex_);regions_.erase(base); + } + template bool release_pages(std::uintptr_t base,std::uintptr_t bytes,bool entire,Release&& release) { + std::lock_guard lock(mutex_); + if(!release()) return false; + for(auto i=regions_.begin();i!=regions_.end();) { + const auto& r=*i->second; + if(r.heap || (entire ? r.allocation_base!=base : + (!bytes ? r.allocation_base!=base : (base>=r.end || (base=bytes))))) { ++i; continue; } + if(entire || i->second->generation==std::numeric_limits::max()) i=regions_.erase(i); + else { ++i->second->generation; ++i; } + } + return true; + } + Target capture(std::uintptr_t address,unsigned bytes) { + if((bytes!=4 && bytes!=8) || (address&(bytes-1)))return {}; + std::lock_guard lock(mutex_); + auto it=regions_.upper_bound(address); + while(it!=regions_.begin()) { + --it;const auto& r=*it->second; + if(address=bytes) return {it->second,address,bytes,r.generation}; + } + return {}; + } + template bool publish(const Target& target,Store&& store) { + std::lock_guard lock(mutex_); + const auto region=target.owner.lock(); + if(!region || target.generation!=region->generation || (target.bytes!=4 && target.bytes!=8) || (target.address&(target.bytes-1)) || + target.addressbegin || target.address>=region->end || region->end-target.addressbegin); + if(it==regions_.end() || it->second!=region) return false; + return store(target.address,target.bytes,region->allocation_base); + } +}; +inline Memory& memory(){static Memory m;return m;} +} // namespace leonida::label diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp index 63bd016e8a..8ea202fa02 100644 --- a/runtime/src/main.cpp +++ b/runtime/src/main.cpp @@ -62,10 +62,40 @@ extern "C" __declspec(allocate(".CRT$XCT")) void(__cdecl* const gta6rt_reserve_t reserve_tls_index0_at_start; #pragma comment(linker, "/INCLUDE:gta6rt_reserve_tls_index0") +// Select the settings used to display the offline first-run UI. Keep explicit caller settings. +bool configure_first_run_ui(const std::filesystem::path& package, std::filesystem::path& overlay) { + const auto set_default = [](const wchar_t* name, const wchar_t* value) { + return GetEnvironmentVariableW(name, nullptr, 0) != 0 || _wputenv_s(name, value) == 0; + }; + const struct { const wchar_t* name; const wchar_t* value; } settings[] = { + {L"LEONIDA_D3D12", L"vulkan"}, {L"LEONIDA_ARENA_MB", L"2048"}, + {L"LEONIDA_GRAPHICS_STAGE_LAYOUT", L"1"}, {L"LEONIDA_PIPELINE_COMPILE", L"on-demand"}, + {L"LEONIDA_GPU_LABELS", L"1"}, {L"LEONIDA_FRAME_PACING", L"1"}, + {L"LEONIDA_LOCAL_SPEECH", L"1"}, {L"LEONIDA_KEYBOARD_PAD", L"always"}, + }; + for (const auto& setting : settings) { + if (!set_default(setting.name, setting.value)) return false; + } + std::wstring executable(32768, L'\0'); + const DWORD length = GetModuleFileNameW(nullptr, executable.data(), static_cast(executable.size())); + if (!length || length >= executable.size()) return false; + executable.resize(length); + const auto state = std::filesystem::path(executable).parent_path() / L"first-run-ui"; + if (overlay.empty()) overlay = state / L"overlay"; + if (!GetEnvironmentVariableW(L"LEONIDA_XMEM_BACKING_DIR", nullptr, 0)) { + std::error_code error; + const auto backing = state / L"xmem"; + std::filesystem::create_directories(backing, error); + if (error || !set_default(L"LEONIDA_XMEM_BACKING_DIR", backing.c_str())) return false; + } + return SetCurrentDirectoryW(package.c_str()) != FALSE; +} + int usage() { std::fprintf(stderr, "usage: gta6rt --dry-run [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace FILE]\n" " gta6rt --init [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace-d3d12] [--trace FILE]\n" + " gta6rt --first-run-ui [--game-dir DIR] [--overlay DIR] [--trace FILE]\n" " gta6rt --run [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace-d3d12] [--trace FILE] [-- game arguments...]\n"); return 2; } @@ -77,7 +107,7 @@ int wmain(int argc, wchar_t** argv) { uint32_t archetype_lookup_rva = 0; // --archetype-lookup RVA[,ARG]: the game's archetype lookup by hash int archetype_lookup_arg = 0; uint32_t view_mode_getter_rva = 0; // --view-mode-getter RVA: the game's view mode of a camera context - bool dry_run = false, init = false, run = false, trace_d3d12 = false; + bool dry_run = false, init = false, run = false, trace_d3d12 = false, first_run_ui = false; std::vector game_args; // wide: path::string() throws on a character the code page lacks (RT-84) std::wstring trace_file; for (int i = 1; i < argc; ++i) { @@ -88,6 +118,7 @@ int wmain(int argc, wchar_t** argv) { } if (a == L"--dry-run") dry_run = true; else if (a == L"--init") init = true; + else if (a == L"--first-run-ui") first_run_ui = true; else if (a == L"--run") run = true; else if (a == L"--trace-d3d12") trace_d3d12 = true; else if (a == L"--trace" && i + 1 < argc) trace_file = argv[++i]; @@ -114,7 +145,8 @@ int wmain(int argc, wchar_t** argv) { } if (image.empty()) return usage(); // Exactly one mode: --dry-run --run would otherwise initialise the modules and call the entry point. - if (dry_run + init + run != 1) return usage(); + if (dry_run + init + run + first_run_ui != 1) return usage(); + run = run || first_run_ui; // The game runs AVX code from its TLS callbacks on; without AVX that is a bare 0xC000001D (src/host_cpu.h). if ((init || run) && !rt::host_cpu::check_skipped()) if (const auto missing = rt::host_cpu::missing_host_features(); !missing.empty()) { @@ -129,6 +161,11 @@ int wmain(int argc, wchar_t** argv) { std::filesystem::path a = std::filesystem::absolute(p, ec); return ec ? p : a; }; + if (first_run_ui) { + image = absolute_or_same(image); + if (!mods_dir.empty()) mods_dir = absolute_or_same(mods_dir); + if (!trace_file.empty()) trace_file = absolute_or_same(trace_file).wstring(); + } game_dir = game_dir.empty() ? absolute_or_same(image).parent_path() : absolute_or_same(game_dir); if (!overlay_dir.empty()) overlay_dir = absolute_or_same(overlay_dir); // LEONIDA_SHADERS too: the D3D12 device reads it at the title's first pipeline state, after it may have moved. @@ -145,6 +182,10 @@ int wmain(int argc, wchar_t** argv) { if (!rt::base_reservation::inherited()) if (const auto range = rt::base_reservation::needed(image)) return rt::base_reservation::relaunch(*range); // GAME: paths read under --game-dir; whatever a title writes lands in the overlay, never in the package. + if (first_run_ui && !configure_first_run_ui(game_dir, overlay_dir)) { + std::fprintf(stderr, "cannot initialize the first-run UI paths or graphics settings\n"); + return 1; + } if (overlay_dir.empty()) overlay_dir = game_dir / "overlay"; rt::fs::configure(game_dir, overlay_dir); // Mods (docs/modding.md): \mods unless --mods names another. Loaded and reported here; @@ -178,6 +219,7 @@ int wmain(int argc, wchar_t** argv) { rt::d3d12_trace::set_enabled(trace_d3d12); // Slot 133 imports the title's pages; xmem commits them on first touch, so they are committed first. rt::d3d12_xs::set_placed_at_va_pages_hook(&rt::xmem::commit_physical_range); + rt::d3d12_xs::set_texture_page_provider(&rt::xmem::pin_mapped_data); if (int trace_error = 0; !trace_file.empty() && !rt::startup_trace::open(trace_file.c_str(), &trace_error)) { std::fprintf(stderr, trace_error == EEXIST ? "error: the trace file already exists; --trace only creates a new file\n" : "error: cannot create the trace file\n"); diff --git a/runtime/src/native_pso.h b/runtime/src/native_pso.h new file mode 100644 index 0000000000..88a260ca87 --- /dev/null +++ b/runtime/src/native_pso.h @@ -0,0 +1,332 @@ +#pragma once + +// The description Xbox device slot 57 receives (native graphics pipelines) and how its stages find the game's own +// shader containers. Standard library only, so the parsing is tested on every platform. +// +// Layout measured by LooperSalty on 1.0.2.1 and implemented by enx in 5c175db90: 0x108 bytes, the root +// signature at +0x00, pairs at +0x08 and +0x18, then seven blocks {code, size, records, size} at +0x28 + k * 0x20. +// Measured by KkelebekK: pair 0 is state blob A (380-388 bytes: blend, raster, +// depth, not decoded), pair 1 is state blob B (80-188 bytes: formats and input layout, decode_state_b), and each +// stage's records blob carries the source container's HASH digest after its 0x43 word (docs/fspx.md, kind 7). +// The block index is not trusted as the stage: the stage comes from the translator's index entry of the container. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace leonida::native_pso { + +struct Pair { + const void* data; + std::uint64_t size; +}; + +struct StageBlock { + Pair code; // +0x00: the stage's native program + Pair records; // +0x10: kind-7 style records holding the container's HASH digest +}; + +inline constexpr std::size_t kStageBlocks = 7; + +struct GraphicsDesc { + const void* root_signature; // +0x00 + Pair state_a; // +0x08 + Pair state_b; // +0x18 + StageBlock stages[kStageBlocks]; // +0x28 +}; + +static_assert(sizeof(Pair) == 0x10 && sizeof(StageBlock) == 0x20, "pairs are {pointer, u64 size}"); +static_assert(offsetof(GraphicsDesc, state_a) == 0x08 && offsetof(GraphicsDesc, state_b) == 0x18); +static_assert(offsetof(GraphicsDesc, stages) == 0x28 && sizeof(GraphicsDesc) == 0x108, + "the slot-57 description has a 0x108-byte prefix"); + +// Far above the largest blob measured (a few KiB), and small enough for 32-bit offsets inside one. +inline constexpr std::uint64_t kPairLimit = 16u << 20; + +// The size, not the pointer, determines whether a pair is absent. +enum class PairState { absent, present, malformed }; + +// A table entry with size 0 is absent whatever its pointer (the title passes base + offset, measured on 1.0.2.1). +inline PairState pair_state(const Pair& p) { + if (!p.size) return PairState::absent; + if (!p.data || p.size > kPairLimit) return PairState::malformed; + return PairState::present; +} + +inline std::span bytes(const Pair& p) { + if (pair_state(p) != PairState::present) return {}; + return {static_cast(p.data), static_cast(p.size)}; +} + +inline std::uint32_t read_u32(std::span b, std::size_t at) { + std::uint32_t v = 0; + if (at + 4 <= b.size()) std::memcpy(&v, b.data() + at, 4); + return v; +} + +struct InputElement { + std::string name; + std::uint32_t semantic_index = 0; + std::uint32_t format = 0; + std::uint32_t input_slot = 0; + std::uint32_t aligned_byte_offset = 0; + std::uint32_t classification = 0; + std::uint32_t step_rate = 0; +}; + +// State blob B. The u32 field widths after each name are a hypothesis that fits the +// measured sizes: 0x50 bytes with no element, and 188 bytes with POSITION, COLOR and TEXCOORD. +struct FixedState { + std::array rtv_formats{}; // +0x10, DXGI_FORMAT values + std::uint32_t sample_mask = 0; // +0x1c + std::uint8_t dsv_format = 0; // +0x24 + std::uint8_t rt_count = 0; // +0x25 + std::uint8_t topology_type = 0; // +0x26, low nibble + std::uint8_t sample_count = 1; // +0x28 + std::vector elements; // count at +0x4c, packed from +0x50 +}; + +inline constexpr std::size_t kStateBHeader = 0x50; +inline constexpr std::uint32_t kMaxInputElements = 32; // D3D12_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT +inline constexpr std::uint32_t kMaxSemanticName = 256; + +// Empty for a blob that is too short, names more than 8 targets, a topology type past PATCH (4), or an element +// list that runs past the blob or has a malformed name. Bytes after the last element are allowed. +inline std::optional decode_state_b(std::span b, const char** why = nullptr) { + const auto fail = [&](const char* reason) { + if (why) *why = reason; + return std::nullopt; + }; + if (b.size() < kStateBHeader) return fail("blob B shorter than its header"); + FixedState s; + std::memcpy(s.rtv_formats.data(), b.data() + 0x10, 8); + s.sample_mask = read_u32(b, 0x1c); + s.dsv_format = b[0x24]; + s.rt_count = b[0x25]; + s.topology_type = b[0x26] & 0x0f; + s.sample_count = b[0x28] ? b[0x28] : 1; + if (s.rt_count > 8) return fail("blob B render target count over 8"); + if (s.topology_type > 4) return fail("blob B topology type over 4"); + const std::uint32_t count = read_u32(b, 0x4c); + if (count > kMaxInputElements) return fail("blob B input element count over 32"); + std::size_t at = kStateBHeader; + for (std::uint32_t i = 0; i < count; ++i) { + if (at + 4 > b.size()) return fail("blob B input element past the end"); + const std::uint32_t length = read_u32(b, at); + at += 4; + if (length < 2 || length > kMaxSemanticName || at + length + 24 > b.size()) + return fail("blob B semantic name length out of range"); + const auto* name = reinterpret_cast(b.data() + at); + if (name[length - 1] != '\0' || std::memchr(name, '\0', length - 1)) + return fail("blob B semantic name not one NUL-terminated string"); + InputElement e; + e.name.assign(name, length - 1); + at += length; + e.semantic_index = read_u32(b, at); + e.format = read_u32(b, at + 4); + e.input_slot = read_u32(b, at + 8); + e.aligned_byte_offset = read_u32(b, at + 12); + e.classification = read_u32(b, at + 16); + e.step_rate = read_u32(b, at + 20); + at += 24; + s.elements.push_back(std::move(e)); + } + return s; +} + +using Digest = std::array; + +// Every 16 bytes that follow a 4-aligned 0x43 word, without duplicates. A register number can also read 0x43, so +// all candidates are returned and the map decides which one names a container. +inline std::vector record_digests(std::span records) { + std::vector out; + std::set seen; + for (std::size_t at = 0; at + 4 + 16 <= records.size(); at += 4) { + if (read_u32(records, at) != 0x43) continue; + Digest d; + std::memcpy(d.data(), records.data() + at + 4, 16); + if (seen.insert(d).second) out.push_back(d); + } + return out; +} + +inline std::string hex(const Digest& d) { + static constexpr char kHex[] = "0123456789abcdef"; + std::string s; + for (const std::uint8_t b : d) { + s += kHex[b >> 4]; + s += kHex[b & 15]; + } + return s; +} + +inline std::optional parse_digest(std::string_view text) { + if (text.size() != 32) return std::nullopt; + Digest d{}; + for (std::size_t i = 0; i < 32; ++i) { + const char c = text[i]; + int v = c >= '0' && c <= '9' ? c - '0' : c >= 'a' && c <= 'f' ? c - 'a' + 10 : -1; + if (v < 0) return std::nullopt; + d[i / 2] = static_cast(d[i / 2] << 4 | v); + } + return d; +} + +struct ShaderRef { + Digest digest; + std::string stage; // the translator's stage: "vs", "ps", "gs", "ms", "cs" + std::string path; // the container, relative to the map file's folder, '/' separated +}; + +// native_hashes.txt, written by tools/native_pso_hashes.py next to the translator's index.json: a first line +// "# native_pso_hashes 1", then one "<32 hex digest>\t\t" line per digest. +class HashMap { +public: + static constexpr std::string_view kHeader = "# native_pso_hashes 1"; + + bool parse(std::string_view text, std::string* error = nullptr) { + const auto fail = [&](std::string why) { + if (error) *error = std::move(why); + map_.clear(); + return false; + }; + map_.clear(); + std::size_t line_no = 0; + bool header = false; + while (!text.empty()) { + const std::size_t end = text.find('\n'); + std::string_view line = text.substr(0, end); + text = end == std::string_view::npos ? std::string_view{} : text.substr(end + 1); + ++line_no; + if (!line.empty() && line.back() == '\r') line.remove_suffix(1); + if (line_no == 1) { + if (line != kHeader) return fail("native_hashes.txt: unknown header"); + header = true; + continue; + } + if (line.empty() || line.front() == '#') continue; + const std::size_t t1 = line.find('\t'); + const std::size_t t2 = t1 == std::string_view::npos ? t1 : line.find('\t', t1 + 1); + if (t2 == std::string_view::npos || t2 + 1 >= line.size()) + return fail("native_hashes.txt line " + std::to_string(line_no) + ": expected three fields"); + const auto digest = parse_digest(line.substr(0, t1)); + const std::string_view stage = line.substr(t1 + 1, t2 - t1 - 1); + if (!digest || stage.empty()) + return fail("native_hashes.txt line " + std::to_string(line_no) + ": bad digest or stage"); + const std::string_view path = line.substr(t2 + 1); + const auto [it, inserted] = map_.try_emplace(*digest, ShaderRef{*digest, std::string(stage), std::string(path)}); + if (!inserted && (it->second.stage != stage || it->second.path != path)) + return fail("native_hashes.txt line " + std::to_string(line_no) + ": conflicting digest"); + } + if (!header) return fail("native_hashes.txt is empty"); + return true; + } + + const ShaderRef* find(const Digest& d) const { + const auto it = map_.find(d); + return it == map_.end() ? nullptr : &it->second; + } + + std::size_t size() const { return map_.size(); } + +private: + std::map map_; +}; + +struct PlannedStage { + std::size_t block = 0; + const ShaderRef* shader = nullptr; +}; + +enum class PlanStatus { + ok, + malformed, // a pair is malformed or blob B does not decode + missing, // a stage has no records, or its digest names no translated container + ambiguous, // a stage's records name two different containers + unsupported, // a stage kind this path does not build (hs, ds, cs), two of one kind, or no VS/MS +}; + +struct Plan { + PlanStatus status = PlanStatus::malformed; + FixedState state; + std::vector stages; // in block order + std::size_t failed_block = 0; // for missing/ambiguous/unsupported/malformed blocks + const char* reason = ""; // why a description is malformed + bool mesh = false; // an MS stage: the pipeline goes through a pipeline state stream + + const ShaderRef* stage(std::string_view name) const { + for (const PlannedStage& s : stages) + if (s.shader->stage == name) return s.shader; + return nullptr; + } +}; + +inline Plan plan(const GraphicsDesc& desc, const HashMap& map) { + Plan p; + if (pair_state(desc.state_a) == PairState::malformed) { + p.reason = "blob A pair malformed"; + return p; + } + if (pair_state(desc.state_b) != PairState::present) { + p.reason = "blob B pair absent or malformed"; + return p; + } + auto state = decode_state_b(bytes(desc.state_b), &p.reason); + if (!state) return p; + p.state = std::move(*state); + for (std::size_t k = 0; k < kStageBlocks; ++k) { + const StageBlock& block = desc.stages[k]; + const PairState code = pair_state(block.code), records = pair_state(block.records); + p.failed_block = k; + if (code == PairState::malformed || records == PairState::malformed) { + p.reason = "a stage pair malformed"; + return p; + } + if (code == PairState::absent && records == PairState::absent) continue; + if (records != PairState::present) { // code without records: nothing names its container + p.status = PlanStatus::missing; + return p; + } + const ShaderRef* found = nullptr; + for (const Digest& d : record_digests(bytes(block.records))) { + const ShaderRef* ref = map.find(d); + if (!ref) continue; + if (found && found != ref) { + p.status = PlanStatus::ambiguous; + p.failed_block = k; + return p; + } + found = ref; + } + p.failed_block = k; + if (!found) { + p.status = PlanStatus::missing; + return p; + } + const std::string& s = found->stage; + if (!(s == "vs" || s == "ps" || s == "gs" || s == "ms") || p.stage(s)) { + p.status = PlanStatus::unsupported; + return p; + } + p.stages.push_back({k, found}); + } + const bool vs = p.stage("vs"), ms = p.stage("ms"); + if (vs == ms || (ms && p.stage("gs"))) { + p.status = PlanStatus::unsupported; + return p; + } + p.mesh = ms; + p.status = PlanStatus::ok; + return p; +} + +} // namespace leonida::native_pso diff --git a/runtime/src/queue_families.h b/runtime/src/queue_families.h index 3148d0ad11..51a8c40c18 100644 --- a/runtime/src/queue_families.h +++ b/runtime/src/queue_families.h @@ -12,6 +12,16 @@ namespace leonida { +// The device's distinct family indices. An object used on more than one family keeps its contents +// across fenced D3D12 queue handoffs without explicit Vulkan ownership transfers. +template +void share_across_queue_families(CreateInfo& create, std::span families) { + if (families.size() < 2) return; + create.sharingMode = VK_SHARING_MODE_CONCURRENT; + create.queueFamilyIndexCount = static_cast(families.size()); + create.pQueueFamilyIndices = families.data(); +} + // Queue families for D3D12's three queue types. Direct needs graphics. Compute prefers a family with compute and no // graphics (async compute), copy one with transfer and neither (a DMA engine); each falls back to a more capable // family, ending at the graphics one. A dedicated copy family is only used when its image transfer granularity is diff --git a/runtime/src/rect_list_geometry.h b/runtime/src/rect_list_geometry.h index 0049394cf4..e90173095d 100644 --- a/runtime/src/rect_list_geometry.h +++ b/runtime/src/rect_list_geometry.h @@ -2,8 +2,10 @@ // Console rectangle lists on Vulkan, which has no such primitive. // -// A rectangle is three corners (v1, v2, v3) and the hardware makes the fourth, v2 + v3 - v1, for the position and for -// every interpolant, after the vertex stage. A list topology of rectangles (D3D_PRIMITIVE_TOPOLOGY 17) and a pipeline +// A rectangle is three corners and the hardware makes the fourth, a + b - p (p the right-angle corner, a and b its +// neighbours), for the position and for every interpolant, after the vertex stage. Which vertex is p is not fixed: +// the retail boot's full-screen rectangle has it at the second vertex. The stage picks the vertex opposite the longest +// screen-space edge, and the first vertex on a tie. A list topology of rectangles (D3D_PRIMITIVE_TOPOLOGY 17) and a pipeline // whose topology type is 19 are console-only. The fact comes from xvalkyrie (GPL-3.0, commit 53af7df77c10, notes in // its backlog); no code is taken from it. // @@ -11,11 +13,15 @@ // the vertex stage: a pre-pass over the vertex buffers is wrong for any shader that is not linear in its inputs (and // the translated vertex shaders fetch by V# themselves, so there is no vertex buffer to expand). The pipeline gets a // small geometry stage instead, built here from the vertex shader's own SPIR-V: it takes the triangle (v1, v2, v3) -// the list draws and emits the parallelogram as the two triangles (v1, v2, v4) and (v1, v4, v3), with the winding of -// (v1, v2, v3). Both start at v1, so a flat input (taken from a triangle's first vertex) is v1's over the whole +// the list draws and emits the parallelogram as the two triangles (p, a, f) and (p, f, b), with the winding of +// (v1, v2, v3). Both start at p, so a flat input (taken from a triangle's first vertex) is p's over the whole // rectangle. Every Location output of the vertex stage is a vec4 float in the translator's output (rdna2spirv.py), // and so is the stage's Position; the generated stage reads and writes exactly those. // +// The edges are measured in normalized device coordinates, not pixels (the stage does not know the viewport). For the +// usual axis-aligned rectangle that is exact; a rotated rectangle drawn into a very non-square viewport can pick a +// different corner than the pixel-space right angle. +// // Not covered, and refused with a reason: a vertex stage that writes ClipDistance, CullDistance, Layer or // ViewportIndex, or a Location output that is not a vec4 float. // @@ -24,7 +30,6 @@ #include #include #include -#include #include #include #include @@ -45,7 +50,9 @@ inline std::vector rect_list_geometry(const std::vector rect_list_geometry(const std::vector rect_list_geometry(const std::vector rect_list_geometry(const std::vector corners; + std::vector> loaded; const std::uint32_t cs[3] = {c0, c1, c2}; for (const Var& v : vars) { - Corners c{}; + std::array three{}; for (int k = 0; k < 3; ++k) { const std::uint32_t ptr = id(); - c.v[k] = id(); + three[k] = id(); emit(body, op_access_chain, {t_pin_v4, ptr, v.in, cs[k]}); - emit(body, op_load, {t_v4, c.v[k], ptr}); + emit(body, op_load, {t_v4, three[k], ptr}); } + loaded.push_back(three); + } + // Which vertex is the right angle: the one opposite the longest edge, measured on screen (position.xy / position.w; + // a right triangle's longest edge is its hypotenuse). Ties go to the first vertex, which keeps the plain + // "v1 is the corner" order for every rectangle whose right angle is there. A triangle that is not a right + // triangle gets the same rule, so the choice is at least consistent. + std::uint32_t screen[3][2]; + for (int k = 0; k < 3; ++k) { + const std::uint32_t x = id(), y = id(), w = id(); + emit(body, op_composite_extract, {t_float, x, loaded[0][k], 0}); + emit(body, op_composite_extract, {t_float, y, loaded[0][k], 1}); + emit(body, op_composite_extract, {t_float, w, loaded[0][k], 3}); + screen[k][0] = id(); + screen[k][1] = id(); + emit(body, op_fdiv, {t_float, screen[k][0], x, w}); + emit(body, op_fdiv, {t_float, screen[k][1], y, w}); + } + const auto squared_edge = [&](int a, int b) { + const std::uint32_t dx = id(), dy = id(), xx = id(), yy = id(), sum = id(); + emit(body, op_fsub, {t_float, dx, screen[a][0], screen[b][0]}); + emit(body, op_fsub, {t_float, dy, screen[a][1], screen[b][1]}); + emit(body, op_fmul, {t_float, xx, dx, dx}); + emit(body, op_fmul, {t_float, yy, dy, dy}); + emit(body, op_fadd, {t_float, sum, xx, yy}); + return sum; + }; + const std::uint32_t e01 = squared_edge(0, 1), e02 = squared_edge(0, 2), e12 = squared_edge(1, 2); + const std::uint32_t g12_01 = id(), g12_02 = id(), at_first = id(), g02_01 = id(), not_first = id(), at_second = id(); + emit(body, op_ford_greater_equal, {t_bool, g12_01, e12, e01}); + emit(body, op_ford_greater_equal, {t_bool, g12_02, e12, e02}); + emit(body, op_logical_and, {t_bool, at_first, g12_01, g12_02}); // the edge opposite v1 is longest: v1 is the corner + emit(body, op_ford_greater_equal, {t_bool, g02_01, e02, e01}); + emit(body, op_logical_not, {t_bool, not_first, at_first}); + emit(body, op_logical_and, {t_bool, at_second, not_first, g02_01}); // else the edge opposite v2: v2; else v3 + const std::uint32_t first4 = id(), second4 = id(); + emit(body, op_composite_construct, {t_bool4, first4, at_first, at_first, at_first, at_first}); + emit(body, op_composite_construct, {t_bool4, second4, at_second, at_second, at_second, at_second}); + // The corner p, its neighbours a = next and b = the one after (the same cyclic order as v1 v2 v3, so the winding + // is the drawn triangle's), and the fourth corner a + b - p, for the position and for every interpolant alike. + for (const auto& three : loaded) { + Corners c{}; + const auto pick = [&](std::uint32_t first, std::uint32_t second, std::uint32_t third) { + const std::uint32_t inner = id(), outer = id(); + emit(body, op_select, {t_v4, inner, second4, second, third}); + emit(body, op_select, {t_v4, outer, first4, first, inner}); + return outer; + }; + c.v[0] = pick(three[0], three[1], three[2]); + c.v[1] = pick(three[1], three[2], three[0]); + c.v[2] = pick(three[2], three[0], three[1]); const std::uint32_t sum = id(), diff = id(); - // The fourth corner is v2 + v3 - v1, the rule d3d12_rect_list tests. OPEN QUESTION, opt-in with - // LEONIDA_RECT_FOURTH=v1v3: the retail title's full-screen rectangle draws were measured with corners - // top-left, bottom-left, bottom-right, where only v1 + v3 - v2 covers the target (see the pull request). - static const bool local_old_rule = [] { const char* e = std::getenv("LEONIDA_RECT_FOURTH"); return !(e && *e == 'v'); }(); - if (local_old_rule) { - emit(body, op_fadd, {t_v4, sum, c.v[1], c.v[2]}); - emit(body, op_fsub, {t_v4, diff, sum, c.v[0]}); - } else { - emit(body, op_fadd, {t_v4, sum, c.v[0], c.v[2]}); - emit(body, op_fsub, {t_v4, diff, sum, c.v[1]}); - } + emit(body, op_fadd, {t_v4, sum, c.v[1], c.v[2]}); + emit(body, op_fsub, {t_v4, diff, sum, c.v[0]}); c.v[3] = diff; corners.push_back(c); } - // Two triangles, (v1, v2, v4) and (v1, v4, v3): the diagonal is v1 to v4, so both start at v1 and a flat input - // (which Vulkan takes from a triangle's first vertex) is v1's over the whole rectangle. The attributes are + // Two triangles, (p, a, f) and (p, f, b): the diagonal is p to f, so both start at p and a flat input + // (which Vulkan takes from a triangle's first vertex) is p's over the whole rectangle. The attributes are // affine over the parallelogram, so the split does not change any interpolated value. - static const bool local_old_split = [] { const char* e = std::getenv("LEONIDA_RECT_FOURTH"); return !(e && *e == 'v'); }(); - const int triangles_old[2][3] = {{0, 1, 3}, {0, 3, 2}}; - const int triangles_new[2][3] = {{0, 1, 2}, {0, 2, 3}}; // diagonal v1 to v3, both start at v1 - const auto& triangles = local_old_split ? triangles_old : triangles_new; + const int triangles[2][3] = {{0, 1, 3}, {0, 3, 2}}; for (const auto& triangle : triangles) { for (int k : triangle) { for (std::size_t i = 0; i < vars.size(); ++i) emit(body, op_store, {vars[i].out, corners[i].v[k]}); diff --git a/runtime/src/rgba4_fragment.h b/runtime/src/rgba4_fragment.h new file mode 100644 index 0000000000..b621628482 --- /dev/null +++ b/runtime/src/rgba4_fragment.h @@ -0,0 +1,81 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +namespace leonida::rgba4 { +using Inst=std::vector; +inline Inst instruction(std::uint32_t op,std::initializer_list args) { + Inst w{(std::uint32_t(args.size()+1)<<16)|op};w.insert(w.end(),args);return w; +} +// Quantize only written color outputs at the requested locations. For a wider fallback attachment +// this reproduces four-bit UNORM writes for pipelines whose affected attachments use no blending. +inline bool quantize(Inst& words,unsigned mask) { + if(!mask)return true; + if(words.size()<5 || words[0]!=0x07230203)return false; + std::vector code,declarations; + std::map locations, pointer_type, width, scalar, variables; + unsigned import_id=0,next=words[3],float_type=0; + for(std::size_t at=5;at>16,op=words[at]&65535u; + if(!n || n>words.size()-at)return false; + Inst i(words.begin()+at,words.begin()+at+n);at+=n; + if(op==11 && n>=3) { + const char* s=reinterpret_cast(i.data()+2);const auto bytes=(n-2)*4; + if(bytes>=13 && std::memcmp(s,"GLSL.std.450",13)==0)import_id=i[1]; + } else if(op==71 && n==4 && i[2]==30)locations[i[1]]=i[3]; + else if(op==22 && n==3 && i[2]==32){float_type=i[1];width[i[1]]=1;scalar[i[1]]=i[1];} + else if(op==23 && n==4){width[i[1]]=i[3];scalar[i[1]]=i[2];} + else if(op==32 && n==4 && i[2]==3)pointer_type[i[1]]=i[3]; + else if(op==59 && n>=4 && i[3]==3)variables[i[2]]=i[1]; + code.push_back(std::move(i)); + } + if(!float_type)return false; + std::map outputs; + for(auto [id,ptr]:variables)if(locations.count(id)&&locations[id]<8&&(mask&(1u<> constants; + auto components=[&](unsigned type) -> const std::array& { + auto [it,inserted]=constants.try_emplace(type); + if(!inserted)return it->second; + constexpr std::array vals{0.f,1.f,15.f,1.f/15.f}; + std::array base{}; + for(unsigned j=0;j<4;++j){base[j]=next++;declarations.push_back(instruction(43,{scalar[type],base[j],std::bit_cast(vals[j])}));} + if(width[type]==1){it->second=base;return it->second;} + for(unsigned j=0;j<4;++j){const auto id=next++;Inst c=instruction(44,{type,id});c.resize(3+width[type],base[j]);c[0]=(unsigned(c.size())<<16)|44u;declarations.push_back(std::move(c));it->second[j]=id;} + return it->second; + }; + std::vector rewritten;bool changed=false; + for(auto& i:code) { + const auto op=i[0]&65535u; + if((op==65||op==66||op==83) && i.size()>=4 && outputs.count(i[3]) && pointer_type.count(i[1])) + outputs[i[2]]=pointer_type[i[1]]; + if(op==63 && i.size()>=3 && outputs.count(i[1]))return false; + if(op==62 && i.size()>=3 && outputs.count(i[1])) { + const auto type=outputs[i[1]]; + if(!width.count(type)||width[type]<1||width[type]>4||scalar[type]!=float_type)return false; + const auto& c=components(type); + const auto clamped=next++,scaled=next++,rounded=next++,value=next++; + rewritten.push_back(instruction(12,{type,clamped,import_id,43,i[2],c[0],c[1]})); // GLSL FClamp + rewritten.push_back(instruction(133,{type,scaled,clamped,c[2]})); + rewritten.push_back(instruction(12,{type,rounded,import_id,2,scaled})); // GLSL RoundEven + rewritten.push_back(instruction(133,{type,value,rounded,c[3]}));i[2]=value;changed=true; + } + rewritten.push_back(std::move(i)); + } + if(!changed)return false; + Inst result(words.begin(),words.begin()+5);result[3]=next;bool declared=false; + for(const auto& i:rewritten) { + const auto op=i[0]&65535u; + if(op==14 && add_import){Inst imp=instruction(11,{import_id,0,0,0,0});std::memcpy(imp.data()+2,"GLSL.std.450",13);result.insert(result.end(),imp.begin(),imp.end());} + if(op==54&&!declared){for(const auto& dec:declarations)result.insert(result.end(),dec.begin(),dec.end());declared=true;} + result.insert(result.end(),i.begin(),i.end()); + } + if(!declared)return false;words=std::move(result);return true; +} +} diff --git a/runtime/src/title_va_alias.h b/runtime/src/title_va_alias.h index 829c1d8740..ac1871e17b 100644 --- a/runtime/src/title_va_alias.h +++ b/runtime/src/title_va_alias.h @@ -12,10 +12,9 @@ // submission), or its device address minus heap_base (mod 2^64) when it has its own memory (an imported slot-133 // buffer). Addresses that are not in the title's memory are passed through unchanged. // -// The table is process-wide, like the title's address space. The device behind it registers two hooks: a resolver -// that makes a GPU copy for an address in the title's memory that has none yet, and a scanner that rewrites the -// buffer V#s of a bound descriptor table before a submission. Without hooks the table only translates what was -// added to it, so it is tested without a GPU (title_va_alias_test). +// The table is process-wide, like the title's address space. A resolver makes a GPU copy for an address in the +// title's memory that has none yet. Without it the table only translates previously added ranges. +#include #include #include #include @@ -37,7 +36,6 @@ class TitleVaAliases { // An address in the title's memory: true, with `shader_va` what a shader must be given (the address itself when // no copy could be made). False: not the title's memory (an arena VA, a buffer of the layer's). using Resolver = bool (*)(void* context, std::uint64_t va, std::uint64_t bytes, std::uint64_t& shader_va); - using TableScanner = void (*)(void* context, std::uint64_t table_va, std::uint32_t descriptors); // [title_va, title_va + bytes) is reached as [shader_va, shader_va + bytes). A range that overlaps a live one // replaces it (the title has placed a new buffer over pages it released). False for an empty or wrapping range. @@ -109,19 +107,6 @@ class TitleVaAliases { if (va && shader_va(va) != va) untranslated_[kind].fetch_add(1, std::memory_order_relaxed); } - // Before a submission: the device rewrites the buffer V#s of the `descriptors` slots the root signature declares - // for the table at `table_va` (a console VA in one of its shader-visible CBV/SRV/UAV heaps). - void scan_table(std::uint64_t table_va, std::uint32_t descriptors) { - TableScanner scanner; - void* context; - { - std::lock_guard lock(hook_mutex_); - scanner = scanner_; - context = hook_context_; - } - if (scanner) scanner(context, table_va, descriptors); - } - // The scan's cost, per ExecuteCommandLists that had tables to scan. void note_scan(std::uint64_t nanoseconds) { scans_.fetch_add(1, std::memory_order_relaxed); @@ -189,20 +174,18 @@ class TitleVaAliases { } std::uint64_t pulled() const { return pulled_.load(std::memory_order_relaxed); } - // The first device to register keeps the hooks until it clears them. - void set_hooks(void* context, Resolver resolver, TableScanner scanner) { + // The first device to register keeps the resolver until it clears it. + void set_resolver(void* context, Resolver resolver) { std::lock_guard lock(hook_mutex_); if (hook_context_) return; hook_context_ = context; resolver_ = resolver; - scanner_ = scanner; } - void clear_hooks(void* context) { + void clear_resolver(void* context) { std::lock_guard lock(hook_mutex_); if (hook_context_ != context) return; hook_context_ = nullptr; resolver_ = nullptr; - scanner_ = nullptr; } std::size_t size() const { return count_.load(std::memory_order_acquire); } @@ -230,7 +213,6 @@ class TitleVaAliases { std::mutex hook_mutex_; void* hook_context_ = nullptr; Resolver resolver_ = nullptr; - TableScanner scanner_ = nullptr; void* source_context_ = nullptr; DescriptorSource source_ = nullptr; std::atomic pulled_{0}; diff --git a/runtime/src/vulkan13_features.h b/runtime/src/vulkan13_features.h index ea65caa2d2..8f2dd61f83 100644 --- a/runtime/src/vulkan13_features.h +++ b/runtime/src/vulkan13_features.h @@ -32,6 +32,8 @@ class Vulkan13Features { Vulkan13Features& operator=(const Vulkan13Features&) = delete; bool core = false; // a Vulkan 1.3 device: the features are core + bool pipeline_cache_control = false; + bool enable_pipeline_cache_control = false; bool dynamic_rendering = false; // supported, as a core feature or through VK_KHR_dynamic_rendering bool synchronization2 = false; // supported, as a core feature or through VK_KHR_synchronization2 // Optional 1.3 core features, available through VK_EXT_subgroup_size_control on a 1.2 device. @@ -45,6 +47,7 @@ class Vulkan13Features { void query(VkPhysicalDevice physical, std::uint32_t api_version, PFN_vkGetPhysicalDeviceFeatures2 features2, PFN_vkEnumerateDeviceExtensionProperties enumerate_extensions) { core = api_version >= VK_API_VERSION_1_3; + pipeline_cache_control=false;enable_pipeline_cache_control=false; dynamic_rendering = synchronization2 = subgroup_size_control = compute_full_subgroups = false; extended_dynamic_state = false; if (!features2) return; @@ -53,6 +56,7 @@ class Vulkan13Features { VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &f13}; features2(physical, &query); dynamic_rendering = f13.dynamicRendering == VK_TRUE; + pipeline_cache_control = f13.pipelineCreationCacheControl == VK_TRUE; synchronization2 = f13.synchronization2 == VK_TRUE; subgroup_size_control = f13.subgroupSizeControl == VK_TRUE; compute_full_subgroups = f13.computeFullSubgroups == VK_TRUE; @@ -98,6 +102,7 @@ class Vulkan13Features { // Copies the flags of the device query() chose (a later query() for another candidate overwrites them). void choose(const Vulkan13Features& from) { core = from.core; + pipeline_cache_control=from.pipeline_cache_control;enable_pipeline_cache_control=false; dynamic_rendering = from.dynamic_rendering; synchronization2 = from.synchronization2; subgroup_size_control = from.subgroup_size_control; @@ -111,6 +116,7 @@ class Vulkan13Features { if (core) { enable13_.pNext = chain; enable13_.dynamicRendering = VK_TRUE; + enable13_.pipelineCreationCacheControl = pipeline_cache_control && enable_pipeline_cache_control ? VK_TRUE : VK_FALSE; enable13_.synchronization2 = VK_TRUE; enable13_.subgroupSizeControl = subgroup_size_control ? VK_TRUE : VK_FALSE; enable13_.computeFullSubgroups = compute_full_subgroups ? VK_TRUE : VK_FALSE; diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 4bb6b53e36..566b7ccd48 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -1,4 +1,5 @@ #pragma once +#include "vulkan_gpu_labels.h" // The execution side of the D3D12 layer, without COM: the per-device Vulkan context (resources, layout tracker, // image views), queues that execute command lists, and timeline-semaphore fences. The COM objects in @@ -85,7 +86,7 @@ struct VulkanDeviceFunctions { X(vkCmdClearAttachments) X(vkDeviceWaitIdle) X(vkCreateImage) X(vkDestroyImage) \ X(vkGetImageMemoryRequirements) X(vkBindImageMemory) X(vkCreateBuffer) X(vkDestroyBuffer) \ X(vkGetBufferMemoryRequirements) X(vkBindBufferMemory) X(vkAllocateMemory) X(vkFreeMemory) X(vkMapMemory) \ - X(vkUnmapMemory) X(vkCmdCopyBuffer) X(vkCmdCopyBufferToImage) X(vkCmdCopyImageToBuffer) X(vkCmdCopyImage) \ + X(vkUnmapMemory) X(vkCmdCopyBuffer) X(vkCmdCopyBufferToImage) X(vkCmdCopyImageToBuffer) X(vkCmdCopyImage) X(vkCmdBlitImage) \ X(vkCmdResolveImage) X(vkCmdFillBuffer) X(vkCmdUpdateBuffer) X(vkCreateSampler) X(vkDestroySampler) \ X(vkCmdBeginConditionalRenderingEXT) X(vkCmdEndConditionalRenderingEXT) X(vkCreateQueryPool) \ X(vkDestroyQueryPool) X(vkCmdResetQueryPool) X(vkCmdBeginQuery) X(vkCmdEndQuery) X(vkCmdWriteTimestamp) \ @@ -941,6 +942,7 @@ class VulkanContext { replay_.copy_buffer_to_image = vk.vkCmdCopyBufferToImage; replay_.copy_image_to_buffer = vk.vkCmdCopyImageToBuffer; replay_.copy_image = vk.vkCmdCopyImage; + replay_.blit_image = vk.vkCmdBlitImage; replay_.resolve_image = vk.vkCmdResolveImage; replay_.fill_buffer = vk.vkCmdFillBuffer; replay_.update_buffer = vk.vkCmdUpdateBuffer; @@ -1202,6 +1204,7 @@ class VulkanContext { } { std::lock_guard lock(storage_mutex_); // a buffer destroyed before any submission is not filled + storage_pending_.erase(id); std::erase_if(zero_pending_, [id](const PendingZero& zero) { return zero.id == id; }); } if (img) { @@ -1274,6 +1277,18 @@ class VulkanContext { replay_.zero_size = size; } + struct GeometryUpload { + std::uint64_t source{}, size{}; + VkBuffer buffer{}; + VkDeviceSize offset{}; + std::shared_ptr owner; + }; + using GeometryProvider = std::function; + void set_geometry_provider(GeometryProvider provider) { + std::unique_lock lock(resource_mutex_); + geometry_provider_=std::move(provider); + } + // LOCAL: the copy-in fallback for vertex and index views in title memory (ReplayFunctions::title_memory). void set_title_memory(std::function copy) { std::unique_lock lock(resource_mutex_); @@ -1419,12 +1434,29 @@ class VulkanContext { // written: the device brings the bindless set 0 of the translated shaders up to date there (vulkan_bindless.h) // and records what the set needs first. When it fails, nothing of that call is executed. void set_transfer_only_family(std::uint32_t family) { transfer_only_family_ = family; } + void set_graphics_family(std::uint32_t family) { graphics_family_ = family; } + void set_compute_copy_aspects(std::function check) { + replay_.compute_copy_aspects = std::move(check); + } // `before` is called at the start of every submission of command lists (a held batch: when it is released), // before any lock here is taken: the device re-copies its slot-133 shadow buffers from the title's pages there. // Set once, before the first queue exists. void set_before_execute(std::function before) { before_execute_ = std::move(before); } + // Table VAs are offsets in this device's arena. Install its scanner before creating any queues. + using TableScanner = std::function; + void set_table_scanner(TableScanner scan) { table_scanner_ = std::move(scan); } + void set_cpu_texture_publisher(std::function f) { cpu_texture_publisher_ = std::move(f); } + bool publish_cpu_textures() const { return !cpu_texture_publisher_ || cpu_texture_publisher_(); } + void set_sample_table_resolver(std::function f) { sample_table_resolver_ = std::move(f); } + bool prepare_sample_table(std::uint64_t address, std::uint32_t count) const { + return !sample_table_resolver_ || sample_table_resolver_(address,count); + } + void scan_table(std::uint64_t va, std::uint32_t descriptors) const { + if (table_scanner_) table_scanner_(va, descriptors); + } + void set_bindless_prepare(std::function prepare) { std::unique_lock lock(resource_mutex_); bindless_prepare_ = std::move(prepare); @@ -1448,9 +1480,10 @@ class VulkanContext { // Copies the replay stages through a buffer (depth <-> colour, vulkan_replay.h) take device-local scratch from // `allocate`. Without this such a copy is refused as unsupported. - void enable_copy_scratch(PFN_vkGetDeviceProcAddr get, ScratchBuffers::Allocate allocate) { + void enable_copy_scratch(PFN_vkGetDeviceProcAddr get, ScratchBuffers::Allocate allocate, + std::vector families = {}) { std::unique_lock lock(resource_mutex_); - scratch_ = std::make_unique(get, device_, std::move(allocate)); + scratch_ = std::make_unique(get, device_, std::move(allocate), std::move(families)); if (!scratch_->loaded()) scratch_.reset(); } @@ -1611,7 +1644,11 @@ class VulkanContext { const ResourceBinding* resolve(ResourceId id) const { const auto it = resources_.find(id); - return it == resources_.end() ? nullptr : &it->second; + if (it == resources_.end()) return nullptr; + const auto& binding = it->second; + // The caller holds resource_mutex_, so the registered owner's lifetime includes this bind. + if (binding.ensure_residency && !binding.ensure_residency(binding.residency_owner)) return nullptr; + return &binding; } // Called from prepare; protected by views_mutex_ so concurrent shared_lock readers are safe. @@ -1739,6 +1776,10 @@ class VulkanContext { resolve_passes_; std::map, VkFramebuffer> resolve_framebuffers_; std::function before_execute_; + TableScanner table_scanner_; + GeometryProvider geometry_provider_; + std::function sample_table_resolver_; + std::function cpu_texture_publisher_; std::function bindless_prepare_; std::function bindless_current_; bool bindless_upload_pending_ = false; // tracker_mutex_ @@ -1760,6 +1801,7 @@ class VulkanContext { std::unique_ptr counted_dispatch_; std::uint32_t predicate_family_ = UINT32_MAX; std::uint32_t transfer_only_family_ = UINT32_MAX; + std::uint32_t graphics_family_ = UINT32_MAX; DebugLabelFunctions labels_; }; #ifdef _MSC_VER @@ -2345,6 +2387,23 @@ class VulkanQueue : private QueueHolds::Holder { // use only the first lists.size() entries, so stale entries are never prepared, queried or emitted. if (prepared.size() < lists.size()) prepared.resize(lists.size()); ReplayFunctions replay = context_.replay_; + std::vector geometry; + if (context_.geometry_provider_) { + replay.title_memory = [&](std::uint64_t va, std::uint64_t bytes, VkBuffer& buffer, VkDeviceSize& offset) { + if (!va || !bytes || bytes>UINT64_MAX-va) return false; + for (const auto& upload : geometry) { + if (va < upload.source || va-upload.source > upload.size || bytes > upload.size-(va-upload.source)) continue; + buffer=upload.buffer; offset=upload.offset+(va-upload.source); + return true; + } + VulkanContext::GeometryUpload upload; + if (!context_.geometry_provider_(va,bytes,upload)) return false; + buffer=upload.buffer;offset=upload.offset; + geometry.push_back(std::move(upload)); + return true; + }; + } + replay.graphics_family = family_ == context_.graphics_family_; replay.queue_stages = kind_ == QueueKind::copy ? detail::queue_stages_copy : kind_ == QueueKind::compute ? detail::queue_stages_compute : 0; @@ -2555,6 +2614,7 @@ class VulkanQueue : private QueueHolds::Holder { }; VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + label::completions().begin_record(command_buffer); if (context_.vk.vkBeginCommandBuffer(command_buffer, &begin) != VK_SUCCESS) { discard(); return ReplayResult::unsupported; @@ -2598,8 +2658,7 @@ class VulkanQueue : private QueueHolds::Holder { storage_init_seen_ = context_.storage_init_version_; } // The set this submission binds may be a new generation whose table another queue's submission uploads: - // wait for that one, as for the storage images (the table's buffers are used by one queue family only: - // every D3D12 queue of the device is made in info.queue_family). + // wait for that one, as for the storage images. The table and fallback images share the device's families. if (context_.bindless_upload_semaphore_ && context_.bindless_upload_semaphore_ != progress_ && context_.bindless_upload_version_ != bindless_upload_seen_) { waits_.push_back(context_.bindless_upload_semaphore_); @@ -2706,6 +2765,7 @@ class VulkanQueue : private QueueHolds::Holder { slot->counted_dispatch = std::move(counted_batch); queries.commit(); slot->segments = std::move(queries.retained); + slot->geometry = std::move(geometry); } else { discard(); } @@ -2940,6 +3000,7 @@ class VulkanQueue : private QueueHolds::Holder { std::unique_ptr predicate; // retained until this slot completes std::vector khr_instances; // KHR ARRAY_OF_POINTERS staging, same lifetime std::vector khr_as_queries; // KHR postbuild COMPACTED_SIZE query pools, same lifetime + std::vector geometry; }; struct PendingBindings { @@ -2962,6 +3023,7 @@ class VulkanQueue : private QueueHolds::Holder { auto& vk = context_.vk; VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + label::completions().begin_record(command_buffer); if (vk.vkBeginCommandBuffer(command_buffer, &begin) != VK_SUCCESS) { slot->ticket = 0; return false; @@ -3100,6 +3162,7 @@ class VulkanQueue : private QueueHolds::Holder { for (auto& slot : buffers_) { if (slot.ticket > done) continue; slot.segments.clear(); + slot.geometry.clear(); recycle_khr_stages(slot.khr_instances); recycle_khr_as_queries(slot.khr_as_queries); for (VkEvent event : slot.events) @@ -3236,7 +3299,9 @@ class VulkanQueue : private QueueHolds::Holder { submit.pCommandBuffers = &command_buffer; submit.signalSemaphoreCount = signal_count; submit.pSignalSemaphores = signals; - res = context_.vk.vkQueueSubmit(queue_, 1, &submit, VK_NULL_HANDLE); + const auto label_fence=label::completions().submit_fence(command_buffer); + res = context_.vk.vkQueueSubmit(queue_, 1, &submit, label_fence); + label::completions().submitted(command_buffer,res==VK_SUCCESS); if (res == VK_SUCCESS) { context_.record_submit_locked(progress_, ticket); if (signals_fence) context_.holds().signaled(fence, value); diff --git a/runtime/src/vulkan_bindless.h b/runtime/src/vulkan_bindless.h index cb5b61f655..1477a9924c 100644 --- a/runtime/src/vulkan_bindless.h +++ b/runtime/src/vulkan_bindless.h @@ -8,9 +8,10 @@ // 2 the descriptor hash table 1 7 3D r32ui storage images 256 // 3 sampled 2D-array images 1024 8 + 3 * dimension + class 256 each: // 4 2D r32ui storage images 1024 storage images by component class -// dimension: 0 = 2D, 1 = 2D array, 2 = 3D, 3 = 1D (the translator's STORE_DIMS); class: 0 = float, 1 = uint, 2 = sint. +// dimension: 0 = 2D, 1 = 2D array, 2 = 3D, 3 = 1D (the first four STORE_DIMS); class: 0 = float, 1 = uint, 2 = sint. // bindings 20/21: sampled multisample 2D images / 2D arrays, 256 each (runtime SRVs). // bindings 22/23 and 24/25 are their UINT and SINT equivalents on devices supporting those classes. +// bindings 26-28: storage-only 1D-array images by component class, 256 each (STORE_DIMS index 4). // These are the default counts (BindlessFeatures::counts). size_bindings() sizes the 2D, sampler and storage arrays // from the device's limits instead; the shaders declare runtime arrays, so any count works for them. // @@ -43,6 +44,7 @@ #define VK_NO_PROTOTYPES #endif #include "descriptor_table.h" +#include "queue_families.h" #include @@ -52,12 +54,13 @@ #include #include #include +#include #include namespace leonida { -// The first four dimensions are the translator's STORE_DIMS indices. A cube is a 2D array of six layers. -enum class ImageDimension : std::uint32_t { dim_2d, dim_2d_array, dim_3d, dim_1d, dim_2d_ms, dim_2d_ms_array }; +// The first five dimensions are the translator's STORE_DIMS indices. A cube is a 2D array of six layers. +enum class ImageDimension : std::uint32_t { dim_2d, dim_2d_array, dim_3d, dim_1d, dim_1d_array, dim_2d_ms, dim_2d_ms_array }; // Storage views of one image by the component type a shader reads or writes it with (the translator picks by the // T# format at run time). r32ui is for the atomic instructions, whose image type is R32ui (2D and 3D only). @@ -70,7 +73,7 @@ struct StorageViews { }; namespace bindless { -inline constexpr std::uint32_t binding_count = 26; +inline constexpr std::uint32_t binding_count = 29; constexpr std::array default_counts(); } // namespace bindless @@ -94,10 +97,12 @@ struct Binding { inline constexpr std::uint32_t table_binding = 2; inline constexpr std::uint32_t sampler_binding = 1; inline constexpr std::uint32_t first_ms_binding = 20; +inline constexpr std::uint32_t ms_binding_count = 6; +inline constexpr std::uint32_t first_1d_array_storage_binding = first_ms_binding + ms_binding_count; inline constexpr std::uint32_t no_binding = 0xffffffffu; -// Indexed by binding number. -inline constexpr std::array bindings = {{ +// Indexed by binding number. Keep the literal extent for tools/spirv_metal_set0.py. +inline constexpr std::array bindings = {{ {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 4096}, {VK_DESCRIPTOR_TYPE_SAMPLER, 1024}, {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1024}, {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1024}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, @@ -111,6 +116,8 @@ inline constexpr std::array bindings = {{ {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, + {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256}, + {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256}, }}; static_assert(bindings.size() == binding_count); @@ -121,8 +128,12 @@ constexpr std::array default_counts() { return counts; } +constexpr bool ms_binding(std::uint32_t binding) { + return binding >= first_ms_binding && binding < first_ms_binding + ms_binding_count; +} + constexpr bool binding_enabled(std::uint32_t binding, const BindlessFeatures& features) { - return binding < first_ms_binding || features.ms_samples[(binding - first_ms_binding) / 2] != VK_SAMPLE_COUNT_1_BIT; + return !ms_binding(binding) || features.ms_samples[(binding - first_ms_binding) / 2] != VK_SAMPLE_COUNT_1_BIT; } // Every binding is visible to every shader stage. Preserve the single-sample layout on devices whose @@ -131,7 +142,8 @@ constexpr void limit_ms_bindings(BindlessFeatures& features, std::uint32_t sampl std::uint32_t resource_limit) { const auto& counts = features.counts; std::uint32_t sampled = 0, total = 0; - for (std::uint32_t b = 0; b < first_ms_binding; ++b) { + for (std::uint32_t b = 0; b < binding_count; ++b) { + if (ms_binding(b)) continue; if (bindings[b].type == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) sampled += counts[b]; if (bindings[b].type != VK_DESCRIPTOR_TYPE_SAMPLER) total += counts[b]; } @@ -153,12 +165,13 @@ constexpr bool multisampled(ImageDimension dimension) { } constexpr std::uint32_t sampled_binding(ImageDimension dimension, std::uint32_t component_class = 0) { - constexpr std::uint32_t by_dimension[] = {0, 3, 6, 5, first_ms_binding, first_ms_binding + 1}; + constexpr std::uint32_t by_dimension[] = {0, 3, 6, 5, no_binding, first_ms_binding, first_ms_binding + 1}; return by_dimension[std::uint32_t(dimension)] + (multisampled(dimension) ? component_class * 2 : 0); } // component_class: 0 = float, 1 = uint, 2 = sint. constexpr std::uint32_t storage_binding(ImageDimension dimension, std::uint32_t component_class) { + if (dimension == ImageDimension::dim_1d_array) return first_1d_array_storage_binding + component_class; return multisampled(dimension) ? no_binding : 8 + 3 * std::uint32_t(dimension) + component_class; } @@ -196,8 +209,9 @@ struct SetLayout { }; // What size_bindings() grows to where the device's limits allow. At 32-64 bytes a descriptor the whole set is then -// 3-6 MiB (93793 descriptors on an RTX 5070). +// roughly 4-8 MiB with 119137 descriptors when all MS classes and array bindings reach their limits. inline constexpr std::uint32_t max_2d_images = 65536; +inline constexpr std::uint32_t max_2d_array_images = 16384; inline constexpr std::uint32_t max_storage_indices = 4096; // in each storage array, at most its dimension's images // A full D3D12 shader-visible sampler heap (2048) and room for literal and static S#s, within what the device can // create (maxSamplerAllocationCount, at least 4000) less the samplers that are not in the set. @@ -214,8 +228,9 @@ inline constexpr std::uint32_t growth_headroom = 64; // 2. The MS pairs that fit beside them (limit_ms_bindings, which may turn classes off). // 3. Growth towards the maximums above, in the same order, within maxPerSetDescriptors. That limit only says // what is sure to work (vkGetDescriptorSetLayoutSupport may allow more), so it never shrinks step 1. -// A storage array holds the smaller of the storage count and its dimension's images: add_image never gives a -// storage view an index past the sampled array. The other bindings keep their default counts. +// A storage array holds the smaller of the storage count and its dimension's sampled count: add_image never +// gives a storage view an index past the sampled array. The storage-only 1D array is capped at its default of 256. +// The other bindings keep their default counts. // layout_supported, when given, answers vkGetDescriptorSetLayoutSupport for set 0 at the counts in its argument: // step 3 then also grows past maxPerSetDescriptors where the device says the layout works (Intel's Xe-LP reports // 6159 and supports the full sizes, D3D-219). It is asked only once the sum is above maxPerSetDescriptors. @@ -243,15 +258,20 @@ inline bool size_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimi auto& counts = features.counts; counts = default_counts(); std::uint32_t images = 1, samplers = 1, storage = 1; + std::uint32_t array_images = bindings[sampled_binding(ImageDimension::dim_2d_array)].count; // Until the end the 2D storage arrays are not capped by the 2D images, which grow after them: capping can only // take descriptors away. const auto apply = [&](bool final) { counts[sampled_binding(ImageDimension::dim_2d)] = images; + counts[sampled_binding(ImageDimension::dim_2d_array)] = array_images; counts[sampler_binding] = samplers; - for (std::uint32_t d = 0; d < 4; ++d) { + for (std::uint32_t d = 0; d <= std::uint32_t(ImageDimension::dim_1d_array); ++d) { const auto dimension = ImageDimension(d); + const auto sampled_at = sampled_binding(dimension); + const auto capacity = sampled_at == no_binding ? bindings[storage_binding(dimension, 0)].count + : counts[sampled_at]; const bool capped = final || dimension != ImageDimension::dim_2d; - const std::uint32_t held = capped ? std::min(storage, counts[sampled_binding(dimension)]) : storage; + const std::uint32_t held = capped ? std::min(storage, capacity) : storage; for (std::uint32_t c = 0; c < 3; ++c) counts[storage_binding(dimension, c)] = held; if (r32ui_binding(dimension) != no_binding) counts[r32ui_binding(dimension)] = held; } @@ -305,6 +325,9 @@ inline bool size_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimi grow(samplers, std::max(samplers, std::min(max_samplers, creatable)), growth_headroom, set_limit); grow(images, std::max(images, max_2d_images), growth_headroom, set_limit); grow(storage, std::max(storage, max_storage_indices), growth_headroom, set_limit); + // A material can keep many array-layer and cube views alive at once. Grow them only out of + // the remaining set budget, including any storage bindings that share their index range. + grow(array_images, max_2d_array_images, growth_headroom, set_limit); apply(true); return full; } @@ -314,8 +337,8 @@ inline bool size_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimi class BindlessSet { public: BindlessSet(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceMemoryProperties& memory, - BindlessFeatures features = {}) - : device_(device), memory_(memory), features_(features) { + BindlessFeatures features = {}, std::vector families = {}) + : device_(device), memory_(memory), features_(features), families_(std::move(families)) { ok_ = vk_.load(get, device) && create_layout() && create_fallbacks() && create_table_buffers() && fill(); } @@ -342,7 +365,8 @@ class BindlessSet { // How many images of a dimension the set holds, the fallback included, and how many of the lowest of those // indices its storage arrays hold (0 for the MS dimensions, which have none). The same for samplers. std::uint32_t image_capacity(ImageDimension dimension) const { - return features_.counts[bindless::sampled_binding(dimension)]; + const auto binding = bindless::sampled_binding(dimension); + return binding == bindless::no_binding ? storage_capacity(dimension) : features_.counts[binding]; } std::uint32_t storage_capacity(ImageDimension dimension) const { return bindless::multisampled(dimension) ? 0 : features_.counts[bindless::storage_binding(dimension, 0)]; @@ -401,6 +425,7 @@ class BindlessSet { std::uint32_t add_image(ImageDimension dimension, VkImageView sampled, VkImageLayout sampled_layout, const StorageViews& storage = {}, std::uint32_t sampled_class = 0) { const bool stores = storage.as_float || storage.as_uint || storage.as_sint || storage.r32ui; + if (!stores && bindless::sampled_binding(dimension) == bindless::no_binding) return 0; if (bindless::multisampled(dimension) && (stores || !supports_ms_class(sampled_class))) return 0; auto& used = image_used_[std::uint32_t(dimension)]; const std::uint32_t low_end = std::min(std::uint32_t(used.size()), storage_capacity(dimension)); @@ -597,7 +622,7 @@ class BindlessSet { VkDescriptorImageInfo info; }; - static constexpr std::uint32_t dimensions = 6, classes = 3; + static constexpr std::uint32_t dimensions = 7, classes = 3; // The first free index in [begin, end), marked used; 0 when there is none. static std::uint32_t allocate(std::vector& used, std::uint32_t begin, std::uint32_t end) { @@ -695,10 +720,11 @@ class BindlessSet { constexpr std::uint32_t ms_type = 3; constexpr VkFormat formats[classes] = {VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R32_UINT, VK_FORMAT_R32_SINT}; // dimension -> (index into types, view type) - constexpr std::uint32_t type_of[dimensions] = {0, 0, 1, 2, ms_type, ms_type}; + constexpr std::uint32_t type_of[dimensions] = {0, 0, 1, 2, 2, ms_type, ms_type}; constexpr VkImageViewType view_types[dimensions] = {VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_VIEW_TYPE_2D_ARRAY, - VK_IMAGE_VIEW_TYPE_3D, VK_IMAGE_VIEW_TYPE_1D, - VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_VIEW_TYPE_2D_ARRAY}; + VK_IMAGE_VIEW_TYPE_3D, VK_IMAGE_VIEW_TYPE_1D, + VK_IMAGE_VIEW_TYPE_1D_ARRAY, + VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_VIEW_TYPE_2D_ARRAY}; for (std::uint32_t t = 0; t < std::size(types); ++t) { for (std::uint32_t c = 0; c < classes; ++c) { if (t == ms_type && !supports_ms_class(c)) continue; @@ -713,6 +739,7 @@ class BindlessSet { if (t != ms_type) info.usage |= VK_IMAGE_USAGE_STORAGE_BIT; if (t == ms_type || c == 0) info.usage |= VK_IMAGE_USAGE_SAMPLED_BIT; FallbackImage& image = fallback_images_[t * classes + c]; + share_across_queue_families(info, families_); if (vk_.vkCreateImage(device_, &info, nullptr, &image.image) != VK_SUCCESS) return false; VkMemoryRequirements requirements{}; vk_.vkGetImageMemoryRequirements(device_, image.image, &requirements); @@ -737,8 +764,9 @@ class BindlessSet { VkImageView view = VK_NULL_HANDLE; if (vk_.vkCreateImageView(device_, &info, nullptr, &view) != VK_SUCCESS) return false; fallback_views_.push_back(view); - if (c == 0 || bindless::multisampled(dimension)) - fallback_by_binding_[bindless::sampled_binding(dimension, c)] = view; + const auto sampled_at = bindless::sampled_binding(dimension, c); + if (sampled_at != bindless::no_binding && (c == 0 || bindless::multisampled(dimension))) + fallback_by_binding_[sampled_at] = view; const auto storage_at = bindless::storage_binding(dimension, c); if (storage_at != bindless::no_binding) fallback_by_binding_[storage_at] = view; const auto r32ui_at = bindless::r32ui_binding(dimension); @@ -760,6 +788,7 @@ class BindlessSet { (device_local ? VK_BUFFER_USAGE_TRANSFER_DST_BIT : VK_BUFFER_USAGE_TRANSFER_SRC_BIT); TableBuffer made; made.size = bytes; + share_across_queue_families(info, families_); if (vk_.vkCreateBuffer(device_, &info, nullptr, &made.buffer) != VK_SUCCESS) return false; VkMemoryRequirements requirements{}; vk_.vkGetBufferMemoryRequirements(device_, made.buffer, &requirements); @@ -998,8 +1027,9 @@ class BindlessSet { return; } const std::uint32_t sampled_at = bindless::sampled_binding(dimension); - queue(sampled_at, index, - sampled ? VkDescriptorImageInfo{VK_NULL_HANDLE, sampled, sampled_layout} : fallback_info(sampled_at)); + if (sampled_at != bindless::no_binding) + queue(sampled_at, index, + sampled ? VkDescriptorImageInfo{VK_NULL_HANDLE, sampled, sampled_layout} : fallback_info(sampled_at)); const auto store = [&](std::uint32_t binding, VkImageView view) { if (binding == bindless::no_binding || index >= features_.counts[binding]) return; queue(binding, index, @@ -1014,6 +1044,7 @@ class BindlessSet { VkDevice device_; VkPhysicalDeviceMemoryProperties memory_; BindlessFeatures features_; + std::vector families_; Functions vk_; bool ok_ = false; VkDescriptorSetLayout layout_ = VK_NULL_HANDLE; diff --git a/runtime/src/vulkan_gpu_labels.h b/runtime/src/vulkan_gpu_labels.h new file mode 100644 index 0000000000..d507fb171a --- /dev/null +++ b/runtime/src/vulkan_gpu_labels.h @@ -0,0 +1,156 @@ +#pragma once +#include "gpu_label_memory.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#include +#endif + +namespace leonida::label { +inline bool enabled() { + static const bool active=[] {const char* v=std::getenv("LEONIDA_GPU_LABELS");return v && v[0]=='1';}(); + return active; +} +// Each submitted Vulkan command buffer owns a fence and its query slots until the GPU finishes it. +// The CPU destination is a generation-checked title data allocation. No guest pointer is a GPU command destination. +class Completions { + static constexpr unsigned per_pool=64; + struct Batch { + VkFence fence{}; + std::vector pools; + std::vector labels; + }; + std::mutex mutex_; std::condition_variable changed_; bool closing_=false; + std::thread worker_; bool process_shutdown_=false; VkDevice device_{}; + std::unordered_map> recording_; + std::vector> pending_; + std::vector idle_pools_; std::vector idle_fences_; + PFN_vkCreateQueryPool create_pool_{}; PFN_vkDestroyQueryPool destroy_pool_{}; + PFN_vkCmdResetQueryPool reset_query_{}; PFN_vkCmdWriteTimestamp timestamp_{}; PFN_vkGetQueryPoolResults results_{}; + PFN_vkCreateFence create_fence_{}; PFN_vkDestroyFence destroy_fence_{}; PFN_vkGetFenceStatus fence_status_{}; + PFN_vkResetFences reset_fences_{}; PFN_vkDeviceWaitIdle device_idle_{}; + std::uint64_t published_[3]{},lost_{},errors_{}; + VkQueryPool pool() { + if(!idle_pools_.empty()){auto h=idle_pools_.back();idle_pools_.pop_back();return h;} + VkQueryPoolCreateInfo c{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO};c.queryType=VK_QUERY_TYPE_TIMESTAMP;c.queryCount=per_pool; + VkQueryPool p{};return create_pool_(device_,&c,nullptr,&p)==VK_SUCCESS?p:VK_NULL_HANDLE; + } + VkFence fence() { + if(!idle_fences_.empty()){auto f=idle_fences_.back();idle_fences_.pop_back();if(reset_fences_(device_,1,&f)==VK_SUCCESS)return f;destroy_fence_(device_,f,nullptr);} + VkFenceCreateInfo c{VK_STRUCTURE_TYPE_FENCE_CREATE_INFO};VkFence f{};return create_fence_(device_,&c,nullptr,&f)==VK_SUCCESS?f:VK_NULL_HANDLE; + } + void recycle(Batch& b) {for(auto p:b.pools)idle_pools_.push_back(p);if(b.fence)idle_fences_.push_back(b.fence);} + static bool store(const Target& target,std::uint64_t value) { +#ifdef _WIN32 + return memory().publish(target,[&](std::uintptr_t address,unsigned width,std::uintptr_t allocation_base){ + MEMORY_BASIC_INFORMATION mbi{}; + if(!VirtualQuery(reinterpret_cast(address),&mbi,sizeof(mbi)) || mbi.State!=MEM_COMMIT || + mbi.Type!=MEM_PRIVATE || reinterpret_cast(mbi.AllocationBase)!=allocation_base || + (mbi.Protect&PAGE_GUARD) || ((mbi.Protect&0xff)!=PAGE_READWRITE && (mbi.Protect&0xff)!=PAGE_WRITECOPY)) return false; + const auto begin=reinterpret_cast(mbi.BaseAddress); + if(addressmbi.RegionSize || mbi.RegionSize-(address-begin)(address),static_cast(value)); + else InterlockedExchange64(reinterpret_cast(address),static_cast(value)); + return true; + }); +#else + (void)target;(void)value;return false; +#endif + } + void publish(const Batch& batch) { + for(std::size_t i=0;i(i%per_pool),1,sizeof(value),&value, + sizeof(value),VK_QUERY_RESULT_64_BIT)!=VK_SUCCESS){++errors_;continue;} + } else if(op.clock==2) { +#ifdef _WIN32 + LARGE_INTEGER qpc{}; if(!QueryPerformanceCounter(&qpc)){++errors_;continue;} + value=static_cast(qpc.QuadPart); +#else + ++errors_;continue; +#endif + } + if(store(op.target,value))++published_[op.clock];else ++lost_; + } + } + void run() { + std::unique_lock lock(mutex_); + for(;;) { + if(pending_.empty() && !closing_) changed_.wait(lock,[&]{return closing_ || !pending_.empty();}); + if(process_shutdown_)return; + for(auto i=pending_.begin();i!=pending_.end();) { + auto& b=**i;const auto status=fence_status_(device_,b.fence); + if(status==VK_NOT_READY && !closing_){++i;continue;} + if(status==VK_SUCCESS)publish(b);else ++errors_; + recycle(b);i=pending_.erase(i); + } + if(closing_)return; + if(!pending_.empty())changed_.wait_for(lock,std::chrono::milliseconds(1)); + } + } +public: + ~Completions() { + if(!worker_.joinable())return; + {std::lock_guard lock(mutex_);process_shutdown_=true;closing_=true;changed_.notify_all();} + worker_.join(); + } + void initialize(VkDevice dev,PFN_vkGetDeviceProcAddr get) { + if(!enabled() || !dev || !get)return; + std::lock_guard lock(mutex_);if(device_)return; +#define LABEL_FN(name) reinterpret_cast(get(dev,#name)) + create_pool_=LABEL_FN(vkCreateQueryPool);destroy_pool_=LABEL_FN(vkDestroyQueryPool); + reset_query_=LABEL_FN(vkCmdResetQueryPool);timestamp_=LABEL_FN(vkCmdWriteTimestamp);results_=LABEL_FN(vkGetQueryPoolResults); + create_fence_=LABEL_FN(vkCreateFence);destroy_fence_=LABEL_FN(vkDestroyFence);fence_status_=LABEL_FN(vkGetFenceStatus); + reset_fences_=LABEL_FN(vkResetFences);device_idle_=LABEL_FN(vkDeviceWaitIdle); +#undef LABEL_FN + if(!create_pool_||!destroy_pool_||!reset_query_||!timestamp_||!results_||!create_fence_||!destroy_fence_||!fence_status_||!reset_fences_||!device_idle_)return; + device_=dev;closing_=false;worker_=std::thread([this]{run();}); + } + void begin_record(VkCommandBuffer cb) { + if(!enabled())return;std::lock_guard lock(mutex_);auto i=recording_.find(cb); + if(i!=recording_.end()){recycle(*i->second);recording_.erase(i);} + } + void record(VkCommandBuffer cb,const Write& op) { + if(!enabled())return;std::lock_guard lock(mutex_);if(!device_||closing_){++errors_;return;} + auto& slot=recording_[cb]; + if(!slot){slot=std::make_unique();slot->fence=fence();} + if(!slot->fence){++errors_;return;} + const auto i=slot->labels.size();const auto j=static_cast(i%per_pool); + if(!j){auto p=pool();if(!p){++errors_;return;}slot->pools.push_back(p);} + auto p=slot->pools[i/per_pool];reset_query_(cb,p,j,1);timestamp_(cb,VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,p,j); + slot->labels.push_back(op); + } + VkFence submit_fence(VkCommandBuffer cb) { + if(!enabled()||!cb)return VK_NULL_HANDLE;std::lock_guard lock(mutex_);auto i=recording_.find(cb); + return i==recording_.end()?VK_NULL_HANDLE:i->second->fence; + } + void submitted(VkCommandBuffer cb,bool ok) { + if(!enabled()||!cb)return;std::lock_guard lock(mutex_);auto i=recording_.find(cb);if(i==recording_.end())return; + if(ok && i->second->fence){pending_.push_back(std::move(i->second));changed_.notify_one();}else recycle(*i->second); + recording_.erase(i); + } + void stop(VkDevice dev) { + {std::lock_guard lock(mutex_);if(!dev||device_!=dev)return;} + device_idle_(dev); + {std::lock_guard lock(mutex_);closing_=true;changed_.notify_all();} + if(worker_.joinable())worker_.join();std::lock_guard lock(mutex_); + for(auto& pair:recording_)recycle(*pair.second);recording_.clear(); + for(auto f:idle_fences_)destroy_fence_(dev,f,nullptr);idle_fences_.clear(); + for(auto p:idle_pools_)destroy_pool_(dev,p,nullptr);idle_pools_.clear(); + device_=VK_NULL_HANDLE; + } +}; +inline Completions& completions(){static Completions engine;return engine;} +} // namespace leonida::label diff --git a/runtime/src/vulkan_graphics_shader_modules.h b/runtime/src/vulkan_graphics_shader_modules.h new file mode 100644 index 0000000000..5c2b1bd712 --- /dev/null +++ b/runtime/src/vulkan_graphics_shader_modules.h @@ -0,0 +1,61 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace leonida { +class GraphicsShaderModules { +public: + struct Module { + VkDevice device; + PFN_vkDestroyShaderModule destroy; + std::vector words; + VkShaderModule handle = VK_NULL_HANDLE; + Module(VkDevice d, PFN_vkDestroyShaderModule fn, std::span input) + : device(d), destroy(fn), words(input.begin(), input.end()) {} + ~Module() { if (handle) destroy(device, handle, nullptr); } + }; + using Reference = std::shared_ptr; + Reference acquire(VkDevice device, PFN_vkCreateShaderModule create, PFN_vkDestroyShaderModule destroy, + std::span words, bool reuse = true) { + if (words.empty()) return {}; + std::uint64_t hash = 14695981039346656037ull; + if (reuse) { + for (std::uint32_t word : words) hash = (hash ^ word) * 1099511628211ull; + std::lock_guard lock(mutex_); + if (auto found = find_locked(hash, words)) { ++hits_; return found; } + } + auto result = std::make_shared(device, destroy, words); + VkShaderModuleCreateInfo info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + info.pCode = words.data(); info.codeSize = words.size_bytes(); + if (create(device, &info, nullptr, &result->handle) != VK_SUCCESS) { result->handle=VK_NULL_HANDLE; return {}; } + if (!reuse) return result; + std::lock_guard lock(mutex_); + if (auto found = find_locked(hash, words)) { ++hits_; return found; } + if ((++created_ % 1024) == 0) + std::erase_if(modules_, [](const auto& entry) { return entry.second.expired(); }); + modules_.emplace(hash,result); + return result; + } + std::pair counts() { + std::lock_guard lock(mutex_); return {created_,hits_}; + } +private: + Reference find_locked(std::uint64_t hash, std::span words) { + const auto [first,last] = modules_.equal_range(hash); + for (auto i=first; i!=last; ++i) + if (auto live=i->second.lock(); live && std::equal(words.begin(),words.end(),live->words.begin(),live->words.end())) + return live; + return {}; + } + std::mutex mutex_; + std::unordered_multimap> modules_; + std::uint64_t created_=0,hits_=0; +}; +} // namespace leonida diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index cdc6b5bfe8..54dd7c9266 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -1,5 +1,7 @@ #include #pragma once +#include +#include "vulkan_gpu_labels.h" #include "resource_tiling.h" @@ -100,6 +102,13 @@ struct ResourceBinding { bool sampled = false; // has SAMPLED usage (no DENY_SHADER_RESOURCE): the present compose pass reads it bool host_readable = false; // D3D12_HEAP_TYPE_READBACK (or CUSTOM write-back): needs host-read flush bool sparse_buffer = false; + bool xbox_depth16_stencil8=false; + bool rgba4_render_fallback=false; + // The two independently addressable storage images of an Xbox depth/stencil UAV. + ResourceId depth_uav = 0, stencil_uav = 0; + void* residency_owner = nullptr; + bool (*ensure_residency)(void*) = nullptr; + ResourceId depth_conversion = 0; // R32_FLOAT transfer image for a widened Xbox D16+S8 attachment }; struct VulkanAccess { @@ -465,6 +474,7 @@ inline BlockFormat block_format(VkFormat format, VkImageAspectFlags aspect) { case VK_FORMAT_R16_SINT: case VK_FORMAT_A4R4G4B4_UNORM_PACK16: case VK_FORMAT_R4G4B4A4_UNORM_PACK16: + case VK_FORMAT_D16_UNORM_S8_UINT: case VK_FORMAT_D16_UNORM: return {2, 1}; case VK_FORMAT_R8_UNORM: case VK_FORMAT_R8_SNORM: @@ -759,6 +769,7 @@ struct ComputePipeline { VkPipelineLayout layout = VK_NULL_HANDLE; std::uint64_t code_base = 0; VkDescriptorSet bindless_set = VK_NULL_HANDLE; // set 0 of the layout, bound at every dispatch; null: none + std::function materialize; }; // A graphics pipeline as replay needs it: the formats its attachments must have and which vertex-input slots it @@ -780,8 +791,11 @@ struct GraphicsPipeline { // unbound (D3D12 allows it; dynamic rendering needs the formats to agree). Bit i: colour slot i, bit 8: depth // 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; + bool base_rectangle_stage = false; std::function variant; std::uint32_t samples = 1; // rasterizationSamples; every bound attachment must have this count + bool pending_base_compile = false; }; // The 144-byte push-constant block every translated shader declares: s0..s31, heap base, code base. @@ -819,6 +833,9 @@ struct ReplayFunctions { // Optional; a list that needs a missing one is rejected with ReplayResult::unsupported. PFN_vkCmdPipelineBarrier2 pipeline_barrier2 = nullptr; // enhanced barriers VkPipelineStageFlags2 queue_stages = 0; + bool graphics_family = true; + // Aspects with maintenance10 depth/stencil transfer support on a dedicated compute family. + std::function compute_copy_aspects; PFN_vkCmdBeginRendering begin_rendering = nullptr; // rectangle clears PFN_vkCmdEndRendering end_rendering = nullptr; PFN_vkCmdClearAttachments clear_attachments = nullptr; @@ -826,6 +843,7 @@ struct ReplayFunctions { PFN_vkCmdCopyBufferToImage copy_buffer_to_image = nullptr; PFN_vkCmdCopyImageToBuffer copy_image_to_buffer = nullptr; PFN_vkCmdCopyImage copy_image = nullptr; + PFN_vkCmdBlitImage blit_image = nullptr; PFN_vkCmdResolveImage resolve_image = nullptr; // resolves PFN_vkCmdFillBuffer fill_buffer = nullptr; // unordered-access buffer clears, with copy_buffer PFN_vkCmdUpdateBuffer update_buffer = nullptr; // WriteBufferImmediate, unordered-access clears @@ -1039,6 +1057,7 @@ struct Prepared { // A depth <-> colour copy: the source into `staged` (image to buffer), then `staged` into the destination. VkBuffer staged = VK_NULL_HANDLE; std::vector staged_reads, staged_writes; + VkDeviceSize clear_pattern_bytes = 0; // rectangular UAV clear on a compute-only queue std::vector discards; // DiscardResource: the subresources to discard VkBuffer write_buffer = VK_NULL_HANDLE; // WriteBufferImmediate: where the address lands VkDeviceSize write_offset = 0; @@ -1050,6 +1069,8 @@ struct Prepared { QueryPool* queries = nullptr; // query commands: the heap ComputePipeline pipeline; // dispatches std::uint32_t draw = 0; // draws: its PreparedDraw in PreparedList::draws + std::uint32_t depth_uav_copy = UINT32_MAX; + bool order_depth_uav = false; VkAccelerationStructureKHR accel_dst = VK_NULL_HANDLE; VkDeviceAddress khr_instances = 0; // staged ARRAY_OF_POINTERS instance list for a KHR TLAS; 0: use the VA directly std::uint64_t xdxr_bytes = 0; // CopyAccelerationStructure: the most bytes the copy may write @@ -1057,6 +1078,26 @@ struct Prepared { std::uint32_t khr_postbuild = ~0u; // index into PreparedList::khr_postbuilds; ~0u: skipped or XDXR }; +struct DepthUavCopy { + std::array storage; + ResourceBinding conversion{}; + VkBuffer scratch; + VkDeviceSize offset; + bool to_storage; +}; + +inline bool texture_uav_layout(std::uint32_t layout) { + return layout == d3d12_layout::unordered_access || layout == d3d12_layout::direct_queue_unordered_access || + layout == d3d12_layout::compute_queue_unordered_access; +} + +inline bool unsupported_depth_uav_access(std::uint32_t layout, std::uint32_t access) { + // A queue-specific COMMON layout permits implicit storage writes. Generic COMMON permits only + // sampling and copies, even when the access scope is COMMON (zero). + return layout == d3d12_layout::direct_queue_common || layout == d3d12_layout::compute_queue_common || + (layout == d3d12_layout::common && (access & d3d12_access::unordered_access)); +} + inline constexpr std::size_t max_render_targets = 8; // D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT // What a draw needs beyond Prepared, kept apart in PreparedList::draws: every command's entry is refilled on every @@ -1371,14 +1412,12 @@ inline LayoutPieces current(const LayoutTracker* tracker, ResourceId id, const V return out; } -// Zero-fills a block-compressed image range via vkCmdCopyBufferToImage from either the device's zero page -// (`vk.zero_buffer`) or a zeroed transfer-scratch chunk (`vk.copy_scratch` + `vk.fill_buffer`). Vulkan forbids -// vkCmdClearColorImage on BC formats, yet D3D12 committed resources start zeroed unless CREATE_NOT_ZEROED is set -// (D3D-220). -inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer command_buffer, - const ResourceBinding& resource, const VkImageSubresourceRange& range, - VkImageLayout dst_layout) { - const BlockFormat fmt = block_format(resource.format, VK_IMAGE_ASPECT_COLOR_BIT); +// Copies zeroes from the device's zero page or transfer scratch. A buffer can initialize block-compressed +// images and, with maintenance10, a depth or stencil aspect on a compute-only queue where a clear is illegal. +inline bool zero_image_aspect(const ReplayFunctions& vk, VkCommandBuffer command_buffer, + const ResourceBinding& resource, const VkImageSubresourceRange& range, + VkImageAspectFlags aspect, VkImageLayout dst_layout) { + const BlockFormat fmt = block_format(resource.format, aspect); if (fmt.block < 1 || !fmt.bytes || !vk.copy_buffer_to_image) return false; const std::uint32_t mip_begin = range.baseMipLevel; const std::uint32_t mip_end = @@ -1412,7 +1451,7 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com VkDeviceSize zero_off = 0; VkDeviceSize zero_cap = 0; if (vk.zero_buffer && vk.zero_size >= fmt.bytes) { - const VkDeviceSize align = fmt.bytes; + const VkDeviceSize align = std::max(4, fmt.bytes); const VkDeviceSize pad = (align - (vk.zero_offset % align)) % align; if (vk.zero_size >= pad + fmt.bytes) { zero_buf = vk.zero_buffer; @@ -1421,12 +1460,11 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com } } if (!zero_buf && vk.copy_scratch && vk.fill_buffer) { - // Round up to a multiple of fmt.bytes (8 or 16, always a multiple of 4 for vkCmdFillBuffer). - const VkDeviceSize fill_bytes = ((needed + fmt.bytes - 1) / fmt.bytes) * fmt.bytes; + const VkDeviceSize align = std::max(4, fmt.bytes); + const VkDeviceSize fill_bytes = ((needed + align - 1) / align) * align; VkBuffer scratch = VK_NULL_HANDLE; VkDeviceSize offset = 0; if (vk.copy_scratch(fill_bytes, scratch, offset)) { - const VkDeviceSize align = fmt.bytes; const VkDeviceSize pad = (align - (offset % align)) % align; if (fill_bytes >= pad + fmt.bytes) { vk.fill_buffer(command_buffer, scratch, offset + pad, fill_bytes - pad, 0); @@ -1451,7 +1489,7 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com layer_count <= zero_cap / (slice_bytes * mip_d)) { VkBufferImageCopy r{}; r.bufferOffset = zero_off; - r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, mip, layer_begin, layer_count}; + r.imageSubresource = {aspect, mip, layer_begin, layer_count}; r.imageExtent = {ext.width, ext.height, mip_d}; regions.push_back(r); continue; @@ -1464,7 +1502,7 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com for (std::uint32_t z = 0; z < mip_d; z += slices_per_copy) { VkBufferImageCopy r{}; r.bufferOffset = zero_off; - r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, mip, layer, 1}; + r.imageSubresource = {aspect, mip, layer, 1}; r.imageOffset = {0, 0, std::int32_t(z)}; r.imageExtent = {ext.width, ext.height, std::min(slices_per_copy, mip_d - z)}; regions.push_back(r); @@ -1478,7 +1516,7 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com const std::uint32_t eh = std::min(rows_per_copy * fmt.block, ext.height - oy); VkBufferImageCopy r{}; r.bufferOffset = zero_off; - r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, mip, layer, 1}; + r.imageSubresource = {aspect, mip, layer, 1}; r.imageOffset = {0, std::int32_t(oy), std::int32_t(z)}; r.imageExtent = {ext.width, eh, 1}; regions.push_back(r); @@ -1497,7 +1535,7 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com std::min(cols_per_copy * fmt.block, ext.width - ox); VkBufferImageCopy r{}; r.bufferOffset = zero_off; - r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, mip, layer, 1}; + r.imageSubresource = {aspect, mip, layer, 1}; r.imageOffset = {std::int32_t(ox), std::int32_t(oy), std::int32_t(z)}; r.imageExtent = {ew, eh, 1}; regions.push_back(r); @@ -1524,12 +1562,15 @@ inline void initialize(const ReplayFunctions& vk, VkCommandBuffer command_buffer if (piece.layout != VK_IMAGE_LAYOUT_UNDEFINED) continue; const BlockFormat fmt = block_format(resource.format, VK_IMAGE_ASPECT_COLOR_BIT); const bool color = piece.range.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT; - const bool can_clear = !vk.queue_stages || ((vk.queue_stages & VK_PIPELINE_STAGE_2_CLEAR_BIT) && color); - const bool compressed = fmt.block > 1 || (!can_clear && color); - if (resource.not_zeroed || (!can_clear && !color)) { + const bool can_clear = !vk.queue_stages || ((vk.queue_stages & VK_PIPELINE_STAGE_2_CLEAR_BIT) && color) || + (resource.depth_uav && vk.graphics_family); + const bool compute_depth = !color && resource.depth_uav && !vk.graphics_family && + (vk.queue_stages & VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT) && vk.compute_copy_aspects && + (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); - } else if (compressed) { + } else if (fmt.block > 1 || !can_clear) { const bool can_zero = vk.copy_buffer_to_image && ((vk.zero_buffer && vk.zero_size >= fmt.bytes) || (vk.copy_scratch && vk.fill_buffer)); @@ -1538,7 +1579,10 @@ inline void initialize(const ReplayFunctions& vk, VkCommandBuffer command_buffer 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); - const bool zeroed = zero_compressed_image(vk, command_buffer, resource, piece.range, dst); + 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) + zeroed &= zero_image_aspect(vk, command_buffer, resource, piece.range, aspect, dst); 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, @@ -2102,6 +2146,77 @@ void round_trip(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const } } +// Vulkan cannot copy a depth or stencil image aspect directly to or from a color image. The transfer +// buffer preserves the native D16, D32 or S8 bits. Only the requested layers and planes are copied, even when the device +// requires both parent aspects to transition layouts together. A storage descriptor always names GENERAL. +inline void copy_depth_uav(const ReplayFunctions& vk, VkCommandBuffer cb, const Prepared& p, const DepthUavCopy& copy, + VkImageLayout parent_layout, LayoutTracker* tracker) { + constexpr auto all = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; + constexpr auto transfer = VK_PIPELINE_STAGE_TRANSFER_BIT; + constexpr VkAccessFlags any = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; + const auto parent_access = copy.to_storage ? VK_ACCESS_TRANSFER_READ_BIT : VK_ACCESS_TRANSFER_WRITE_BIT; + const auto child_access = copy.to_storage ? VK_ACCESS_TRANSFER_WRITE_BIT : VK_ACCESS_TRANSFER_READ_BIT; + const auto parent_range = planes_for_layout(p.binding, p.range, vk.separate_depth_stencil_layouts); + image_barrier(vk, cb, p.binding, parent_range, parent_layout, VK_IMAGE_LAYOUT_GENERAL, + any, all, parent_access, transfer); + auto color = p.range; + color.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + for (unsigned plane = 0; plane < copy.storage.size(); ++plane) { + const ResourceBinding& child = copy.storage[plane]; + if (!child.image) continue; + const ResourceId child_id = plane ? p.binding.stencil_uav : p.binding.depth_uav; + auto pieces = current(tracker, child_id, color, VK_IMAGE_LAYOUT_GENERAL); + if (!copy.to_storage) initialize(vk, cb, child, child_id, pieces, VK_IMAGE_LAYOUT_GENERAL, tracker); + for (const auto& piece : pieces) + image_barrier(vk, cb, child, piece.range, piece.layout, VK_IMAGE_LAYOUT_GENERAL, + piece.layout == VK_IMAGE_LAYOUT_UNDEFINED ? 0 : any, all, child_access, transfer); + if (tracker) tracker->set(child_id, color, VK_IMAGE_LAYOUT_GENERAL); + VkBufferImageCopy parent_region{}; + parent_region.bufferOffset = copy.offset; + const VkImageAspectFlags aspect = plane ? VK_IMAGE_ASPECT_STENCIL_BIT : VK_IMAGE_ASPECT_DEPTH_BIT; + parent_region.imageSubresource = {aspect, p.range.baseMipLevel, p.range.baseArrayLayer, p.range.layerCount}; + parent_region.imageExtent = {p.binding.width, p.binding.height, 1}; + VkBufferImageCopy child_region = parent_region; + child_region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + // Last use of this staging range was a read by CopyBufferToImage, possibly on the previous barrier. + memory_barrier(vk, cb, VK_ACCESS_TRANSFER_READ_BIT, transfer, VK_ACCESS_TRANSFER_WRITE_BIT, transfer); + // A D32 depth aspect and R32_FLOAT colour carry the same bits through transfer scratch. The + // intermediate colour image permits a real normalized blit between R32_FLOAT and R16_UNORM; + // shaders see the latter's exact bits through an R16_UINT view. + const bool convert = plane == 0 && copy.conversion.image; + const VkImage colour = convert ? copy.conversion.image : child.image; + VkImageBlit blit{}; + if (convert) { + const auto id = p.binding.depth_conversion; + const auto previous = current(tracker, id, color, VK_IMAGE_LAYOUT_UNDEFINED); + for (const auto& piece : previous) + image_barrier(vk, cb, copy.conversion, piece.range, piece.layout, VK_IMAGE_LAYOUT_GENERAL, + piece.layout == VK_IMAGE_LAYOUT_UNDEFINED ? 0 : any, all, + VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, transfer); + if (tracker) tracker->set(id, color, VK_IMAGE_LAYOUT_GENERAL); + blit.srcSubresource = blit.dstSubresource = child_region.imageSubresource; + blit.srcOffsets[1] = blit.dstOffsets[1] = {int32_t(p.binding.width), int32_t(p.binding.height), 1}; + if (!copy.to_storage) { + vk.blit_image(cb, child.image, VK_IMAGE_LAYOUT_GENERAL, colour, VK_IMAGE_LAYOUT_GENERAL, 1, &blit, VK_FILTER_NEAREST); + memory_barrier(vk, cb, VK_ACCESS_TRANSFER_WRITE_BIT, transfer, VK_ACCESS_TRANSFER_READ_BIT, transfer); + } + } + vk.copy_image_to_buffer(cb, copy.to_storage ? p.binding.image : colour, VK_IMAGE_LAYOUT_GENERAL, + copy.scratch, 1, copy.to_storage ? &parent_region : &child_region); + memory_barrier(vk, cb, VK_ACCESS_TRANSFER_WRITE_BIT, transfer, VK_ACCESS_TRANSFER_READ_BIT, transfer); + vk.copy_buffer_to_image(cb, copy.scratch, copy.to_storage ? colour : p.binding.image, VK_IMAGE_LAYOUT_GENERAL, + 1, copy.to_storage ? &child_region : &parent_region); + if (convert && copy.to_storage) { + memory_barrier(vk, cb, VK_ACCESS_TRANSFER_WRITE_BIT, transfer, VK_ACCESS_TRANSFER_READ_BIT, transfer); + vk.blit_image(cb, colour, VK_IMAGE_LAYOUT_GENERAL, child.image, VK_IMAGE_LAYOUT_GENERAL, 1, &blit, VK_FILTER_NEAREST); + } + image_barrier(vk, cb, child, color, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL, + child_access, transfer, any, all); + } + image_barrier(vk, cb, p.binding, parent_range, VK_IMAGE_LAYOUT_GENERAL, parent_layout, + parent_access, transfer, any, all); +} + } // namespace detail namespace detail { @@ -2117,7 +2232,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct !vk.draw_indexed || !vk.bind_pipeline || !vk.push_constants) return ReplayResult::unsupported; const GraphicsPipeline* pipeline = vk.graphics_pipeline(draw.pipeline); - if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; + if (!pipeline || (!pipeline->pipeline && !pipeline->pending_base_compile)) return ReplayResult::unresolved_resource; if (pipeline->mesh != draw.mesh) return ReplayResult::invalid_draw; if (draw.mesh && !vk.draw_mesh_tasks) return ReplayResult::unsupported; if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; @@ -2180,7 +2295,9 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct 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 (unbound) { + if (!draw.mesh && draw.topology == topology_rect_list && !pipeline->base_rectangle_stage) + unbound |= GraphicsPipeline::rectangle_stage; + if (unbound || (!p.pipeline && pipeline->pending_base_compile)) { p.pipeline = pipeline->variant ? pipeline->variant(unbound) : VK_NULL_HANDLE; if (!p.pipeline) return ReplayResult::unsupported; } @@ -2314,6 +2431,7 @@ class PreparedList { // The draws' own data, by Prepared::draw. Kept from one execution to the next like the PreparedList itself: the // first draw_count entries are this list's, and the rest keep their vectors' storage for later draws. std::vector draws; + std::vector depth_uav_copies; std::size_t draw_count = 0; std::vector queries; VkQueryPool segment_pool = VK_NULL_HANDLE; @@ -2574,6 +2692,13 @@ inline bool zero_clear_unavailable(const PreparedList& prepared, const ReplayFun }, command); if (missing(id, p.binding, p.range)) return true; + if (p.depth_uav_copy != UINT32_MAX) { + const auto& copy = prepared.depth_uav_copies[p.depth_uav_copy]; + auto color = p.range; + color.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + if (!copy.to_storage && (missing(p.binding.depth_uav, copy.storage[0], color) || + missing(p.binding.stencil_uav, copy.storage[1], color))) return true; + } } return false; } @@ -2591,6 +2716,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun out.list = &list; out.commands.assign(commands.size(), {}); out.draw_count = 0; + out.depth_uav_copies.clear(); out.queries.clear(); out.segment_pool = VK_NULL_HANDLE; out.segment_base = out.segment_count = 0; @@ -2621,6 +2747,60 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun out.wrote_readback = false; out.readback_src_stages = 0; + // Successive plane transfers use the same transient range and order their buffer accesses in emit(). + VkBuffer plane_scratch = VK_NULL_HANDLE; + VkDeviceSize plane_capacity = 0, plane_offset = 0; + const auto prepare_depth_uav = [&](detail::Prepared& p, bool before, bool after) { + if (!p.binding.depth_uav && !p.binding.stencil_uav) return ReplayResult::success; + if (before == after) { + p.order_depth_uav = after; + return ReplayResult::success; + } + if (!vk.copy_image_to_buffer || !vk.copy_buffer_to_image || !vk.copy_scratch) + return ReplayResult::unsupported; + if (!vk.graphics_family) { + // Coupled layouts can also need to zero-initialize the sibling plane on first use. + const auto aspects = detail::planes_for_layout(p.binding, p.range, vk.separate_depth_stencil_layouts).aspectMask; + if (!(vk.queue_stages & VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT) || !vk.compute_copy_aspects || + (vk.compute_copy_aspects(p.binding.format) & aspects) != aspects) + return ReplayResult::unsupported; + } + if (p.range.baseMipLevel || p.range.levelCount != 1) return ReplayResult::unsupported; + detail::DepthUavCopy copy{}; + if (p.binding.depth_conversion && (p.range.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT)) { + if (!vk.graphics_family || !vk.blit_image) return ReplayResult::unsupported; + const auto* middle = resolve(p.binding.depth_conversion); + if (!middle || !middle->image) return ReplayResult::unresolved_resource; + copy.conversion = *middle; + } + const ResourceId ids[] = {p.binding.depth_uav, p.binding.stencil_uav}; + for (unsigned plane = 0; plane < 2; ++plane) { + const auto aspect = plane ? VK_IMAGE_ASPECT_STENCIL_BIT : VK_IMAGE_ASPECT_DEPTH_BIT; + if (!(p.range.aspectMask & aspect)) continue; + const auto* child = resolve(ids[plane]); + if (!child || !child->image) return ReplayResult::unresolved_resource; + copy.storage[plane] = *child; + } + const VkDeviceSize texels = VkDeviceSize(p.binding.width) * p.binding.height; + const auto largest_aspect = p.range.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT ? VK_IMAGE_ASPECT_DEPTH_BIT : + VK_IMAGE_ASPECT_STENCIL_BIT; + const VkDeviceSize bytes_per_texel = block_format(p.binding.format, largest_aspect).bytes; + if (!texels || !bytes_per_texel || texels > UINT64_MAX / bytes_per_texel / p.range.layerCount) + return ReplayResult::unsupported; + const VkDeviceSize bytes = texels * bytes_per_texel * p.range.layerCount; + if (bytes > plane_capacity) { + if (!vk.copy_scratch(bytes, plane_scratch, plane_offset) || !plane_scratch || plane_offset % 4) + return ReplayResult::unsupported; + plane_capacity = bytes; + } + copy.scratch = plane_scratch; + copy.offset = plane_offset; + copy.to_storage = after; + p.depth_uav_copy = static_cast(out.depth_uav_copies.size()); + out.depth_uav_copies.push_back(copy); + return ReplayResult::success; + }; + for (std::size_t i = 0; i < commands.size(); ++i) { const auto& command = commands[i]; auto& p = out.commands[i]; @@ -2658,6 +2838,9 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun } else if (!image_range(p.binding, transition->subresource, p.range)) { return ReplayResult::invalid_subresource; } + const auto result = prepare_depth_uav(p, transition->before & d3d12_state::unordered_access, + transition->after & d3d12_state::unordered_access); + if (result != ReplayResult::success) return result; } else if (std::holds_alternative(command) || std::holds_alternative(command)) { if (!vk.pipeline_barrier2) return ReplayResult::unsupported; if (const auto* buffer_barrier = std::get_if(&command)) @@ -2667,6 +2850,18 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!bind(texture->resource)) return ReplayResult::unresolved_resource; if (!p.binding.image || !barrier_range(p.binding, texture->range, p.range)) return ReplayResult::invalid_subresource; + // In a queue-specific COMMON layout shaders can write a UAV then read the SRV or copy the + // parent after only a global barrier. Bindless shaders need no per-resource bind command, so + // there is no observable ownership transition at which to synchronize the two images. + if (p.binding.depth_uav && + (detail::unsupported_depth_uav_access(texture->layout_before, texture->access_before) || + detail::unsupported_depth_uav_access(texture->layout_after, texture->access_after))) + return ReplayResult::unsupported; + if (!(texture->flags & texture_barrier_discard) && texture->layout_before != d3d12_layout::undefined) { + const auto result = prepare_depth_uav(p, detail::texture_uav_layout(texture->layout_before), + detail::texture_uav_layout(texture->layout_after)); + if (result != ReplayResult::success) return result; + } } else if (const auto* color_clear = std::get_if(&command)) { if (!bind(color_clear->target.resource)) return ReplayResult::unresolved_resource; if (!p.binding.image || p.binding.aspects != VK_IMAGE_ASPECT_COLOR_BIT) return ReplayResult::invalid_clear; @@ -2739,20 +2934,55 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun // Emulated R9G9B9E5_SHAREDEXP images (backed by R32_UINT) lack COLOR_ATTACHMENT on E5B9G9R9 and keep the // bit-exact R32_UINT backing path. const VkFormat view_format = view.format ? VkFormat(view.format) : p.binding.format; + const bool packed_rgb9e5 = view_format == VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 && + p.binding.format == VK_FORMAT_R32_UINT; if (!uav_clear::encode(view_format, uav->is_float, uav->values, p.element)) return ReplayResult::unsupported; const auto* image_layout = uav_clear::layout(p.binding.format); if (!image_layout || image_layout->bytes != p.element.size) return ReplayResult::unsupported; - const bool attachment = p.binding.color_attachment && !p.binding.volume; + // The UAV attachment path supports 1D-array and 2D-array views. Keep 3D clears on the transfer + // path and retain the exact-format restriction for 1D/3D UAVs below. + const bool attachment = p.binding.color_attachment && !p.binding.volume && + (!view.exact_clear_format || p.binding.line); const bool view_attachable = vk.color_attachment_format ? vk.color_attachment_format(view_format) : view_format != VK_FORMAT_E5B9G9R9_UFLOAT_PACK32; - const bool reinterpret = view_format != p.binding.format && attachment && view_attachable; + const bool reinterpret = view_format != p.binding.format && attachment && view_attachable && !packed_rgb9e5; + if (view.exact_clear_format && view_format != p.binding.format && !packed_rgb9e5) + return ReplayResult::unsupported; const VkFormat clear_format = reinterpret ? view_format : p.binding.format; if (!uav_clear::decode(clear_format, p.element, p.clear_color)) return ReplayResult::unsupported; if (reinterpret) p.clear_format = view_format; + // Compute list barriers have no attachment stages, and a dedicated compute queue cannot render. + // Copy the encoded texel bits from a filled buffer. Transfers cannot implement a predicated clear. + if ((vk.queue_stages & VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT) && + (!uav->rects.empty() || reinterpret || predicated)) { + if (predicated || p.binding.volume || !vk.copy_scratch || !vk.fill_buffer || !vk.copy_buffer_to_image || + (p.element.size != 1 && p.element.size != 2 && p.element.size != 4)) + return ReplayResult::unsupported; + const auto rects = uav->rects.empty() ? std::span(&whole_view, 1) : + std::span(uav->rects); + detail::clip(rects, detail::mip_extent(p.binding, view.mip), view.layer_count, p.rects); + if (p.rects.empty()) { p.skip = true; continue; } + for (const auto& rect : p.rects) { + VkBufferImageCopy region{}; + region.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, view.mip, view.first_layer, view.layer_count}; + region.imageOffset = {rect.rect.offset.x, rect.rect.offset.y, 0}; + region.imageExtent = {rect.rect.extent.width, rect.rect.extent.height, 1}; + const VkDeviceSize pixels = VkDeviceSize(region.imageExtent.width) * region.imageExtent.height; + const VkDeviceSize stride = VkDeviceSize(view.layer_count) * p.element.size; + if (pixels > (UINT64_MAX - 3) / stride) return ReplayResult::unsupported; + p.clear_pattern_bytes = std::max(p.clear_pattern_bytes, (pixels * stride + 3) & ~VkDeviceSize(3)); + p.staged_writes.push_back(region); + } + VkDeviceSize offset = 0; + if (!vk.copy_scratch(p.clear_pattern_bytes, p.staged, offset) || !p.staged || offset % 4) + return ReplayResult::unsupported; + for (auto& region : p.staged_writes) region.bufferOffset = offset; + continue; + } if (!uav->rects.empty() && !attachment) return ReplayResult::unsupported; // Under a predicate a whole view is cleared as one rectangle where the image can be an attachment, as @@ -2818,6 +3048,9 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (result == ReplayResult::success && texture_copy->tile_footprint && !p.buffer_image_copies.empty() && p.buffer_image_copies.front().bufferOffset % 4 && !detail::stage_unaligned_tile(vk, p, upload)) return ReplayResult::unsupported; + if(result==ReplayResult::success && image.rgba4_render_fallback) return ReplayResult::unsupported; + if(result==ReplayResult::success && image.xbox_depth16_stencil8 && image.format!=VK_FORMAT_D16_UNORM_S8_UINT && + !p.buffer_image_copies.empty() && p.buffer_image_copies[0].imageSubresource.aspectMask==VK_IMAGE_ASPECT_DEPTH_BIT) return ReplayResult::unsupported; const bool depth24_footprint = result == ReplayResult::success && image.depth24_as_float && !p.buffer_image_copies.empty() && p.buffer_image_copies[0].imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT; @@ -2950,6 +3183,8 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!discard->partial) p.discards.push_back(range); } } + } else if (std::holds_alternative(command)) { + // No GPU destination pointer is expected: the batch publishes only a registered title allocation. } else if (const auto* write = std::get_if(&command)) { if (!vk.update_buffer || !vk.buffer_at) return ReplayResult::unsupported; std::uint64_t bytes = 4; @@ -3082,9 +3317,13 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (ind->kind == IndirectKind::dispatch && ind->pipeline) { // the pipeline and root arguments it was recorded if (!vk.bind_pipeline || !vk.push_constants || !vk.compute_pipeline) return ReplayResult::unsupported; const ComputePipeline* pipeline = vk.compute_pipeline(ind->pipeline); - if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; + if (!pipeline || (!pipeline->pipeline && !pipeline->materialize)) return ReplayResult::unresolved_resource; if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; p.pipeline = *pipeline; + if (!p.pipeline.pipeline) { + p.pipeline.pipeline=pipeline->materialize(); + if (!p.pipeline.pipeline) return ReplayResult::unsupported; + } } } else if (const auto* build = std::get_if(&command)) { p.khr_instances = 0; @@ -3170,9 +3409,13 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!vk.bind_pipeline || !vk.push_constants || !vk.dispatch || !vk.compute_pipeline) return ReplayResult::unsupported; const ComputePipeline* pipeline = vk.compute_pipeline(dispatch->pipeline); - if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; + if (!pipeline || (!pipeline->pipeline && !pipeline->materialize)) return ReplayResult::unresolved_resource; if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; p.pipeline = *pipeline; + if (!p.pipeline.pipeline) { + p.pipeline.pipeline=pipeline->materialize(); + if (!p.pipeline.pipeline) return ReplayResult::unsupported; + } } else if (const auto* draw = std::get_if(&command)) { if (out.draw_count == out.draws.size()) out.draws.emplace_back(); auto& prepared_draw = out.draws[out.draw_count]; @@ -3456,6 +3699,15 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c vk.depth24_run(command_buffer, job); if (predicate.buffer) vk.begin_conditional_rendering(command_buffer, &predicate); }; + const auto finish_depth_uav_barrier = [&](const detail::Prepared& p, VkImageLayout layout) { + if (p.depth_uav_copy != UINT32_MAX) { + detail::copy_depth_uav(vk, command_buffer, p, prepared.depth_uav_copies[p.depth_uav_copy], layout, tracker); + } else if (p.order_depth_uav) { + // A UAV-to-UAV texture barrier names the parent, but the actual shader accesses target its children. + detail::memory_barrier(vk, command_buffer, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); + } + }; for (std::size_t i = 0; i < commands.size(); ++i) { const auto& command = commands[i]; @@ -3523,6 +3775,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c detail::image_barrier(vk, command_buffer, p.binding, piece.range, piece.layout, new_layout, from.access, from.stages, to.access, to.stages); if (tracker) tracker->set(id, range, new_layout); + finish_depth_uav_barrier(p, new_layout); } else if (std::holds_alternative(command)) { const VulkanAccess uav = vulkan_access(d3d12_state::unordered_access, false); VkAccessFlags src_access = VK_ACCESS_SHADER_WRITE_BIT; @@ -3539,7 +3792,10 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c detail::memory_barrier(vk, command_buffer, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); - } else if (std::holds_alternative(command) || std::holds_alternative(command)) { + } else if (const auto* texture_memory = std::get_if(&command); + std::holds_alternative(command) || std::holds_alternative(command) || + (texture_memory && p.binding.depth_uav && texture_memory->layout_before == d3d12_layout::undefined && + texture_memory->layout_after == d3d12_layout::undefined)) { const auto [sync_before, sync_after, access_before, access_after] = std::visit( [](const auto& c) -> std::array { if constexpr (requires { c.sync_before; }) @@ -3568,10 +3824,13 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c const VkImageLayout new_layout = image_layout(p.binding, vulkan_layout(texture->layout_after, p.binding.presentable)); LayoutPieces pieces; - if (discard) + // With coupled layouts, discarding a single plane must preserve the other plane's data. + const bool keep_sibling = p.binding.depth_uav && range.aspectMask != p.range.aspectMask; + if (discard && !keep_sibling) pieces.push_back({range, VK_IMAGE_LAYOUT_UNDEFINED}); else { const VkImageLayout before = + 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); detail::initialize(vk, command_buffer, p.binding, id, pieces, before, tracker); @@ -3605,12 +3864,16 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c dependency.pImageMemoryBarriers = barriers; vk.pipeline_barrier2(command_buffer, &dependency); if (tracker) tracker->set(id, range, new_layout); + finish_depth_uav_barrier(p, new_layout); } else if (const auto* color_clear = std::get_if(&command)) { if (p.skip) continue; 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); - const VkClearColorValue color = detail::render_target_clear_color(p.clear_format, color_clear->color); + 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; + const VkClearColorValue color=detail::render_target_clear_color(p.clear_format,clear_value); if (p.rects.empty()) { detail::round_trip(vk, command_buffer, p.binding, pieces, image_layout(p.binding, transfer_dst.layout), state, transfer_dst.access, transfer_dst.stages, [&] { @@ -3645,7 +3908,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c 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); - const float depth = p.binding.depth24 ? depth24_clear_value(depth_clear->depth) // see depth24.h + const float depth = p.binding.xbox_depth16_stencil8 ? std::round(std::clamp(depth_clear->depth,0.0f,1.0f)*65535.0f)/65535.0f : p.binding.depth24 ? depth24_clear_value(depth_clear->depth) // see depth24.h : p.binding.format == VK_FORMAT_D16_UNORM ? detail::quantize_unorm(depth_clear->depth, 65535.0) // see quantize_unorm : depth_clear->depth; @@ -3703,6 +3966,21 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c 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); + 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, [&] { + detail::emit_buffer_fill(vk, command_buffer, p.staged, p.element, p.staged_writes.front().bufferOffset, + p.clear_pattern_bytes); + for (const auto& region : p.staged_writes) { + // The fill must be visible, and two clear rectangles may overlap. + detail::memory_barrier(vk, command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT); + vk.copy_buffer_to_image(command_buffer, p.staged, p.binding.image, layout, 1, ®ion); + } + }); + 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, [&] { @@ -3974,6 +4252,8 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c piece.layout, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); } + } else if (const auto* label_write=std::get_if(&command)) { + label::completions().record(command_buffer,*label_write); } else if (const auto* write = std::get_if(&command)) { // vkCmdUpdateBuffer runs in the transfer stage. MARKER_OUT waits for every earlier command to finish // and sees its writes. MARKER_IN only needs them started, which Vulkan cannot express (TOP_OF_PIPE in a diff --git a/runtime/src/vulkan_scratch.h b/runtime/src/vulkan_scratch.h index 4a8a59ddd7..48bfa50487 100644 --- a/runtime/src/vulkan_scratch.h +++ b/runtime/src/vulkan_scratch.h @@ -9,6 +9,7 @@ #define VK_NO_PROTOTYPES #endif #include +#include "queue_families.h" #include #include @@ -23,8 +24,9 @@ class ScratchBuffers { // A device-local allocation for a chunk; null on failure. using Allocate = std::function; - ScratchBuffers(PFN_vkGetDeviceProcAddr get, VkDevice device, Allocate allocate) - : device_(device), allocate_(std::move(allocate)) { + ScratchBuffers(PFN_vkGetDeviceProcAddr get, VkDevice device, Allocate allocate, + std::vector families = {}) + : device_(device), allocate_(std::move(allocate)), families_(std::move(families)) { loaded_ = vk_.load(get, device); } @@ -149,6 +151,8 @@ class ScratchBuffers { VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; info.size = size; info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; + // A retired chunk can be reused by a submission on a different queue family. + share_across_queue_families(info, families_); if (vk_.vkCreateBuffer(device_, &info, nullptr, &out.buffer) != VK_SUCCESS) return false; VkMemoryRequirements requirements{}; vk_.vkGetBufferMemoryRequirements(device_, out.buffer, &requirements); @@ -172,6 +176,7 @@ class ScratchBuffers { VkDevice device_; Allocate allocate_; + std::vector families_; Functions vk_; bool loaded_ = false; Batch current_; // handed out, not yet submitted diff --git a/runtime/test/bindless_sizing_test.cpp b/runtime/test/bindless_sizing_test.cpp index 4553f25b60..3a4ddb7ba9 100644 --- a/runtime/test/bindless_sizing_test.cpp +++ b/runtime/test/bindless_sizing_test.cpp @@ -84,6 +84,13 @@ bool storage_consistent(const BindlessFeatures& f) { f.counts[bindless::r32ui_binding(dimension)] != held) return false; } + // 1D arrays have no sampled capacity, but all three storage classes are always present. + const auto array = ImageDimension::dim_1d_array; + const auto held = storage(f, array); + for (std::uint32_t c = 0; c < 3; ++c) { + const auto binding = bindless::storage_binding(array, c); + if (!held || !bindless::binding_enabled(binding, f) || f.counts[binding] != held) return false; + } return true; } @@ -93,6 +100,33 @@ int main() { using D = ImageDimension; constexpr auto defaults = bindless::default_counts(); static_assert(defaults[0] == 4096 && defaults[bindless::sampler_binding] == 1024 && defaults[8] == 256); + static_assert(bindless::sampled_binding(D::dim_1d_array) == bindless::no_binding); + static_assert(bindless::storage_binding(D::dim_1d_array, 0) == 26 && + bindless::storage_binding(D::dim_1d_array, 1) == 27 && + bindless::storage_binding(D::dim_1d_array, 2) == 28); + static_assert(bindless::sampled_binding(D::dim_2d_ms, 0) == 20 && + bindless::sampled_binding(D::dim_2d_ms_array, 0) == 21 && + bindless::sampled_binding(D::dim_2d_ms, 1) == 22 && + bindless::sampled_binding(D::dim_2d_ms_array, 1) == 23 && + bindless::sampled_binding(D::dim_2d_ms, 2) == 24 && + bindless::sampled_binding(D::dim_2d_ms_array, 2) == 25); + + // SetLayout compacts disabled MS pairs without renumbering either the enabled pair or the storage-only tail. + { + BindlessFeatures f{}; + f.update_after_bind = f.partially_bound = true; + f.ms_samples[1] = VK_SAMPLE_COUNT_4_BIT; + const bindless::SetLayout layout(f); + EXPECT(layout.info.bindingCount == 25 && layout.flags_info.bindingCount == 25); + EXPECT(layout.entries[20].binding == 22 && layout.entries[21].binding == 23); + for (std::uint32_t c = 0; c < 3; ++c) { + const auto& entry = layout.entries[22 + c]; + EXPECT(entry.binding == 26 + c && entry.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE && + entry.descriptorCount == 256); + EXPECT(layout.flags[22 + c] == + (VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT | VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT)); + } + } // An RTX 5070 (driver 621.24): 1048576 of each descriptor type, update-after-bind or not, 4000 samplers. for (const bool update_after_bind : {true, false}) { @@ -103,8 +137,9 @@ int main() { EXPECT(f.counts[bindless::sampler_binding] == 4000 - bindless::reserved_samplers); EXPECT(f.counts[bindless::sampler_binding] > 2048); // a full sampler heap and the fallback EXPECT(storage(f, D::dim_2d) == bindless::max_storage_indices); - EXPECT(storage(f, D::dim_2d_array) == 1024 && storage(f, D::dim_3d) == 256 && storage(f, D::dim_1d) == 256); - EXPECT(count(f, D::dim_2d_array) == 1024 && count(f, D::dim_3d) == 256 && count(f, D::dim_1d) == 256); + EXPECT(storage(f, D::dim_2d_array) == bindless::max_storage_indices && storage(f, D::dim_3d) == 256 && storage(f, D::dim_1d) == 256); + EXPECT(storage(f, D::dim_1d_array) == 256 && totals(f).all == 119137); + EXPECT(count(f, D::dim_2d_array) == bindless::max_2d_array_images && count(f, D::dim_3d) == 256 && count(f, D::dim_1d) == 256); EXPECT(f.ms_samples[0] == VK_SAMPLE_COUNT_4_BIT && f.ms_samples[2] == VK_SAMPLE_COUNT_4_BIT); EXPECT(storage_consistent(f)); if (update_after_bind) @@ -112,12 +147,12 @@ int main() { count(f, D::dim_2d), f.counts[bindless::sampler_binding], storage(f, D::dim_2d), totals(f).all); } - // At today's sizes exactly (5632 sampled images, 1024 samplers, 3584 storage images): today's set, no MS pairs. + // At today's sizes exactly (5632 sampled images, 1024 samplers, 4352 storage images): no MS pairs. { Device d = uniform(1048576, 1048576); d.v12.maxPerStageDescriptorUpdateAfterBindSampledImages = 5632; d.v12.maxPerStageDescriptorUpdateAfterBindSamplers = 1024; - d.v12.maxPerStageDescriptorUpdateAfterBindStorageImages = 3584; + d.v12.maxPerStageDescriptorUpdateAfterBindStorageImages = 4352; BindlessFeatures f = with_ms(true); EXPECT(bindless::size_bindings(f, d.limits, d.v11, d.v12)); EXPECT(count(f, D::dim_2d) == 4096 && f.counts[bindless::sampler_binding] == 1024 && @@ -125,6 +160,7 @@ int main() { for (std::uint32_t b = 0; b < bindless::first_ms_binding; ++b) if (bindless::bindings[b].type != VK_DESCRIPTOR_TYPE_STORAGE_IMAGE) EXPECT(f.counts[b] == defaults[b]); EXPECT(f.ms_samples == (std::array{VK_SAMPLE_COUNT_1_BIT, VK_SAMPLE_COUNT_1_BIT, VK_SAMPLE_COUNT_1_BIT})); + EXPECT(totals(f).storage == 4352 && storage(f, D::dim_1d_array) == 256); EXPECT(storage_consistent(f)); } @@ -178,15 +214,19 @@ int main() { Device d = uniform(1048576, 1048576); d.v11.maxPerSetDescriptors = 6159; d.limits.maxSamplerAllocationCount = 4000; - unsigned asked = 0, asked_within = 0; + unsigned asked = 0, asked_within = 0, missing_storage = 0; const auto all_supported = [&](const BindlessFeatures& candidate) { ++asked; asked_within += totals(candidate).all <= 6159; + const bindless::SetLayout layout(candidate); + const auto& last = layout.entries[layout.info.bindingCount - 1]; + missing_storage += last.binding != 28 || last.descriptorType != VK_DESCRIPTOR_TYPE_STORAGE_IMAGE || + last.descriptorCount != storage(candidate, D::dim_1d_array); return true; }; BindlessFeatures f = with_ms(true); EXPECT(bindless::size_bindings(f, d.limits, d.v11, d.v12, all_supported)); - EXPECT(asked > 0 && asked_within == 0); + EXPECT(asked > 0 && asked_within == 0 && missing_storage == 0); EXPECT(count(f, D::dim_2d) == bindless::max_2d_images && f.counts[bindless::sampler_binding] == 4000 - bindless::reserved_samplers); EXPECT(storage(f, D::dim_2d) == bindless::max_storage_indices && storage_consistent(f)); diff --git a/runtime/test/d3d12_bundle_test.cpp b/runtime/test/d3d12_bundle_test.cpp index 115a7d96f7..b7db739257 100644 --- a/runtime/test/d3d12_bundle_test.cpp +++ b/runtime/test/d3d12_bundle_test.cpp @@ -24,6 +24,7 @@ #include #include +#include #include #include #include @@ -751,7 +752,77 @@ bool layer_checks(ID3D12Device* device, const std::vector& vs, con return true; } -int main() { +// Check the user data captured by DrawInstanced without submitting the synthetic table address to the GPU. +bool root_layout_case(Rig& rig, UINT table_count, UINT constants, bool expect_graphics, bool compact) { + std::vector ranges(table_count); + std::vector params(table_count + (constants != 0)); + for (UINT i = 0; i < table_count; ++i) { + ranges[i] = {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, i, 0, 0}; + params[i].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[i].DescriptorTable = {1, &ranges[i]}; + } + if (constants) { + params.back().ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params.back().Constants = {0, 0, constants}; + } + D3D12_VERSIONED_ROOT_SIGNATURE_DESC desc{}; + desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + desc.Desc_1_0 = {UINT(params.size()), params.data(), 0, nullptr, + D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT}; + const auto blob = serialize_root_signature(desc); + CHECK(!blob.empty()); + Ref root; + CHECK(rig.device->CreateRootSignature(0, blob.data(), blob.size(), IID_PPV_ARGS(&root.p)) == S_OK); + Ref alloc; + Ref list; + CHECK(rig.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc.p)) == S_OK); + CHECK(rig.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc.p, nullptr, + IID_PPV_ARGS(&list.p)) == S_OK); + // These signatures fit the compute layout, including the graphics spill case. + list->SetComputeRootSignature(root.p); + CHECK(list->Close() == S_OK); + CHECK(list->Reset(alloc.p, nullptr) == S_OK); + list->SetGraphicsRootSignature(root.p); + if (!expect_graphics) { + CHECK(list->Close() == E_INVALIDARG); + return true; + } + + Ref pso; + CHECK(rig.make_pso(root.p, D3D12_COLOR_WRITE_ENABLE_ALL, pso)); + list->SetPipelineState(pso.p); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + const D3D12_VIEWPORT viewport{0, 0, 1, 1, 0, 1}; + list->RSSetViewports(1, &viewport); + constexpr UINT sentinel = 0xabcdef01; + if (constants) list->SetGraphicsRoot32BitConstant(table_count, sentinel, 0); + std::array expected{}; + UINT offset = compact ? 8 : 0; + for (UINT i = 0; i < table_count; ++i) { + const UINT64 handle = 0x1122334455667788ull + i; + list->SetGraphicsRootDescriptorTable(i, {handle}); + expected[offset++] = UINT(handle); + if (!compact) expected[offset++] = UINT(handle >> 32); + } + if (constants) expected[offset] = sentinel; + list->DrawInstanced(3, 1, 0, 0); + CHECK(list->Close() == S_OK); + std::vector commands; + CHECK(rt::d3d12::recorded_commands(list.p, commands)); + CHECK(commands.size() == 1); + const auto* draw = std::get_if(&commands.front()); + CHECK(draw); + for (std::size_t i = 0; i < expected.size(); ++i) { + if (draw->user_data[i] != expected[i]) { + std::fprintf(stderr, "%u tables and %u constants: s%zu = %08x, expected %08x\n", + table_count, constants, i, draw->user_data[i], expected[i]); + return false; + } + } + return true; +} + +int main(int argc, char** argv) { std::setvbuf(stdout, nullptr, _IONBF, 0); vktest::Device vk; const auto device_status = vk.initialize(); @@ -796,6 +867,22 @@ int main() { info.shader_dir = library.string(); Ref ours; REQUIRE(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))); + if (argc == 2) { + const bool stage = std::strcmp(argv[1], "--compact") == 0; + REQUIRE(stage || std::strcmp(argv[1], "--legacy") == 0); + Rig rig; + rig.device = ours.p; + rig.vs_code = vs_container; + rig.ps_code = ps_container; + const bool fallback = root_layout_case(rig, 1, 24, true, false); + const bool ordinary = root_layout_case(rig, 1, 1, true, stage); + const bool wide = root_layout_case(rig, 17, 0, stage, stage); + const bool last_register = root_layout_case(rig, 24, 0, stage, stage); + const bool spill = root_layout_case(rig, 25, 0, false, false); + REQUIRE(fallback && ordinary && wide && last_register && spill); + REQUIRE(vk.validation_errors() == errors_before); + return 0; + } REQUIRE(run_all(ours.p, false, nullptr, vs_container, ps_container, list, layer_grids, layer_closes)); REQUIRE(layer_checks(ours.p, vs_container, ps_container, library)); } diff --git a/runtime/test/d3d12_compute_test.cpp b/runtime/test/d3d12_compute_test.cpp index b4ed0fafe9..bea51a6176 100644 --- a/runtime/test/d3d12_compute_test.cpp +++ b/runtime/test/d3d12_compute_test.cpp @@ -308,6 +308,8 @@ int main() { srv_struct_b(elements), srv_typed(elements), srv_null(elements); { rt::d3d12::VulkanDeviceInfo info{}; + info.first_use_backend_pipelines=d.first_use_backend_pipelines; + info.prepare_on_bind=d.prepare_on_bind; info.get_instance_proc = d.instance_proc; info.instance = d.instance; info.physical = d.physical; @@ -691,11 +693,11 @@ int main() { leonida::gfx10::Buffer decoded{}; EXPECT(leonida::gfx10::decode(raw, decoded)); EXPECT(decoded.address == expected_va); - EXPECT(decoded.stride == 0); - EXPECT(decoded.num_records == 256); + EXPECT(decoded.stride == 16); + EXPECT(decoded.num_records == 16); EXPECT(decoded.format == leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT)); EXPECT(decoded.swizzle == leonida::gfx10::identity_swizzle); - EXPECT(decoded.oob_select == leonida::gfx10::OobSelect::raw); + EXPECT(decoded.oob_select == leonida::gfx10::OobSelect::structured_with_offset); EXPECT(std::memcmp(reinterpret_cast(slot_cpu(slot_idx).ptr) + 16, zeros, 16) == 0); } diff --git a/runtime/test/d3d12_depth_stencil_uav_test.cpp b/runtime/test/d3d12_depth_stencil_uav_test.cpp new file mode 100644 index 0000000000..d88abfc637 --- /dev/null +++ b/runtime/test/d3d12_depth_stencil_uav_test.cpp @@ -0,0 +1,556 @@ +// Xbox depth/stencil creation, shader read-modify-write and exhaustive readback across queue submissions. +// A synthetic compute shader looks up the T#s that the device writes. No game data. +#include "d3d12_copy_compare.h" +#include "d3d12_depth_stencil_uav_views.h" +#include "d3d12_placed_depth_test.h" +#include "d3d12_test_shaders.h" +#include "shader_fixture_path.h" +#include "test_temp_dir.h" +#include "vk_test_device.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/shader_library.h" + +#include +#include +#include + +#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #x); return 1; } } while (0) + +namespace { +using d3d12test::Ref; + +void enhanced_transition(ID3D12GraphicsCommandList7* list, ID3D12Resource* texture, + D3D12_BARRIER_SYNC before_sync, D3D12_BARRIER_ACCESS before_access, + D3D12_BARRIER_LAYOUT before_layout, D3D12_BARRIER_SYNC after_sync, + D3D12_BARRIER_ACCESS after_access, D3D12_BARRIER_LAYOUT after_layout) { + D3D12_TEXTURE_BARRIER barrier{}; + barrier.SyncBefore = before_sync; + barrier.AccessBefore = before_access; + barrier.LayoutBefore = before_layout; + barrier.SyncAfter = after_sync; + barrier.AccessAfter = after_access; + barrier.LayoutAfter = after_layout; + barrier.Subresources = {D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, 0, 0, 0, 0, 0}; + barrier.pResource = texture; + D3D12_BARRIER_GROUP group{}; + group.Type = D3D12_BARRIER_TYPE_TEXTURE; + group.NumBarriers = 1; + group.pTextureBarriers = &barrier; + list->Barrier(1, &group); +} + +enum class Handoff { direct, graphics_transitions, compute_transitions }; + +struct Batch { + Ref allocator; + Ref list; + bool open(ID3D12Device* device, D3D12_COMMAND_LIST_TYPE type) { + return SUCCEEDED(device->CreateCommandAllocator(type, IID_PPV_ARGS(&allocator.p))) && + SUCCEEDED(device->CreateCommandList(0, type, allocator.p, nullptr, IID_PPV_ARGS(&list.p))); + } + bool submit(ID3D12CommandQueue* queue, ID3D12Fence* done, UINT64 value) { + if (FAILED(list->Close())) return false; + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + return rt::d3d12::last_execute_result(queue) == leonida::ReplayResult::success && + SUCCEEDED(queue->Signal(done, value)); + } +}; + +bool compute_transfers(const vktest::Device& vk, VkFormat format, bool stencil) { + if (vk.compute_family == vk.family) return true; +#ifdef VK_KHR_maintenance10 + if (!vk.maintenance10) return false; + VkFormatProperties3 flags{VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_3}; + VkFormatProperties2 properties{VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2, &flags}; + vk.instance_fn("vkGetPhysicalDeviceFormatProperties2")( + vk.physical, format, &properties); + const VkFormatFeatureFlags2 required = VK_FORMAT_FEATURE_2_DEPTH_COPY_ON_COMPUTE_QUEUE_BIT_KHR | + (stencil ? VK_FORMAT_FEATURE_2_STENCIL_COPY_ON_COMPUTE_QUEUE_BIT_KHR : 0); + return (flags.optimalTilingFeatures & required) == required; +#else + return false; +#endif +} + +struct GuestAllocation { + void* address = nullptr; + ~GuestAllocation() { if (address) VirtualFree(address, 0, MEM_RELEASE); } +}; + +enum class Texture { committed, committed3, placed }; + +// The boot stack's Xbox slot 127 forwards this call to the real device's CreateCommittedResource3. +// Test the actual thunk when present, or the same normalized input at its destination on a standalone build. +HRESULT create_committed3(ID3D12Device* device, ID3D12Device* xbox, const D3D12_HEAP_PROPERTIES& heap, + const D3D12_RESOURCE_DESC& desc, D3D12_BARRIER_LAYOUT initial, + const D3D12_CLEAR_VALUE& clear, ID3D12Resource** out, + UINT castable_count = 0, const DXGI_FORMAT* castable = nullptr) { + D3D12_RESOURCE_DESC1 input{desc.Dimension, desc.Alignment, desc.Width, desc.Height, desc.DepthOrArraySize, + desc.MipLevels, desc.Format, desc.SampleDesc, desc.Layout, desc.Flags, {}}; + if (xbox && rt::d3d12_xs::device_slot_overridden(127)) { + using Slot127 = HRESULT(WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS, + const D3D12_RESOURCE_DESC1*, D3D12_BARRIER_LAYOUT, const D3D12_CLEAR_VALUE*, + ID3D12ProtectedResourceSession*, UINT, const DXGI_FORMAT*, REFIID, void**); + const auto create = reinterpret_cast(d3d12test::slot(xbox, 127)); + return create(xbox, &heap, D3D12_HEAP_FLAG_NONE, &input, initial, &clear, nullptr, + castable_count, castable, IID_PPV_ARGS(out)); + } + Ref device10; + const HRESULT hr = device->QueryInterface(IID_PPV_ARGS(&device10.p)); + if (FAILED(hr)) return hr; + input.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + return device10->CreateCommittedResource3(&heap, D3D12_HEAP_FLAG_NONE, &input, initial, &clear, nullptr, + castable_count, castable, IID_PPV_ARGS(out)); +} + +int run(vktest::Device& vk, UINT width, UINT height, bool enhanced, Texture kind, UINT16 layers, + DXGI_FORMAT format, Handoff handoff) { + const bool array = layers > 1; + // Array views cover the last two layers so the shader reaches slice 5 in the six-layer case. + const UINT first_slice = array ? layers - 2u : 0; + const bool placed = kind == Texture::placed; + const bool modern = kind == Texture::committed3; + const bool depth16 = format == DXGI_FORMAT_R16_TYPELESS; + const UINT planes = depth16 ? 1 : 2; + const UINT subresources = planes * layers; + const char* fixture = array ? LEONIDA_DEPTH_STENCIL_ARRAY_SPV : LEONIDA_DEPTH_STENCIL_2D_SPV; + const char* bindings = array ? "2,11,12" : "2,8,9"; + if (depth16) { + fixture = array ? LEONIDA_DEPTH16_ARRAY_SPV : LEONIDA_DEPTH16_2D_SPV; + bindings = array ? "2,12" : "2,9"; + } + const auto program = d3d12test::fssm_program({0x44535541, 0xbf810000}); + const auto shader = d3d12test::shader_container(program); + const testfiles::ScratchDir library("leonida_depth_stencil_uav"); + CHECK(testfiles::copy_file(vktest::shader_fixture_path(fixture), library.path() / "write.spv")); + { + std::ofstream index(library.path() / "index.json", std::ios::binary); + index << "{\"write\":{\"stage\":\"cs\",\"fssm_sha256\":\"" << leonida::sha256_hex(program) + << "\",\"bindings\":[" << bindings << "],\"push_constant_bytes\":80,\"local_size\":[1,1,1],\"wave64\":false}}"; + CHECK(index.good()); + } + + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = vk.instance_proc; + info.instance = vk.instance; + info.physical = vk.physical; + info.device = vk.device; + info.queue = vk.queue; + info.queue_family = vk.family; + info.compute_family = vk.compute_family; + info.compute_queues = {vk.compute_queue}; + info.maintenance10 = vk.maintenance10; + info.bindless = vk.bindless; + info.bindless_partially_bound = vk.partially_bound; + info.buffer_device_address = vk.buffer_device_address; + info.shader_dir = library.path().string(); + ID3D12Device* device = nullptr; + CHECK(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device)))); + Ref xbox; + CHECK(SUCCEEDED(rt::d3d12_xs::create_device_proxy(device, IID_PPV_ARGS(&xbox.p)))); // takes ownership + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = width; + desc.Height = height; + desc.MipLevels = 1; + desc.DepthOrArraySize = layers; + desc.SampleDesc.Count = 1; + desc.Format = format; + desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + desc.Layout = static_cast(0x101); + D3D12_HEAP_PROPERTIES props{}; + props.Type = D3D12_HEAP_TYPE_DEFAULT; + D3D12_CLEAR_VALUE optimized{}; + optimized.Format = depth16 ? DXGI_FORMAT_D16_UNORM : DXGI_FORMAT_D32_FLOAT_S8X24_UINT; + optimized.DepthStencil.Depth = 1.0f; + auto normalized = desc; + normalized.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + if (modern) { + // The standalone PC Device10 retains its ordinary rejection of the combined creation flags. + Ref refused; + CHECK(create_committed3(device, nullptr, props, desc, D3D12_BARRIER_LAYOUT_COMMON, + optimized, &refused.p) == E_INVALIDARG && !refused.p); + } + rt::d3d12::set_device_outer(device, xbox.p); + if (!enhanced && !array && !depth16) CHECK(placeddepthtest::check_alias_lifetime(device, xbox.p) && placeddepthtest::check_alias_lifetime(device, xbox.p, true)); + using CreateFn = HRESULT(WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS, + const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_STATES, const D3D12_CLEAR_VALUE*, + REFIID, void**); + // The baseline uses PC sizing. In builds with the Xbox slot-25 dependency, size the placement through + // the console's return-buffer-first ABI; keep native footprints for the host pixel readback. + auto native_depth = normalized; + native_depth.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + auto size = device->GetResourceAllocationInfo(0, 1, &native_depth); + CHECK(size.SizeInBytes > 0 && size.SizeInBytes != UINT64_MAX); + if (modern) { + const auto logical = device->GetResourceAllocationInfo(0, 1, &normalized); + CHECK(logical.SizeInBytes == size.SizeInBytes && logical.Alignment == size.Alignment); + } + if (rt::d3d12_xs::device_slot_overridden(25)) { + using SizeFn = D3D12_RESOURCE_ALLOCATION_INFO*(WINAPI*)(D3D12_RESOURCE_ALLOCATION_INFO*, void*, + UINT, UINT, const D3D12_RESOURCE_DESC*); + D3D12_RESOURCE_ALLOCATION_INFO xbox_size{}; + const auto get_size = reinterpret_cast(d3d12test::slot(xbox.p, 25)); + CHECK(get_size(&xbox_size, xbox.p, 0, 1, &desc) == &xbox_size); + CHECK(xbox_size.SizeInBytes >= size.SizeInBytes && xbox_size.SizeInBytes != UINT64_MAX && + xbox_size.Alignment >= size.Alignment); + size = xbox_size; + } + GuestAllocation guest; + Ref texture, alias; + const auto create_texture = reinterpret_cast(d3d12test::slot(xbox.p, 76)); + if (placed) { + using PlaceFn = HRESULT(WINAPI*)(void*, UINT64, const D3D12_RESOURCE_DESC*, D3D12_BARRIER_LAYOUT, + const D3D12_CLEAR_VALUE*, REFIID, void**); + const auto place = reinterpret_cast(d3d12test::slot(xbox.p, 133)); + guest.address = VirtualAlloc(nullptr, SIZE_T(size.SizeInBytes), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + CHECK(guest.address); + const auto va = reinterpret_cast(guest.address); + const auto layout = enhanced ? D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS : D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE; + CHECK(SUCCEEDED(place(xbox.p, va, &desc, layout, nullptr, + IID_PPV_ARGS(&texture.p)))); + Ref rejected; + CHECK(place(xbox.p, va, &desc, D3D12_BARRIER_LAYOUT_RENDER_TARGET, nullptr, + IID_PPV_ARGS(&rejected.p)) == E_INVALIDARG && !rejected.p); + CHECK(SUCCEEDED(place(xbox.p, va, &desc, D3D12_BARRIER_LAYOUT_SHADER_RESOURCE, nullptr, + IID_PPV_ARGS(&alias.p)))); + CHECK(texture.p != alias.p && texture->GetGPUVirtualAddress() == va && alias->GetGPUVirtualAddress() == va); + } else if (modern) { + // Exercise the exact no-list overload as well as lists naming both the attachment and its writable planes. + const DXGI_FORMAT d16_views[] = {DXGI_FORMAT_D16_UNORM, DXGI_FORMAT_R16_UNORM, DXGI_FORMAT_R16_UINT}; + const DXGI_FORMAT d32s8_views[] = {DXGI_FORMAT_D32_FLOAT_S8X24_UINT, DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS, + DXGI_FORMAT_X32_TYPELESS_G8X24_UINT, DXGI_FORMAT_R32_FLOAT, DXGI_FORMAT_R8_UINT}; + const UINT count = layers == 3 ? UINT(depth16 ? std::size(d16_views) : std::size(d32s8_views)) : 0; + const DXGI_FORMAT* castable = count ? (depth16 ? d16_views : d32s8_views) : nullptr; + CHECK(SUCCEEDED(create_committed3(device, xbox.p, props, desc, D3D12_BARRIER_LAYOUT_COMMON, + optimized, &texture.p, count, castable)) && texture.p); + if (!array) { + Ref refused; + CHECK(create_committed3(device, xbox.p, props, desc, D3D12_BARRIER_LAYOUT_RENDER_TARGET, + optimized, &refused.p) == E_INVALIDARG && !refused.p); + auto wrong_clear = optimized; + wrong_clear.Format = DXGI_FORMAT_D32_FLOAT; + CHECK(create_committed3(device, xbox.p, props, desc, D3D12_BARRIER_LAYOUT_COMMON, + wrong_clear, &refused.p) == E_INVALIDARG && !refused.p); + const DXGI_FORMAT incompatible = DXGI_FORMAT_R32G32_FLOAT; + CHECK(create_committed3(device, xbox.p, props, desc, D3D12_BARRIER_LAYOUT_COMMON, + optimized, &refused.p, 1, &incompatible) == E_INVALIDARG && !refused.p); + // The PC Device10 endpoint returns S_FALSE for a successful validation-only call. + CHECK(create_committed3(device, nullptr, props, desc, D3D12_BARRIER_LAYOUT_COMMON, + optimized, nullptr) == S_FALSE); + } + } else { + const auto heap_flags = !enhanced && !array && !depth16 + ? D3D12_HEAP_FLAG_ALLOW_SHADER_ATOMICS : D3D12_HEAP_FLAG_NONE; + CHECK(SUCCEEDED(create_texture(xbox.p, &props, heap_flags, &desc, D3D12_RESOURCE_STATE_DEPTH_WRITE, + nullptr, IID_PPV_ARGS(&texture.p)))); + D3D12_HEAP_FLAGS reported{}; + CHECK(SUCCEEDED(texture->GetHeapProperties(nullptr, &reported))); + CHECK((reported & D3D12_HEAP_FLAG_ALLOW_SHADER_ATOMICS) == heap_flags); + if (heap_flags) { + Ref depth_only; + CHECK(device->CreateCommittedResource(&props, heap_flags, &native_depth, D3D12_RESOURCE_STATE_DEPTH_WRITE, + nullptr, IID_PPV_ARGS(&depth_only.p)) == E_INVALIDARG && !depth_only.p); + for (auto type : {D3D12_HEAP_TYPE_UPLOAD, D3D12_HEAP_TYPE_READBACK}) { + auto cpu_heap = props; + cpu_heap.Type = type; + Ref invalid; + CHECK(create_texture(xbox.p, &cpu_heap, heap_flags, &desc, D3D12_RESOURCE_STATE_COMMON, + nullptr, IID_PPV_ARGS(&invalid.p)) == E_INVALIDARG && !invalid.p); + } + } + } + CHECK(texture->GetDesc().Flags == desc.Flags); + if (array) CHECK(check_depth_uav_array_views(device, texture.p, depth16)); + + const D3D12_DESCRIPTOR_HEAP_DESC dsv_desc{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, layers, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + const D3D12_DESCRIPTOR_HEAP_DESC views_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4, + D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + Ref dsv, views; + CHECK(SUCCEEDED(device->CreateDescriptorHeap(&dsv_desc, IID_PPV_ARGS(&dsv.p)))); + CHECK(SUCCEEDED(device->CreateDescriptorHeap(&views_desc, IID_PPV_ARGS(&views.p)))); + D3D12_DEPTH_STENCIL_VIEW_DESC depth_view{}; + depth_view.Format = depth16 ? DXGI_FORMAT_D16_UNORM : DXGI_FORMAT_D32_FLOAT_S8X24_UINT; + depth_view.ViewDimension = array ? D3D12_DSV_DIMENSION_TEXTURE2DARRAY : D3D12_DSV_DIMENSION_TEXTURE2D; + const SIZE_T dsv_step = device->GetDescriptorHandleIncrementSize(dsv_desc.Type); + const auto depth_handle = dsv->GetCPUDescriptorHandleForHeapStart(); + for (UINT layer = 0; layer < layers; ++layer) { + if (array) depth_view.Texture2DArray = {0, layer, 1}; + device->CreateDepthStencilView(texture.p, &depth_view, {depth_handle.ptr + dsv_step * layer}); + } + const SIZE_T base = views->GetCPUDescriptorHandleForHeapStart().ptr; + const SIZE_T step = device->GetDescriptorHandleIncrementSize(views_desc.Type); + CHECK(base && step >= 32); + std::uint32_t keys[2][8]{}; + for (UINT plane = 0; plane < planes; ++plane) { + D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; + view.ViewDimension = array ? D3D12_UAV_DIMENSION_TEXTURE2DARRAY : D3D12_UAV_DIMENSION_TEXTURE2D; + view.Format = depth16 ? DXGI_FORMAT_R16_UINT : plane == 0 ? DXGI_FORMAT_R32_FLOAT : DXGI_FORMAT_R8_UINT; + if (array) view.Texture2DArray = {0, first_slice, 2, plane}; + else view.Texture2D.PlaneSlice = plane; + const D3D12_CPU_DESCRIPTOR_HANDLE handle{base + plane * step}; + device->CreateUnorderedAccessView(texture.p, nullptr, &view, handle); + std::memcpy(keys[plane], reinterpret_cast(handle.ptr), sizeof(keys[plane])); + CHECK(rt::d3d12::bindless_hash_lookup(device, keys[plane]) != 0); + } + if (planes == 2) CHECK(std::memcmp(keys[0], keys[1], sizeof(keys[0])) != 0); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = depth16 ? DXGI_FORMAT_R16_UNORM : DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.ViewDimension = array ? D3D12_SRV_DIMENSION_TEXTURE2DARRAY : D3D12_SRV_DIMENSION_TEXTURE2D; + if (array) srv.Texture2DArray = {0, 1, first_slice, 2, 0, 0.0f}; + else srv.Texture2D.MipLevels = 1; + const D3D12_CPU_DESCRIPTOR_HANDLE sampled{base + 2 * step}; + device->CreateShaderResourceView(texture.p, &srv, sampled); + std::uint32_t sampled_key[8]{}; + std::memcpy(sampled_key, reinterpret_cast(sampled.ptr), sizeof(sampled_key)); + CHECK(rt::d3d12::bindless_hash_lookup(device, sampled_key) != 0); + CHECK(std::memcmp(sampled_key, keys[0], sizeof(sampled_key)) != 0); + const D3D12_CPU_DESCRIPTOR_HANDLE invalid{base + 3 * step}; + std::uint32_t zero[8]{}; + for (UINT plane = 0; plane < 2; ++plane) { + std::memset(reinterpret_cast(invalid.ptr), 0x55, sizeof(zero)); + D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; + view.ViewDimension = array ? D3D12_UAV_DIMENSION_TEXTURE2DARRAY : D3D12_UAV_DIMENSION_TEXTURE2D; + if (array) view.Texture2DArray = {0, first_slice, 2, plane}; + else view.Texture2D.PlaneSlice = plane; + view.Format = plane == 0 ? DXGI_FORMAT_R8_UINT : DXGI_FORMAT_R32_FLOAT; + device->CreateUnorderedAccessView(texture.p, nullptr, &view, invalid); + CHECK(std::memcmp(reinterpret_cast(invalid.ptr), zero, sizeof(zero)) == 0); + } + + // ClearUAV takes matching handles to two copies of the descriptor and the original Xbox resource. + const D3D12_DESCRIPTOR_HEAP_DESC visible_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + Ref visible; + CHECK(SUCCEEDED(device->CreateDescriptorHeap(&visible_desc, IID_PPV_ARGS(&visible.p)))); + device->CopyDescriptorsSimple(planes, visible->GetCPUDescriptorHandleForHeapStart(), {base}, visible_desc.Type); + const auto gpu = visible->GetGPUDescriptorHandleForHeapStart(); + const FLOAT depth_clear[] = {0.75f, 0, 0, 0}; + const UINT stencil_clear[] = {0x31, 0, 0, 0}; + if (!array) { + // Both parents have a real R32_FLOAT storage plane, but this T# belongs to the first parent only. + auto other_desc = desc; + other_desc.Width = other_desc.Height = 2; + Ref other; + CHECK(SUCCEEDED(create_texture(xbox.p, &props, D3D12_HEAP_FLAG_NONE, &other_desc, + D3D12_RESOURCE_STATE_DEPTH_WRITE, nullptr, IID_PPV_ARGS(&other.p)))); + copycmp::Run rejected; + CHECK(rejected.init(device, true)); + rejected.begin(); + rejected.barrier(other.p, D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + ID3D12DescriptorHeap* heaps[] = {visible.p}; + rejected.list->SetDescriptorHeaps(1, heaps); + rejected.list->ClearUnorderedAccessViewFloat(gpu, {base}, other.p, depth_clear, 0, nullptr); + CHECK(rejected.list->Close() == E_INVALIDARG); + } + + D3D12_ROOT_PARAMETER param{}; + param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + param.Constants.Num32BitValues = 16; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC rs{}; + rs.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + rs.Desc_1_0 = {1, ¶m, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + const auto root_blob = d3d12test::serialize_root_signature(rs); + Ref root; + CHECK(!root_blob.empty()); + CHECK(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p)))); + D3D12_COMPUTE_PIPELINE_STATE_DESC pipeline_desc{}; + pipeline_desc.pRootSignature = root.p; + pipeline_desc.CS = {shader.data(), shader.size()}; + Ref pipeline; + CHECK(SUCCEEDED(device->CreateComputePipelineState(&pipeline_desc, IID_PPV_ARGS(&pipeline.p)))); + + // Three submissions. Only the final fence is waited on by the CPU. + copycmp::Run graphics; + CHECK(graphics.init(device, true)); + const auto worker_type = handoff == Handoff::direct ? D3D12_COMMAND_LIST_TYPE_DIRECT : D3D12_COMMAND_LIST_TYPE_COMPUTE; + D3D12_COMMAND_QUEUE_DESC worker_desc{}; + worker_desc.Type = worker_type; + Ref worker; + CHECK(SUCCEEDED(device->CreateCommandQueue(&worker_desc, IID_PPV_ARGS(&worker.p)))); + Batch shader_batch, read_batch; + CHECK(shader_batch.open(device, worker_type) && read_batch.open(device, D3D12_COMMAND_LIST_TYPE_DIRECT)); + std::vector layouts(subresources); + std::vector row_bytes(subresources); + UINT64 total = 0; + device->GetCopyableFootprints(&native_depth, 0, subresources, 0, layouts.data(), nullptr, row_bytes.data(), &total); + CHECK(row_bytes[0] == width * (depth16 ? 2 : 4)); + if (planes == 2) CHECK(row_bytes[layers] == width); + copycmp::Ptr readback; + CHECK(graphics.buffer(D3D12_HEAP_TYPE_READBACK, total, D3D12_RESOURCE_STATE_COPY_DEST, readback)); + + const float depth_seed[] = {0.5f, 0.25f, 1.0f}; + const UINT8 stencil_seed[] = {0x5a, 0x37, 0xcb}; + const UINT16 d16_seed[] = {0, 0xffff, 257, 514, 771, 1028}; + const auto flags = depth16 ? D3D12_CLEAR_FLAG_DEPTH : D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL; + if (modern) { + Ref list; + CHECK(SUCCEEDED(graphics.list->QueryInterface(IID_PPV_ARGS(&list.p)))); + enhanced_transition(list.p, texture.p, D3D12_BARRIER_SYNC_ALL, + D3D12_BARRIER_ACCESS_COMMON, D3D12_BARRIER_LAYOUT_COMMON, D3D12_BARRIER_SYNC_DEPTH_STENCIL, + D3D12_BARRIER_ACCESS_DEPTH_STENCIL_WRITE, D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE); + } + for (UINT layer = 0; layer < layers; ++layer) + graphics.list->ClearDepthStencilView({depth_handle.ptr + dsv_step * layer}, flags, + depth16 ? float(d16_seed[layer]) / 65535.0f : depth_seed[layer], depth16 ? 0 : stencil_seed[layer], + 0, nullptr); + + const bool compute_copy = handoff == Handoff::compute_transitions; + // Graphics-side transfers use ordinary cross-queue UAV layout. With maintenance10 the compute family can + // also perform the transfers, with COMMON as the shared handoff layout at both fences. + if (enhanced) { + Ref list; + CHECK(SUCCEEDED(graphics.list->QueryInterface(IID_PPV_ARGS(&list.p)))); + enhanced_transition(list.p, texture.p, D3D12_BARRIER_SYNC_DEPTH_STENCIL, + D3D12_BARRIER_ACCESS_DEPTH_STENCIL_WRITE, D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE, + D3D12_BARRIER_SYNC_ALL, compute_copy ? D3D12_BARRIER_ACCESS_COMMON : D3D12_BARRIER_ACCESS_UNORDERED_ACCESS, + compute_copy ? D3D12_BARRIER_LAYOUT_COMMON : D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS); + } else { + graphics.barrier(texture.p, D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + } + CHECK(SUCCEEDED(graphics.list->Close())); + ID3D12CommandList* write_lists[] = {graphics.list.p}; + graphics.queue->ExecuteCommandLists(1, write_lists); + CHECK(rt::d3d12::last_execute_result(graphics.queue.p) == leonida::ReplayResult::success); + CHECK(SUCCEEDED(graphics.queue->Signal(graphics.fence.p, 1))); + CHECK(SUCCEEDED(worker->Wait(graphics.fence.p, 1))); + Ref compute_list; + if (compute_copy) { + CHECK(SUCCEEDED(shader_batch.list->QueryInterface(IID_PPV_ARGS(&compute_list.p)))); + enhanced_transition(compute_list.p, texture.p, D3D12_BARRIER_SYNC_ALL, D3D12_BARRIER_ACCESS_COMMON, + D3D12_BARRIER_LAYOUT_COMMON, D3D12_BARRIER_SYNC_COMPUTE_SHADING, D3D12_BARRIER_ACCESS_UNORDERED_ACCESS, + D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS); + } + const D3D12_RECT depth_rect{1, 3, 2, 4}, stencil_rect{3, 2, 4, 3}; + ID3D12DescriptorHeap* clear_heaps[] = {visible.p}; + auto* list = shader_batch.list.p; + list->SetDescriptorHeaps(1, clear_heaps); + const UINT d16_clear[] = {0x4512, 0, 0, 0}; + if (depth16) list->ClearUnorderedAccessViewUint(gpu, {base}, texture.p, d16_clear, 1, &depth_rect); + else { + list->ClearUnorderedAccessViewFloat(gpu, {base}, texture.p, depth_clear, 1, &depth_rect); + list->ClearUnorderedAccessViewUint({gpu.ptr + step}, {base + step}, texture.p, stencil_clear, 1, &stencil_rect); + } + D3D12_RESOURCE_BARRIER order{}; + order.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + order.UAV.pResource = texture.p; + list->ResourceBarrier(1, &order); + list->SetComputeRootSignature(root.p); + list->SetPipelineState(pipeline.p); + list->SetComputeRoot32BitConstants(0, 16, keys, 0); + list->Dispatch(1, 1, 1); + if (compute_copy) + enhanced_transition(compute_list.p, texture.p, D3D12_BARRIER_SYNC_COMPUTE_SHADING, + D3D12_BARRIER_ACCESS_UNORDERED_ACCESS, D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS, + D3D12_BARRIER_SYNC_ALL, D3D12_BARRIER_ACCESS_COMMON, D3D12_BARRIER_LAYOUT_COMMON); + CHECK(shader_batch.submit(worker.p, graphics.fence.p, 2)); + CHECK(SUCCEEDED(graphics.queue->Wait(graphics.fence.p, 2))); + + // The second placement reads the first one's writes at the same guest address. + auto* reader = placed ? alias.p : texture.p; + if (placed) { + D3D12_RESOURCE_BARRIER activate{}; + activate.Type = D3D12_RESOURCE_BARRIER_TYPE_ALIASING; + activate.Aliasing = {texture.p, reader}; + read_batch.list->ResourceBarrier(1, &activate); + } + if (enhanced) { + Ref read_list; + CHECK(SUCCEEDED(read_batch.list->QueryInterface(IID_PPV_ARGS(&read_list.p)))); + enhanced_transition(read_list.p, reader, D3D12_BARRIER_SYNC_ALL, + compute_copy ? D3D12_BARRIER_ACCESS_COMMON : D3D12_BARRIER_ACCESS_UNORDERED_ACCESS, + compute_copy ? D3D12_BARRIER_LAYOUT_COMMON : D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS, + D3D12_BARRIER_SYNC_COPY, D3D12_BARRIER_ACCESS_COPY_SOURCE, D3D12_BARRIER_LAYOUT_COPY_SOURCE); + } else { + D3D12_RESOURCE_BARRIER copy{}; + copy.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + copy.Transition = {reader, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE}; + read_batch.list->ResourceBarrier(1, ©); + } + for (UINT sub = 0; sub < subresources; ++sub) { + const auto src = copycmp::sub_loc(reader, sub); + const auto dst = copycmp::foot_loc(readback.p, layouts[sub]); + read_batch.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + } + CHECK(read_batch.submit(graphics.queue.p, graphics.fence.p, 3)); + CHECK(SUCCEEDED(graphics.fence->SetEventOnCompletion(3, nullptr))); + CHECK(graphics.fence->GetCompletedValue() >= 3 && SUCCEEDED(device->GetDeviceRemovedReason())); + unsigned char* mapped = nullptr; + CHECK(SUCCEEDED(readback->Map(0, nullptr, reinterpret_cast(&mapped))) && mapped); + for (UINT sub = 0; sub < subresources; ++sub) { + const UINT layer = sub % layers; + const UINT plane = sub / layers; + const UINT bytes = plane ? 1 : depth16 ? 2 : 4; + for (UINT y = 0; y < height; ++y) { + for (UINT x = 0; x < width; ++x) { + const bool in_view = layer >= first_slice; + const bool cleared = in_view && (plane ? x == 3 && y == 2 : x == 1 && y == 3); + UINT32 expected = 0; + if (depth16) { + expected = cleared ? d16_clear[0] : d16_seed[layer]; + if (layer == layers - 1u && x == 2 && y == 1) expected ^= 0x1357u; + } else if (plane == 0) { + float depth = cleared ? depth_clear[0] : depth_seed[layer]; + if (layer == first_slice && x == 2 && y == 1) depth *= 0.25f; + std::memcpy(&expected, &depth, sizeof(depth)); + } else { + expected = cleared ? stencil_clear[0] : stencil_seed[layer]; + if (layer == layers - 1u && x == 5 && y == 3) expected ^= 0xffu; + } + UINT32 actual = 0; + std::memcpy(&actual, mapped + layouts[sub].Offset + y * layouts[sub].Footprint.RowPitch + x * bytes, bytes); + if (actual != expected) { + std::fprintf(stderr, "subresource %u pixel (%u,%u): got %#x, expected %#x\n", sub, x, y, actual, expected); + readback->Unmap(0, nullptr); + return 1; + } + } + } + } + readback->Unmap(0, nullptr); + const char* path = placed ? "slot 133" : "slot 76"; + if (modern) path = rt::d3d12_xs::device_slot_overridden(127) ? "slot 127" : "CreateCommittedResource3"; + std::printf("%s, %ux%u, %u layers, %u planes, %s barriers, graphics family %u, shader family %u, " + "plane transfers on %s: every pixel matched\n", path, width, height, UINT(layers), planes, + enhanced ? "enhanced" : "legacy", vk.family, handoff == Handoff::direct ? vk.family : vk.compute_family, + compute_copy ? "compute" : "graphics"); + return 0; +} +} // namespace + +int main() { + vktest::Device vk; + vk.request_buffer_device_address = true; + vk.all_queue_types = true; + const auto status = vk.initialize(); + if (status == vktest::DeviceStatus::unavailable) return 77; + if (status != vktest::DeviceStatus::ready) return 1; + if (!vk.bindless || !vk.storage_image_extended_formats) { + std::fprintf(stderr, "SKIP: shader requires bindless images and typed r8ui storage\n"); + return 77; + } + const auto d32s8 = DXGI_FORMAT_R32G8X24_TYPELESS, d16 = DXGI_FORMAT_R16_TYPELESS; + if (run(vk, 9, 7, false, Texture::committed, 1, d32s8, Handoff::direct) || + run(vk, 2560, 1440, true, Texture::committed, 1, d32s8, Handoff::direct) || + run(vk, 9, 7, true, Texture::placed, 1, d16, Handoff::graphics_transitions)) return 1; + for (const auto format : {d32s8, d16}) { + if (run(vk, 9, 7, false, Texture::committed, 3, format, Handoff::graphics_transitions) || + run(vk, 13, 9, true, Texture::placed, 3, format, Handoff::graphics_transitions)) return 1; + const auto vk_format = format == d16 ? VK_FORMAT_D16_UNORM : VK_FORMAT_D32_SFLOAT_S8_UINT; + if (compute_transfers(vk, vk_format, format != d16)) { + if (run(vk, 9, 7, true, Texture::placed, 3, format, Handoff::compute_transitions)) return 1; + } else { + std::printf("compute-side depth transfers unavailable for VkFormat %u; graphics-side handoff tested\n", + unsigned(vk_format)); + } + } + // Array lengths reported by the Xbox boot trace. The texels are synthetic. + constexpr UINT16 reported_layers[] = {1, 3, 6}; + for (const UINT16 layers : reported_layers) + if (run(vk, 9, 7, true, Texture::committed3, layers, d16, Handoff::graphics_transitions)) return 1; + if (run(vk, 9, 7, true, Texture::committed3, 3, d32s8, Handoff::graphics_transitions)) return 1; + return vk.validation_errors() ? 1 : 0; +} diff --git a/runtime/test/d3d12_depth_stencil_uav_views.h b/runtime/test/d3d12_depth_stencil_uav_views.h new file mode 100644 index 0000000000..8800132adf --- /dev/null +++ b/runtime/test/d3d12_depth_stencil_uav_views.h @@ -0,0 +1,79 @@ +#pragma once + +#include "d3d12_test_shaders.h" +#include "../src/gfx10_descriptors.h" + +#include +#include + +// Exercise the descriptors as seen by a console shader, including the array size sentinel and invalid ranges. +inline bool check_depth_uav_array_views(ID3D12Device* device, ID3D12Resource* resource, bool depth16) { + namespace g = leonida::gfx10; + const UINT layers = resource->GetDesc().DepthOrArraySize; + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, + D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + d3d12test::Ref heap; + if (layers < 2 || FAILED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p)))) return false; + const auto slot = heap->GetCPUDescriptorHandleForHeapStart(); + const auto read = [&] { + g::ImageWords words{}; + std::memcpy(words.data(), reinterpret_cast(slot.ptr), sizeof(words)); + return words; + }; + const auto uav = [&](const D3D12_UNORDERED_ACCESS_VIEW_DESC* view) { + std::memset(reinterpret_cast(slot.ptr), 0x55, sizeof(g::ImageWords)); + device->CreateUnorderedAccessView(resource, nullptr, view, slot); + return read(); + }; + const g::ImageWords empty{}; + D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; + view.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + view.Format = depth16 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_FLOAT; + view.Texture2DArray = {0, 0, 1, 0}; + g::Image first{}, tail{}; + if (!g::decode(uav(&view), first) || first.type != g::ImageType::image_2d_array || + first.first_layer != 0 || first.layer_count != 1) return false; + view.Texture2DArray = {0, 1, UINT_MAX, 0}; + const auto remaining = uav(&view); + view.Texture2DArray.ArraySize = layers - 1; + if (remaining != uav(&view) || !g::decode(remaining, tail) || tail.address != first.address || + tail.first_layer != 1 || tail.layer_count != layers - 1) return false; + + // A depth SRV still names the original image, with the same base layer and count. + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = depth16 ? DXGI_FORMAT_R16_UNORM : DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; + srv.Texture2DArray = {0, 1, 1, layers - 1, 0, 0}; + device->CreateShaderResourceView(resource, &srv, slot); + g::Image attachment{}; + if (!g::decode(read(), attachment) || attachment.type != g::ImageType::image_2d_array || + attachment.address == tail.address || attachment.first_layer != 1 || attachment.layer_count != layers - 1) + return false; + if (!depth16) { + srv.Format = DXGI_FORMAT_X32_TYPELESS_G8X24_UINT; + srv.Texture2DArray.PlaneSlice = 1; + device->CreateShaderResourceView(resource, &srv, slot); + g::Image stencil{}; + if (!g::decode(read(), stencil) || stencil.address != attachment.address || + stencil.format != g::stencil_format || stencil.first_layer != 1 || stencil.layer_count != layers - 1) + return false; + } + for (const D3D12_TEX2D_ARRAY_UAV invalid : { + D3D12_TEX2D_ARRAY_UAV{1, 0, 1, 0}, {0, 0, 0, 0}, {0, layers, UINT_MAX, 0}, + {0, 1, layers, 0}, {0, 0, 1, depth16 ? 1u : 2u}}) { + view.Texture2DArray = invalid; + if (uav(&view) != empty) { + std::fprintf(stderr, "accepted invalid UAV mip %u layers %u+%u plane %u\n", + invalid.MipSlice, invalid.FirstArraySlice, invalid.ArraySize, invalid.PlaneSlice); + return false; + } + } + view.Texture2DArray = {0, 0, 1, 0}; + view.Format = DXGI_FORMAT_R8_UINT; + if (uav(&view) != empty) return false; + view.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; + view.Format = depth16 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_FLOAT; + view.Texture2D = {}; + return uav(&view) == empty && uav(nullptr) == empty; +} diff --git a/runtime/test/d3d12_draw_test.cpp b/runtime/test/d3d12_draw_test.cpp index b979ea42b9..4a70a3b260 100644 --- a/runtime/test/d3d12_draw_test.cpp +++ b/runtime/test/d3d12_draw_test.cpp @@ -16,6 +16,7 @@ // or across B8G8R8X8 and B8G8R8A8: the bytes land in the view's order and encoding. // The shaders are GLSL written to the translator's contract (test/glsl/vs_draw.vert, ps_draw.frag). No game data. // Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. +#include "../src/title_va_alias.h" #include "shader_fixture_path.h" #include "test_temp_dir.h" #include "vk_test_device.h" @@ -44,6 +45,24 @@ using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slot 9: ha namespace { +struct TitleGeometryPages { + static constexpr UINT bytes_per_view = 3 * 1024 * 1024; + static constexpr UINT count = 7; + std::byte* base = nullptr; + ~TitleGeometryPages() { + if (base) { + leonida::title_va_aliases().remove_title_memory(reinterpret_cast(base)); + VirtualFree(base,0,MEM_RELEASE); + } + } + bool allocate() { + base = static_cast(VirtualAlloc(nullptr,SIZE_T(bytes_per_view)*count,MEM_RESERVE|MEM_COMMIT,PAGE_READWRITE)); + if(!base) return false; + leonida::title_va_aliases().add_title_memory(reinterpret_cast(base),SIZE_T(bytes_per_view)*count); + return true; + } +}; + struct Vertex { float x, y; std::uint8_t r, g, b, a; @@ -381,7 +400,15 @@ int main() { // State for the draws; the pipeline came with CreateCommandList. list->SetGraphicsRootSignature(root.p); list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - const D3D12_VERTEX_BUFFER_VIEW vbv{vertex_buffer->GetGPUVirtualAddress(), sizeof(vertices), sizeof(Vertex)}; + const bool large_batch = std::getenv("LEONIDA_TEST_GEOMETRY_BATCH") != nullptr; + TitleGeometryPages title_vertices; + D3D12_VERTEX_BUFFER_VIEW vbv{vertex_buffer->GetGPUVirtualAddress(), sizeof(vertices), sizeof(Vertex)}; + if (large_batch) { + EXPECT(title_vertices.allocate()); + std::memcpy(title_vertices.base,vertices,sizeof(vertices)); + vbv.BufferLocation=reinterpret_cast(title_vertices.base); + vbv.SizeInBytes=TitleGeometryPages::bytes_per_view; + } list->IASetVertexBuffers(0, 1, &vbv); const D3D12_INDEX_BUFFER_VIEW ibv{upload_va + 256, sizeof(indices), DXGI_FORMAT_R16_UINT}; list->IASetIndexBuffer(&ibv); @@ -426,6 +453,18 @@ int main() { list->SetGraphicsRoot32BitConstants(0, 2, down_right, 0); list->DrawIndexedInstanced(6, 1, 0, 0, 0); + if (large_batch) { + // More live bytes than the old 16 MiB ring. These zero-area triangles genuinely consume + // six separate CPU-backed views without changing the reference image of the five prior draws. + list->SetPipelineState(pso.p); + for (UINT i=1; i(title_vertices.base)+ + UINT64(i)*TitleGeometryPages::bytes_per_view,TitleGeometryPages::bytes_per_view,sizeof(Vertex)}; + list->IASetVertexBuffers(0,1,&extra); + list->DrawInstanced(3,1,0,0); + } + list->IASetVertexBuffers(0,1,&vbv); + } D3D12_RESOURCE_BARRIER to_copy = transition(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); list->ResourceBarrier(1, &to_copy); diff --git a/runtime/test/d3d12_m2_textured_test.cpp b/runtime/test/d3d12_m2_textured_test.cpp index cd9448c757..04d2e705ae 100644 --- a/runtime/test/d3d12_m2_textured_test.cpp +++ b/runtime/test/d3d12_m2_textured_test.cpp @@ -25,6 +25,8 @@ // pixels are predicted on the CPU, error 0, and 1536 of them differ from the plain reflection. // The control also keeps one unbounded SRV table bound and selects its two entries by a root constant. // Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation (0 errors required). +#include "../src/gfx10_tiling.h" +#include "../src/title_va_alias.h" #include "vk_test_device.h" #include "d3d12_test_shaders.h" #include "../shims/d3d12_com.h" @@ -34,6 +36,7 @@ #include #include #include +#include #include #include #include @@ -64,10 +67,26 @@ constexpr UINT target_size = 64; // the target: each texel covers 8x8 pixels constexpr UINT target_pitch = target_size * 4; // 256 // The synthetic gradient: red rises with x, green with y, blue falls along the diagonal. -Texel gradient(UINT x, UINT y) { +struct RawPages { + std::byte* data = nullptr; + ~RawPages() { + if (!data) return; + leonida::title_va_aliases().remove_title_memory(reinterpret_cast(data)); + VirtualFree(data, 0, MEM_RELEASE); + } +}; +bool large_raw_surface() { return std::getenv("LEONIDA_TEST_LARGE_RAW_TEXTURE") != nullptr; } +bool test_raw_surface() { return large_raw_surface() || std::getenv("LEONIDA_TEST_RAW_TEXTURE") != nullptr; } +bool test_packed4444(){return std::getenv("LEONIDA_TEST_FIXED4")!=nullptr;} +Texel raw_gradient(UINT x, UINT y) { return {std::uint8_t(x * 36), std::uint8_t(y * 36), std::uint8_t(255 - (x + y) * 16), 255}; } // The second texture: the first one point-reflected, so no texel of it is in the same place. +Texel gradient(UINT x,UINT y) { + auto value=raw_gradient(x,y); + if(test_packed4444())for(auto& c:value)c=static_cast(std::nearbyint(double(c)*15.0/255.0)*17.0); + return value; +} Texel reflected(UINT x, UINT y) { return gradient(texture_size - 1 - x, texture_size - 1 - y); } Texel linear_clamp(UINT col, UINT row) { @@ -92,7 +111,10 @@ Texel linear_clamp(UINT col, UINT row) { } // namespace -int main() { +int main(int argc, char** argv) { + const bool unbounded = argc == 2 && std::strcmp(argv[1], "--refresh-unbounded-samplers") == 0; + const bool disabled = argc == 2 && std::strcmp(argv[1], "--refresh-samplers-off") == 0; + const bool refresh = unbounded || disabled || (argc == 2 && std::strcmp(argv[1], "--refresh-samplers") == 0); vktest::Device d; const auto device_status = d.initialize(); if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips @@ -127,7 +149,10 @@ int main() { std::vector pixels(std::size_t(target_pitch) * target_size), control_pixels = pixels, linear_pixels = pixels; unsigned image_hits = 0, sampler_hits = 0; { + const bool direct_views = std::getenv("LEONIDA_TEST_VISIBLE_VIEWS") != nullptr; + const bool staged_views = direct_views || std::getenv("LEONIDA_TEST_STAGED_VIEWS") != nullptr; rt::d3d12::VulkanDeviceInfo info{}; + info.prepare_on_bind = staged_views; info.get_instance_proc = d.instance_proc; info.instance = d.instance; info.physical = d.physical; @@ -139,6 +164,9 @@ int main() { info.bindless_partially_bound = d.partially_bound; info.image_view_min_lod = d.image_view_min_lod; info.shader_dir = (root_dir / "spirv").string(); + RawPages raw_pages[2]; + RawPages placed_pages[4]; + const bool placed = staged_views || std::getenv("LEONIDA_TEST_PLACED_FIRST_USE") != nullptr; ID3D12Device* inner = nullptr; EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; @@ -149,7 +177,7 @@ int main() { // Root signature: [0] a table of one SRV (s0:s1), [1] a table of one sampler (s2:s3). D3D12_DESCRIPTOR_RANGE srv_range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; - D3D12_DESCRIPTOR_RANGE sampler_range{D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, 1, 0, 0, 0}; + D3D12_DESCRIPTOR_RANGE sampler_range{D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, unbounded ? UINT_MAX : 1u, 0, 0, 0}; D3D12_ROOT_PARAMETER params[2] = {}; params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; params[0].DescriptorTable = {1, &srv_range}; @@ -221,18 +249,45 @@ int main() { texture_desc.Width = texture_desc.Height = texture_size; texture_desc.DepthOrArraySize = 1; texture_desc.MipLevels = 1; - texture_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + texture_desc.Format = test_packed4444()?static_cast(115):DXGI_FORMAT_R8G8B8A8_UNORM; + if(test_packed4444())texture_desc.Flags=D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + const auto initial_state=test_packed4444()?D3D12_RESOURCE_STATE_RENDER_TARGET:D3D12_RESOURCE_STATE_COPY_DEST; texture_desc.SampleDesc.Count = 1; + const auto size=device->GetResourceAllocationInfo(0,1,&texture_desc); + EXPECT(size.SizeInBytes && size.SizeInBytes!=~UINT64{0}); Ref textures[2], upload, readback, readback2, target; - for (auto& texture : textures) - EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &texture_desc, - D3D12_RESOURCE_STATE_COPY_DEST, nullptr, - IID_PPV_ARGS(&texture.p)))); + const auto at_address = [&](RawPages& pages, const D3D12_RESOURCE_DESC& desc, D3D12_BARRIER_LAYOUT layout, + ID3D12Resource** result) { + const auto required = inner->GetResourceAllocationInfo(0,1,&desc); + if (!required.SizeInBytes || required.SizeInBytes == UINT64_MAX) return E_FAIL; + pages.data = static_cast(VirtualAlloc(nullptr, SIZE_T(required.SizeInBytes), MEM_COMMIT|MEM_RESERVE, PAGE_READWRITE)); + if (!pages.data) return E_OUTOFMEMORY; + const auto va = reinterpret_cast(pages.data); + leonida::title_va_aliases().add_title_memory(va, required.SizeInBytes); + using Place = HRESULT(WINAPI*)(void*, UINT64, const D3D12_RESOURCE_DESC*, UINT, const D3D12_CLEAR_VALUE*, const IID*, void**); + return reinterpret_cast(slot(device.p,133))(device.p,va,&desc,UINT(layout),nullptr,&__uuidof(ID3D12Resource), + reinterpret_cast(result)); + }; + for (UINT i=0; i<2; ++i) { + if (placed) { + EXPECT(SUCCEEDED(at_address(placed_pages[i],texture_desc,D3D12_BARRIER_LAYOUT_COPY_DEST,&textures[i].p))); + EXPECT(rt::d3d12::vulkan_memory_flags(textures[i].p) == 0); + } else { + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &texture_desc, + initial_state, nullptr, IID_PPV_ARGS(&textures[i].p)))); + } + } auto rt_desc = texture_desc; + rt_desc.Format=DXGI_FORMAT_R8G8B8A8_UNORM; rt_desc.Width = rt_desc.Height = target_size; rt_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; - EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &rt_desc, - D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&target.p)))); + if (placed) { + EXPECT(SUCCEEDED(at_address(placed_pages[2],rt_desc,D3D12_BARRIER_LAYOUT_COMMON,&target.p))); + EXPECT(rt::d3d12::vulkan_memory_flags(target.p) == 0); + } else { + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &rt_desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&target.p)))); + } // The upload buffer: texture A at 0, texture B at 2048 (8 rows of the 256-byte pitch), the indices at 4096. constexpr UINT64 b_offset = 2048, index_offset = 4096; const auto upload_desc = buffer_desc(8192); @@ -261,13 +316,20 @@ int main() { std::memcpy(up + index_offset, indices, sizeof(indices)); // The two heaps; their start handles come back in RAX (heap slots 9 and 10). - const D3D12_DESCRIPTOR_HEAP_DESC srv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4, + const D3D12_DESCRIPTOR_HEAP_DESC srv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, direct_views ? 5u : 4u, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; - const D3D12_DESCRIPTOR_HEAP_DESC sampler_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 3, + const UINT sampler_slots = unbounded ? D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE : 3u; + const D3D12_DESCRIPTOR_HEAP_DESC sampler_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, sampler_slots, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; Ref srv_heap, sampler_heap; EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&srv_heap_desc, IID_PPV_ARGS(&srv_heap.p)))); + if (refresh) { + rt::d3d12_xs::set_descriptor_heap_allocator( + [](std::size_t n, std::uint64_t) -> void* { return std::calloc(1, n); }, + [](void* p, std::uint64_t) { std::free(p); }); + } EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&sampler_heap_desc, IID_PPV_ARGS(&sampler_heap.p)))); + if (refresh) rt::d3d12_xs::set_descriptor_heap_allocator(nullptr, nullptr); const std::uint64_t srv_cpu = reinterpret_cast(slot(srv_heap.p, 9))(srv_heap.p); const std::uint64_t srv_gpu = reinterpret_cast(slot(srv_heap.p, 10))(srv_heap.p); const std::uint64_t sampler_cpu = reinterpret_cast(slot(sampler_heap.p, 9))(sampler_heap.p); @@ -276,14 +338,56 @@ int main() { EXPECT(srv_cpu && sampler_cpu && srv_gpu >= 0x10000 && sampler_gpu >= 0x10000); EXPECT(srv_gpu < (1ull << 32) && sampler_gpu < (1ull << 32) && step >= 32); + Ref staging_heap; + Ref unused_texture; + D3D12_CPU_DESCRIPTOR_HANDLE staging_start{}; + if (staged_views) { + D3D12_DESCRIPTOR_HEAP_DESC staging{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,3,D3D12_DESCRIPTOR_HEAP_FLAG_NONE,0}; + EXPECT(SUCCEEDED(inner->CreateDescriptorHeap(&staging,IID_PPV_ARGS(&staging_heap.p)))); + staging_start = staging_heap->GetCPUDescriptorHandleForHeapStart(); + EXPECT(SUCCEEDED(at_address(placed_pages[3],texture_desc,D3D12_BARRIER_LAYOUT_COMMON,&unused_texture.p))); + } // The SRVs go into slots 0 and 1 (offset by the increment size), the POINT sampler into the sampler heap. for (UINT i = 0; i < 2; ++i) { D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; - srv.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + srv.Format = texture_desc.Format; srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; srv.Texture2D = {0, 1, 0, 0.0f}; - device->CreateShaderResourceView(textures[i].p, &srv, D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(srv_cpu + i * step)}); + const D3D12_CPU_DESCRIPTOR_HANDLE handle{SIZE_T(srv_cpu + i * step)}; + if (test_raw_surface()) { + const UINT raw_size = large_raw_surface() ? 1024 : texture_size; + leonida::gfx10::TiledSurface2D layout; + EXPECT(leonida::gfx10::TiledSurface2D::make(leonida::gfx10::TileMode::sw_4kb_s, 4, raw_size, raw_size, layout)); + raw_pages[i].data = static_cast(VirtualAlloc(nullptr,layout.tiled_size(),MEM_RESERVE|MEM_COMMIT,PAGE_READWRITE)); + EXPECT(raw_pages[i].data); + const auto addr = reinterpret_cast(raw_pages[i].data); + leonida::title_va_aliases().add_title_memory(addr,layout.tiled_size()); + std::vector source(raw_size*raw_size); + for (UINT y=0; y(0x105); + struct Shape { D3D12_SHADER_RESOURCE_VIEW_DESC view; UINT64 va; } shape{srv,addr}; + static_assert(offsetof(Shape,va)==sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC)); + using RawView = void(WINAPI*)(void*, const D3D12_RESOURCE_DESC*, const Shape*, D3D12_CPU_DESCRIPTOR_HANDLE); + reinterpret_cast(slot(device.p,70))(device.p,&raw,&shape,handle); + leonida::gfx10::ImageWords words{}; + std::memcpy(words.data(),reinterpret_cast(handle.ptr),sizeof(words)); + EXPECT(leonida::gfx10::is_image(words)); + } else if (direct_views) { + device->CreateShaderResourceView(textures[i].p,&srv,handle); + if (!i) device->CreateShaderResourceView(unused_texture.p,&srv,{SIZE_T(srv_cpu+4*step)}); + } else if (staged_views) { + const D3D12_CPU_DESCRIPTOR_HANDLE cpu{staging_start.ptr + i*step}; + device->CreateShaderResourceView(textures[i].p,&srv,cpu); + if (!i) device->CreateShaderResourceView(unused_texture.p,&srv,{staging_start.ptr + 2*step}); + device->CopyDescriptorsSimple(1,handle,cpu,D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + } else { + device->CreateShaderResourceView(textures[i].p, &srv, handle); + } } D3D12_SAMPLER_DESC sampler_desc{}; sampler_desc.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT; @@ -302,6 +406,13 @@ int main() { device->CreateSampler(&sampler_desc, D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(sampler_cpu + 2 * sampler_step)}); + // Seed the game backing directly so the submission test is independent of API write-through. + const auto sampler_real = rt::d3d12_xs::translate_cpu_descriptor_handle(device.p, {SIZE_T(sampler_cpu)}); + if (refresh) { + EXPECT(sampler_real.ptr && sampler_real.ptr != sampler_cpu); + std::memcpy(reinterpret_cast(sampler_cpu), reinterpret_cast(sampler_real.ptr), 3 * sampler_step); + } + // The hash table, after the descriptors were created and before anything has run: a T# is 8 dwords of the // heap slot, an S# 4 dwords followed by 0xFFFFFFFF x4. Each of the three has an index, they differ, and // bytes nothing was created for have none. @@ -313,11 +424,13 @@ int main() { for (unsigned i = 0; i < 8; ++i) key_unknown[i] = 0x5a5a0000u + i; EXPECT(std::memcmp(key_a, key_b, 32) != 0); EXPECT(std::any_of(key_a, key_a + 8, [](std::uint32_t w) { return w != 0; })); - const std::uint32_t index_a = rt::d3d12::bindless_hash_lookup(device.p, key_a); - const std::uint32_t index_b = rt::d3d12::bindless_hash_lookup(device.p, key_b); + std::uint32_t index_a = rt::d3d12::bindless_hash_lookup(device.p, key_a); + std::uint32_t index_b = rt::d3d12::bindless_hash_lookup(device.p, key_b); const std::uint32_t index_s = rt::d3d12::bindless_hash_lookup(device.p, key_s); std::fprintf(stderr, "hash table: T# A -> %u, T# B -> %u, S# -> %u\n", index_a, index_b, index_s); - EXPECT(index_a && index_b && index_s && index_a != index_b); + EXPECT(index_s); + if (staged_views) EXPECT(index_a == 0 && index_b == 0); + else EXPECT(index_a && index_b && index_a != index_b); std::uint32_t key_wrap[8]; std::memcpy(key_wrap, reinterpret_cast(sampler_cpu + sampler_step), 16); std::fill(key_wrap + 4, key_wrap + 8, 0xffffffffu); @@ -333,6 +446,10 @@ int main() { const D3D12_CPU_DESCRIPTOR_HANDLE rtv{ SIZE_T(reinterpret_cast(slot(rtv_heap.p, 9))(rtv_heap.p))}; device->CreateRenderTargetView(target.p, nullptr, rtv); + if (placed) { + EXPECT(rt::d3d12::vulkan_memory_flags(target.p) == 0); + for (const auto& texture : textures) EXPECT((rt::d3d12::vulkan_memory_flags(texture.p) == 0) == staged_views); + } D3D12_COMMAND_QUEUE_DESC queue_desc{}; Ref queue; @@ -346,20 +463,38 @@ int main() { EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); // Upload both textures, then make them shader resources and the target a render target. - for (UINT i = 0; i < 2; ++i) { - D3D12_TEXTURE_COPY_LOCATION dst{}; - dst.pResource = textures[i].p; - dst.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; - D3D12_TEXTURE_COPY_LOCATION src{}; - src.pResource = upload.p; - src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; - src.PlacedFootprint = footprint; - src.PlacedFootprint.Offset = i ? b_offset : 0; - list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + Ref packed_rtv; + if(test_packed4444()){ + D3D12_DESCRIPTOR_HEAP_DESC desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV,2,D3D12_DESCRIPTOR_HEAP_FLAG_NONE,0}; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&desc,IID_PPV_ARGS(&packed_rtv.p)))); + const auto first=reinterpret_cast(slot(packed_rtv.p,9))(packed_rtv.p); + const auto stride=device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); + for(unsigned i=0;i<2;++i){ + const D3D12_CPU_DESCRIPTOR_HANDLE dest{SIZE_T(first+i*stride)}; + device->CreateRenderTargetView(textures[i].p,nullptr,dest); + for(unsigned y=0;yClearRenderTargetView(dest,channels,1,&area); + } + } + } else { + for (UINT i = 0; i < 2; ++i) { + D3D12_TEXTURE_COPY_LOCATION dst{}; + dst.pResource = textures[i].p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + D3D12_TEXTURE_COPY_LOCATION src{}; + src.pResource = upload.p; + src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + src.PlacedFootprint = footprint; + src.PlacedFootprint.Offset = i ? b_offset : 0; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + } } D3D12_RESOURCE_BARRIER barriers[3] = { - transition(textures[0].p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE), - transition(textures[1].p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE), + transition(textures[0].p, initial_state, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE), + transition(textures[1].p, initial_state, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE), transition(target.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET)}; list->ResourceBarrier(3, barriers); const FLOAT clear[4] = {1.0f, 0.0f, 1.0f, 1.0f}; // magenta: a pixel the draws missed shows @@ -409,6 +544,7 @@ int main() { EXPECT(list->Close() == S_OK); ID3D12CommandList* lists[] = {list.p}; queue->ExecuteCommandLists(1, lists); + if (staged_views) EXPECT(rt::d3d12::vulkan_memory_flags(unused_texture.p)==0); EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); EXPECT(SUCCEEDED(queue->Signal(fence.p, 1))); EXPECT(SUCCEEDED(fence->SetEventOnCompletion(1, nullptr))); @@ -460,10 +596,65 @@ int main() { EXPECT(SUCCEEDED(readback2->Map(0, nullptr, &mapped2))); std::memcpy(control_pixels.data(), mapped2, control_pixels.size()); + if (refresh) { + // Only CPU stores reach the game's backing after the control list has closed. Both samplers + // already have hash entries. The offset texture coordinates distinguish their address modes. + auto* title = reinterpret_cast(sampler_cpu); + const auto* mapped_heap = reinterpret_cast(sampler_real.ptr); + const std::vector original(mapped_heap, mapped_heap + 3 * sampler_step); + EXPECT(std::memcmp(original.data(), original.data() + sampler_step, sampler_step) != 0); + readback2->Unmap(0, nullptr); + const SIZE_T last = SIZE_T(sampler_slots - 1) * sampler_step; + bool extent_matches = true; + unsigned matches[2]{}; + for (unsigned pass = 0; pass < 2; ++pass) { + const bool swapped = pass == 0; + for (unsigned slot = 0; slot < 2; ++slot) + std::memcpy(title + slot * sampler_step, original.data() + (swapped ? 1 - slot : slot) * sampler_step, + sampler_step); + // An unbounded table reaches the heap's last slot. For one-slot tables this is a guard slot. + std::memcpy(title + last, original.data() + pass * sampler_step, sampler_step); + queue->ExecuteCommandLists(1, lists2); + EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(queue->Signal(fence.p, 3 + pass))); + EXPECT(SUCCEEDED(fence->SetEventOnCompletion(3 + pass, nullptr))); + const auto* expected_last = original.data() + (unbounded ? pass : 2u) * sampler_step; + extent_matches &= std::memcmp(mapped_heap + last, expected_last, sampler_step) == 0; + EXPECT(SUCCEEDED(readback2->Map(0, nullptr, &mapped2))); + for (UINT y = 0; y < target_size; ++y) { + for (UINT x = 0; x < target_size; ++x) { + const bool left = x < target_size / 2; + const bool wraps = (swapped && !disabled) ? !left : left; + const UINT tx = wraps ? x * texture_size / target_size : texture_size - 1; + const UINT ty = y * texture_size / target_size; + const Texel want = left ? gradient(tx, ty) : reflected(tx, ty); + const auto* pixel = static_cast(mapped2) + y * target_pitch + 4 * x; + matches[pass] += std::memcmp(pixel, want.data(), 4) == 0; + } + } + readback2->Unmap(0, nullptr); + } + std::printf("resubmitted sampler tables: %u/%u swapped, %u/%u restored\n", matches[0], + target_size * target_size, matches[1], target_size * target_size); + std::printf("sampler slot %u: %s\n", sampler_slots - 1, extent_matches ? "matched" : "mismatch"); + EXPECT(extent_matches && matches[0] == target_size * target_size && matches[1] == target_size * target_size); + } + + if (staged_views) { + index_a = rt::d3d12::bindless_hash_lookup(device.p,key_a); + index_b = rt::d3d12::bindless_hash_lookup(device.p,key_b); + EXPECT(index_a && index_b && index_a!=index_b); + // The control pass declares an unbounded SRV table. Its entire visible heap becomes reachable, + // including the extra slot; the source-only staging heap does not. + EXPECT((rt::d3d12::vulkan_memory_flags(unused_texture.p)!=0) == direct_views); + EXPECT(rt::d3d12::vulkan_memory_flags(textures[0].p)!=0 && rt::d3d12::vulkan_memory_flags(target.p)!=0); + } // The entries are still there after the draws. EXPECT(rt::d3d12::bindless_hash_lookup(device.p, key_a) == index_a); EXPECT(rt::d3d12::bindless_hash_lookup(device.p, key_s) == index_s); + unused_texture.reset(); + staging_heap.reset(); for (auto& texture : textures) texture.reset(); for (auto* r : {&upload, &readback, &readback2, &target}) r->reset(); pso.reset(); @@ -479,6 +670,7 @@ int main() { allocator.reset(); queue.reset(); fence.reset(); + packed_rtv.reset(); EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); } @@ -489,7 +681,7 @@ int main() { const UINT tx = col / (target_size / texture_size), ty = row / (target_size / texture_size); const Texel want = col < target_size / 2 ? gradient(tx, ty) : reflected(tx, ty); const std::uint8_t* got = &pixels[std::size_t(row) * target_pitch + col * 4]; - const Texel filtered = linear_clamp(col, row); + const Texel filtered = large_raw_surface() ? want : linear_clamp(col, row); const auto* linear = &linear_pixels[std::size_t(row) * target_pitch + col * 4]; for (unsigned k = 0; k < filtered.size(); ++k) { const int error = std::abs(int(linear[k]) - filtered[k]); diff --git a/runtime/test/d3d12_mesh_test.cpp b/runtime/test/d3d12_mesh_test.cpp index 590d3507b9..0625a0291f 100644 --- a/runtime/test/d3d12_mesh_test.cpp +++ b/runtime/test/d3d12_mesh_test.cpp @@ -131,6 +131,9 @@ int main() { const auto device_info = [&](bool mesh) { rt::d3d12::VulkanDeviceInfo info{}; + info.first_use_backend_pipelines=d.first_use_backend_pipelines; + info.prepare_on_bind=d.prepare_on_bind; + info.cold_graphics_compile=d.cold_graphics_compile; info.get_instance_proc = d.instance_proc; info.instance = d.instance; info.physical = d.physical; diff --git a/runtime/test/d3d12_native_graphics_fixture.h b/runtime/test/d3d12_native_graphics_fixture.h new file mode 100644 index 0000000000..4eaac5bd73 --- /dev/null +++ b/runtime/test/d3d12_native_graphics_fixture.h @@ -0,0 +1,55 @@ +#pragma once + +// A native pipeline description and catalog for the vertex and mesh pixel readback tests. The source +// programs are built by the tests. The extra row names a container whose actual HASH does not match. +#include "d3d12_test_shaders.h" +#include "../src/native_pso.h" + +namespace d3d12test { +namespace np = leonida::native_pso; +inline constexpr np::Digest producer_digest{1}, ps_digest{2}, stale_digest{3}; + +inline bool write_native_catalog(const std::filesystem::path& dest, const char* producer_stage, + const std::vector& producer, const std::vector& ps) { + std::error_code ec; + if (!std::filesystem::create_directory(dest / "dxbc", ec)) return false; + std::ofstream index(dest / "spirv" / "native_hashes.txt"); + index << np::HashMap::kHeader << '\n'; + const auto add = [&](const char* stage, const np::Digest& digest, const std::vector& program) { + const std::string name = std::string(stage) + ".dxbc"; + const auto container = shader_container(program, &digest); + std::ofstream file(dest / "dxbc" / name, std::ios::binary); + file.write(reinterpret_cast(container.data()), container.size()); + index << np::hex(digest) << '\t' << stage << "\t../dxbc/" << name << '\n'; + return file.good() && index.good(); + }; + if (!add(producer_stage, producer_digest, producer) || !add("ps", ps_digest, ps)) return false; + index << np::hex(stale_digest) << '\t' << producer_stage << "\t../dxbc/" << producer_stage << ".dxbc\n"; + return index.good(); +} + +inline HRESULT create_native_pso(ID3D12Device* device, ID3D12RootSignature* root, DXGI_FORMAT target, + const np::Digest& producer, ID3D12PipelineState** out) { + std::array state{}; + state[0x10] = static_cast(target); + std::memset(state.data() + 0x1c, 0xff, sizeof(UINT)); + state[0x25] = 1; + state[0x26] = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + state[0x28] = 1; + const auto record = [](const np::Digest& d) { + std::array bytes{0x43}; + std::memcpy(bytes.data() + 4, d.data(), d.size()); + return bytes; + }; + const auto v = record(producer), p = record(ps_digest); + np::GraphicsDesc desc{}; + desc.root_signature = root; + desc.state_b = {state.data(), state.size()}; + desc.stages[5].records = {v.data(), v.size()}; + desc.stages[2].records = {p.data(), p.size()}; + using Create = HRESULT(WINAPI*)(void*, const np::GraphicsDesc*, const IID*, void**); + return reinterpret_cast(slot(device, 57))(device, &desc, &__uuidof(ID3D12PipelineState), + reinterpret_cast(out)); +} + +} // namespace d3d12test diff --git a/runtime/test/d3d12_placed_depth_test.h b/runtime/test/d3d12_placed_depth_test.h new file mode 100644 index 0000000000..95d32772bd --- /dev/null +++ b/runtime/test/d3d12_placed_depth_test.h @@ -0,0 +1,141 @@ +// Slot-133 aliases share GPU contents and retain individual COM identities. +#pragma once +#include "d3d12_copy_compare.h" + +namespace placeddepthtest { + +inline bool check_alias_lifetime(ID3D12Device* device, ID3D12Device* xbox, bool opaque = false) { + using copycmp::Ptr; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = 256; + desc.Height = 128; + desc.DepthOrArraySize = desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Format = DXGI_FORMAT_R32G8X24_TYPELESS; + desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + const auto allocation = device->GetResourceAllocationInfo(0, 1, &desc); + if (!allocation.Alignment || allocation.SizeInBytes == UINT64_MAX || allocation.SizeInBytes <= allocation.Alignment) + return false; + struct Pages { + void* ptr; + ~Pages() { if (ptr) VirtualFree(ptr, 0, MEM_RELEASE); } + } pages{VirtualAlloc(nullptr, SIZE_T(allocation.SizeInBytes * 2), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)}; + if (!pages.ptr) return false; + const UINT64 address = reinterpret_cast(pages.ptr); + auto xbox_desc = desc; + xbox_desc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + xbox_desc.Layout = opaque ? D3D12_TEXTURE_LAYOUT_UNKNOWN : static_cast(0x101); + using Create = HRESULT(WINAPI*)(void*, UINT64, const D3D12_RESOURCE_DESC*, UINT, + const D3D12_CLEAR_VALUE*, REFIID, void**); + const auto create = reinterpret_cast((*reinterpret_cast(xbox))[133]); + const auto place = [&](UINT64 va, const D3D12_RESOURCE_DESC& shape, Ptr& result, + const D3D12_CLEAR_VALUE* clear = nullptr) { + return create(xbox, va, &shape, UINT_MAX, clear, IID_PPV_ARGS(&result.p)); + }; + Ptr first, alias, next, invalid; + if (FAILED(place(address, xbox_desc, first)) || FAILED(place(address, xbox_desc, alias)) || + FAILED(place(address + allocation.SizeInBytes, xbox_desc, next))) return false; + if (first.p == alias.p || alias->GetGPUVirtualAddress() != address || + next->GetGPUVirtualAddress() != address + allocation.SizeInBytes) return false; + // Independent COM private data helps catch accidental reuse of the object itself as the alias. + constexpr GUID cookie_key{0x650cf350, 0xa07e, 0x428d, {0xb4, 0x14, 0xdc, 0xaf, 0xc6, 0x97, 0xe8, 0x4b}}; + const UINT cookie = 12; + UINT bytes = 0; + if (FAILED(first->SetPrivateData(cookie_key, sizeof(cookie), &cookie)) || + alias->GetPrivateData(cookie_key, &bytes, nullptr) != DXGI_ERROR_NOT_FOUND) return false; + auto smaller = xbox_desc; + smaller.Width /= 2; + Ptr other_shape; + if (opaque && (FAILED(place(address, smaller, other_shape)) || other_shape->GetDesc().Width != smaller.Width || + other_shape->GetGPUVirtualAddress() != address)) return false; + D3D12_CLEAR_VALUE optimized{}; + optimized.Format = DXGI_FORMAT_D32_FLOAT_S8X24_UINT; + optimized.DepthStencil = {1.0f, 0}; + if (place(address, xbox_desc, invalid, &optimized) != E_NOTIMPL || invalid.p) return false; + if ((!opaque && (place(address, smaller, invalid) != E_NOTIMPL || invalid.p)) || + place(address + allocation.Alignment, xbox_desc, invalid) != E_NOTIMPL || invalid.p || + place(address + 1, xbox_desc, invalid) != E_INVALIDARG || invalid.p) return false; + + Ptr heap; + D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 2}; + if (FAILED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p)))) return false; + D3D12_DEPTH_STENCIL_VIEW_DESC dsv{}; + dsv.Format = DXGI_FORMAT_D32_FLOAT_S8X24_UINT; + dsv.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D; + const auto handle = heap->GetCPUDescriptorHandleForHeapStart(); + device->CreateDepthStencilView(first.p, &dsv, handle); + auto other_view = handle; + other_view.ptr += device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV); + if (opaque) device->CreateDepthStencilView(other_shape.p, &dsv, other_view); + copycmp::Run commands; + if (!commands.init(device, true)) return false; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT layouts[2]{}; + UINT64 total = 0; + device->GetCopyableFootprints(&desc, 0, 2, 0, layouts, nullptr, nullptr, &total); + Ptr readback; + const UINT64 sample_offset = (total + 511) & ~UINT64(511); + if (!commands.buffer(D3D12_HEAP_TYPE_READBACK, sample_offset + 256, D3D12_RESOURCE_STATE_COPY_DEST, readback)) return false; + commands.begin(); + if (opaque) { + D3D12_RESOURCE_BARRIER use{}; + use.Type = D3D12_RESOURCE_BARRIER_TYPE_ALIASING; + use.Aliasing = {nullptr, other_shape.p}; + commands.list->ResourceBarrier(1, &use); + commands.list->ClearDepthStencilView(other_view, D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, 0.625f, 0x34, 0, nullptr); + commands.barrier(other_shape.p, D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_COPY_SOURCE); + D3D12_TEXTURE_COPY_LOCATION src{}, dst{}; + src.pResource = other_shape.p; + dst.pResource = readback.p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = {sample_offset,{DXGI_FORMAT_R32_TYPELESS,1,1,1,256}}; + const D3D12_BOX pixel{0,0,0,1,1,1}; + commands.list->CopyTextureRegion(&dst,0,0,0,&src,&pixel); + use.Aliasing = {other_shape.p, first.p}; + commands.list->ResourceBarrier(1,&use); + } + commands.list->ClearDepthStencilView(handle, D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, + 0.375f, 0xb7, 0, nullptr); + D3D12_RESOURCE_BARRIER activate{}; + activate.Type = D3D12_RESOURCE_BARRIER_TYPE_ALIASING; + activate.Aliasing = {first.p, alias.p}; + commands.list->ResourceBarrier(1, &activate); + if (!commands.submit().empty()) return false; + first.reset(); + if (!opaque && (place(address, smaller, invalid) != E_NOTIMPL || invalid.p)) return false; + commands.begin(); + commands.barrier(alias.p, D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_COPY_SOURCE); + for (UINT plane = 0; plane < 2; ++plane) { + D3D12_TEXTURE_COPY_LOCATION src{}, dst{}; + src.pResource = alias.p; + src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + src.SubresourceIndex = plane; + dst.pResource = readback.p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = layouts[plane]; + commands.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + } + if (!commands.submit().empty()) return false; + unsigned char* mapped = nullptr; + if (FAILED(readback->Map(0, nullptr, reinterpret_cast(&mapped)))) return false; + float earlier = 0; + if (opaque) std::memcpy(&earlier, mapped + sample_offset, sizeof(earlier)); + bool valid = !opaque || earlier == 0.625f; + for (UINT y = 0; y < desc.Height && valid; ++y) { + for (UINT x = 0; x < desc.Width; ++x) { + float depth; + std::memcpy(&depth, mapped + layouts[0].Offset + y * layouts[0].Footprint.RowPitch + x * sizeof(depth), + sizeof(depth)); + if (depth != 0.375f || mapped[layouts[1].Offset + y * layouts[1].Footprint.RowPitch + x] != 0xb7) { + std::fprintf(stderr, "slot-133 alias: wrong readback at (%u, %u)\n", x, y); + valid = false; + break; + } + } + } + readback->Unmap(0, nullptr); + alias.reset(); + return valid && SUCCEEDED(place(address, smaller, invalid)) && invalid->GetGPUVirtualAddress() == address; +} + +} // namespace placeddepthtest diff --git a/runtime/test/d3d12_r9g9b9e5_uav_test.cpp b/runtime/test/d3d12_r9g9b9e5_uav_test.cpp index 13b3bace56..0cb85332c7 100644 --- a/runtime/test/d3d12_r9g9b9e5_uav_test.cpp +++ b/runtime/test/d3d12_r9g9b9e5_uav_test.cpp @@ -205,14 +205,14 @@ struct ShaderParams { std::uint32_t mode; std::uint32_t width; std::uint32_t height; - std::uint32_t pad; + std::uint32_t slice; }; bool run_bindless_roundtrip(vktest::Device& d, VkDescriptorSet set0, VkDescriptorSetLayout set0_layout, const g::ImageWords& uav_words, const g::ImageWords& srv_words, const g::SamplerWords& sampler_words, bool do_uint_write, const std::array& input_words, - std::array& out_rgba) { + std::array& out_rgba, int z = -1, bool sliced = false) { std::vector code; if (!read_spirv(LEONIDA_TEST_CS_R9G9B9E5_UAV_SPV, code)) return false; @@ -320,7 +320,8 @@ bool run_bindless_roundtrip(vktest::Device& d, VkDescriptorSet set0, VkDescripto ShaderParams wp{}; std::memcpy(wp.tsharp, uav_words.data(), sizeof(wp.tsharp)); std::memcpy(wp.ssharp, sampler_words.data(), sizeof(wp.ssharp)); - wp.mode = 0; + wp.mode = z < 0 ? 0u : 2u; + wp.slice = sliced ? 1u : 0u; wp.width = 4; wp.height = 4; push(cb, pipe_layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(wp), &wp); @@ -336,7 +337,8 @@ bool run_bindless_roundtrip(vktest::Device& d, VkDescriptorSet set0, VkDescripto ShaderParams sp{}; std::memcpy(sp.tsharp, srv_words.data(), sizeof(sp.tsharp)); std::memcpy(sp.ssharp, sampler_words.data(), sizeof(sp.ssharp)); - sp.mode = 1; + sp.mode = z < 0 ? 1u : 3u; + sp.slice = z < 0 ? 0u : UINT(z); sp.width = 4; sp.height = 4; push(cb, pipe_layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(sp), &sp); @@ -358,7 +360,7 @@ bool run_bindless_roundtrip(vktest::Device& d, VkDescriptorSet set0, VkDescripto int main() { vktest::Device d; - const auto status = d.initialize(); + const auto status = d.initialize(true, true); // exercise sliced RGB9E5 volumes when the driver supports them if (status == vktest::DeviceStatus::unavailable) return 77; if (status != vktest::DeviceStatus::ready) return 1; @@ -381,6 +383,8 @@ int main() { info.bindless_partially_bound = d.partially_bound; info.image_view_min_lod = d.image_view_min_lod; info.host_image_copy = d.host_image_copy; + info.robust_image_access = d.robust_image_access; + info.sliced_3d_uav = d.sliced_3d_uav; Ref device; EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p)))); @@ -441,7 +445,7 @@ int main() { D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&tex_1d.p)))); - const auto desc_3d = tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE3D, 8, 8, 4, 2, + const auto desc_3d = tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE3D, 8, 8, 8, 2, DXGI_FORMAT_R9G9B9E5_SHAREDEXP, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); Ref tex_3d; EXPECT(SUCCEEDED(device->CreateCommittedResource(&def_heap, D3D12_HEAP_FLAG_NONE, &desc_3d, @@ -785,27 +789,77 @@ int main() { std::array sampled{}; EXPECT(run_bindless_roundtrip(d, set0, set0_layout, rt_uav_words, rt_srv_words, smp_words, !native_storage, input_words, sampled)); - for (UINT i = 0; i < 16; ++i) { - const std::uint32_t want_word = native_storage ? 0x94010040u : input_words[i]; - leonida::uav_clear::Element elem{}; - elem.size = 4; - std::memcpy(elem.bytes.data(), &want_word, 4); - VkClearColorValue want{}; - EXPECT(leonida::uav_clear::decode(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, elem, want)); - for (UINT c = 0; c < 4; ++c) { - const float got = sampled[i * 4 + c]; - const float exp_v = want.float32[c]; - const float tol = std::max(1e-6f, std::fabs(exp_v) * 1e-5f); - if (std::fabs(got - exp_v) > tol) { - std::fprintf(stderr, "bindless sample texel %u ch %u: got %g, want %g (word 0x%08x)\n", - i, c, got, exp_v, want_word); - return 1; + const auto check_samples = [&](bool seed_only) { + for (UINT i = 0; i < 16; ++i) { + const std::uint32_t want_word = seed_only ? 0x94010040u : input_words[i]; + leonida::uav_clear::Element elem{}; + elem.size = 4; + std::memcpy(elem.bytes.data(), &want_word, 4); + VkClearColorValue want{}; + if (!leonida::uav_clear::decode(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, elem, want)) return false; + for (UINT c = 0; c < 4; ++c) { + const float got = sampled[i * 4 + c]; + const float exp_v = want.float32[c]; + const float tol = std::max(1e-6f, std::fabs(exp_v) * 1e-5f); + if (!(std::fabs(got - exp_v) <= tol)) { + std::fprintf(stderr, "bindless sample texel %u ch %u: got %g, want %g (word 0x%08x)\n", + i, c, got, exp_v, want_word); + return false; + } } } - } + return true; + }; + EXPECT(check_samples(native_storage)); std::printf("Bindless set-0 GPU round-trip: 16/16 HDR RGB9E5 texels matched (%s)\n", native_storage ? "clear -> sampled E5B9G9R9" : "storage R32_UINT [bindings 9 & 4] -> sampled E5B9G9R9 [binding 0]"); + + if (!native_storage && d.robust_image_access) { + // Mip 1 of tex_3d is 4x4x4. Seed it through the logical RGB9E5 clear, then write packed data + // through R32_UINT. A sliced view selects only absolute Z=1; relative Z=1 must not write Z=2. + D3D12_UNORDERED_ACCESS_VIEW_DESC volume_uav{}; + volume_uav.Format = DXGI_FORMAT_R9G9B9E5_SHAREDEXP; + volume_uav.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; + volume_uav.Texture3D = {1, 0, ~0u}; + device->CreateUnorderedAccessView(tex_3d.p, nullptr, &volume_uav, slot(10)); + const auto whole = words_at(10); + EXPECT(g::decode(whole, decoded) && decoded.first_mip == 1 && decoded.format == 132 && + (whole[7] & g::packed_uav_flag) && !g::partial_volume_uav(whole, decoded)); + volume_uav.Texture3D.FirstWSlice = 1; + volume_uav.Texture3D.WSize = 1; + device->CreateUnorderedAccessView(tex_3d.p, nullptr, &volume_uav, slot(11)); + const auto partial = words_at(11); + if (d.sliced_3d_uav) { + EXPECT(g::decode(partial, decoded) && g::partial_volume_uav(partial, decoded)); + } else { + EXPECT(all_zero(partial.data(), sizeof(partial))); + } + D3D12_SHADER_RESOURCE_VIEW_DESC volume_srv{}; + volume_srv.Format = volume_uav.Format; + volume_srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; + volume_srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + volume_srv.Texture3D = {1, 1, 0}; + device->CreateShaderResourceView(tex_3d.p, &volume_srv, slot(12)); + const auto volume_sampled = words_at(12); + EXPECT(g::decode(volume_sampled, decoded) && decoded.format == 132 && volume_sampled[7] == 0); + + EXPECT(SUCCEEDED(alloc->Reset()) && SUCCEEDED(list->Reset(alloc.p, nullptr))); + list->ClearUnorderedAccessViewFloat({0}, slot(10), tex_3d.p, seed, 0, nullptr); + EXPECT(list->Close() == S_OK); + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(queue->Signal(fence.p, 2)) && SUCCEEDED(fence->SetEventOnCompletion(2, nullptr))); + const auto& write_key = d.sliced_3d_uav ? partial : whole; + EXPECT(run_bindless_roundtrip(d, set0, set0_layout, write_key, volume_sampled, smp_words, + true, input_words, sampled, d.sliced_3d_uav ? 1 : 0, d.sliced_3d_uav)); + EXPECT(check_samples(false)); + EXPECT(run_bindless_roundtrip(d, set0, set0_layout, write_key, volume_sampled, smp_words, + false, input_words, sampled, 2)); + EXPECT(check_samples(true)); + std::printf("RGB9E5 volume: 16/16 raw-store samples and 16/16 untouched neighbor texels (%s)\n", + d.sliced_3d_uav ? "sliced" : "whole-mip; partial view refused"); + } } #endif } diff --git a/runtime/test/d3d12_rect_list_test.cpp b/runtime/test/d3d12_rect_list_test.cpp index 05b90a81c8..ae1cbc6a83 100644 --- a/runtime/test/d3d12_rect_list_test.cpp +++ b/runtime/test/d3d12_rect_list_test.cpp @@ -7,6 +7,10 @@ // v1 (-1, 1), v2 (1, 1), v3 (-1, -1) cover the top-left, top-right and bottom-left of the 64x64 target; the fourth // corner, v2 + v3 - v1 = (1, -1) with colour c2 + c3 - c1, is made by the layer. Every pixel must carry the plane // through the three corner colours; the bottom-right quadrant is only right when the fourth corner is. +// frames 3 to 5, rectangle lists whose right angle is at the second vertex, at the third vertex, and a triangle with +// no right angle at all. The layer takes the right-angle corner as the vertex opposite the longest screen edge, so +// the first two must cover all 64x64 pixels on the colour plane too (the retail boot's full-screen draw has its +// right angle at the second vertex); the third only has to draw something and not fail. // frame 2, quad list: PSO topology type TRIANGLE, IASetPrimitiveTopology(19), DrawInstanced(8): two quads (corners // in order around the quad), the top-left and bottom-right quadrants, each one colour. These pixels are exact. // Pixels are read back and compared; the other two quadrants of frame 2 stay the clear colour. LEONIDA_VK_VALIDATION=1 @@ -86,12 +90,21 @@ int main() { // Frame 1: the rectangle's three corners. Vertices 0..2. Frame 2: two quads, vertices 3..10. const float ca[4] = {0.0f, 0.0f, 0.0f, 1.0f}, cb[4] = {1.0f, 0.0f, 0.5f, 1.0f}, cc[4] = {0.0f, 0.5f, 1.0f, 1.0f}; const float q1[4] = {0.25f, 0.5f, 0.75f, 1.0f}, q2[4] = {1.0f, 0.0f, 0.5f, 1.0f}; - const Vertex vertices[11] = {vertex(-1, 1, ca), vertex(1, 1, cb), vertex(-1, -1, cc), + const Vertex vertices[20] = {vertex(-1, 1, ca), vertex(1, 1, cb), vertex(-1, -1, cc), vertex(-1, 1, q1), vertex(0, 1, q1), vertex(0, 0, q1), vertex(-1, 0, q1), - vertex(0, 0, q2), vertex(1, 0, q2), vertex(1, -1, q2), vertex(0, -1, q2)}; - static_assert(sizeof(Vertex) == 32 && sizeof(vertices) == 352); + vertex(0, 0, q2), vertex(1, 0, q2), vertex(1, -1, q2), vertex(0, -1, q2), + // vertices 11..13: right angle at the second vertex; 14..16: at the third; 17..19: none + vertex(-1, 1, ca), vertex(1, 1, cb), vertex(1, -1, cc), + vertex(-1, 1, ca), vertex(1, -1, cb), vertex(-1, -1, cc), + vertex(-1, 1, ca), vertex(0.5f, 0.75f, cb), vertex(-0.25f, -1, cc)}; + static_assert(sizeof(Vertex) == 32 && sizeof(vertices) == 640); + const Vertex* const corner_cases[2] = {&vertices[11], &vertices[14]}; - std::vector rect_pixels(target_extent * target_extent), quad_pixels(target_extent * target_extent); + std::vector rect_pixels(target_extent * target_extent), quad_pixels(target_extent * target_extent), + second_pixels(target_extent * target_extent), third_pixels(target_extent * target_extent), + skew_pixels(target_extent * target_extent); + std::vector dynamic_pixels(rect_pixels.size()), triangle_pixels(rect_pixels.size()), + repeated_pixels(rect_pixels.size()); { rt::d3d12::VulkanDeviceInfo info{}; info.get_instance_proc = d.instance_proc; @@ -172,8 +185,9 @@ int main() { EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast(&up)))); std::memcpy(up, vertices, sizeof(vertices)); - // Two V#s over the one vertex buffer: slot 0 the rectangle's three corners, slot 1 the eight quad corners. - const D3D12_DESCRIPTOR_HEAP_DESC srv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2, + // V#s over the one vertex buffer: slot 0 the rectangle's three corners, slot 1 the eight quad corners, slots 2 to 4 + // the three more rectangles. + const D3D12_DESCRIPTOR_HEAP_DESC srv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 5, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; Ref srv_heap; EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&srv_heap_desc, IID_PPV_ARGS(&srv_heap.p)))); @@ -183,9 +197,12 @@ int main() { EXPECT(cpu && gpu >= 0x10000 && gpu < (1ull << 32) && step >= 16); const std::uint64_t buffer_va = vertex_buffer->GetGPUVirtualAddress(); EXPECT(buffer_va >= 0x10000); - const std::array vsharps[2] = {make_vsharp(buffer_va, 3), - make_vsharp(buffer_va + 3 * sizeof(Vertex), 8)}; - for (unsigned i = 0; i < 2; ++i) + const std::array vsharps[5] = {make_vsharp(buffer_va, 3), + make_vsharp(buffer_va + 3 * sizeof(Vertex), 8), + make_vsharp(buffer_va + 11 * sizeof(Vertex), 3), + make_vsharp(buffer_va + 14 * sizeof(Vertex), 3), + make_vsharp(buffer_va + 17 * sizeof(Vertex), 3)}; + for (unsigned i = 0; i < 5; ++i) std::memcpy(reinterpret_cast(cpu + std::uint64_t(i) * step), vsharps[i].data(), 16); const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; @@ -263,6 +280,12 @@ int main() { }; EXPECT(render_frame(1, rect_pso.p, rect_list, 0, 3, rect_pixels) == 0); EXPECT(render_frame(2, quad_pso.p, quad_list, 1, 8, quad_pixels) == 0); + EXPECT(render_frame(3, rect_pso.p, rect_list, 2, 3, second_pixels) == 0); + EXPECT(render_frame(4, rect_pso.p, rect_list, 3, 3, third_pixels) == 0); + EXPECT(render_frame(5, rect_pso.p, rect_list, 4, 3, skew_pixels) == 0); + EXPECT(render_frame(6, quad_pso.p, rect_list, 0, 3, dynamic_pixels) == 0); + EXPECT(render_frame(7, quad_pso.p, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, 0, 3, triangle_pixels) == 0); + EXPECT(render_frame(8, quad_pso.p, rect_list, 0, 3, repeated_pixels) == 0); for (auto* r : {&vertex_buffer, &upload, &readback, &target}) r->reset(); rect_pso.reset(); quad_pso.reset(); @@ -311,6 +334,80 @@ int main() { } } EXPECT(covered == target_extent * target_extent); + // The same triangle-family PSO can select either primitive at draw time. Compare both rectangle draws + // to the verified type-19 reference; exclude only the shared diagonal from the triangle coverage check. + const Pixel clear_value = {0.5f, 0.125f, 0.25f, 0.5f}; + for (UINT y = 0; y < target_extent; ++y) { + for (UINT x = 0; x < target_extent; ++x) { + const auto i = y * target_extent + x; + EXPECT(std::memcmp(&dynamic_pixels[i], &rect_pixels[i], sizeof(Pixel)) == 0); + EXPECT(std::memcmp(&repeated_pixels[i], &rect_pixels[i], sizeof(Pixel)) == 0); + if (x + y + 1 < target_extent) + EXPECT(std::memcmp(&triangle_pixels[i], &rect_pixels[i], sizeof(Pixel)) == 0); + if (x + y + 1 > target_extent) + EXPECT(std::memcmp(&triangle_pixels[i], &clear_value, sizeof(Pixel)) == 0); + } + } + + // Right angle at the second and at the third vertex: the plane through the three drawn corners, everywhere. + const std::vector* const corner_pixels[2] = {&second_pixels, &third_pixels}; + const char* const corner_names[2] = {"second", "third"}; + unsigned corner_covered[2] = {0, 0}; + float corner_worst = 0.0f; + for (int which = 0; which < 2; ++which) { + const Vertex* t = corner_cases[which]; + const float x0 = t[0].position[0], y0 = t[0].position[1]; + const float ax = t[1].position[0] - x0, ay = t[1].position[1] - y0; + const float bx = t[2].position[0] - x0, by = t[2].position[1] - y0; + const float det = ax * by - ay * bx; + for (UINT row = 0; row < target_extent; ++row) { + for (UINT col = 0; col < target_extent; ++col) { + const float px = 2.0f * (float(col) + 0.5f) / target_extent - 1.0f - x0; + const float py = 1.0f - 2.0f * (float(row) + 0.5f) / target_extent - y0; + const float s = (px * by - py * bx) / det, r = (ax * py - ay * px) / det; + const Pixel& got = (*corner_pixels[which])[row * target_extent + col]; + bool pixel_ok = true; + for (int c = 0; c < 4; ++c) { + const float want = (t[0].color[c] + s * (t[1].color[c] - t[0].color[c]) + + r * (t[2].color[c] - t[0].color[c])) * scale[c]; + const float error = std::fabs(got[c] - want); + corner_worst = std::fmax(corner_worst, error); + if (!(error <= 2e-5f)) pixel_ok = false; + } + corner_covered[which] += pixel_ok; + } + } + if (corner_covered[which] != target_extent * target_extent) { + std::fprintf(stderr, "rect list with the right angle at the %s vertex: %u of %u pixels on the plane\n", + corner_names[which], corner_covered[which], target_extent * target_extent); + return 1; + } + } + // Not a right triangle: any consistent corner is fine, but every corner choice makes a parallelogram that holds the + // drawn triangle, so each pixel well inside the triangle must be drawn (not the clear colour). + const Pixel clear_pixel = {0.5f, 0.125f, 0.25f, 0.5f}; + unsigned skew_drawn = 0, skew_inside = 0, skew_missing = 0; + { + const Vertex* t = &vertices[17]; + const float x0 = t[0].position[0], y0 = t[0].position[1]; + const float ax = t[1].position[0] - x0, ay = t[1].position[1] - y0; + const float bx = t[2].position[0] - x0, by = t[2].position[1] - y0; + const float det = ax * by - ay * bx; + for (UINT row = 0; row < target_extent; ++row) { + for (UINT col = 0; col < target_extent; ++col) { + const float px = 2.0f * (float(col) + 0.5f) / target_extent - 1.0f - x0; + const float py = 1.0f - 2.0f * (float(row) + 0.5f) / target_extent - y0; + const float s = (px * by - py * bx) / det, r = (ax * py - ay * px) / det; + const bool drawn = std::memcmp(&skew_pixels[row * target_extent + col], &clear_pixel, sizeof(Pixel)) != 0; + skew_drawn += drawn; + if (s > 0.02f && r > 0.02f && s + r < 0.98f) { + ++skew_inside; + skew_missing += !drawn; + } + } + } + } + EXPECT(skew_inside > 1000 && skew_missing == 0); // Quad list: whole-bit comparison; two quadrants one colour each, the rest the clear colour. const Pixel clear_color = {0.5f, 0.125f, 0.25f, 0.5f}; @@ -333,9 +430,11 @@ int main() { std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); return 1; } - std::printf("rect list: %u of %u pixels on the colour plane (worst error %g), all four quadrants; quad list: " - "%u of %u pixels exact\n", - covered, target_extent * target_extent, double(worst), target_extent * target_extent - quad_wrong, - target_extent * target_extent); + std::printf("rect list: %u of %u pixels on the colour plane (worst error %g), all four quadrants; right angle at " + "the second vertex %u and at the third %u of %u (worst error %g); no right angle: %u pixels drawn; " + "quad list: %u of %u pixels exact\n", + covered, target_extent * target_extent, double(worst), corner_covered[0], corner_covered[1], + target_extent * target_extent, double(corner_worst), skew_drawn, + target_extent * target_extent - quad_wrong, target_extent * target_extent); return 0; } diff --git a/runtime/test/d3d12_test_shaders.h b/runtime/test/d3d12_test_shaders.h index d778d1bc69..c424ef5bed 100644 --- a/runtime/test/d3d12_test_shaders.h +++ b/runtime/test/d3d12_test_shaders.h @@ -7,6 +7,7 @@ #include #include +#include #include #include #include @@ -44,7 +45,8 @@ inline std::vector fssm_program(std::initializer_list shader_container(const std::vector& fssm) { +inline std::vector shader_container(const std::vector& fssm, + const std::array* digest = nullptr) { const auto stream = zlib_stored(fssm); std::vector xbch = {'X', 'B', 'C', 'H'}; for (const std::uint32_t v : {1u, std::uint32_t(stream.size()), 0u, std::uint32_t(fssm.size()), 0u}) put32(xbch, v); @@ -59,11 +61,18 @@ inline std::vector shader_container(const std::vector out = {'D', 'X', 'B', 'C'}; out.resize(28, 0); - put32(out, 1); - put32(out, 36); + put32(out, digest ? 2 : 1); + put32(out, digest ? 40 : 36); + if (digest) put32(out, 40 + 8 + std::uint32_t(dxil.size())); out.insert(out.end(), {'D', 'X', 'I', 'L'}); put32(out, std::uint32_t(dxil.size())); out.insert(out.end(), dxil.begin(), dxil.end()); + if (digest) { + out.insert(out.end(), {'H', 'A', 'S', 'H'}); + put32(out, 20); + put32(out, 0); + out.insert(out.end(), digest->begin(), digest->end()); + } return out; } diff --git a/runtime/test/d3d12_texture1d_target_test.cpp b/runtime/test/d3d12_texture1d_target_test.cpp index 4642440faf..4f12801db9 100644 --- a/runtime/test/d3d12_texture1d_target_test.cpp +++ b/runtime/test/d3d12_texture1d_target_test.cpp @@ -234,6 +234,7 @@ struct Format { int main() { vktest::Device vk; + vk.request_buffer_device_address = true; const auto device_status = vk.initialize(); if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips if (device_status != vktest::DeviceStatus::ready) return 1; @@ -250,6 +251,9 @@ int main() { info.conditional_rendering = vk.conditional_rendering; info.storage_buffer_8bit = vk.storage_buffer_8bit; info.buffer_device_address = vk.buffer_device_address; + info.robust_image_access = vk.robust_image_access; + info.bindless = vk.bindless; + info.bindless_partially_bound = vk.partially_bound; if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))) return 1; if (hostwine::host_is_wine()) return 77; // every check is a comparison with Windows D3D12 Ref factory; diff --git a/runtime/test/d3d12_texture1d_test.cpp b/runtime/test/d3d12_texture1d_test.cpp index 007c513b4f..b32847a90c 100644 --- a/runtime/test/d3d12_texture1d_test.cpp +++ b/runtime/test/d3d12_texture1d_test.cpp @@ -116,7 +116,7 @@ int main() { uav1d.Texture1D.MipSlice = 1; dev->CreateUnorderedAccessView(tex1d, nullptr, &uav1d, {cbv_cpu.ptr + cbv_inc * 5}); - // Default (nullptr) SRV and UAV on a 1D array must write a null descriptor (set 0 has no 1D-array binding). + // Set 0 has storage-only 1D-array bindings: a default SRV is null, but a default UAV covers the whole array. std::memset(reinterpret_cast(cbv_cpu.ptr + cbv_inc * 6), 0x77, cbv_inc * 2); dev->CreateShaderResourceView(tex1d, nullptr, {cbv_cpu.ptr + cbv_inc * 6}); dev->CreateUnorderedAccessView(tex1d, nullptr, nullptr, {cbv_cpu.ptr + cbv_inc * 7}); @@ -147,11 +147,12 @@ int main() { if (!decode_and_lookup(5, img) || img.type != g::ImageType::image_1d || img.first_mip != 1 || img.mip_count != 1 || img.layer_count != 1) return fail("explicit 1D UAV on array T# or bindless lookup mismatch"); - for (UINT slot = 6; slot < 8; ++slot) { - const auto* bytes = reinterpret_cast(cbv_cpu.ptr + cbv_inc * slot); - for (UINT b = 0; b < 32; ++b) - if (bytes[b] != 0) return fail("default 1DArray view should write a null descriptor"); - } + const auto* srv_bytes = reinterpret_cast(cbv_cpu.ptr + cbv_inc * 6); + for (UINT b = 0; b < 32; ++b) + if (srv_bytes[b] != 0) return fail("default 1DArray SRV should write a null descriptor"); + if (!decode_and_lookup(7, img) || img.type != g::ImageType::image_1d_array || img.first_mip != 0 || + img.mip_count != 1 || img.first_layer != 0 || img.layer_count != tex1d_desc.DepthOrArraySize) + return fail("default 1DArray UAV T# or bindless lookup mismatch"); // RTV / DSV 1D bounds validation (out-of-bounds mip/slice must write a null TargetView) D3D12_RENDER_TARGET_VIEW_DESC bad_rtv{}; @@ -267,6 +268,6 @@ int main() { cbv_heap->Release(); dev->Release(); - std::printf("PASS: d3d12_texture1d_test (1D/1DArray SRV, UAV + CopyTextureRegion round-trip)\n"); + std::printf("PASS: d3d12_texture1d_test (1D views, 1DArray UAV + CopyTextureRegion round-trip)\n"); return 0; } diff --git a/runtime/test/d3d12_texture_uav_oracle.h b/runtime/test/d3d12_texture_uav_oracle.h new file mode 100644 index 0000000000..d9d9dfaea1 --- /dev/null +++ b/runtime/test/d3d12_texture_uav_oracle.h @@ -0,0 +1,279 @@ +#pragma once + +// Native Windows D3D12/WARP reference for synthetic texture UAV dispatches. +// Link d3d12 and dxgi; the HLSL compiler is loaded from System32. +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace uav_oracle { +enum class Status { ready, unavailable, failed }; + +namespace detail { +using Microsoft::WRL::ComPtr; + +inline bool fail(const char* message) { + std::fprintf(stderr, "WARP texture UAV: %s\n", message); + return false; +} + +inline bool check(HRESULT hr, const char* action, ID3DBlob* errors = nullptr) { + if (SUCCEEDED(hr)) return true; + std::fprintf(stderr, "WARP texture UAV: %s failed (0x%08lx)\n", action, static_cast(hr)); + if (errors) std::fputs(static_cast(errors->GetBufferPointer()), stderr); + return false; +} + +struct View { + unsigned shader; + UINT mip; +}; + +inline View select_view(const D3D12_RESOURCE_DESC& resource, const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc) { + if (desc) { + switch (desc->ViewDimension) { + case D3D12_UAV_DIMENSION_TEXTURE1D: return {0, desc->Texture1D.MipSlice}; + case D3D12_UAV_DIMENSION_TEXTURE1DARRAY: return {1, desc->Texture1DArray.MipSlice}; + case D3D12_UAV_DIMENSION_TEXTURE2D: return {2, desc->Texture2D.MipSlice}; + case D3D12_UAV_DIMENSION_TEXTURE2DARRAY: return {3, desc->Texture2DArray.MipSlice}; + case D3D12_UAV_DIMENSION_TEXTURE3D: return {4, desc->Texture3D.MipSlice}; + default: return {5, 0}; + } + } + switch (resource.Dimension) { + case D3D12_RESOURCE_DIMENSION_TEXTURE1D: return {resource.DepthOrArraySize > 1 ? 1u : 0u, 0}; + case D3D12_RESOURCE_DIMENSION_TEXTURE2D: return {resource.DepthOrArraySize > 1 ? 3u : 2u, 0}; + case D3D12_RESOURCE_DIMENSION_TEXTURE3D: return {4, 0}; + default: return {5, 0}; + } +} + +inline D3D12_HEAP_PROPERTIES heap_properties(D3D12_HEAP_TYPE type) { + D3D12_HEAP_PROPERTIES heap{}; + heap.Type = type; + heap.CreationNodeMask = heap.VisibleNodeMask = 1; + return heap; +} + +struct Context { + ComPtr device; + ComPtr root; + std::array, 5> pipelines; + + Status prepare_device() { + if (device) return Status::ready; + ComPtr factory; + ComPtr warp; + HRESULT hr = CreateDXGIFactory1(IID_PPV_ARGS(factory.GetAddressOf())); + if (hr == E_NOINTERFACE || hr == DXGI_ERROR_UNSUPPORTED) return Status::unavailable; + if (!check(hr, "CreateDXGIFactory1")) return Status::failed; + hr = factory->EnumWarpAdapter(IID_PPV_ARGS(warp.GetAddressOf())); + if (hr == DXGI_ERROR_NOT_FOUND || hr == DXGI_ERROR_UNSUPPORTED || hr == E_NOTIMPL) + return Status::unavailable; + if (!check(hr, "EnumWarpAdapter")) return Status::failed; + hr = D3D12CreateDevice(warp.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(device.GetAddressOf())); + if (hr == DXGI_ERROR_UNSUPPORTED || hr == E_NOTIMPL) return Status::unavailable; + return check(hr, "D3D12CreateDevice") ? Status::ready : Status::failed; + } + + bool init() { + if (root) return true; + if (prepare_device() != Status::ready) return false; + const D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, 0, 0, 0}; + D3D12_ROOT_PARAMETER parameter{}; + parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + parameter.DescriptorTable = {1, &range}; + parameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + const D3D12_ROOT_SIGNATURE_DESC desc{1, ¶meter, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr blob, errors; + const HRESULT hr = D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1_0, + blob.GetAddressOf(), errors.GetAddressOf()); + return check(hr, "D3D12SerializeRootSignature", errors.Get()) && + check(device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), + IID_PPV_ARGS(root.GetAddressOf())), "CreateRootSignature"); + } + + bool create_pipeline(unsigned index) { + if (pipelines[index]) return true; + static constexpr const char* types[] = { + "RWTexture1D", "RWTexture1DArray", "RWTexture2D", "RWTexture2DArray", "RWTexture3D", + }; + static constexpr const char* coordinates[] = {"id.x", "id.xz", "id.xy", "id.xyz", "id.xyz"}; + static constexpr char source[] = + "UAV_TYPE dst : register(u0);\n" + "[numthreads(1, 1, 1)]\n" + "void main(uint3 id : SV_DispatchThreadID) {\n" + " dst[UAV_COORD] += 1000u + id.x + 16u * id.y + 256u * id.z;\n" + "}\n"; + struct Compiler { + HMODULE module = LoadLibraryExW(L"d3dcompiler_47.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); + ~Compiler() { if (module) FreeLibrary(module); } + } compiler; + if (!compiler.module) return check(HRESULT_FROM_WIN32(GetLastError()), "load d3dcompiler_47.dll"); + auto compile = std::bit_cast(GetProcAddress(compiler.module, "D3DCompile")); + if (!compile) return check(HRESULT_FROM_WIN32(GetLastError()), "find D3DCompile"); + const D3D_SHADER_MACRO macros[] = { + {"UAV_TYPE", types[index]}, {"UAV_COORD", coordinates[index]}, {nullptr, nullptr}, + }; + ComPtr blob, errors; + const HRESULT hr = compile(source, sizeof(source) - 1, "texture_uav_oracle.hlsl", macros, nullptr, "main", + "cs_5_1", D3DCOMPILE_ENABLE_STRICTNESS, 0, blob.GetAddressOf(), errors.GetAddressOf()); + if (!check(hr, "D3DCompile", errors.Get())) return false; + D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = root.Get(); + desc.CS = {blob->GetBufferPointer(), blob->GetBufferSize()}; + return check(device->CreateComputePipelineState(&desc, IID_PPV_ARGS(pipelines[index].GetAddressOf())), + "CreateComputePipelineState"); + } + + HRESULT create_buffer(UINT64 bytes, D3D12_HEAP_TYPE heap_type, D3D12_RESOURCE_STATES state, ID3D12Resource** out) { + const auto heap = heap_properties(heap_type); + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = bytes; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + return device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, IID_PPV_ARGS(out)); + } +}; + +inline Context& context() { + static thread_local Context ctx; + return ctx; +} +} // namespace detail + +inline Status prepare() { + return detail::context().prepare_device(); +} + +// Provide a valid R32_UINT or R32_TYPELESS texture descriptor and a valid UINT UAV view; a null view +// asks D3D12 to create the default view of a typed R32_UINT resource. Both spans cover the entire +// selected mip (x fastest, then y, then array layer or 3D depth). Other mips are neither read nor written. +inline bool run(const D3D12_RESOURCE_DESC& resource_desc, const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc, + std::span before, std::span after, UINT dispatch_depth = 0) { + using namespace detail; + const View view = select_view(resource_desc, desc); + auto& ctx = context(); + if (view.shader >= ctx.pipelines.size() || + (resource_desc.Format != DXGI_FORMAT_R32_UINT && resource_desc.Format != DXGI_FORMAT_R32_TYPELESS)) + return fail("expected an R32_UINT or R32_TYPELESS texture and a texture UAV"); + if (!ctx.init() || !ctx.create_pipeline(view.shader)) return false; + + ComPtr texture, upload, readback; + const auto heap = heap_properties(D3D12_HEAP_TYPE_DEFAULT); + if (!check(ctx.device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &resource_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(texture.GetAddressOf())), + "CreateCommittedResource (texture)")) return false; + + const auto actual_desc = texture->GetDesc(); // MipLevels = 0 in the input requests the full chain. + if (view.mip >= actual_desc.MipLevels) return fail("UAV mip slice is out of range"); + const bool volume = actual_desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; + const UINT subresources = volume ? 1 : actual_desc.DepthOrArraySize; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT64 bytes = 0; + ctx.device->GetCopyableFootprints(&actual_desc, view.mip, 1, 0, &footprint, nullptr, nullptr, &bytes); + if (bytes == (std::numeric_limits::max)()) return fail("GetCopyableFootprints rejected the texture"); + const auto& fp = footprint.Footprint; + const UINT depth = volume ? fp.Depth : subresources; + const std::uint64_t texels = std::uint64_t(fp.Width) * fp.Height * depth; + if (before.size() != texels || after.size() != texels) + return fail("input and output must span the whole selected mip"); + // Array layers are separate subresources; a 3D mip is one subresource with depth slices at rowPitch * height. + constexpr UINT64 alignment = D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT; + const UINT64 layer_pitch = (bytes + alignment - 1) & ~(alignment - 1); + const UINT64 total = bytes + (subresources - 1) * layer_pitch; + if (total > (std::numeric_limits::max)()) return fail("staging buffers exceed the host address space"); + const auto z_pitch = static_cast(volume ? UINT64(fp.RowPitch) * fp.Height : layer_pitch); + const SIZE_T row_bytes = SIZE_T(fp.Width) * sizeof(std::uint32_t); + if (!check(ctx.create_buffer(total, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, + upload.GetAddressOf()), "CreateCommittedResource (upload)") || + !check(ctx.create_buffer(total, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, + readback.GetAddressOf()), "CreateCommittedResource (readback)")) return false; + const auto each_row = [&](auto copy) { + for (UINT z = 0; z < depth; ++z) + for (UINT y = 0; y < fp.Height; ++y) + copy((SIZE_T(z) * fp.Height + y) * fp.Width, z * z_pitch + SIZE_T(y) * fp.RowPitch); + }; + const D3D12_RANGE none{}, all{0, static_cast(total)}; + void* mapped = nullptr; + if (!check(upload->Map(0, &none, &mapped), "Map upload")) return false; + each_row([&](SIZE_T word, SIZE_T offset) { + std::memcpy(static_cast(mapped) + offset, before.data() + word, row_bytes); + }); + upload->Unmap(0, &all); + + ComPtr uavs; + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{ + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0, + }; + if (!check(ctx.device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(uavs.GetAddressOf())), "CreateDescriptorHeap")) + return false; + ctx.device->CreateUnorderedAccessView(texture.Get(), nullptr, desc, uavs->GetCPUDescriptorHandleForHeapStart()); + + // Use fresh submission objects per run, so no allocator or descriptor heap is reset while in use. + ComPtr queue; + ComPtr allocator; + ComPtr list; + ComPtr fence; + constexpr auto direct = D3D12_COMMAND_LIST_TYPE_DIRECT; + const D3D12_COMMAND_QUEUE_DESC queue_desc{direct}; + if (!check(ctx.device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(queue.GetAddressOf())), "CreateCommandQueue") || + !check(ctx.device->CreateCommandAllocator(direct, IID_PPV_ARGS(allocator.GetAddressOf())), "CreateCommandAllocator") || + !check(ctx.device->CreateCommandList(0, direct, allocator.Get(), ctx.pipelines[view.shader].Get(), + IID_PPV_ARGS(list.GetAddressOf())), "CreateCommandList") || + !check(ctx.device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(fence.GetAddressOf())), "CreateFence")) + return false; + const auto copy_mip = [&](ID3D12Resource* buffer, bool to_texture) { + D3D12_TEXTURE_COPY_LOCATION tex{}, staging{}; + tex.pResource = texture.Get(); + tex.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + staging.pResource = buffer; + staging.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + staging.PlacedFootprint = footprint; + for (UINT layer = 0; layer < subresources; ++layer) { + tex.SubresourceIndex = view.mip + layer * actual_desc.MipLevels; + staging.PlacedFootprint.Offset = layer * layer_pitch; + list->CopyTextureRegion(to_texture ? &tex : &staging, 0, 0, 0, to_texture ? &staging : &tex, nullptr); + } + }; + const auto transition = [&](D3D12_RESOURCE_STATES from, D3D12_RESOURCE_STATES to) { + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Transition = {texture.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, from, to}; + list->ResourceBarrier(1, &barrier); + }; + copy_mip(upload.Get(), true); + transition(D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + ID3D12DescriptorHeap* heaps[] = {uavs.Get()}; + list->SetDescriptorHeaps(1, heaps); + list->SetComputeRootSignature(ctx.root.Get()); + list->SetComputeRootDescriptorTable(0, uavs->GetGPUDescriptorHandleForHeapStart()); + list->Dispatch(fp.Width, fp.Height, dispatch_depth ? dispatch_depth : depth); + transition(D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + copy_mip(readback.Get(), false); + if (!check(list->Close(), "Close command list")) return false; + ID3D12CommandList* lists[] = {list.Get()}; + queue->ExecuteCommandLists(1, lists); + if (!check(queue->Signal(fence.Get(), 1), "Signal queue fence") || + !check(fence->SetEventOnCompletion(1, nullptr), "wait for queue fence") || + !check(ctx.device->GetDeviceRemovedReason(), "D3D12 execution")) return false; + if (!check(readback->Map(0, &all, &mapped), "Map readback")) return false; + each_row([&](SIZE_T word, SIZE_T offset) { + std::memcpy(after.data() + word, static_cast(mapped) + offset, row_bytes); + }); + readback->Unmap(0, &none); + return true; +} +} // namespace uav_oracle diff --git a/runtime/test/d3d12_texture_uav_test.cpp b/runtime/test/d3d12_texture_uav_test.cpp new file mode 100644 index 0000000000..f8ef5177b6 --- /dev/null +++ b/runtime/test/d3d12_texture_uav_test.cpp @@ -0,0 +1,629 @@ +// Synthetic texture UAVs through the Vulkan D3D12 device. It has no compute PSOs yet, so dispatch the translated +// cs_texture_uav.asm through its actual Vulkan set 0. Non-atomic UINT cases also compare in-view writes with +// Windows WARP. Build the shader with runtime/test/shaders/build.py and pass the .spv as argv[1]. +// LEONIDA_VK_VALIDATION=1 enables the Khronos validation layer. No game files are used. +#include "vk_test_device.h" +#include "vk_pc_tail.h" +#include "../shims/d3d12_com.h" +#include "../src/gfx10_descriptors.h" +#include "d3d12_texture_uav_oracle.h" + +#include + +#include +#include +#include +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return false; } \ +} while (0) + +namespace { + +using Microsoft::WRL::ComPtr; +namespace g = leonida::gfx10; +constexpr auto uav_heap = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; +constexpr auto formatless_read = VK_FORMAT_FEATURE_2_STORAGE_READ_WITHOUT_FORMAT_BIT; +constexpr auto formatless_write = VK_FORMAT_FEATURE_2_STORAGE_WRITE_WITHOUT_FORMAT_BIT; + +// Only the layer sees the masked capabilities. The real device and validation layer see the unmodified driver. +PFN_vkGetInstanceProcAddr real_instance_proc = nullptr; +PFN_vkGetPhysicalDeviceFormatProperties2 real_format_properties = nullptr; +VkFormatFeatureFlags2 missing_format_features = 0; + +VKAPI_ATTR void VKAPI_CALL masked_format_properties(VkPhysicalDevice physical, VkFormat format, + VkFormatProperties2* properties) { + real_format_properties(physical, format, properties); + if (format != VK_FORMAT_R32_UINT) return; + for (auto* next = static_cast(properties->pNext); next; next = next->pNext) + if (next->sType == VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_3) + reinterpret_cast(next)->optimalTilingFeatures &= ~missing_format_features; +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL masked_instance_proc(VkInstance instance, const char* name) { + if (std::strcmp(name, "vkGetPhysicalDeviceFormatProperties2") == 0) + return reinterpret_cast(masked_format_properties); + return real_instance_proc(instance, name); +} + +// Numeric values are also the branches selected by cs_texture_uav.asm. +enum class Kind : UINT { one_d, array, volume, two_d, float_volume, float_array, atomic_volume }; + +D3D12_RESOURCE_DESC texture(Kind kind, UINT layers, DXGI_FORMAT format = DXGI_FORMAT_R32_UINT) { + using enum Kind; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = kind == one_d || kind == array || kind == float_array ? D3D12_RESOURCE_DIMENSION_TEXTURE1D : + kind == two_d ? D3D12_RESOURCE_DIMENSION_TEXTURE2D : D3D12_RESOURCE_DIMENSION_TEXTURE3D; + desc.Width = 8; + desc.Height = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D ? 1 : 4; + desc.DepthOrArraySize = UINT16(layers); + desc.MipLevels = 3; + desc.Format = format; + desc.SampleDesc.Count = 1; + desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + return desc; +} + +D3D12_UNORDERED_ACCESS_VIEW_DESC uav(Kind kind, UINT mip, UINT first, UINT count, + DXGI_FORMAT format = DXGI_FORMAT_R32_UINT) { + using enum Kind; + D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; + view.Format = format; + switch (kind) { + case one_d: view.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1D; view.Texture1D = {mip}; break; + case array: + case float_array: view.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1DARRAY; view.Texture1DArray = {mip, first, count}; break; + case two_d: view.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; view.Texture2D = {mip, 0}; break; + default: view.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; view.Texture3D = {mip, first, count}; break; + } + return view; +} + +struct Push { + g::ImageWords key; + UINT kind; +}; + +std::uint32_t push_bytes() { + return leonida::vk_test::pc_tail_requested() ? 128u : 144u; +} + +class Compute { +public: + explicit Compute(vktest::Device& vk) : vk_(vk) {} + ~Compute() { + if (pipeline_) vk_.fn("vkDestroyPipeline")(vk_.device, pipeline_, nullptr); + if (layout_) vk_.fn("vkDestroyPipelineLayout")(vk_.device, layout_, nullptr); + if (module_) vk_.fn("vkDestroyShaderModule")(vk_.device, module_, nullptr); + } + + bool create(ID3D12Device* device, const char* path) { + const auto set_layout = rt::d3d12::bindless_set_layout(device); + set_ = rt::d3d12::bindless_set(device); + EXPECT(set_layout && set_); + std::ifstream file(path, std::ios::binary | std::ios::ate); + EXPECT(file && file.tellg() > 0 && file.tellg() % 4 == 0); + std::vector code(std::size_t(file.tellg()) / 4); + file.seekg(0); + EXPECT(file.read(reinterpret_cast(code.data()), std::streamsize(code.size() * 4))); + // This fixture reads only the descriptor and case selector in s0..s8, not the heap/code-base tail. + EXPECT(!leonida::vk_test::spirv_declares_set(code.data(), code.size() * 4, leonida::vk_test::pc_tail_set)); + VkShaderModuleCreateInfo shader{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + shader.codeSize = code.size() * 4; + shader.pCode = code.data(); + EXPECT(vk_.fn("vkCreateShaderModule")(vk_.device, &shader, nullptr, &module_) == + VK_SUCCESS); + const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, push_bytes()}; + VkPipelineLayoutCreateInfo layout{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + layout.setLayoutCount = 1; + layout.pSetLayouts = &set_layout; + layout.pushConstantRangeCount = 1; + layout.pPushConstantRanges = &push; + EXPECT(vk_.fn("vkCreatePipelineLayout")(vk_.device, &layout, nullptr, &layout_) == + VK_SUCCESS); + VkComputePipelineCreateInfo pipeline{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; + pipeline.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; + pipeline.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; + pipeline.stage.module = module_; + pipeline.stage.pName = "main"; + pipeline.layout = layout_; + EXPECT(vk_.fn("vkCreateComputePipelines")( + vk_.device, VK_NULL_HANDLE, 1, &pipeline, nullptr, &pipeline_) == VK_SUCCESS); + return true; + } + + bool run(ID3D12Resource* resource, UINT mip, VkExtent3D extent, const Push& push, + std::span input, std::span output) { + const auto desc = resource->GetDesc(); + const bool volume = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; + const bool check_base_mip = push.kind == UINT(Kind::float_volume) && mip != 0; + const std::size_t base_texels = check_base_mip ? std::size_t(desc.Width) * desc.Height * desc.DepthOrArraySize : 0; + constexpr std::uint32_t base_marker = std::bit_cast(4096.0f); + const VkDeviceSize bytes = input.size_bytes() + base_texels * sizeof(base_marker); + const VkImage image = rt::d3d12::vulkan_image(resource); + EXPECT(image); + void *src = nullptr, *dst = nullptr; + const VkBuffer upload = vk_.buffer(bytes, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &src); + const VkBuffer readback = vk_.buffer(bytes, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &dst); + EXPECT(upload && readback); + std::memcpy(src, input.data(), input.size_bytes()); + std::fill_n(static_cast(src) + input.size(), base_texels, base_marker); + + EXPECT(vk_.run([&](VkCommandBuffer cb) { + const auto barrier = vk_.fn("vkCmdPipelineBarrier"); + VkImageMemoryBarrier texture_barrier{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; + texture_barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; + texture_barrier.newLayout = VK_IMAGE_LAYOUT_GENERAL; + texture_barrier.srcQueueFamilyIndex = texture_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + texture_barrier.image = image; + texture_barrier.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, check_base_mip ? 0u : mip, + check_base_mip ? mip + 1 : 1, 0, volume ? 1 : extent.depth}; + texture_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + barrier(cb, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, + 1, &texture_barrier); + VkBufferImageCopy copies[2]{}; + copies[0].imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, mip, 0, volume ? 1 : extent.depth}; + copies[0].imageExtent = {extent.width, extent.height, volume ? extent.depth : 1}; + copies[1].bufferOffset = input.size_bytes(); + copies[1].imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; + copies[1].imageExtent = {UINT(desc.Width), desc.Height, desc.DepthOrArraySize}; + const UINT copy_count = check_base_mip ? 2 : 1; + vk_.fn("vkCmdCopyBufferToImage")(cb, upload, image, VK_IMAGE_LAYOUT_GENERAL, + copy_count, copies); + texture_barrier.oldLayout = VK_IMAGE_LAYOUT_GENERAL; + texture_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + texture_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + barrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, + nullptr, 1, &texture_barrier); + vk_.fn("vkCmdBindPipeline")(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_); + vk_.fn("vkCmdBindDescriptorSets")(cb, VK_PIPELINE_BIND_POINT_COMPUTE, layout_, + 0, 1, &set_, 0, nullptr); + std::array sgprs{}; + std::memcpy(sgprs.data(), &push, sizeof(push)); + vk_.fn("vkCmdPushConstants")(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, + push_bytes(), sgprs.data()); + const UINT dispatch_depth = push.kind == UINT(Kind::one_d) ? 1 : extent.depth; + vk_.fn("vkCmdDispatch")(cb, extent.width, extent.height, dispatch_depth); + texture_barrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT; + texture_barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; + barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &texture_barrier); + vk_.fn("vkCmdCopyImageToBuffer")(cb, image, VK_IMAGE_LAYOUT_GENERAL, readback, + copy_count, copies); + VkMemoryBarrier host{VK_STRUCTURE_TYPE_MEMORY_BARRIER, nullptr, VK_ACCESS_TRANSFER_WRITE_BIT, + VK_ACCESS_HOST_READ_BIT}; + barrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &host, 0, nullptr, 0, + nullptr); + return true; + })); + std::memcpy(output.data(), dst, output.size_bytes()); + const auto* base = static_cast(dst) + output.size(); + EXPECT(std::all_of(base, base + base_texels, [&](std::uint32_t word) { return word == base_marker; })); + return true; + } + +private: + vktest::Device& vk_; + VkShaderModule module_ = VK_NULL_HANDLE; + VkPipelineLayout layout_ = VK_NULL_HANDLE; + VkPipeline pipeline_ = VK_NULL_HANDLE; + VkDescriptorSet set_ = VK_NULL_HANDLE; +}; + +bool create_texture(ID3D12Device* device, const D3D12_RESOURCE_DESC& desc, ID3D12Resource** resource) { + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + // The refusal test needs a valid read-only resource; only a UAV-capable resource can start in UAV state. + const auto state = desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS ? D3D12_RESOURCE_STATE_UNORDERED_ACCESS + : D3D12_RESOURCE_STATE_COMMON; + return SUCCEEDED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, + state, nullptr, IID_PPV_ARGS(resource))); +} + +auto read_slot(D3D12_CPU_DESCRIPTOR_HANDLE h) { + g::ImageWords words{}; + std::memcpy(words.data(), reinterpret_cast(h.ptr), sizeof(words)); + return words; +} + +bool flush_descriptors(ID3D12Device* device) { + ComPtr queue; + ComPtr allocator; + ComPtr list; + const D3D12_COMMAND_QUEUE_DESC desc{}; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&desc, IID_PPV_ARGS(&queue)))); + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, + IID_PPV_ARGS(&list)))); + EXPECT(SUCCEEDED(list->Close())); + ID3D12CommandList* lists[] = {list.Get()}; + queue->ExecuteCommandLists(1, lists); + // Queue destruction waits for the device-local descriptor upload before the raw Vulkan dispatch. + return rt::d3d12::last_execute_result(queue.Get()) == leonida::ReplayResult::success; +} + +bool rejects_partial_clear(ID3D12Device* device, ID3D12Resource* resource, D3D12_CPU_DESCRIPTOR_HANDLE view) { + ComPtr allocator; + ComPtr list; + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, + IID_PPV_ARGS(&list)))); + const UINT colors[4] = {42, 0, 0, 0}; + list->ClearUnorderedAccessViewUint({}, view, resource, colors, 0, nullptr); + return list->Close() == E_INVALIDARG; +} + +bool check_case(ID3D12Device* device, Compute* compute, Kind kind, const D3D12_RESOURCE_DESC& shape, + D3D12_CPU_DESCRIPTOR_HANDLE source, D3D12_CPU_DESCRIPTOR_HANDLE copy, bool sliced, + UINT mip, UINT first, UINT count, bool use_default = false) { + const bool volume = kind == Kind::volume || kind == Kind::float_volume || kind == Kind::atomic_volume; + const bool floating = kind == Kind::float_volume || kind == Kind::float_array; + const VkExtent3D extent{UINT(shape.Width) >> mip, std::max(1u, shape.Height >> mip), + volume ? std::max(1u, UINT(shape.DepthOrArraySize) >> mip) : shape.DepthOrArraySize}; + const UINT writable = count == ~0u ? extent.depth - first : count; + const auto desc = uav(kind, mip, first, count, floating ? DXGI_FORMAT_R32_FLOAT : DXGI_FORMAT_R32_UINT); + ComPtr resource; + EXPECT(create_texture(device, shape, &resource)); + device->CreateUnorderedAccessView(resource.Get(), nullptr, use_default ? nullptr : &desc, source); + const auto key = read_slot(source); + const bool partial = volume && (first || writable != extent.depth); + if (partial && !sliced) { + EXPECT(key == g::ImageWords{}); + return true; + } + g::Image decoded{}; + EXPECT(g::decode(key, decoded) && decoded.first_mip == mip && decoded.mip_count == 1); + EXPECT(bool(key[4] & g::volume_uav_flag) == volume); + EXPECT(key[7] == (volume ? g::volume_uav_word(first, writable) : 0)); + EXPECT(g::partial_volume_uav(key, decoded) == partial); + EXPECT(!volume || (decoded.depth == shape.DepthOrArraySize && decoded.first_layer == 0 && decoded.layer_count == 1)); + EXPECT((kind != Kind::array && kind != Kind::float_array) || + (decoded.first_layer == first && decoded.layer_count == writable)); + device->CopyDescriptorsSimple(1, copy, source, uav_heap); + EXPECT(read_slot(copy) == key); + if (partial) EXPECT(rejects_partial_clear(device, resource.Get(), copy)); + if (partial && first > 0) { + // A second view of the same volume and mip must not collide with the copied T#. + auto other = desc; + other.Texture3D.FirstWSlice = 0; + device->CreateUnorderedAccessView(resource.Get(), nullptr, &other, source); + EXPECT(read_slot(source) != key && g::is_image(read_slot(source))); + } + if (partial && kind == Kind::float_volume && shape.Format == DXGI_FORMAT_R32_FLOAT) { + // The typed SRV of this same mip must remain unsliced and must not replace the live partial UAV. + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = shape.Format; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Texture3D = {mip, 1, 0.0f}; + device->CreateShaderResourceView(resource.Get(), &srv, source); + const auto srv_key = read_slot(source); + g::Image sampled{}; + EXPECT(g::decode(srv_key, sampled) && sampled.type == g::ImageType::image_3d && + sampled.address == decoded.address && sampled.first_mip == mip && sampled.mip_count == 1 && + sampled.depth == decoded.depth && sampled.first_layer == 0 && sampled.layer_count == 1); + EXPECT(!(srv_key[4] & g::volume_uav_flag) && srv_key[7] == 0 && srv_key != read_slot(copy)); + } + EXPECT(flush_descriptors(device)); + if (!compute) return true; // CTest exercises the complete descriptor setup, without translated SPIR-V. + + std::vector input(extent.width * extent.height * extent.depth); + auto bits = [&](UINT value) { return floating ? std::bit_cast(float(value)) : value; }; + for (UINT i = 0; i < input.size(); ++i) input[i] = bits(17 + i); + std::vector expected = input, output(input.size()), host(input.size()); + for (UINT z = first; z < first + writable; ++z) + for (UINT y = 0; y < extent.height; ++y) + for (UINT x = 0; x < extent.width; ++x) { + const UINT i = (z * extent.height + y) * extent.width + x; + const UINT initial = 17 + i; + const UINT add = 1000 + x + 16 * y + 256 * (z - first); + if (kind == Kind::atomic_volume) + expected[i] = add + (initial << 16) + ((initial + 5) << 8) + 7 + 99; + else + expected[i] = bits(initial + add + (kind == Kind::float_volume && x % 2 == 0 ? initial : 0)); + } + EXPECT(compute->run(resource.Get(), mip, extent, {read_slot(copy), UINT(kind)}, input, output)); + for (UINT i = 0; i < output.size(); ++i) { + if (output[i] == expected[i]) continue; + std::fprintf(stderr, "kind %u mip %u first %u count %u texel %u: got %#x, expected %#x\n", + UINT(kind), mip, first, count, i, output[i], expected[i]); + return false; + } + if (!floating && kind != Kind::atomic_volume) { + // WARP did not clip out-of-range W accesses to WSize in the native probe. Compare documented in-view + // D3D12 accesses and independently require Vulkan to preserve every non-view slice, even under overdispatch. + EXPECT(uav_oracle::run(shape, use_default ? nullptr : &desc, input, host, + volume ? writable : kind == Kind::one_d ? 1 : 0)); + EXPECT(output == host); + } + return true; +} + +bool check_refusals(ID3D12Device* device, D3D12_CPU_DESCRIPTOR_HANDLE slot) { + using enum Kind; + const auto bad = [&](ID3D12Resource* resource, const D3D12_UNORDERED_ACCESS_VIEW_DESC* view) { + std::memset(reinterpret_cast(slot.ptr), 0x55, sizeof(g::ImageWords)); + device->CreateUnorderedAccessView(resource, nullptr, view, slot); + return read_slot(slot) == g::ImageWords{}; + }; + ComPtr line, layers, depth, typeless, read_only; + EXPECT(create_texture(device, texture(one_d, 1), &line)); + EXPECT(create_texture(device, texture(array, 4), &layers)); + EXPECT(create_texture(device, texture(volume, 8), &depth)); + EXPECT(create_texture(device, texture(volume, 8, DXGI_FORMAT_R32_TYPELESS), &typeless)); + auto shape = texture(one_d, 1); + shape.Flags = D3D12_RESOURCE_FLAG_NONE; + EXPECT(create_texture(device, shape, &read_only)); + EXPECT(bad(read_only.Get(), nullptr) && bad(typeless.Get(), nullptr)); + const auto good = uav(one_d, 0, 0, 1); + EXPECT(bad(nullptr, &good) && bad(depth.Get(), &good)); + for (const auto view : {uav(one_d, 3, 0, 1), uav(one_d, 0, 0, 1, DXGI_FORMAT_R16_FLOAT)}) + EXPECT(bad(line.Get(), &view)); + for (const auto view : {uav(array, 0, 4, 1), uav(array, 0, 1, 0), uav(array, 0, 2, 3), uav(array, 3, 0, 1)}) + EXPECT(bad(layers.Get(), &view)); + for (const auto view : {uav(volume, 3, 0, 1), uav(volume, 2, 2, 1), uav(volume, 1, 1, 0), uav(volume, 1, 2, 3)}) + EXPECT(bad(depth.Get(), &view)); + auto rgba = texture(volume, 4, DXGI_FORMAT_R8G8B8A8_TYPELESS); + ComPtr srgb; + EXPECT(create_texture(device, rgba, &srgb)); + const auto srgb_view = uav(volume, 0, 0, ~0u, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB); + EXPECT(bad(srgb.Get(), &srgb_view)); + ComPtr refused; + const auto typed_srgb = texture(volume, 4, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB); + ComPtr typed, warp_typed; + uav_oracle::detail::Context host; + const bool created = create_texture(device, typed_srgb, &typed); + if (host.prepare_device() == uav_oracle::Status::ready) + EXPECT(created == create_texture(host.device.Get(), typed_srgb, &warp_typed)); + if (created) { + EXPECT(bad(typed.Get(), &srgb_view)); + const auto raw_view = uav(volume, 0, 0, ~0u, DXGI_FORMAT_R8G8B8A8_UNORM); + EXPECT(!bad(typed.Get(), &raw_view)); + } + auto invalid_shape = texture(volume, 4); + invalid_shape.MipLevels = 8; + EXPECT(!create_texture(device, invalid_shape, &refused) && !refused); + invalid_shape = texture(one_d, 1); + invalid_shape.Width = (1ull << 32) + 8; + EXPECT(!create_texture(device, invalid_shape, &refused) && !refused); + return true; +} + +bool check_formatless_features(ID3D12Device* device, D3D12_CPU_DESCRIPTOR_HANDLE slot, bool sliced) { + using enum Kind; + const auto check = [&](Kind kind, const D3D12_RESOURCE_DESC& shape, UINT first, UINT count) { + ComPtr resource; + EXPECT(create_texture(device, shape, &resource)); + const auto view = uav(kind, 1, first, count); + device->CreateUnorderedAccessView(resource.Get(), nullptr, &view, slot); + const auto valid = read_slot(slot); + g::Image decoded{}; + EXPECT(g::decode(valid, decoded) && decoded.first_mip == 1 && decoded.mip_count == 1); + for (const auto missing : {formatless_read, formatless_write, formatless_read | formatless_write}) { + std::memcpy(reinterpret_cast(slot.ptr), valid.data(), sizeof(valid)); + missing_format_features = missing; + device->CreateUnorderedAccessView(resource.Get(), nullptr, &view, slot); + missing_format_features = 0; + if (read_slot(slot) != g::ImageWords{}) { + std::fprintf(stderr, "kind %u first slice %u: accepted mip 1 UAV without format features %#llx\n", + UINT(kind), first, static_cast(missing)); + return false; + } + } + return true; + }; + EXPECT(check(one_d, texture(one_d, 1), 0, 1)); + EXPECT(check(array, texture(array, 4), 1, 2)); + // The mask applies to the R32_UINT view, not its typeless resource's backing format. + const auto volume_shape = texture(volume, 8, DXGI_FORMAT_R32_TYPELESS); + EXPECT(check(volume, volume_shape, 0, ~0u)); + if (sliced) EXPECT(check(volume, volume_shape, 1, 2)); + return true; +} + +bool check_packed_formatless_exemption(ID3D12Device* device, vktest::Device& vk, + D3D12_CPU_DESCRIPTOR_HANDLE slot, bool sliced) { + VkFormatProperties features{}; + vk.instance_fn("vkGetPhysicalDeviceFormatProperties")( + vk.physical, VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, &features); + if (features.optimalTilingFeatures & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) { + std::puts("Packed R32_UINT exemption not exercised: native RGB9E5 storage"); + return true; + } + constexpr auto format = DXGI_FORMAT_R9G9B9E5_SHAREDEXP; + ComPtr resource; + if (!create_texture(device, texture(Kind::volume, 8, format), &resource)) { + std::puts("Packed R32_UINT exemption not exercised: no emulated RGB9E5 3D storage"); + return true; + } + const UINT first = sliced ? 1 : 0, count = sliced ? 2 : 4; + const auto view = uav(Kind::volume, 1, first, count, format); + missing_format_features = formatless_read | formatless_write; + device->CreateUnorderedAccessView(resource.Get(), nullptr, &view, slot); + missing_format_features = 0; + const auto key = read_slot(slot); + g::Image decoded{}; + EXPECT(g::decode(key, decoded) && decoded.first_mip == 1 && (key[4] & g::volume_uav_flag)); + EXPECT(key[7] == (g::volume_uav_word(first, count) | g::packed_uav_flag)); + return true; +} + +bool check_standalone(bool sliced) { + ComPtr device; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&device)))); + ComPtr volume; + EXPECT(create_texture(device.Get(), texture(Kind::volume, 8), &volume)); + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{uav_heap, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + ComPtr heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap)))); + const auto slot = heap->GetCPUDescriptorHandleForHeapStart(); + device->CreateUnorderedAccessView(volume.Get(), nullptr, nullptr, slot); + EXPECT(g::is_image(read_slot(slot))); + const auto view = uav(Kind::volume, 1, 1, 2); + device->CreateUnorderedAccessView(volume.Get(), nullptr, &view, slot); + EXPECT(read_slot(slot)[7] == (sliced ? g::volume_uav_word(1, 2) : 0)); + return true; +} + +bool check_cpu_clear(ID3D12Device* device, vktest::Device& vk, D3D12_CPU_DESCRIPTOR_HANDLE slot) { + EXPECT(!rt::d3d12::bindless_set(device)); + ComPtr queue; + ComPtr allocator; + ComPtr list; + const D3D12_COMMAND_QUEUE_DESC queue_desc{}; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue)))); + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, + IID_PPV_ARGS(&list)))); + ComPtr image; + EXPECT(create_texture(device, texture(Kind::two_d, 1), &image)); + device->CreateUnorderedAccessView(image.Get(), nullptr, nullptr, slot); + EXPECT(g::is_image(read_slot(slot))); + const UINT value[] = {42, 0, 0, 0}; + list->ClearUnorderedAccessViewUint({}, slot, image.Get(), value, 0, nullptr); + EXPECT(SUCCEEDED(list->Close())); + ID3D12CommandList* lists[] = {list.Get()}; + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue.Get()) == leonida::ReplayResult::success); + void* mapped = nullptr; + const VkBuffer output = vk.buffer(32 * sizeof(UINT), VK_BUFFER_USAGE_TRANSFER_DST_BIT, &mapped); + EXPECT(output); + EXPECT(vk.run([&](VkCommandBuffer cb) { + const VkMemoryBarrier memory{VK_STRUCTURE_TYPE_MEMORY_BARRIER, nullptr, VK_ACCESS_TRANSFER_WRITE_BIT, + VK_ACCESS_TRANSFER_READ_BIT}; + vk.fn("vkCmdPipelineBarrier")(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &memory, 0, nullptr, 0, nullptr); + vk.read_back(cb, rt::d3d12::vulkan_image(image.Get()), VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_ASPECT_COLOR_BIT, + 8, 4, 1, output, 0); + return true; + })); + const auto* pixels = static_cast(mapped); + EXPECT(std::all_of(pixels, pixels + 32, [](UINT pixel) { return pixel == 42; })); + + // A typeless backing may reinterpret bits in a transfer clear; an unsupported clear must not be submitted. + EXPECT(SUCCEEDED(allocator->Reset())); + EXPECT(SUCCEEDED(list->Reset(allocator.Get(), nullptr))); + ComPtr volume; + EXPECT(create_texture(device, texture(Kind::volume, 4, DXGI_FORMAT_R32_TYPELESS), &volume)); + const auto view = uav(Kind::volume, 0, 0, ~0u); + device->CreateUnorderedAccessView(volume.Get(), nullptr, &view, slot); + EXPECT(g::is_image(read_slot(slot))); + list->ClearUnorderedAccessViewUint({}, slot, volume.Get(), value, 0, nullptr); + EXPECT(SUCCEEDED(list->Close())); + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue.Get()) == leonida::ReplayResult::unsupported); + return true; +} + +bool test(vktest::Device& vk, const char* shader, bool enable_slices) { + rt::d3d12::VulkanDeviceInfo info{}; + real_instance_proc = vk.instance_proc; + real_format_properties = vk.instance_fn( + "vkGetPhysicalDeviceFormatProperties2"); + EXPECT(real_format_properties); + info.get_instance_proc = masked_instance_proc; + info.instance = vk.instance; + info.physical = vk.physical; + info.device = vk.device; + info.queue = vk.queue; + info.queue_family = vk.family; + info.bindless = vk.bindless; + info.bindless_partially_bound = vk.partially_bound; + info.robust_image_access = vk.robust_image_access; + info.sliced_3d_uav = enable_slices && vk.sliced_3d_uav; + ComPtr device; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device)))); + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{uav_heap, 2, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + ComPtr heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap)))); + const auto source = heap->GetCPUDescriptorHandleForHeapStart(); + const D3D12_CPU_DESCRIPTOR_HANDLE copy{source.ptr + device->GetDescriptorHandleIncrementSize(uav_heap)}; + if (!enable_slices) { + ComPtr volume; + EXPECT(create_texture(device.Get(), texture(Kind::volume, 8), &volume)); + device->CreateUnorderedAccessView(volume.Get(), nullptr, nullptr, source); + EXPECT(g::is_image(read_slot(source))); + const auto view = uav(Kind::volume, 1, 1, 2); + device->CreateUnorderedAccessView(volume.Get(), nullptr, &view, source); + EXPECT(read_slot(source) == g::ImageWords{}); + info.bindless = false; + ComPtr cpu_only; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&cpu_only)))); + ComPtr cpu_heap; + EXPECT(SUCCEEDED(cpu_only->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&cpu_heap)))); + return check_cpu_clear(cpu_only.Get(), vk, cpu_heap->GetCPUDescriptorHandleForHeapStart()); + } + + using enum Kind; + EXPECT(check_refusals(device.Get(), source)); + EXPECT(check_formatless_features(device.Get(), source, info.sliced_3d_uav)); + EXPECT(check_packed_formatless_exemption(device.Get(), vk, source, info.sliced_3d_uav)); + Compute compute(vk); + if (shader) EXPECT(compute.create(device.Get(), shader)); + auto* dispatch = shader ? &compute : nullptr; + EXPECT(check_case(device.Get(), dispatch, one_d, texture(one_d, 1), source, copy, false, 0, 0, 1, true)); + EXPECT(check_case(device.Get(), dispatch, one_d, texture(one_d, 1), source, copy, false, 2, 0, 1)); + EXPECT(check_case(device.Get(), dispatch, one_d, texture(array, 4), source, copy, false, 1, 0, 1)); + EXPECT(check_case(device.Get(), dispatch, array, texture(array, 4), source, copy, false, 0, 0, 4, true)); + EXPECT(check_case(device.Get(), dispatch, array, texture(array, 4), source, copy, false, 1, 1, 2)); + EXPECT(check_case(device.Get(), dispatch, array, texture(array, 4), source, copy, false, 1, 1, ~0u)); + EXPECT(check_case(device.Get(), dispatch, float_array, texture(float_array, 4, DXGI_FORMAT_R32_FLOAT), + source, copy, false, 1, 1, 2)); + EXPECT(check_case(device.Get(), dispatch, volume, texture(volume, 8), source, copy, vk.sliced_3d_uav, 0, 0, 8, true)); + EXPECT(check_case(device.Get(), dispatch, volume, texture(volume, 8, DXGI_FORMAT_R32_TYPELESS), source, copy, + vk.sliced_3d_uav, 1, 1, 2)); + EXPECT(check_case(device.Get(), dispatch, volume, texture(volume, 8), source, copy, vk.sliced_3d_uav, 1, 2, ~0u)); + EXPECT(check_case(device.Get(), dispatch, float_volume, texture(float_volume, 8, DXGI_FORMAT_R32_FLOAT), + source, copy, vk.sliced_3d_uav, 1, 1, 2)); + EXPECT(check_case(device.Get(), dispatch, atomic_volume, texture(atomic_volume, 8), + source, copy, vk.sliced_3d_uav, 1, 0, 4)); + EXPECT(check_case(device.Get(), dispatch, atomic_volume, texture(atomic_volume, 8), + source, copy, vk.sliced_3d_uav, 1, 1, 2)); + EXPECT(check_case(device.Get(), dispatch, two_d, texture(two_d, 1), source, copy, false, 1, 0, 1)); + return true; +} + +} // namespace + +int main(int argc, char** argv) { + if (argc != 2) { + std::fprintf(stderr, "usage: d3d12_texture_uav_test |--descriptors-only\n"); + return 2; + } + vktest::Device vk; + // Exercise Vulkan 1.3 per-format access even on a logical device without the legacy feature bits. + const auto status = vk.initialize(true, false); + if (status == vktest::DeviceStatus::unavailable && !vk.validation_errors()) { + std::printf("SKIP: no Vulkan 1.3 device with a graphics queue\n"); + return 77; + } + if (status != vktest::DeviceStatus::ready) return 1; + const char* shader = std::strcmp(argv[1], "--descriptors-only") == 0 ? nullptr : argv[1]; + VkPhysicalDeviceProperties props{}; + vk.instance_fn("vkGetPhysicalDeviceProperties")(vk.physical, &props); + if (!vk.bindless || !vk.robust_image_access || (shader && props.limits.maxPushConstantsSize < push_bytes())) { + std::printf("SKIP: requires bindless descriptors and robustImageAccess%s\n", + shader ? " and 144 bytes of push constants" : ""); + return vk.validation_errors() ? 1 : 77; + } + if (shader) { + const auto warp = uav_oracle::prepare(); + if (warp == uav_oracle::Status::unavailable) { + std::printf("SKIP: no D3D12 WARP adapter\n"); + return vk.validation_errors() ? 1 : 77; + } + if (warp != uav_oracle::Status::ready) return 1; + } + if (!test(vk, shader, false) || !test(vk, shader, true) || !check_standalone(vk.sliced_3d_uav) || + vk.validation_errors()) + return 1; + if (!shader) { + std::puts("texture UAV descriptors: creation, copy, range/refusal and clear checks passed"); + return 0; + } + if (!vk.sliced_3d_uav) std::printf("SKIP: sliced 3D UAV GPU writes (feature unavailable); rejection verified\n"); + std::printf("texture UAVs: %u GPU cases (%u compared with WARP), format/range/refusal checks passed\n", + vk.sliced_3d_uav ? 14u : 10u, vk.sliced_3d_uav ? 10u : 8u); + return 0; +} diff --git a/runtime/test/d3d12_title_va_test.cpp b/runtime/test/d3d12_title_va_test.cpp index 7be1e880b4..75a2c4c71e 100644 --- a/runtime/test/d3d12_title_va_test.cpp +++ b/runtime/test/d3d12_title_va_test.cpp @@ -26,6 +26,7 @@ #include #include +#include #include #include #include @@ -455,9 +456,137 @@ int check_title_memory(Context& c, int& checks) { return 0; } +// Bind the same interior GPU handle first through a short graphics table, then a wide compute table. +// Update its last CBV after Close and again before resubmitting the identical list. +int check_rebound_tables(Context& c, ID3D12RootSignature* narrow, bool mirror, bool api_copy) { + constexpr UINT selected = 64; + const auto alloc_backing = [](std::size_t n, std::uint64_t) -> void* { + return VirtualAlloc(nullptr, n, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + }; + const auto free_backing = [](void* p, std::uint64_t) { VirtualFree(p, 0, MEM_RELEASE); }; + Ref heap; + const D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, selected + 4, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + rt::d3d12_xs::set_descriptor_heap_allocator(alloc_backing, free_backing); + const HRESULT created = c.device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&heap.p)); + rt::d3d12_xs::set_descriptor_heap_allocator(nullptr, nullptr); + EXPECT(created == S_OK); + const UINT step = c.device->GetDescriptorHandleIncrementSize(hd.Type); + const auto cpu = reinterpret_cast(slot(heap.p, 9))(heap.p); + const auto gpu = reinterpret_cast(slot(heap.p, 10))(heap.p); + const auto real = rt::d3d12_xs::translate_cpu_descriptor_handle(c.device, {SIZE_T(cpu)}); + EXPECT(real.ptr && real.ptr != cpu && gpu && step == 32); + + const D3D12_HEAP_PROPERTIES def{D3D12_HEAP_TYPE_DEFAULT}, up{D3D12_HEAP_TYPE_UPLOAD}, + rb{D3D12_HEAP_TYPE_READBACK}; + Ref upload, source, out, readback; + const auto data_desc = buffer_desc(2 * kBytes); + const auto result_desc = buffer_desc(kBytes); + const auto uav_desc = buffer_desc(kBytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + EXPECT(c.device->CreateCommittedResource(&up, {}, &data_desc, D3D12_RESOURCE_STATE_GENERIC_READ, + nullptr, IID_PPV_ARGS(&upload.p)) == S_OK); + EXPECT(c.device->CreateCommittedResource(&def, {}, &data_desc, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&source.p)) == S_OK); + EXPECT(c.device->CreateCommittedResource(&def, {}, &uav_desc, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + nullptr, IID_PPV_ARGS(&out.p)) == S_OK); + EXPECT(c.device->CreateCommittedResource(&rb, {}, &result_desc, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&readback.p)) == S_OK); + std::uint32_t* input = nullptr; + EXPECT(upload->Map(0, nullptr, reinterpret_cast(&input)) == S_OK); + for (UINT i = 0; i < 2 * kElements; ++i) input[i] = 0x10500000u + 37 * i; + upload->Unmap(0, nullptr); + Ref alloc; + Ref list; + EXPECT(c.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc.p)) == S_OK); + EXPECT(c.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc.p, c.pso, IID_PPV_ARGS(&list.p)) == S_OK); + const auto transition_resource = [&](ID3D12Resource* resource, D3D12_RESOURCE_STATES from, D3D12_RESOURCE_STATES to) { + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Transition = {resource, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, from, to}; + list->ResourceBarrier(1, &barrier); + }; + list->CopyBufferRegion(source.p, 0, upload.p, 0, data_desc.Width); + transition_resource(source.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + ID3D12DescriptorHeap* heaps[] = {heap.p}; + list->SetDescriptorHeaps(1, heaps); + const D3D12_GPU_DESCRIPTOR_HANDLE table{gpu + step}; + list->SetGraphicsRootSignature(narrow); + list->SetGraphicsRootDescriptorTable(2, table); + list->SetComputeRootSignature(c.root); + list->SetComputeRootDescriptorTable(2, table); + list->SetGraphicsRootDescriptorTable(2, table); + const UINT args[] = {selected, 0xfffffffcu}; + list->SetComputeRoot32BitConstants(0, 2, args, 0); + list->SetComputeRootUnorderedAccessView(1, out->GetGPUVirtualAddress()); + list->Dispatch(1, 1, 1); + transition_resource(out.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->CopyBufferRegion(readback.p, 0, out.p, 0, kBytes); + transition_resource(out.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + transition_resource(source.p, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COPY_DEST); + EXPECT(list->Close() == S_OK); + + // Build two real CBVs in a CPU-only staging heap. Only raw CPU writes reach the title-owned slots below. + Ref staging; + const D3D12_DESCRIPTOR_HEAP_DESC staging_desc{hd.Type, 2, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + EXPECT(c.inner->CreateDescriptorHeap(&staging_desc, IID_PPV_ARGS(&staging.p)) == S_OK); + const auto staging_cpu = staging->GetCPUDescriptorHandleForHeapStart(); + unsigned matched[2]{}; + bool api_slots_correct = true; + for (UINT pass = 0; pass < 2; ++pass) { + const D3D12_CONSTANT_BUFFER_VIEW_DESC cbv{source->GetGPUVirtualAddress() + kBytes * pass, kBytes}; + const D3D12_CPU_DESCRIPTOR_HANDLE src{staging_cpu.ptr + pass * step}; + c.inner->CreateConstantBufferView(&cbv, src); + const void* copy_from = reinterpret_cast(src.ptr); + if (api_copy) { + // Write to a shader-visible slot outside the bound table. The game copies from its CPU backing. + const D3D12_CPU_DESCRIPTOR_HANDLE from{static_cast(cpu + (selected + 3) * step)}; + copy_from = reinterpret_cast(from.ptr); + if (pass == 0) { + DWORD previous = 0; + EXPECT(VirtualProtect(reinterpret_cast(cpu), hd.NumDescriptors * step, PAGE_READONLY, &previous)); + c.device->CreateConstantBufferView(&cbv, from); + EXPECT(vsharp_base(from.ptr) == 0); + EXPECT(VirtualProtect(reinterpret_cast(cpu), hd.NumDescriptors * step, previous, &previous)); + c.device->CreateConstantBufferView(&cbv, from); + } else { + c.device->CopyDescriptorsSimple(1, from, src, hd.Type); + } + const void* reference = reinterpret_cast(src.ptr); + const auto* inner = reinterpret_cast(real.ptr + (selected + 3) * step); + const bool real_match = std::memcmp(inner, reference, step) == 0; + const bool title_match = std::memcmp(copy_from, reference, step) == 0; + std::printf("API slot %u: real matches staging=%d, title matches staging=%d\n", pass, real_match, title_match); + api_slots_correct &= real_match && (mirror ? title_match : vsharp_base(from.ptr) == 0); + } + for (UINT slot_index : {0u, 1 + selected, 2 + selected}) + std::memcpy(reinterpret_cast(cpu + slot_index * step), copy_from, step); + ID3D12CommandList* lists[] = {list.p}; + c.queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(c.queue) == leonida::ReplayResult::success); + EXPECT(c.queue->Signal(c.fence, ++c.fence_value) == S_OK); + EXPECT(c.fence->SetEventOnCompletion(c.fence_value, nullptr) == S_OK); + void* mapped = nullptr; + EXPECT(readback->Map(0, nullptr, &mapped) == S_OK); + const auto* got = static_cast(mapped); + for (UINT i = 0; i < kElements; ++i) + matched[pass] += got[i] == (mirror ? 0x10500000u + 37 * (kElements * pass + i) : 0u); + readback->Unmap(0, nullptr); + EXPECT(vsharp_base(real.ptr) == 0 && vsharp_base(real.ptr + (selected + 2) * step) == 0); + } + std::printf("rebound table (%s): %u/%u and %u/%u GPU words matched on consecutive submissions\n", + mirror ? "updated CBV" : "null CBV", matched[0], kElements, matched[1], kElements); + EXPECT(api_slots_correct && matched[0] == kElements && matched[1] == kElements); + return 0; +} + } // namespace -int main() { +int main(int argc, char** argv) { + const bool api_copy_off = argc == 2 && std::strcmp(argv[1], "--api-descriptor-copy-off") == 0; + const bool mirror_off = api_copy_off || (argc == 2 && std::strcmp(argv[1], "--rebound-tables-off") == 0); + const bool second_device = argc == 2 && std::strcmp(argv[1], "--rebound-second-device") == 0; + const bool api_copy = api_copy_off || (argc == 2 && std::strcmp(argv[1], "--api-descriptor-copy") == 0); + const bool rebind = api_copy || mirror_off || second_device || (argc == 2 && std::strcmp(argv[1], "--rebound-tables") == 0); vktest::Device d; const auto device_status = d.initialize(); if (device_status == vktest::DeviceStatus::unavailable) { @@ -492,6 +621,9 @@ int main() { info.buffer_device_address = true; info.subgroup = d.subgroup; info.shader_dir = library.string(); + // Keep another compatibility device alive over the same physical GPU. Each owns its own arena. + Ref first; + if (second_device) EXPECT(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&first.p)) == S_OK); ID3D12Device* inner = nullptr; // owned by the proxy, as in d3d12_compute_test EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; @@ -501,7 +633,7 @@ int main() { // [0] two constants (s4, s5), [1] a root UAV (s6:s7), [2] a one-descriptor table (s8): the console compute // layout cs_user_data.comp reads. - D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, 1, 0, 0}; + D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_CBV, rebind ? 65u : 1u, 1, 0, 0}; D3D12_ROOT_PARAMETER params[3] = {}; params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; params[0].Constants = {0, 0, 2}; @@ -539,6 +671,16 @@ int main() { c.fence = fence.p; c.arena = rt::d3d12::device_arena_size(device.p); EXPECT(c.arena > 0); + if (rebind) { + range.NumDescriptors = 1; + const auto narrow_blob = serialize(root_desc); + Ref narrow; + EXPECT(!narrow_blob.empty()); + EXPECT(device->CreateRootSignature(0, narrow_blob.data(), narrow_blob.size(), IID_PPV_ARGS(&narrow.p)) == S_OK); + EXPECT(check_rebound_tables(c, narrow.p, !mirror_off, api_copy) == 0); + EXPECT(d.validation_errors() == 0); + return 0; + } if (check_kind(c, "read-write", PAGE_READWRITE, checks)) return 1; if (check_kind(c, "write-combined", PAGE_READWRITE | PAGE_WRITECOMBINE, checks)) return 1; if (check_title_memory(c, checks)) return 1; diff --git a/runtime/test/d3d12_translated_draw_test.cpp b/runtime/test/d3d12_translated_draw_test.cpp index 87bf185fa2..9bc8d75972 100644 --- a/runtime/test/d3d12_translated_draw_test.cpp +++ b/runtime/test/d3d12_translated_draw_test.cpp @@ -36,6 +36,9 @@ // build. On success it prints one marker line, after every check. #ifndef LEONIDA_M15_GUEST #include "vk_test_device.h" +#include "test_temp_dir.h" +#include "d3d12_native_graphics_fixture.h" +#include #endif #include "d3d12_test_shaders.h" #ifndef LEONIDA_M15_GUEST @@ -80,6 +83,7 @@ std::vector read_file(const std::filesystem::path& path) { return {std::istreambuf_iterator(in), std::istreambuf_iterator()}; } + // One 32-byte vertex record, as vs_m15.asm reads it: position xyzw, then colour rgba. struct Vertex { float position[4]; @@ -115,7 +119,11 @@ int main(int argc, char** argv) { // The FSSM programs the index entries are keyed by; the shim's device finds the index through LEONIDA_SHADERS. const std::filesystem::path root_dir = argv[1]; #else -int main() { +int main(int argc, char** argv) { + const bool derived_zero = argc == 2 && std::strcmp(argv[1], "--derived-zero") == 0; + const bool derived_restore = argc == 2 && std::strcmp(argv[1], "--derived-restore") == 0; + const bool native = derived_zero || derived_restore || (argc == 2 && std::strcmp(argv[1], "--native-pso") == 0); + EXPECT(argc == 1 || native); vktest::Device d; const auto device_status = d.initialize(); if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips @@ -134,6 +142,13 @@ int main() { EXPECT(library.load((root_dir / "spirv").string())); EXPECT(library.find("vs", leonida::sha256_hex(vs_program)) && library.find("ps", leonida::sha256_hex(ps_program))); EXPECT(library.find("ps", leonida::sha256_hex(ps_program))->uses_code_base); + std::optional scratch; + if (native) { + scratch.emplace("leonida_native_graphics_draw"); + std::error_code ec; + std::filesystem::copy(root_dir / "spirv", scratch->path() / "spirv", std::filesystem::copy_options::recursive, ec); + EXPECT(!ec && write_native_catalog(scratch->path(), "vs", vs_program, ps_program)); + } #endif const auto vs_container = shader_container(vs_program), ps_container = shader_container(ps_program); // A program the index does not know (the VS's bytes with one word changed) must be refused by the PSO. @@ -168,6 +183,9 @@ int main() { } #else rt::d3d12::VulkanDeviceInfo info{}; + info.first_use_backend_pipelines=d.first_use_backend_pipelines; + info.prepare_on_bind=d.prepare_on_bind; + info.cold_graphics_compile=d.cold_graphics_compile; info.get_instance_proc = d.instance_proc; info.instance = d.instance; info.physical = d.physical; @@ -175,12 +193,12 @@ int main() { info.queue = d.queue; info.queue_family = d.family; info.buffer_device_address = true; - info.shader_dir = (root_dir / "spirv").string(); + info.shader_dir = ((native ? scratch->path() : root_dir) / "spirv").string(); ID3D12Device* inner = nullptr; EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p), /*console_lists=*/false))); + reinterpret_cast(&device.p)))); rt::d3d12::set_device_outer(inner, device.p); #endif @@ -215,7 +233,40 @@ int main() { pso_desc.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT; pso_desc.SampleDesc.Count = 1; Ref pso, unknown; - EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&pso.p)))); +#ifndef LEONIDA_M15_GUEST + if (native) { + EXPECT(FAILED(create_native_pso(device.p, root.p, pso_desc.RTVFormats[0], stale_digest, &unknown.p)) && !unknown.p); + EXPECT(FAILED(create_native_pso(device.p, root.p, pso_desc.RTVFormats[0], np::Digest{}, &unknown.p)) && !unknown.p); + EXPECT(SUCCEEDED(create_native_pso(device.p, root.p, pso_desc.RTVFormats[0], producer_digest, &pso.p)) && pso.p); + Ref duplicate; + EXPECT(SUCCEEDED(create_native_pso(device.p, root.p, pso_desc.RTVFormats[0], producer_digest, &duplicate.p))); + EXPECT(duplicate.p && duplicate.p != pso.p); + EXPECT(rt::d3d12::graphics_pipeline_id(pso.p) != 0 && + rt::d3d12::graphics_pipeline_id(duplicate.p) == rt::d3d12::graphics_pipeline_id(pso.p)); + const GUID marker{0xe79d6ba2, 0x2d8c, 0x4344, {0xa4, 0x81, 0x34, 0x19, 0x24, 0x4e, 0x2a, 0x0b}}; + const UINT value = 17; + EXPECT(SUCCEEDED(pso->SetPrivateData(marker, sizeof(value), &value))); + UINT private_size = 0; + EXPECT(duplicate->GetPrivateData(marker, &private_size, nullptr) == DXGI_ERROR_NOT_FOUND); + if (derived_zero || derived_restore) { + using Derive=HRESULT(WINAPI*)(void*,ID3D12PipelineState*,UINT,const unsigned char*,const IID*,void**); + const auto call=reinterpret_cast(slot(device.p,55)); + std::array record{}; + const UINT tag=3; std::memcpy(record.data(),&tag,4); + Ref masked; + EXPECT(SUCCEEDED(call(device.p,pso.p,1,record.data(),&__uuidof(ID3D12PipelineState),reinterpret_cast(&masked.p))) && masked.p); + if (derived_restore) { + const UINT mask=~0u; std::memcpy(record.data()+4,&mask,4); + Ref restored; + EXPECT(SUCCEEDED(call(device.p,masked.p,1,record.data(),&__uuidof(ID3D12PipelineState),reinterpret_cast(&restored.p))) && restored.p); + std::swap(restored.p,pso.p); + } else std::swap(masked.p,pso.p); + } else std::swap(duplicate.p,pso.p); // The draw uses the second view after releasing the first one. + } else +#endif + { + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&pso.p)))); + } pso_desc.VS = {unknown_container.data(), unknown_container.size()}; EXPECT(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&unknown.p)) == E_INVALIDARG && !unknown.p); @@ -387,6 +438,14 @@ int main() { const Pixel clear_color = {0.5f, 0.125f, 0.25f, 0.5f}; const Pixel top_left = {0.125f, 1.0f, 0.75f, 1.0f}, bottom_right = {0.25f, 1.125f, 0.875f, 1.0f}; const Pixel bottom_left = {0.75f, 0.25f, 0.75f, 1.0f}; +#ifndef LEONIDA_M15_GUEST + if (derived_zero) { + const Pixel background{0.5f,0.125f,0.25f,0.5f}; + for (const auto& pixel:pixels) EXPECT(std::memcmp(&pixel,&background,sizeof(Pixel))==0); + std::printf("derived mask zero: all %zu pixels equal the clear value\n",pixels.size()); + return 0; + } +#endif unsigned mismatches = 0, edge = 0, edge_triangle = 0, edge_clear = 0; for (UINT row = 0; row < target_extent; ++row) { for (UINT col = 0; col < target_extent; ++col) { diff --git a/runtime/test/d3d12_xmem_placed_test.cpp b/runtime/test/d3d12_xmem_placed_test.cpp index 368b32510b..19fd57ce1f 100644 --- a/runtime/test/d3d12_xmem_placed_test.cpp +++ b/runtime/test/d3d12_xmem_placed_test.cpp @@ -6,6 +6,7 @@ // GPU VA is the window itself and a GPU copy reads what the CPU writes there afterwards. // Needs VK_EXT_external_memory_host (skipped otherwise). No shaders or game data. #include "vk_test_device.h" +#include "d3d12_test_shaders.h" #include "../shims/d3d12_com.h" #include "../shims/d3d12_xs_device.h" #include "../shims/shims.h" @@ -86,7 +87,7 @@ int gpu_reads_cpu_writes(ID3D12Device* real, ID3D12Resource* buffer, const void* return 0; } -int run(ID3D12Device* real, void* device) { +int run(ID3D12Device* real, void* device, bool eager) { const auto virtual_alloc = reinterpret_cast(rt::shims::find("xmem.dll", "XMemVirtualAlloc")); const auto allocate = reinterpret_cast(rt::shims::find("xmem.dll", "XMemAllocatePhysicalPages")); @@ -103,7 +104,7 @@ int run(ID3D12Device* real, void* device) { std::uint64_t count = kPages; EXPECT(allocate(0x280, &count, pages) == TRUE && count == kPages); EXPECT(map(window, kPages, pages) == window); - EXPECT(state_is(window, MEM_RESERVE)); // mapped, never touched: nothing committed yet + EXPECT(state_is(window, eager ? MEM_COMMIT : MEM_RESERVE)); // verify the selected physical-page mapper D3D12_RESOURCE_DESC desc{}; desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; @@ -118,10 +119,16 @@ int run(ID3D12Device* real, void* device) { { Ref fallback; EXPECT(place(device, window, desc, &fallback.p) == S_OK && fallback.p); - EXPECT(fallback->GetGPUVirtualAddress() != window_va); - EXPECT(state_is(window, MEM_RESERVE)); + if (eager) { + EXPECT(fallback->GetGPUVirtualAddress() == window_va && state_is(window, MEM_COMMIT)); + for (UINT64 i = 0; i < size; ++i) window[i] = static_cast(i * 17u + 29u); + if (gpu_reads_cpu_writes(real, fallback.p, window, size)) return 1; + } else { + EXPECT(fallback->GetGPUVirtualAddress() != window_va); + EXPECT(state_is(window, MEM_RESERVE)); + } } - std::printf("%s: untouched physical pages without the hook: still reserved, fallback buffer\n", who); + std::printf("%s: physical pages without the hook: %s\n", who, eager ? "already committed and GPU-visible" : "still reserved"); // With it the range is committed first and imported. rt::d3d12_xs::set_placed_at_va_pages_hook(&rt::xmem::commit_physical_range); @@ -142,9 +149,96 @@ int run(ID3D12Device* real, void* device) { return 0; } +int linear_texture_mapping(ID3D12Device* dev, ID3D12Device* xbox, bool private_backing) { + const auto reserve = reinterpret_cast(rt::shims::find("xmem.dll","XMemVirtualAlloc")); + const auto alloc = reinterpret_cast(rt::shims::find("xmem.dll","XMemAllocatePhysicalPages")); + const auto map = reinterpret_cast(rt::shims::find("xmem.dll","XMemMapPhysicalPages")); + const auto release = reinterpret_cast(rt::shims::find("xmem.dll","XMemFreePhysicalPages")); + EXPECT(reserve && alloc && map && release); + std::uint64_t count=1,page{}; + void* window = private_backing ? VirtualAlloc(nullptr,kPage64k,MEM_RESERVE|MEM_COMMIT,PAGE_READWRITE) + : reserve(nullptr,kPage64k,MEM_RESERVE|kXmem64kPages,0x23,PAGE_READWRITE); + EXPECT(window); + if (!private_backing) EXPECT(alloc(0x280,&count,&page) && map(window,1,&page)==window); + rt::d3d12::set_device_outer(dev,xbox); + rt::d3d12_xs::set_texture_page_provider(&rt::xmem::pin_mapped_data); + constexpr UINT w=9,h=8; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension=D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width=w;desc.Height=h;desc.MipLevels=desc.DepthOrArraySize=1;desc.SampleDesc.Count=1; + desc.Format=DXGI_FORMAT_R32G32B32A32_FLOAT;desc.Flags=D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + desc.Layout=static_cast(0x100); + Ref tex,rb; + EXPECT(place(xbox,window,desc,&tex.p)==S_OK && tex->GetGPUVirtualAddress()==reinterpret_cast(window)); + constexpr UINT pitch=256; + D3D12_RANGE empty{0,0};void* cpu=nullptr; + EXPECT(tex->Map(0,&empty,&cpu)==S_OK && cpu && ((cpu!=window)==private_backing)); + std::array pixel{}; + for(UINT y=0;y(cpu)+y*pitch+x*16,pixel.data(),16); + } + D3D12_HEAP_PROPERTIES read_heap{D3D12_HEAP_TYPE_READBACK}; + const auto buf=d3d12test::buffer_desc(h*pitch); + EXPECT(SUCCEEDED(dev->CreateCommittedResource(&read_heap,D3D12_HEAP_FLAG_NONE,&buf,D3D12_RESOURCE_STATE_COPY_DEST,nullptr,IID_PPV_ARGS(&rb.p)))); + D3D12_COMMAND_QUEUE_DESC q{}; + Ref queue;Ref commands;Ref list;Ref fence; + EXPECT(SUCCEEDED(dev->CreateCommandQueue(&q,IID_PPV_ARGS(&queue.p)))); + EXPECT(SUCCEEDED(dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT,IID_PPV_ARGS(&commands.p)))); + EXPECT(SUCCEEDED(dev->CreateCommandList(0,D3D12_COMMAND_LIST_TYPE_DIRECT,commands.p,nullptr,IID_PPV_ARGS(&list.p)))); + EXPECT(SUCCEEDED(dev->CreateFence(0,D3D12_FENCE_FLAG_NONE,IID_PPV_ARGS(&fence.p)))); + const auto submit=[&](UINT64 value) { + if(FAILED(list->Close())) return false; + ID3D12CommandList* batch[]{list.p};queue->ExecuteCommandLists(1,batch); + if(FAILED(queue->Signal(fence.p,value))) return false; + const auto end=GetTickCount64()+6000; + while(fence->GetCompletedValue()GetCompletedValue()==value; + }; + auto barrier=d3d12test::transition(tex.p,D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1,&barrier); + D3D12_TEXTURE_COPY_LOCATION from{},to{};from.pResource=tex.p;to.pResource=rb.p; + to.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;to.PlacedFootprint={0,{desc.Format,w,h,1,pitch}}; + list->CopyTextureRegion(&to,0,0,0,&from,nullptr); + EXPECT(submit(1)); + void* bytes=nullptr;EXPECT(SUCCEEDED(rb->Map(0,nullptr,&bytes))); + for(UINT y=0;y(bytes)+y*pitch, + static_cast(cpu)+y*pitch,w*16)==0); + rb->Unmap(0,nullptr); + tex->Unmap(0,&empty); + Ref rt; + D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_RTV,1}; + EXPECT(SUCCEEDED(dev->CreateDescriptorHeap(&hd,IID_PPV_ARGS(&rt.p)))); + const auto handle=rt->GetCPUDescriptorHandleForHeapStart(); + dev->CreateRenderTargetView(tex.p,nullptr,handle); + EXPECT(SUCCEEDED(commands->Reset()) && SUCCEEDED(list->Reset(commands.p,nullptr))); + barrier=d3d12test::transition(tex.p,D3D12_RESOURCE_STATE_COPY_SOURCE,D3D12_RESOURCE_STATE_RENDER_TARGET); + list->ResourceBarrier(1,&barrier); + const float rgba[]{.25f,.5f,.75f,1.0f}; + list->ClearRenderTargetView(handle,rgba,0,nullptr); + EXPECT(submit(2)); + D3D12_RANGE read{0,h*pitch};cpu=nullptr; + EXPECT(tex->Map(0,&read,&cpu)==S_OK && cpu && ((cpu!=window)==private_backing)); + for(UINT y=0;y(cpu)+y*pitch+x*16,rgba,16)==0); + tex->Unmap(0,&empty); + if (!private_backing) { + EXPECT(map(window,1,nullptr)==window && release(1,&page)); + cpu=reinterpret_cast(1); + EXPECT(FAILED(tex->Map(0,&empty,&cpu)) && !cpu); + } else { + const auto* original=static_cast(window); + for(UINT i=0;iRelease(); return 1; } - failures += run(real.p, device.p); + if (argc==2 && (std::strcmp(argv[1],"--linear-map")==0 || std::strcmp(argv[1],"--linear-staging")==0)) + failures+=linear_texture_mapping(real.p,device.p,std::strcmp(argv[1],"--linear-staging")==0); + else failures += run(real.p, device.p, eager); } if (vk.validation_errors()) { std::fprintf(stderr, "%u validation errors\n", vk.validation_errors()); diff --git a/runtime/test/device_proxy_test.cpp b/runtime/test/device_proxy_test.cpp index f02d6cd027..08b34d8c9f 100644 --- a/runtime/test/device_proxy_test.cpp +++ b/runtime/test/device_proxy_test.cpp @@ -432,6 +432,22 @@ int main(int argc, char** argv) { check(rt::d3d12_xs::device_slot_hits(76) == 2, "slot 76 hit counter is 2"); check(rt::d3d12_xs::device_slot_first_call_seen(76), "slot 76 first-call flag is set"); + // A backend can run out of memory after allocating the native depth image. Slot 76 must propagate that + // failure without handing a depth-only resource to a caller that requested a working UAV. + { + auto ds_uav = xbox_texture; + ds_uav.Format = DXGI_FORMAT_R32G8X24_TYPELESS; + ds_uav.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + check(rt::d3d12_xs::set_depth_stencil_uav_provider(device.Get(), [](ID3D12Resource*, D3D12_HEAP_FLAGS) -> HRESULT { + return E_OUTOFMEMORY; + }), "install a failing Xbox storage-image provider"); + void* result = reinterpret_cast(1); + hr = create_resource(device.Get(), &heap_properties, D3D12_HEAP_FLAG_NONE, &ds_uav, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, iid_resource, &result); + check(hr == E_OUTOFMEMORY && !result, "slot 76 propagates storage-image allocation failure atomically"); + rt::d3d12_xs::set_depth_stencil_uav_provider(device.Get(), nullptr); + } + // Xbox device slots from the public HLE. On the Vulkan device the PC entries at 78/79 are // CreateReservedResource2/CreateSampler2 and 80 is past the 80-slot table, so success here can only come from // the routes: frame events return S_OK and a fresh token, CreateCommandQueueX returns a queue proxy and diff --git a/runtime/test/file_system_test.cpp b/runtime/test/file_system_test.cpp index 7a5ea6f086..27194f1a4f 100644 --- a/runtime/test/file_system_test.cpp +++ b/runtime/test/file_system_test.cpp @@ -9,6 +9,7 @@ #include #include +#include #include #include #include @@ -183,6 +184,63 @@ bool host_renames_case(const std::filesystem::path& folder) { void run_checks(const std::filesystem::path& root); +// Title memory committed on first touch, as xmem maps physical pages: a view of a reserve-only pagefile section whose +// pages a vectored handler commits when user-mode code faults on them. The kernel's write in ReadFile raises no such +// fault, so the host ReadFile fails with ERROR_NOACCESS; the shim commits the pages and reads again. +char* g_first_touch = nullptr; +SIZE_T g_first_touch_size = 0; + +LONG CALLBACK commit_on_touch(EXCEPTION_POINTERS* info) { + const EXCEPTION_RECORD* r = info->ExceptionRecord; + if (r->ExceptionCode != EXCEPTION_ACCESS_VIOLATION || r->NumberParameters < 2) return EXCEPTION_CONTINUE_SEARCH; + auto* at = reinterpret_cast(r->ExceptionInformation[1]); + if (at < g_first_touch || at >= g_first_touch + g_first_touch_size) return EXCEPTION_CONTINUE_SEARCH; + auto* page = reinterpret_cast(reinterpret_cast(at) & ~uintptr_t{0xfff}); + return VirtualAlloc(page, 0x1000, MEM_COMMIT, PAGE_READWRITE) ? EXCEPTION_CONTINUE_EXECUTION + : EXCEPTION_CONTINUE_SEARCH; +} + +void check_read_file_first_touch(const std::filesystem::path& root) { + using ReadFileFn = BOOL(WINAPI*)(HANDLE, LPVOID, DWORD, LPDWORD, LPOVERLAPPED); + const auto shim_read = reinterpret_cast(rt::shims::find("kernel32.dll", "ReadFile")); + check(shim_read != nullptr, "ReadFile is served by the file shims"); + if (!shim_read) return; + + std::filesystem::create_directories(root); + const std::filesystem::path file = root / "first_touch.bin"; + constexpr DWORD kSize = 3 * 0x10000 + 123; // crosses several pages and ends inside one + std::vector data(kSize); + for (DWORD i = 0; i < kSize; ++i) data[i] = static_cast(i * 7 + 3); + std::ofstream(file, std::ios::binary).write(reinterpret_cast(data.data()), kSize); + + g_first_touch_size = 4 * 0x10000; + HANDLE section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE | SEC_RESERVE, 0, + static_cast(g_first_touch_size), nullptr); + g_first_touch = section ? static_cast(MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 0)) : nullptr; + check(g_first_touch != nullptr, "a reserve-only section view stands in for first-touch title memory"); + if (!g_first_touch) return; + void* const handler = AddVectoredExceptionHandler(1, &commit_on_touch); + + auto read_into_view = [&](ReadFileFn read) { + HANDLE h = CreateFileW(file.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); + DWORD got = 0; + const BOOL ok = read(h, g_first_touch + 0x800, kSize, &got, nullptr); + const DWORD error = ok ? 0 : GetLastError(); + CloseHandle(h); + return std::make_pair(ok ? got : 0, error); + }; + const auto host = read_into_view(&::ReadFile); + check(host.second == ERROR_NOACCESS, "the host ReadFile into uncommitted pages fails with ERROR_NOACCESS"); + const auto shimmed = read_into_view(shim_read); + check(shimmed.second == 0 && shimmed.first == kSize, "the shimmed ReadFile commits the pages and reads it all"); + check(std::memcmp(g_first_touch + 0x800, data.data(), kSize) == 0, "the bytes read are the file's"); + + RemoveVectoredExceptionHandler(handler); + UnmapViewOfFile(g_first_touch); + CloseHandle(section); + g_first_touch = nullptr; +} + } // namespace int main() { @@ -198,6 +256,7 @@ int main() { // An exception from one check (std::filesystem throws on a host error) ends the checks, not the run: it is a // failure, the folder is still removed and the summary is still printed. try { + check_read_file_first_touch(root / "first_touch"); run_checks(root); } catch (const std::exception& e) { check(false, (std::string("the checks run to the end (stopped by: ") + e.what() + ")").c_str()); diff --git a/runtime/test/frame_pacer_test.cpp b/runtime/test/frame_pacer_test.cpp index e86c6f560a..7e7fb49a2f 100644 --- a/runtime/test/frame_pacer_test.cpp +++ b/runtime/test/frame_pacer_test.cpp @@ -155,6 +155,29 @@ int main() { EXPECT(next.get().token == 2); } + // wait_flag_current_token never blocks or times out: a fresh token for the newest passed origin, registered or not. + { + ManualFrameClock clock; + FramePacer pacer(clock); + std::uint64_t token = 0; + EXPECT(pacer.wait_frame_event(frame_event_origin, 0, wait_flag_current_token, &token) == pacer_hr::ok && + token == 1); + EXPECT(setup(pacer, 1)); + clock.advance_us(period * 2 + period / 4); + EXPECT(pacer.wait_frame_event(frame_event_origin, 0, wait_flag_current_token, &token) == pacer_hr::ok && + token == 2); + EXPECT(pacer.wait_frame_event(frame_event_origin, 0, wait_flag_current_token, &token) == pacer_hr::ok && + token == 3); + std::uint32_t count = 1; + FrameStatistic stat; + EXPECT(pacer.get_frame_statistics(3, stat_frame_event, &count, &stat) == pacer_hr::ok); + EXPECT(stat.time_us == period * 2); + auto next = wait_async(pacer, infinite_timeout_ms); + EXPECT(blocked(next)); + clock.advance_us(period * 3 / 4); + EXPECT(next.get().token == 4); + } + // Timeouts: 0 polls, a finite one counts fake time, the token is left alone, and a later wait still works. { ManualFrameClock clock; diff --git a/runtime/test/glsl/cs_depth_stencil_uav.comp b/runtime/test/glsl/cs_depth_stencil_uav.comp new file mode 100644 index 0000000000..277a86df46 --- /dev/null +++ b/runtime/test/glsl/cs_depth_stencil_uav.comp @@ -0,0 +1,55 @@ +#version 460 +#extension GL_EXT_nonuniform_qualifier : require + +// The two T#s are passed as root constants in s4..s19, exactly as written by CreateUnorderedAccessView. +layout(local_size_x = 1) in; +layout(push_constant) uniform UserData { uint s[20]; } pc; +layout(set = 0, binding = 2, std430) readonly buffer DescriptorMap { uint words[]; }; +#if defined(DEPTH16_ARRAY) +layout(set = 0, binding = 12, r16ui) uniform uimage2DArray depths[]; +#elif defined(DEPTH16_2D) +layout(set = 0, binding = 9, r16ui) uniform uimage2D depths[]; +#elif defined(DEPTH_STENCIL_ARRAY) +layout(set = 0, binding = 11, r32f) uniform image2DArray depths[]; +layout(set = 0, binding = 12, r8ui) uniform uimage2DArray stencils[]; +#else +layout(set = 0, binding = 8, r32f) uniform image2D depths[]; +layout(set = 0, binding = 9, r8ui) uniform uimage2D stencils[]; +#endif + +uint lookup(uint first) { + uint hash = 2166136261u; + for (uint i = 0; i < 8; ++i) hash = (hash ^ pc.s[first + i]) * 16777619u; + for (uint probe = 0; probe < 8; ++probe) { + uint slot = 1 + ((hash + probe) & words[0]) * 10; + bool equal = true; + for (uint i = 0; i < 8; ++i) equal = equal && words[slot + i] == pc.s[first + i]; + if (equal) return words[slot + 8]; + } + return 0; +} + +void main() { + // Read before writing. A stale copy (or writing back the wrong plane) changes the expected bytes. + uint depth = lookup(4); +#if defined(DEPTH16_2D) || defined(DEPTH16_ARRAY) +#if defined(DEPTH16_2D) + ivec2 pixel = ivec2(2, 1); +#else + ivec3 pixel = ivec3(2, 1, 1); +#endif + uint before = imageLoad(depths[depth], pixel).r; + imageStore(depths[depth], pixel, uvec4(before ^ 0x1357u)); +#else + uint stencil = lookup(12); +#if defined(DEPTH_STENCIL_ARRAY) + ivec3 depth_pixel = ivec3(2, 1, 0), stencil_pixel = ivec3(5, 3, 1); +#else + ivec2 depth_pixel = ivec2(2, 1), stencil_pixel = ivec2(5, 3); +#endif + float before = imageLoad(depths[depth], depth_pixel).r; + uint mask = imageLoad(stencils[stencil], stencil_pixel).r; + imageStore(depths[depth], depth_pixel, vec4(before * 0.25)); + imageStore(stencils[stencil], stencil_pixel, uvec4(mask ^ 0xffu)); +#endif +} diff --git a/runtime/test/glsl/cs_r9g9b9e5_uav.comp b/runtime/test/glsl/cs_r9g9b9e5_uav.comp index c9879064ac..41c986a412 100644 --- a/runtime/test/glsl/cs_r9g9b9e5_uav.comp +++ b/runtime/test/glsl/cs_r9g9b9e5_uav.comp @@ -10,10 +10,10 @@ layout(local_size_x = 16) in; layout(push_constant) uniform Params { uint tsharp[8]; uint ssharp[4]; - uint mode; // 0: write via binding 9 (first half) + binding 4 (second half); 1: sample via binding 0 + uint mode; // 0/1: 2D store/sample; 2/3: 3D store/sample uint width; uint height; - uint pad; + uint slice; // sample's absolute Z, or whether to probe relative Z=1 past a one-slice UAV } pc; layout(set = 0, binding = 0) uniform texture2D sampled_images[]; @@ -23,6 +23,9 @@ layout(set = 0, binding = 2, std430) readonly buffer DescriptorMap { }; layout(set = 0, binding = 4, r32ui) uniform writeonly uimage2D storage_r32ui_images[]; layout(set = 0, binding = 9, r32ui) uniform writeonly uimage2D storage_uint_images[]; +layout(set = 0, binding = 6) uniform texture3D sampled_volumes[]; +layout(set = 0, binding = 7, r32ui) uniform writeonly uimage3D storage_r32ui_volumes[]; +layout(set = 0, binding = 15, r32ui) uniform writeonly uimage3D storage_uint_volumes[]; layout(set = 1, binding = 0, std430) readonly buffer InputWords { uint packed_words[]; @@ -59,11 +62,23 @@ void main() { } else { imageStore(storage_r32ui_images[image], xy, uvec4(packed_words[i], 0u, 0u, 0u)); } + } else if (pc.mode == 2u) { + const uvec4 word = uvec4(packed_words[i], 0u, 0u, 0u); + if (i < total / 2u) { + imageStore(storage_uint_volumes[image], ivec3(xy, 0), word); + if (pc.slice != 0u) imageStore(storage_uint_volumes[image], ivec3(xy, 1), word); + } else { + imageStore(storage_r32ui_volumes[image], ivec3(xy, 0), word); + if (pc.slice != 0u) imageStore(storage_r32ui_volumes[image], ivec3(xy, 1), word); + } } else { uint sampler_key[8]; for (int k = 0; k < 8; ++k) sampler_key[k] = k < 4 ? pc.ssharp[k] : 0xffffffffu; const uint smp = lookup(sampler_key); const vec2 uv = (vec2(xy) + 0.5) / vec2(float(pc.width), float(pc.height)); - out_values[i] = textureLod(sampler2D(sampled_images[image], samplers[smp]), uv, 0.0); + if (pc.mode == 1u) + out_values[i] = textureLod(sampler2D(sampled_images[image], samplers[smp]), uv, 0.0); + else + out_values[i] = texelFetch(sampler3D(sampled_volumes[image], samplers[smp]), ivec3(xy, int(pc.slice)), 0); } } diff --git a/runtime/test/glsl/cs_user_data.comp b/runtime/test/glsl/cs_user_data.comp index 07b4b7e4d4..3c08a9597a 100644 --- a/runtime/test/glsl/cs_user_data.comp +++ b/runtime/test/glsl/cs_user_data.comp @@ -52,12 +52,18 @@ void main() { target.w[i] = result.w[64u + i] + pc.s[4]; return; } - if (pc.s[5] == 0u) { - // CBV V# mode: table holds a 16-byte GFX10 raw buffer descriptor written by CreateConstantBufferView. - const uint num_records = table.w[2]; - const uint byte_off = pc.s[4] + i * 4u; - if (byte_off + 4u <= num_records) { - Words cbv = at(uvec2(table.w[0], table.w[1] & 0xFFFFu)); + if (pc.s[5] == 0u || pc.s[5] == 0xFFFFFFFCu) { + // CBV V# mode: accept byte-address views and Xbox views counted in 16-byte constant rows. + // The rebound-table test indexes 32-byte CBV slots with s4. + const bool indexed = pc.s[5] == 0xFFFFFFFCu; + const uint word = indexed ? pc.s[4] * 8u : 0u; + const uint num_records = table.w[word + 2u]; + const uint stride = (table.w[word + 1u] >> 16u) & 0x3fffu; + const uint mode = (table.w[word + 3u] >> 28u) & 3u; + const uint bytes_per_record = mode < 2u ? max(stride, 1u) : 1u; + const uint byte_off = (indexed ? 0u : pc.s[4]) + i * 4u; + if (byte_off <= 0xfffffffcu && (byte_off + 3u) / bytes_per_record < num_records) { + Words cbv = at(uvec2(table.w[word], table.w[word + 1u] & 0xFFFFu)); result.w[i] = cbv.w[byte_off >> 2u]; } else { result.w[i] = 0u; diff --git a/runtime/test/pso_stream_test.cpp b/runtime/test/pso_stream_test.cpp new file mode 100644 index 0000000000..07ac13a326 --- /dev/null +++ b/runtime/test/pso_stream_test.cpp @@ -0,0 +1,268 @@ +// Pipeline state stream copies and the derived-state patch (device slot 55) with synthetic streams only: no D3D12 +// device, no game data. The layout rule is the one measured on the console's slot 86 stream (see the offsets check). +#include + +#include +#include +#include + +#include "d3d12_xs_pso_stream.h" + +namespace { + +int g_failures = 0; + +void check(bool ok, const char* what) { + std::printf("%s %s\n", ok ? "PASS" : "FAIL", what); + if (!ok) ++g_failures; +} + +std::size_t align_up(std::size_t v, std::size_t a) { return (v + a - 1) / a * a; } + +// Builds a stream the way the console lays it out: u32 type, payload at its natural alignment, next entry 8-aligned. +struct StreamBuilder { + std::vector bytes; + void entry(unsigned type, const void* payload, std::size_t size, std::size_t payload_align) { + const std::size_t at = bytes.size(); + bytes.resize(at + 4); + std::memcpy(bytes.data() + at, &type, 4); + const std::size_t pay = align_up(at + 4, payload_align); + bytes.resize(pay, 0); + const auto* p = static_cast(payload); + bytes.insert(bytes.end(), p, p + size); + bytes.resize(align_up(bytes.size(), 8), 0); + } +}; + +// The test's own copy of the layout rule: payload offset of the first subobject of `wanted`, or npos. +std::size_t payload_of_type(const std::vector& s, unsigned wanted) { + std::size_t off = 0; + while (off + 4 <= s.size()) { + unsigned type; + std::memcpy(&type, s.data() + off, 4); + std::size_t size = sizeof(D3D12_SHADER_BYTECODE), align = 8; + if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND) { size = sizeof(D3D12_BLEND_DESC); align = 4; } + else if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK) { size = 4; align = 4; } + else if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER) { size = sizeof(D3D12_RASTERIZER_DESC); align = 4; } + else if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1) { size = sizeof(D3D12_DEPTH_STENCIL_DESC1); align = 4; } + else if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE) { size = 8; align = 8; } + else if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT) { size = sizeof(D3D12_INPUT_LAYOUT_DESC); align = 8; } + const std::size_t pay = align_up(off + 4, align); + if (type == wanted) return pay; + off = align_up(pay + size, 8); + } + return static_cast(-1); +} + +const unsigned char kVsCode[32] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, + 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32}; +const char kSemantic[] = "POSITION"; + +D3D12_INPUT_ELEMENT_DESC make_element(const char* name) { + D3D12_INPUT_ELEMENT_DESC e{}; + e.SemanticName = name; + e.Format = DXGI_FORMAT_R32G32B32_FLOAT; + return e; +} + +// Root signature (null), VS, BLEND, SAMPLE_MASK, RASTERIZER, DEPTH_STENCIL1, INPUT_LAYOUT. +std::vector base_stream(const D3D12_INPUT_ELEMENT_DESC* elements, unsigned element_count) { + StreamBuilder s; + ID3D12RootSignature* root = nullptr; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, &root, 8, 8); + D3D12_SHADER_BYTECODE vs{kVsCode, sizeof(kVsCode)}; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, &vs, sizeof(vs), 8); + D3D12_BLEND_DESC blend{}; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, &blend, sizeof(blend), 4); + UINT mask = 0xffffffffu; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, &mask, 4, 4); + D3D12_RASTERIZER_DESC raster{}; + raster.FillMode = D3D12_FILL_MODE_SOLID; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, &raster, sizeof(raster), 4); + D3D12_DEPTH_STENCIL_DESC1 ds1{}; + ds1.DepthEnable = TRUE; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, &ds1, sizeof(ds1), 4); + D3D12_INPUT_LAYOUT_DESC layout{elements, element_count}; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, &layout, sizeof(layout), 8); + return s.bytes; +} + +// One derived record: tag at +0, payload at +4. +std::vector record(unsigned tag, const void* payload, std::size_t size) { + std::vector r(rt::d3d12_xs::kDerivedRecordSize, 0); + std::memcpy(r.data(), &tag, 4); + if (size) std::memcpy(r.data() + 4, payload, size); + return r; +} + +void test_layout_matches_console_offsets() { + // Console slot 86 stream: types 0..5 then BLEND at +0x88 (payload +0x8c), SAMPLE_MASK at +0x1d8, RASTERIZER at + // +0x1e0, DEPTH_STENCIL1 at +0x210 (measured in the notes, mesure sur l'exe). + StreamBuilder s; + ID3D12RootSignature* root = nullptr; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, &root, 8, 8); + D3D12_SHADER_BYTECODE sb{}; + for (unsigned i = 0; i < 5; ++i) s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS + i, &sb, sizeof(sb), 8); + check(s.bytes.size() == 0x88, "six entries (types 0..5) end at +0x88"); + D3D12_BLEND_DESC blend{}; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, &blend, sizeof(blend), 4); + check(payload_of_type(s.bytes, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND) == 0x8c, + "BLEND payload at +0x8c"); + check(s.bytes.size() == 0x1d8, "BLEND entry ends at +0x1d8"); + UINT mask = 1; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, &mask, 4, 4); + check(s.bytes.size() == 0x1e0, "SAMPLE_MASK entry is 8 bytes, next entry at +0x1e0"); +} + +void test_capture_and_deep_copy() { + D3D12_INPUT_ELEMENT_DESC elements[1] = {make_element(kSemantic)}; + std::vector base = base_stream(elements, 1); + D3D12_PIPELINE_STATE_STREAM_DESC desc{base.size(), base.data()}; + auto rec = rt::d3d12_xs::PsoStreamRecord::capture(desc); + check(rec != nullptr, "a synthetic base stream is captured"); + if (!rec) return; + check(rec->bytes().size() == base.size(), "the copy has the stream's size"); + + // Scribble over the source and its pointed-to data: the copy must still hold the original content. + std::memset(base.data(), 0xee, base.size()); + elements[0].SemanticName = "XXXXXXXX"; + D3D12_SHADER_BYTECODE vs_copy{}; + std::memcpy(&vs_copy, rec->bytes().data() + payload_of_type(rec->bytes(), D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS), + sizeof(vs_copy)); + check(vs_copy.pShaderBytecode != kVsCode && vs_copy.BytecodeLength == sizeof(kVsCode) && + std::memcmp(vs_copy.pShaderBytecode, kVsCode, sizeof(kVsCode)) == 0, + "shader bytecode is copied, not referenced"); + D3D12_INPUT_LAYOUT_DESC il{}; + std::memcpy(&il, rec->bytes().data() + payload_of_type(rec->bytes(), D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT), + sizeof(il)); + check(il.NumElements == 1 && std::strcmp(il.pInputElementDescs[0].SemanticName, kSemantic) == 0, + "input layout semantic names are copied"); +} + +void test_derive_single_and_all_tags() { + D3D12_INPUT_ELEMENT_DESC elements[1] = {make_element(kSemantic)}; + std::vector base = base_stream(elements, 1); + auto rec = rt::d3d12_xs::PsoStreamRecord::capture({base.size(), base.data()}); + if (!rec) { check(false, "base captured for derive tests"); return; } + + D3D12_BLEND_DESC blend{}; + blend.RenderTarget[0].RenderTargetWriteMask = 0x5; + auto r2 = record(2, &blend, sizeof(blend)); + std::vector out; + check(rt::d3d12_xs::derive_stream(*rec, r2.data(), 1, out) == rt::d3d12_xs::DeriveStatus::ok, + "tag 2 (blend) derives"); + const std::size_t bp = payload_of_type(out, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND); + check(std::memcmp(out.data() + bp, &blend, sizeof(blend)) == 0, "tag 2 payload lands in the BLEND subobject"); + check(out.size() == rec->bytes().size(), "derived stream keeps the base size"); + + D3D12_RASTERIZER_DESC raster{}; + raster.FillMode = D3D12_FILL_MODE_WIREFRAME; + D3D12_DEPTH_STENCIL_DESC ds{}; + ds.DepthEnable = FALSE; + UINT mask = 0x3; + std::vector three; + auto r0 = record(0, &ds, sizeof(ds)); + auto r1 = record(1, &raster, sizeof(raster)); + auto r3 = record(3, &mask, 4); + three.insert(three.end(), r0.begin(), r0.end()); + three.insert(three.end(), r1.begin(), r1.end()); + three.insert(three.end(), r3.begin(), r3.end()); + check(rt::d3d12_xs::derive_stream(*rec, three.data(), 3, out) == rt::d3d12_xs::DeriveStatus::ok, + "three records (tags 0, 1, 3) derive"); + const std::size_t rp = payload_of_type(out, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER); + const std::size_t mp = payload_of_type(out, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK); + const std::size_t dp = payload_of_type(out, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1); + check(std::memcmp(out.data() + rp, &raster, sizeof(raster)) == 0, "tag 1 payload lands in RASTERIZER"); + check(std::memcmp(out.data() + mp, &mask, 4) == 0, "tag 3 payload lands in SAMPLE_MASK"); + check(std::memcmp(out.data() + dp, &ds, sizeof(ds)) == 0, "tag 0 patches the DS1 prefix"); + const std::size_t tail = dp + sizeof(ds); + check(out[tail] == 0 && out[tail + 1] == 0 && out[tail + 2] == 0 && out[tail + 3] == 0, + "tag 0 keeps the DS1 depth-bounds field of the base"); +} + +void test_stencil_mask_record() { + // Tag 5 carries the two stencil mask bytes at the DEPTH_STENCIL offsets 0x10/0x11 and zeros elsewhere (read from the + // title's writes). It overlays only those two bytes of the base's DEPTH_STENCIL (or DEPTH_STENCIL1) payload. + D3D12_INPUT_ELEMENT_DESC elements[1] = {make_element(kSemantic)}; + std::vector base = base_stream(elements, 1); + auto rec = rt::d3d12_xs::PsoStreamRecord::capture({base.size(), base.data()}); + if (!rec) { check(false, "base captured for the tag 5 tests"); return; } + const std::size_t dp = payload_of_type(rec->bytes(), D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1); + + unsigned char mask_payload[0x16] = {}; + mask_payload[0x10] = 0x0f; // read mask + mask_payload[0x11] = 0x3c; // write mask + auto r5 = record(5, mask_payload, sizeof(mask_payload)); + std::vector out; + check(rt::d3d12_xs::derive_stream(*rec, r5.data(), 1, out) == rt::d3d12_xs::DeriveStatus::ok, + "tag 5 alone derives on a base with DEPTH_STENCIL1"); + check(out[dp + 0x10] == 0x0f && out[dp + 0x11] == 0x3c, "tag 5 overlays the two stencil mask bytes"); + bool rest_same = true; + for (std::size_t i = 0; i < 0x38; ++i) + if (i != 0x10 && i != 0x11 && out[dp + i] != rec->bytes()[dp + i]) rest_same = false; + check(rest_same, "tag 5 leaves the other DEPTH_STENCIL1 bytes unchanged"); + + // Order: records apply in the order they are given. Tag 0 writes its own masks, tag 5 overrides them. + D3D12_DEPTH_STENCIL_DESC ds{}; + ds.StencilReadMask = 0x01; + ds.StencilWriteMask = 0x02; + auto r0 = record(0, &ds, sizeof(ds)); + std::vector seq; + seq.insert(seq.end(), r0.begin(), r0.end()); + seq.insert(seq.end(), r5.begin(), r5.end()); + check(rt::d3d12_xs::derive_stream(*rec, seq.data(), 2, out) == rt::d3d12_xs::DeriveStatus::ok, + "tag 0 then tag 5 derive together"); + check(out[dp + 0x10] == 0x0f && out[dp + 0x11] == 0x3c, "tag 5 after tag 0 wins (record order)"); + + seq.clear(); + seq.insert(seq.end(), r5.begin(), r5.end()); + seq.insert(seq.end(), r0.begin(), r0.end()); + check(rt::d3d12_xs::derive_stream(*rec, seq.data(), 2, out) == rt::d3d12_xs::DeriveStatus::ok, + "tag 5 then tag 0 derive together"); + check(out[dp + 0x10] == 0x01 && out[dp + 0x11] == 0x02, "tag 0 after tag 5 wins (record order)"); +} + +void test_refusals() { + D3D12_INPUT_ELEMENT_DESC elements[1] = {make_element(kSemantic)}; + std::vector base = base_stream(elements, 1); + auto rec = rt::d3d12_xs::PsoStreamRecord::capture({base.size(), base.data()}); + if (!rec) { check(false, "base captured for refusal tests"); return; } + std::vector out; + + auto r6 = record(6, nullptr, 0); + check(rt::d3d12_xs::derive_stream(*rec, r6.data(), 1, out) == rt::d3d12_xs::DeriveStatus::unknown_tag, + "tag 6 is refused (meaning not known)"); + + // A base without a rasterizer subobject cannot take a tag-1 record. + StreamBuilder s; + ID3D12RootSignature* root = nullptr; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, &root, 8, 8); + D3D12_BLEND_DESC blend{}; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, &blend, sizeof(blend), 4); + auto norast = rt::d3d12_xs::PsoStreamRecord::capture({s.bytes.size(), s.bytes.data()}); + if (!norast) { check(false, "stream without rasterizer captured"); return; } + D3D12_RASTERIZER_DESC raster{}; + auto r1 = record(1, &raster, sizeof(raster)); + check(rt::d3d12_xs::derive_stream(*norast, r1.data(), 1, out) == rt::d3d12_xs::DeriveStatus::missing_state, + "tag 1 on a base without RASTERIZER is refused"); + + // A subobject type this module does not walk: VIEW_INSTANCING (payload with a pointer, not modelled). + StreamBuilder v; + unsigned char junk[32] = {}; + v.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VIEW_INSTANCING, junk, sizeof(junk), 8); + check(rt::d3d12_xs::PsoStreamRecord::capture({v.bytes.size(), v.bytes.data()}) == nullptr, + "a stream with an unmodelled subobject type is not captured"); +} + +} // namespace + +int main() { + std::printf("pso_stream_test: derived pipeline state streams\n"); + test_layout_matches_console_offsets(); + test_capture_and_deep_copy(); + test_derive_single_and_all_tags(); + test_stencil_mask_record(); + test_refusals(); + std::printf("%s: %d failure(s)\n", g_failures ? "FAILED" : "OK", g_failures); + return g_failures ? 1 : 0; +} diff --git a/runtime/test/replay_texture_barrier_test.cpp b/runtime/test/replay_texture_barrier_test.cpp index 66c594779e..527c8adec1 100644 --- a/runtime/test/replay_texture_barrier_test.cpp +++ b/runtime/test/replay_texture_barrier_test.cpp @@ -61,9 +61,11 @@ using namespace leonida; // measured emit, so that the record itself does not allocate there. std::vector g_barriers; std::uint32_t g_calls = 0; +std::uint32_t g_memory = 0; void VKAPI_CALL record_barrier2(VkCommandBuffer, const VkDependencyInfo* info) { ++g_calls; + g_memory += info->memoryBarrierCount; for (std::uint32_t i = 0; i < info->imageMemoryBarrierCount; ++i) g_barriers.push_back(info->pImageMemoryBarriers[i]); } @@ -76,6 +78,178 @@ void expect(bool ok, const char* what) { } } +// Run a stencil-only round trip with coupled depth/stencil layouts. Vulkan transitions both aspects +// together on this device, but the data transfer must never read or write the sibling depth plane. +void depth_uav_barriers(VkCommandBuffer cb) { + namespace y = d3d12_sync; + namespace a = d3d12_access; + namespace l = d3d12_layout; + std::array resources{}; + auto& parent = resources[1]; + parent.aspects = depth_stencil_aspects; + parent.format = VK_FORMAT_D32_SFLOAT_S8_UINT; + parent.depth_uav = 2; + parent.stencil_uav = 3; + resources[2].format = VK_FORMAT_R32_SFLOAT; + resources[3].format = VK_FORMAT_R8_UINT; + LayoutTracker tracker; + for (ResourceId i = 1; i <= 3; ++i) { + auto& r = resources[i]; + r.image = reinterpret_cast(std::uintptr_t(i)); + r.width = 5; + r.height = 7; + tracker.track(i, r, VK_IMAGE_LAYOUT_GENERAL); + } + const auto resolve = [&](ResourceId id) -> const ResourceBinding* { + return id && id < resources.size() ? &resources[id] : nullptr; + }; + struct Access { VkImage image; VkImageAspectFlags aspect; bool read; std::uint32_t layer, layers; }; + static std::vector accesses; + accesses.clear(); + ReplayFunctions vk{}; + vk.pipeline_barrier2 = record_barrier2; + vk.pipeline_barrier = [](VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags, VkDependencyFlags, + std::uint32_t, const VkMemoryBarrier*, std::uint32_t, const VkBufferMemoryBarrier*, + std::uint32_t, const VkImageMemoryBarrier*) {}; + vk.copy_image_to_buffer = [](VkCommandBuffer, VkImage image, VkImageLayout, VkBuffer, std::uint32_t, + const VkBufferImageCopy* region) { + const auto& sub = region->imageSubresource; + accesses.push_back({image, sub.aspectMask, true, sub.baseArrayLayer, sub.layerCount}); + }; + vk.copy_buffer_to_image = [](VkCommandBuffer, VkBuffer, VkImage image, VkImageLayout, std::uint32_t, + const VkBufferImageCopy* region) { + const auto& sub = region->imageSubresource; + accesses.push_back({image, sub.aspectMask, false, sub.baseArrayLayer, sub.layerCount}); + }; + const BarrierSubresourceRange stencil{1, 0, 0, 0, 0, 0}; + const BarrierSubresourceRange all_planes{all_subresources, 0, 0, 0, 0, 0}; + g_barriers.clear(); + g_memory = 0; + CommandList list; + expect(list.barrier(TextureBarrier{y::depth_stencil, y::all, a::depth_stencil_write, a::common, + l::undefined, l::undefined, 1, all_planes, 0}) && + list.barrier(TextureBarrier{y::depth_stencil, y::compute_shading, a::depth_stencil_write, a::unordered_access, + l::depth_stencil_write, l::unordered_access, 1, stencil, 0}) && + list.barrier(TextureBarrier{y::compute_shading, y::all, a::unordered_access, a::shader_resource, + l::unordered_access, l::generic_read, 1, stencil, 0}) && + list.barrier(TextureBarrier{y::all, y::copy, a::shader_resource, a::copy_source, + l::generic_read, l::common, 1, stencil, 0}) && list.close(), + "record DSV to stencil UAV then copy source"); + std::uint32_t allocations = 0; + vk.copy_scratch = [&](VkDeviceSize size, VkBuffer& out, VkDeviceSize& offset) { + expect(size == parent.width * parent.height, "stencil scratch holds one byte per texel"); + ++allocations; + out = reinterpret_cast(std::uintptr_t(0x10)); + offset = 0; + return true; + }; + PreparedList prepared; + vk.graphics_family = false; + expect(prepare(list, resolve, vk, prepared) == ReplayResult::unsupported && !allocations, + "reject depth/stencil transfers on a non-graphics family before scratch allocation"); + vk.graphics_family = true; + // A global memory barrier in a queue-specific COMMON layout can switch accesses from a shader write + // on the child to a copy or sample on the parent without a texture layout transition. + for (const auto layout : {l::direct_queue_common, l::compute_queue_common}) { + CommandList implicit; + expect(implicit.barrier(TextureBarrier{y::copy, y::compute_shading, a::copy_dest, a::unordered_access, + l::copy_dest, layout, 1, all_planes, 0}) && + implicit.barrier(GlobalBarrier{y::compute_shading, y::copy, a::unordered_access, a::copy_source}) && + implicit.close(), "record queue-specific COMMON and a global dependency"); + expect(prepare(implicit, resolve, vk, prepared) == ReplayResult::unsupported && !allocations, + "reject ambiguous queue-specific COMMON at prepare"); + } + for (bool before : {false, true}) { + CommandList invalid; + expect(invalid.barrier(TextureBarrier{y::all, y::all, + before ? a::unordered_access : a::copy_source, before ? a::copy_source : a::unordered_access, + before ? l::common : l::copy_source, before ? l::copy_source : l::common, + 1, all_planes, 0}) && invalid.close(), "record explicit UAV access in generic COMMON"); + expect(prepare(invalid, resolve, vk, prepared) == ReplayResult::unsupported && !allocations, + "generic COMMON disallows explicit UAV access on either side of a barrier"); + } + if (prepare(list, resolve, vk, prepared) != ReplayResult::success) { + expect(false, "prepare stencil transfers"); + return; + } + emit(prepared, cb, vk, &tracker); + expect(g_memory == 1 && !g_barriers.empty() && g_barriers.front().oldLayout == VK_IMAGE_LAYOUT_GENERAL && + std::none_of(g_barriers.begin(), g_barriers.end(), [](const auto& b) { return b.newLayout == VK_IMAGE_LAYOUT_UNDEFINED; }), + "UNDEFINED to UNDEFINED only orders memory and preserves both data and tracked layouts"); + expect(allocations == 1 && accesses.size() == 4, "reuse one staging range across both stencil transitions"); + if (accesses.size() == 4) { + expect(accesses[0].read && accesses[0].image == parent.image && accesses[0].aspect == VK_IMAGE_ASPECT_STENCIL_BIT && + !accesses[1].read && accesses[1].image == resources[3].image && accesses[1].aspect == VK_IMAGE_ASPECT_COLOR_BIT && + accesses[2].read && accesses[2].image == resources[3].image && accesses[2].aspect == VK_IMAGE_ASPECT_COLOR_BIT && + !accesses[3].read && accesses[3].image == parent.image && accesses[3].aspect == VK_IMAGE_ASPECT_STENCIL_BIT, + "stencil only moves through the R8 storage image in both directions"); + } + expect(tracker.layout(1, 0) == VK_IMAGE_LAYOUT_GENERAL && + tracker.layout(1, 1) == VK_IMAGE_LAYOUT_GENERAL && + tracker.layout(3, 0) == VK_IMAGE_LAYOUT_GENERAL, "coupled parent and independently tracked storage layouts"); + vk.copy_scratch = [](VkDeviceSize, VkBuffer&, VkDeviceSize&) { return false; }; + expect(prepare(list, resolve, vk, prepared) == ReplayResult::unsupported, "scratch failure refuses the list"); + + // Select layers 1 and 2 (out of 4). The depth-only array has no stencil child. Check the staging size, + // image copy ranges, and the independent initial layouts of the two selected storage layers. + parent.aspects = VK_IMAGE_ASPECT_DEPTH_BIT; + parent.format = VK_FORMAT_D16_UNORM; + parent.stencil_uav = 0; + resources[2].format = VK_FORMAT_R16_UINT; + LayoutTracker arrays; + for (ResourceId id : {1u, 2u}) { + resources[id].array_layers = 4; + arrays.track(id, resources[id], VK_IMAGE_LAYOUT_GENERAL); + } + arrays.set(2, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); + arrays.set(2, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 2, 1}, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); + const BarrierSubresourceRange two_layers{0, 1, 1, 2, 0, 1}; + CommandList compute; + expect(compute.barrier(TextureBarrier{y::all, y::compute_shading, a::common, a::unordered_access, + l::common, l::unordered_access, 1, two_layers, 0}) && + compute.barrier(TextureBarrier{y::compute_shading, y::all, a::unordered_access, a::common, + l::unordered_access, l::common, 1, two_layers, 0}) && compute.close(), + "record D16 array compute handoff"); + vk.graphics_family = false; + vk.queue_stages = detail::queue_stages_compute; + vk.copy_scratch = [&](VkDeviceSize size, VkBuffer& buffer, VkDeviceSize& offset) { + expect(size == 2 * 2 * parent.width * parent.height, "D16 scratch holds two bytes per texel and two layers"); + buffer = reinterpret_cast(std::uintptr_t(0x10)); + offset = 0; + return true; + }; + vk.compute_copy_aspects = [](VkFormat) -> VkImageAspectFlags { return VK_IMAGE_ASPECT_STENCIL_BIT; }; + expect(prepare(compute, resolve, vk, prepared) == ReplayResult::unsupported, + "stencil-only compute copy capability does not authorize a depth transfer"); + vk.compute_copy_aspects = [](VkFormat fmt) -> VkImageAspectFlags { + return fmt == VK_FORMAT_D16_UNORM ? VK_IMAGE_ASPECT_DEPTH_BIT : 0; + }; + if (prepare(compute, resolve, vk, prepared) != ReplayResult::success) { + expect(false, "prepare supported D16 compute transfers"); + return; + } + accesses.clear(); + emit(prepared, cb, vk, &arrays); + expect(accesses.size() == 4 && std::all_of(accesses.begin(), accesses.end(), [](const Access& access) { + return access.layer == 1 && access.layers == 2; + }), "both images are read and written only at the requested layers"); + expect(arrays.layout(2, 0) == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && + arrays.layout(2, 1) == VK_IMAGE_LAYOUT_GENERAL && arrays.layout(2, 2) == VK_IMAGE_LAYOUT_GENERAL, + "selected storage layers end in their descriptor layout and the untouched layer keeps its layout"); + // vkCmdClearDepthStencilImage requires graphics even with maintenance10. A committed depth array first + // seen on compute is initialized from the zero page through a buffer-to-image transfer. + vk.zero_buffer = reinterpret_cast(std::uintptr_t(0x11)); + vk.zero_size = 1024; + const VkImageSubresourceRange fresh{VK_IMAGE_ASPECT_DEPTH_BIT, 0, 1, 1, 2}; + arrays.set(1, fresh, VK_IMAGE_LAYOUT_UNDEFINED); + auto pieces = detail::current(&arrays, 1, fresh, VK_IMAGE_LAYOUT_GENERAL); + accesses.clear(); + detail::initialize(vk, cb, parent, 1, pieces, VK_IMAGE_LAYOUT_GENERAL, &arrays); + expect(accesses.size() == 1 && !accesses[0].read && accesses[0].image == parent.image && + accesses[0].aspect == VK_IMAGE_ASPECT_DEPTH_BIT && accesses[0].layer == 1 && accesses[0].layers == 2, + "first use on compute copies zeros into the selected native depth layers"); +} + } // namespace int main() { @@ -170,6 +344,7 @@ int main() { } } + depth_uav_barriers(cb); if (failures) return 1; std::printf("replay_texture_barrier_test: OK\n"); return 0; diff --git a/runtime/test/replay_uav_clear_offset_test.cpp b/runtime/test/replay_uav_clear_offset_test.cpp index 35818fe8e1..4f70fc6714 100644 --- a/runtime/test/replay_uav_clear_offset_test.cpp +++ b/runtime/test/replay_uav_clear_offset_test.cpp @@ -210,6 +210,44 @@ int main() { tex.array_layers = 4; tex.color_attachment = true; + // A dedicated compute family has no rendering commands. A rectangular clear fills transfer scratch and + // copies the clipped rectangle to the requested array slices without disturbing adjacent pixels. + { + auto image = tex; + image.format = VK_FORMAT_R8_UINT; + auto compute = tex_vk; + compute.graphics_family = false; + compute.queue_stages = detail::queue_stages_compute; + compute.begin_rendering = nullptr; + compute.image_view = {}; + VkDeviceSize requested_bytes = 0; + compute.copy_scratch = [&](VkDeviceSize size, VkBuffer& buffer, VkDeviceSize& offset) { + requested_bytes = size; + buffer = scratch; + offset = 256; + return true; + }; + static std::vector copies; + compute.copy_buffer_to_image = [](VkCommandBuffer, VkBuffer, VkImage, VkImageLayout layout, + std::uint32_t count, const VkBufferImageCopy* regions) { + expect(layout == VK_IMAGE_LAYOUT_GENERAL && count == 1, "one compute clear transfer in UAV layout"); + copies.push_back(regions[0]); + }; + const std::array rects{{{-1, 2, 3, 4}, {1, 3, 2, 4}}}; + writes.clear(); + expect(run_tex(image, {2, false, VK_FORMAT_R8_UINT, 0, 0, 0, 0, 1, 2}, false, {0x39,0,0,0}, + rects, &compute) == ReplayResult::success, "rectangle UAV clear on compute-only family"); + expect(requested_bytes == 12 && writes.size() == 1 && writes[0].kind == 'f' && writes[0].offset == 256 && + writes[0].size == 12 && copies.size() == 2 && attachment_clears == 0, "one fill and two rectangle copies"); + if (copies.size() == 2) { + const auto& r = copies[0]; + expect(r.bufferOffset == 256 && r.imageOffset.x == 0 && r.imageOffset.y == 2 && + r.imageExtent.width == 3 && r.imageExtent.height == 2 && + r.imageSubresource.baseArrayLayer == 1 && r.imageSubresource.layerCount == 2 && + copies[1].imageOffset.x == 1 && copies[1].imageOffset.y == 3, "clipped pixels and exactly two layers"); + } + } + const auto fbits = [](float f) { return std::bit_cast(f); }; // R16G16_TYPELESS (SFLOAT) cleared as R16G16_UNORM Float(1.0, 1.0): uses R16G16_UNORM view and float32 {1, 1}. expect(run_tex(tex, {2, false, VK_FORMAT_R16G16_UNORM, 0, 0, 0, 0, 1, 2}, true, {fbits(1.0f), fbits(1.0f), 0, 0}) == diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py index a677a9de9b..f03c15c42b 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py @@ -1803,6 +1803,29 @@ def clip_test(tools, spirv, name): return "" +def texture_uav_test(tools, spv): + """The Windows D3D12 test compares every texel itself, through both Vulkan and WARP.""" + if os.name != "nt": + return Skip("SKIP (needs the Windows D3D12 runtime)") + exe = os.path.join(tools, "d3d12_texture_uav_test" + EXE) + if not os.path.isfile(exe): + return f"missing {exe}" + code, out = run(exe, spv) + if code == UNSUPPORTED: + reason = next((line for line in out.splitlines() if line.startswith("SKIP:")), "unsupported device") + return Skip(reason) + return "" if code == 0 else failure(code, out, 8) + + +IMAGE_STORE_CASES = { + "cs_imgstore": (), + "cs_imgload": ("load",), + "cs_imgload_d16": ("load-d16",), + "cs_sample_lz_int_d16": ("load-d16",), + "cs_imgload_mip": ("load-mip",), +} + + def main(): if any(arg in ("-h", "--help") for arg in sys.argv[1:]): print(__doc__) @@ -1853,9 +1876,7 @@ def main(): results.append(("ms_wave_info_s3", mesh_w64x_test(tools, spirv, "ms_wave_info_s3"))) with tempfile.TemporaryDirectory(prefix="leonida-mesh-") as tmp: results.append(("ms_v5_workgroup", mesh_v5_test(tools, spirv, Path(tmp) / "groups.raw"))) - for name, args in (("cs_imgstore", []), ("cs_imgload", ["load"]), ("cs_imgload_tfe", ["load"]), - ("cs_imgload_d16", ["load-d16"]), ("cs_imgload_d16_tfe", ["load-d16"]), - ("cs_sample_lz_int_d16", ["load-d16"])): + for name, args in IMAGE_STORE_CASES.items(): code, out = run(os.path.join(tools, "vk_store_test" + EXE), os.path.join(spirv, name + ".spv"), *args) if code == UNSUPPORTED: # vk_store_test: the device lacks a feature this test needs m = re.search(r"unsupported: .*", out) @@ -1863,6 +1884,9 @@ def main(): continue bad = re.findall(r"(\d+) bad", out) results.append((name, "" if code == 0 and len(bad) == 3 and set(bad) == {"0"} else failure(code, out, 3))) + texture_uav_spv = os.path.join(spirv, "cs_texture_uav.spv") + if os.path.isfile(texture_uav_spv): + results.append(("cs_texture_uav", texture_uav_test(tools, texture_uav_spv))) for name in STORE_WORDS: # TEST-184: image atomics and image_get_resinfo results.append((name, store_words_test(tools, spirv, name))) for name in GET_LOD_TESTS: # TEST-184: image_get_lod, 2D and 2D array diff --git a/runtime/test/shaders/cs_cbv_vector_rows.asm b/runtime/test/shaders/cs_cbv_vector_rows.asm new file mode 100644 index 0000000000..6dd26a845d --- /dev/null +++ b/runtime/test/shaders/cs_cbv_vector_rows.asm @@ -0,0 +1,42 @@ +; group: 1,1,1 +; Read four 16-byte register rows through the actual Xbox constant-buffer descriptor staged at byte 64. +s_mov_b32 s4, 64 +s_mov_b32 s5, 0 +s_load_dwordx4 s[8:11], s[4:5], 0 +s_waitcnt lgkmcnt(0) +v_mov_b32 v20, 0 +v_mov_b32 v0, 0 +buffer_load_dwordx4 v[4:7], v0, s[8:11], 0 idxen +s_waitcnt vmcnt(0) +buffer_store_dword v4, v20, s[0:3], 0 offen offset:0 +v_mov_b32 v0, 1 +buffer_load_dwordx4 v[4:7], v0, s[8:11], 0 idxen +s_waitcnt vmcnt(0) +buffer_store_dword v4, v20, s[0:3], 0 offen offset:4 +v_mov_b32 v0, 2 +buffer_load_dwordx4 v[4:7], v0, s[8:11], 0 idxen +s_waitcnt vmcnt(0) +buffer_store_dword v4, v20, s[0:3], 0 offen offset:8 +v_mov_b32 v0, 3 +buffer_load_dwordx4 v[4:7], v0, s[8:11], 0 idxen +s_waitcnt vmcnt(0) +buffer_store_dword v4, v20, s[0:3], 0 offen offset:12 +s_buffer_load_dwordx2 s[12:13], s[8:11], 0x30 +s_waitcnt lgkmcnt(0) +v_mov_b32 v4, s12 +v_mov_b32 v5, s13 +buffer_store_dword v4, v20, s[0:3], 0 offen offset:16 +buffer_store_dword v5, v20, s[0:3], 0 offen offset:20 +v_mov_b32 v0, 16 +buffer_load_dword v4, v0, s[8:11], 0 idxen +s_waitcnt vmcnt(0) +buffer_store_dword v4, v20, s[0:3], 0 offen offset:24 +v_mov_b32 v0, 15 +buffer_load_dword v4, v0, s[8:11], 0 idxen offset:12 +s_waitcnt vmcnt(0) +buffer_store_dword v4, v20, s[0:3], 0 offen offset:28 +s_buffer_load_dword s14, s[8:11], 0x100 +s_waitcnt lgkmcnt(0) +v_mov_b32 v4, s14 +buffer_store_dword v4, v20, s[0:3], 0 offen offset:32 +s_endpgm diff --git a/runtime/test/shaders/cs_imgatomic3d.asm b/runtime/test/shaders/cs_imgatomic3d.asm index 29f4477a4a..cd6b6a1130 100644 --- a/runtime/test/shaders/cs_imgatomic3d.asm +++ b/runtime/test/shaders/cs_imgatomic3d.asm @@ -18,10 +18,10 @@ s_mov_b32 s16, 0x5000 s_mov_b32 s17, 0x1400000 s_mov_b32 s18, 0x55 s_mov_b32 s19, 0x55 -s_mov_b32 s20, 0x55 +s_mov_b32 s20, 0x80000055 s_mov_b32 s21, 0x55 s_mov_b32 s22, 0x55 -s_mov_b32 s23, 0x55 +s_mov_b32 s23, 0xd7801800 s_mov_b32 s24, 0x3000 s_mov_b32 s25, 0x1500000 s_mov_b32 s26, 0x33 diff --git a/runtime/test/shaders/cs_imgload_mip.asm b/runtime/test/shaders/cs_imgload_mip.asm new file mode 100644 index 0000000000..c9d4d33067 --- /dev/null +++ b/runtime/test/shaders/cs_imgload_mip.asm @@ -0,0 +1,44 @@ +; vk_store_test load-mip: x/y are a texel in the 8x8 mip 1. The 16x16 mip 0 has decoy data and receives +; the results. Fetch each mip-1 format twice: full-width and D16 (RG for UNORM, RA for R32 UINT/SINT). +; Store the float RG bits, and check both packed halves (including integer saturation) in the integer outputs. +v_and_b32_e32 v1, 7, v0 +v_lshrrev_b32_e32 v2, 3, v0 +v_mov_b32_e32 v3, 1 +s_mov_b32 s8, 0x1000 +s_mov_b32 s9, 0x3800000 +s_mov_b32 s10, 0x11 +s_mov_b32 s11, 0x11 +s_mov_b32 s12, 0x11 +s_mov_b32 s13, 0x11 +s_mov_b32 s14, 0x11 +s_mov_b32 s15, 0x11 +image_load_mip v[4:5], v[1:3], s[8:15] dmask:0x3 dim:SQ_RSRC_IMG_2D unorm +image_load_mip v6, v[1:3], s[8:15] dmask:0x3 dim:SQ_RSRC_IMG_2D unorm d16 +s_mov_b32 s16, 0x2000 +s_mov_b32 s17, 0x1400000 +s_mov_b32 s18, 0x22 +s_mov_b32 s19, 0x22 +s_mov_b32 s20, 0x22 +s_mov_b32 s21, 0x22 +s_mov_b32 s22, 0x22 +s_mov_b32 s23, 0x22 +image_load_mip v7, v[1:3], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm +image_load_mip v8, v[1:3], s[16:23] dmask:0x9 dim:SQ_RSRC_IMG_2D unorm d16 +s_mov_b32 s24, 0x3000 +s_mov_b32 s25, 0x1500000 +s_mov_b32 s26, 0x33 +s_mov_b32 s27, 0x33 +s_mov_b32 s28, 0x33 +s_mov_b32 s29, 0x33 +s_mov_b32 s30, 0x33 +s_mov_b32 s31, 0x33 +image_load_mip v9, v[1:3], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm +image_load_mip v10, v[1:3], s[24:31] dmask:0x9 dim:SQ_RSRC_IMG_2D unorm d16 +s_waitcnt vmcnt(0) +v_add_nc_u32_e32 v7, v7, v8 +v_add_nc_u32_e32 v7, v7, v6 +v_add_nc_u32_e32 v9, v9, v10 +image_store v[4:5], v[1:2], s[8:15] dmask:0x3 dim:SQ_RSRC_IMG_2D unorm +image_store v7, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm +image_store v9, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm +s_endpgm diff --git a/runtime/test/shaders/cs_texture_uav.asm b/runtime/test/shaders/cs_texture_uav.asm new file mode 100644 index 0000000000..b5180a881a --- /dev/null +++ b/runtime/test/shaders/cs_texture_uav.asm @@ -0,0 +1,105 @@ +; group: 1,1,1 +; rsrc2: 0x392 +; s[0:7] = UAV T#, s8 = case (0: 1D, 1: 1D array, 2: 3D UINT, 3: 2D, 4: 3D FLOAT, 5: 1D array FLOAT, 6: 3D atomics). +; s[9:11] = workgroup XYZ. Add 1000 + x + 16*y + 256*z to each existing texel (z is the array +; layer for 1D arrays). d3d12_texture_uav_test pushes production heap descriptors and compares +; every texel against the CPU expectation and, for non-atomic UINT, against Windows WARP. +; The float volume adds the texel twice at even x (LOD 0), once at odd x (LOD 1 reads zero). +; The atomic volume stores the coordinate increment + (initial << 16) + ((initial + 5) << 8) + 7 + 99. +v_mov_b32_e32 v0, s9 +v_mov_b32_e32 v1, s10 +v_mov_b32_e32 v2, s11 +v_lshlrev_b32_e32 v3, 8, v2 +v_lshl_add_u32 v3, v1, 4, v3 +v_add_nc_u32_e32 v3, v0, v3 +v_add_nc_u32_e32 v3, 1000, v3 +s_cmp_eq_u32 s8, 0 +s_cbranch_scc0 11 +image_load v4, v0, s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_1D unorm +; The sampled and formatless coherent reads must agree; a mismatch changes the result. +image_load v5, v0, s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_1D unorm glc dlc +s_waitcnt vmcnt(0) +v_xor_b32_e32 v5, v4, v5 +v_add_nc_u32_e32 v3, v3, v5 +v_add_nc_u32_e32 v3, v3, v4 +image_store v3, v0, s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_1D unorm +s_endpgm +s_cmp_eq_u32 s8, 1 +s_cbranch_scc0 7 +v_mov_b32_e32 v1, v2 +image_load v4, v[0:1], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_1D_ARRAY unorm +v_add_nc_u32_e32 v3, v3, v4 +image_store v3, v[0:1], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_1D_ARRAY unorm +s_endpgm +s_cmp_eq_u32 s8, 2 +s_cbranch_scc0 11 +image_load v4, v[0:2], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm +; A sliced UAV must see the same texel via the rebased sampled alias and the sliced storage view. +image_load v5, v[0:2], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm glc dlc +s_waitcnt vmcnt(0) +v_xor_b32_e32 v5, v4, v5 +v_add_nc_u32_e32 v3, v3, v5 +v_add_nc_u32_e32 v3, v3, v4 +image_store v3, v[0:2], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm +s_endpgm +s_cmp_eq_u32 s8, 3 +s_cbranch_scc0 6 +image_load v4, v[0:1], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm +v_add_nc_u32_e32 v3, v3, v4 +image_store v3, v[0:1], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm +s_endpgm +s_cmp_eq_u32 s8, 5 +s_cbranch_scc0 13 +v_mov_b32_e32 v1, v2 +image_load v4, v[0:1], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_1D_ARRAY unorm +v_cvt_f32_u32_e32 v3, v3 +v_add_f32_e32 v3, v3, v4 +; Float array view covers two layers. Verify that the next-layer read does not contribute. +v_add_nc_u32_e32 v1, 2, v1 +image_load v4, v[0:1], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_1D_ARRAY unorm +v_add_f32_e32 v3, v3, v4 +v_mov_b32_e32 v1, v2 +image_store v3, v[0:1], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_1D_ARRAY unorm +s_endpgm +s_cmp_eq_u32 s8, 6 +s_cbranch_scc0 31 +; Use a separate T# SGPR group so the non-atomic UINT volume case exercises the sampled alias. +s_mov_b64 s[12:13], s[0:1] +s_mov_b64 s[14:15], s[2:3] +s_mov_b64 s[16:17], s[4:5] +s_mov_b64 s[18:19], s[6:7] +; Inactive add and CAS must neither write nor change their glc destinations. The active add returns +; the initial texel, the active CAS returns that texel + 5, and the following load reads 99. +v_mov_b32_e32 v4, 7 +v_mov_b32_e32 v5, 0 +s_mov_b32 exec_lo, 0 +image_atomic_add v4, v[0:2], s[12:19] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm glc +image_atomic_cmpswap v[4:5], v[0:2], s[12:19] dmask:0x3 dim:SQ_RSRC_IMG_3D unorm glc +s_mov_b32 exec_lo, 1 +v_mov_b32_e32 v6, 5 +image_atomic_add v6, v[0:2], s[12:19] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm glc +v_mov_b32_e32 v8, 99 +v_add_nc_u32_e32 v9, 5, v6 +image_atomic_cmpswap v[8:9], v[0:2], s[12:19] dmask:0x3 dim:SQ_RSRC_IMG_3D unorm glc +image_load v7, v[0:2], s[12:19] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm +v_lshl_add_u32 v3, v6, 16, v3 +v_lshl_add_u32 v3, v8, 8, v3 +v_add_nc_u32_e32 v3, v4, v3 +v_add_nc_u32_e32 v3, v7, v3 +image_store v3, v[0:2], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm +s_endpgm +image_load v4, v[0:2], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm +v_cvt_f32_u32_e32 v3, v3 +v_add_f32_e32 v3, v3, v4 +; Relative LOD 0 reuses the physical mip selected by the view; LOD 1 is outside the single-mip view. +v_mov_b32_e32 v6, v3 +v_and_b32_e32 v3, 1, v0 +image_load_mip v5, v[0:3], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm +v_add_f32_e32 v3, v6, v5 +; Float test uses WSize=2: an outside-Z fetch must be zero even if still inside the image. +v_add_nc_u32_e32 v2, 2, v2 +image_load v4, v[0:2], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm +v_add_f32_e32 v3, v3, v4 +v_mov_b32_e32 v2, s11 +image_store v3, v[0:2], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm +s_endpgm diff --git a/runtime/test/shaders/ps_imgatomic.asm b/runtime/test/shaders/ps_imgatomic.asm index b8f888c131..253cd2c9e7 100644 --- a/runtime/test/shaders/ps_imgatomic.asm +++ b/runtime/test/shaders/ps_imgatomic.asm @@ -1,8 +1,8 @@ ; Image atomics in a pixel shader, the forms the game uses (1,018 of its 1,038 image-atomic shaders are pixel shaders: ; image_atomic_or / umin / umax on a 2D image and umax on a 3D one), through the descriptor table and the set-0 ; r32ui storage arrays (binding 4 for 2D, 7 for 3D). User data s2:s3 is the console VA of a table of four T#s: -; +0x00 the 2D umax image, +0x20 the 2D umin image, +0x40 the 2D or image, +0x60 the 3D umax image (any 8 dwords: -; only the key matters). Each of the 64x64 pixels computes px, py from attr0 (vs_ids runs it 0..1 over the target), +; +0x00 the 2D umax image, +0x20 the 2D umin image, +0x40 the 2D or image, +0x60 the tagged R32_UINT 3D UAV. +; Each of the 64x64 pixels computes px, py from attr0 (vs_ids runs it 0..1 over the target), ; its id = px + 64 * py, and its texel tx = px >> 3, ty = py >> 3, so 64 pixels contend for each texel of the 8x8 ; images: ; umax2d[ty][tx] = max(id), umin2d[ty][tx] = min(id), or2d[ty][tx] |= 1 << (id & 31), diff --git a/runtime/test/vk_bindless_test.cpp b/runtime/test/vk_bindless_test.cpp index d6276d8ad4..194df74a9b 100644 --- a/runtime/test/vk_bindless_test.cpp +++ b/runtime/test/vk_bindless_test.cpp @@ -34,6 +34,7 @@ #include #include #include +#include #include #include #include @@ -315,6 +316,7 @@ int main(int argc, char** argv) { LD(vkDestroyCommandPool); LD(vkDestroyShaderModule); LD(vkDestroyFramebuffer); LD(vkDestroyRenderPass); LD(vkDestroySampler); LD(vkDestroyImageView); LD(vkDestroyImage); LD(vkDestroyBuffer); LD(vkFreeMemory); LD(vkDestroyDevice); LD(vkCmdClearColorImage); + LD(vkGetDescriptorSetLayoutSupport); VkQueue queue = VK_NULL_HANDLE; vkGetDeviceQueue(dev, qi, 0, &queue); VkPhysicalDeviceMemoryProperties mp; @@ -536,47 +538,60 @@ int main(int argc, char** argv) { } CHECK(submit()); - // An adapter at the original 5632 sampled-image limit must keep the original set. The per-stage - // resource budget can also leave room for just one class (9985 original resources + 512). + constexpr auto descriptors = [](VkDescriptorType type, const BindlessFeatures& f) { + std::uint32_t count = 0; + for (std::uint32_t b = 0; b < bindless::bindings.size(); ++b) + if (bindless::bindings[b].type == type && bindless::binding_enabled(b, f)) + count += f.counts[b]; + return count; + }; + + // An adapter at the single-sample limit must keep the original set. The stage resource budget + // can also leave room for just one MS class. Include the non-MS bindings after the MS pairs. + constexpr BindlessFeatures defaults{}; + constexpr auto base_sampled = descriptors(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, defaults); + constexpr auto base_resources = base_sampled + descriptors(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, defaults) + + descriptors(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, defaults); + constexpr auto ms_pair = + defaults.counts[bindless::first_ms_binding] + defaults.counts[bindless::first_ms_binding + 1]; constexpr auto ms_classes = [](std::uint32_t sampled, std::uint32_t total) { BindlessFeatures f{}; f.ms_samples.fill(VK_SAMPLE_COUNT_4_BIT); bindless::limit_ms_bindings(f, sampled, total); return f.ms_samples; }; - static_assert(ms_classes(5632, 20000) == + static_assert(ms_classes(base_sampled, base_resources + ms_pair) == std::array{VK_SAMPLE_COUNT_1_BIT, VK_SAMPLE_COUNT_1_BIT, VK_SAMPLE_COUNT_1_BIT}); - static_assert(ms_classes(7168, 10497) == + static_assert(ms_classes(base_sampled + 3 * ms_pair, base_resources + ms_pair) == std::array{VK_SAMPLE_COUNT_4_BIT, VK_SAMPLE_COUNT_1_BIT, VK_SAMPLE_COUNT_1_BIT}); - // Does a set with these flags fit the device? Every binding is visible to every stage. - const auto descriptors = [](VkDescriptorType type, const BindlessFeatures& f) { - std::uint32_t count = 0; - for (std::uint32_t b = 0; b < bindless::bindings.size(); ++b) - if (bindless::bindings[b].type == type && bindless::binding_enabled(b, f)) - count += f.counts[b]; - return count; - }; + // Check the sized layout against the device's limits. Standalone samplers count in the pool, + // but not towards the per-stage resource budget. const auto fits = [&](const BindlessFeatures& f) { const auto sampled_total = descriptors(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, f); const auto sampler_total = descriptors(VK_DESCRIPTOR_TYPE_SAMPLER, f); const auto storage_total = descriptors(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, f); - const auto stage_resources = sampled_total + storage_total + 2; // table buffer and fragment output + const auto buffer_total = descriptors(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, f); + const auto stage_resources = sampled_total + storage_total + buffer_total + 1; // fragment output + const auto pool_descriptors = sampled_total + sampler_total + storage_total + buffer_total; const VkPhysicalDeviceLimits& l = props.properties.limits; if (f.update_after_bind) return props12.maxPerStageDescriptorUpdateAfterBindSampledImages >= sampled_total && props12.maxPerStageDescriptorUpdateAfterBindSamplers >= sampler_total && props12.maxPerStageDescriptorUpdateAfterBindStorageImages >= storage_total && + props12.maxPerStageDescriptorUpdateAfterBindStorageBuffers >= buffer_total && props12.maxPerStageUpdateAfterBindResources >= stage_resources && - props12.maxUpdateAfterBindDescriptorsInAllPools >= sampled_total + sampler_total + storage_total + 1 && + props12.maxUpdateAfterBindDescriptorsInAllPools >= pool_descriptors && props12.maxDescriptorSetUpdateAfterBindSampledImages >= sampled_total && props12.maxDescriptorSetUpdateAfterBindSamplers >= sampler_total && - props12.maxDescriptorSetUpdateAfterBindStorageImages >= storage_total; + props12.maxDescriptorSetUpdateAfterBindStorageImages >= storage_total && + props12.maxDescriptorSetUpdateAfterBindStorageBuffers >= buffer_total; return l.maxPerStageDescriptorSampledImages >= sampled_total && l.maxPerStageDescriptorSamplers >= sampler_total && l.maxPerStageDescriptorStorageImages >= storage_total && + l.maxPerStageDescriptorStorageBuffers >= buffer_total && l.maxPerStageResources >= stage_resources && l.maxDescriptorSetSampledImages >= sampled_total && l.maxDescriptorSetSamplers >= sampler_total && - l.maxDescriptorSetStorageImages >= storage_total; + l.maxDescriptorSetStorageImages >= storage_total && l.maxDescriptorSetStorageBuffers >= buffer_total; }; unsigned mismatches = 0, runs = 0, readbacks = 0; @@ -602,11 +617,19 @@ int main(int argc, char** argv) { BindlessFeatures configurations[2] = {device_flags, {}}; const int configuration_count = (device_flags.update_after_bind || device_flags.partially_bound) ? 2 : 1; + std::function layout_supported; + if (vkGetDescriptorSetLayoutSupport) + layout_supported = [&](const BindlessFeatures& candidate) { + const bindless::SetLayout layout(candidate); + VkDescriptorSetLayoutSupport support{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_SUPPORT}; + vkGetDescriptorSetLayoutSupport(dev, &layout.info, &support); + return support.supported == VK_TRUE; + }; for (int configuration = 0; configuration < configuration_count; ++configuration) { BindlessFeatures flags = configurations[configuration]; flags.ms_samples[0] = VK_SAMPLE_COUNT_4_BIT; // A device below the default counts gets a smaller set; this test needs at least those. - const bool full = bindless::size_bindings(flags, props.properties.limits, props11, props12); + const bool full = bindless::size_bindings(flags, props.properties.limits, props11, props12, layout_supported); const char* name = flags.update_after_bind && flags.partially_bound ? "update after bind, partially bound" : flags.update_after_bind ? "update after bind" : flags.partially_bound ? "partially bound" : "no flags"; if (!full || !fits(flags)) { @@ -615,6 +638,8 @@ int main(int argc, char** argv) { } BindlessSet set(vkGetDeviceProcAddr, dev, mp, flags); EXPECT(set.ok() && set.layout() && set.set()); + EXPECT(set.image_capacity(ImageDimension::dim_1d_array) == set.storage_capacity(ImageDimension::dim_1d_array)); + EXPECT(set.add_image(ImageDimension::dim_1d_array, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL) == 0); const VkPushConstantRange push{VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, push_bytes}; const VkDescriptorSetLayout set_layout = set.layout(); @@ -746,7 +771,8 @@ int main(int argc, char** argv) { const std::array keys{{{0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8}, {0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8}, {0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8}, - {0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8}}}; + {0xd1, 20u << 20, 0xd3, 0xd4, 0x800000d5, 0xd6, 0xd7, + 0xd7801800}}}; for (std::uint32_t k = 0; k < 4; ++k) std::memcpy(static_cast(heap_map) + atomic_va + 32 * k, keys[k].data(), 32); const VkImageUsageFlags atomic_usage = diff --git a/runtime/test/vk_pipeline_check.cpp b/runtime/test/vk_pipeline_check.cpp index ec9a395194..3a57b1f772 100644 --- a/runtime/test/vk_pipeline_check.cpp +++ b/runtime/test/vk_pipeline_check.cpp @@ -1,7 +1,7 @@ // Driver-level check of the translated corpus: vk_pipeline_check [pipeline_cache.bin] // Reads /index.json (written by tools/rdna2spirv.py) and checks module and pipeline creation for compatible // entries with the translator's resource contract (set 0: sampled images 0, 3, 5, 6; samplers 1; descriptor hash -// table 2; storage images 4, 7 and 8..19; set 1 binding 0 dynamic UBO for --pc-tail-ubo shaders; push constants +// table 2; storage images 4, 7 and 8..19 and 26..28; set 1 binding 0 dynamic UBO for --pc-tail-ubo shaders; push constants // sized from push_constant_bytes, default 144 or 128 with pc_tail): // - cs: compute pipeline via vkCreateComputePipelines, using the runtime layout and subgroup request for // descriptor-free shaders with the standard push-constant range @@ -53,6 +53,7 @@ #include "pipeline_summary.h" #include "../src/spirv_words.h" #include "../src/subgroup_size.h" +#include "../src/vulkan_bindless.h" #include #include @@ -69,6 +70,7 @@ #include #include #include +#include #include #include #include @@ -1099,10 +1101,13 @@ int main(int argc, char** argv) { } VkPhysicalDeviceProperties props; vkGetPhysicalDeviceProperties(pd, &props); VkPhysicalDeviceSubgroupSizeControlProperties sgProps{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_PROPERTIES}; - VkPhysicalDeviceFloatControlsProperties fcProps{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FLOAT_CONTROLS_PROPERTIES}; + VkPhysicalDeviceVulkan11Properties indexing_limits{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_PROPERTIES}; + // Vulkan12Properties already includes the float controls (do not chain both promoted structs). + VkPhysicalDeviceVulkan12Properties indexed{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_PROPERTIES}; VkPhysicalDeviceProperties2 props2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2}; + indexing_limits.pNext = &indexed; + sgProps.pNext = &indexing_limits; props2.pNext = &sgProps; - sgProps.pNext = &fcProps; vkGetPhysicalDeviceProperties2(pd, &props2); std::fprintf(stderr, "device: %s (subgroup %u..%u)\n", props.deviceName, sgProps.minSubgroupSize, sgProps.maxSubgroupSize); @@ -1240,6 +1245,7 @@ int main(int argc, char** argv) { } #define LOADD(name) auto name = reinterpret_cast(vkGetDeviceProcAddr(dev, #name)) LOADD(vkCreateShaderModule); LOADD(vkDestroyShaderModule); LOADD(vkCreateDescriptorSetLayout); + LOADD(vkGetDescriptorSetLayoutSupport); LOADD(vkCreatePipelineLayout); LOADD(vkCreateComputePipelines); LOADD(vkCreateGraphicsPipelines); LOADD(vkDestroyPipeline); LOADD(vkCreatePipelineCache); LOADD(vkGetPipelineCacheData); LOADD(vkGetPipelineExecutablePropertiesKHR); LOADD(vkGetPipelineExecutableStatisticsKHR); @@ -1293,15 +1299,16 @@ int main(int argc, char** argv) { // DenormPreserve 16) need a device property, not a feature. for (const auto& fc : meta.float_controls) { if (fc == "shaderSignedZeroInfNanPreserveFloat32") { - if (!fcProps.shaderSignedZeroInfNanPreserveFloat32) return "no " + fc; + if (!indexed.shaderSignedZeroInfNanPreserveFloat32) return "no " + fc; } else if (fc == "shaderSignedZeroInfNanPreserveFloat64") { - if (!fcProps.shaderSignedZeroInfNanPreserveFloat64) return "no " + fc; + if (!indexed.shaderSignedZeroInfNanPreserveFloat64) return "no " + fc; } else if (fc == "shaderDenormPreserveFloat16") { - if (!fcProps.shaderDenormPreserveFloat16) return "no " + fc; + if (!indexed.shaderDenormPreserveFloat16) return "no " + fc; } else { return "unknown float control " + fc; } } + // Per-format read/write support for formatless storage is checked when the runtime binds the actual view. for (const auto& feat : meta.features) { if (feat == "meshShader" && !(ext_mesh && mesh.meshShader)) return "no VK_EXT_mesh_shader"; if (feat == "geometryShader" && !f2.features.geometryShader) return "no geometryShader"; @@ -1316,28 +1323,38 @@ int main(int argc, char** argv) { if (feat == "runtimeDescriptorArray" && !f12.runtimeDescriptorArray) return "no runtimeDescriptorArray"; if (feat == "shaderImageGatherExtended" && !f2.features.shaderImageGatherExtended) return "no shaderImageGatherExtended"; if (feat == "shaderResourceMinLod" && !f2.features.shaderResourceMinLod) return "no shaderResourceMinLod"; - if (feat == "shaderStorageImageWriteWithoutFormat" && !f2.features.shaderStorageImageWriteWithoutFormat) - return "no shaderStorageImageWriteWithoutFormat"; - if (feat == "shaderStorageImageReadWithoutFormat" && !f2.features.shaderStorageImageReadWithoutFormat) - return "no shaderStorageImageReadWithoutFormat"; + if (props.apiVersion < VK_API_VERSION_1_3) { + if (feat == "shaderStorageImageWriteWithoutFormat" && !f2.features.shaderStorageImageWriteWithoutFormat) + return "no shaderStorageImageWriteWithoutFormat"; + if (feat == "shaderStorageImageReadWithoutFormat" && !f2.features.shaderStorageImageReadWithoutFormat) + return "no shaderStorageImageReadWithoutFormat"; + } } return {}; }; - // Resource contract (docs/design.md): set 0, runtime-sized arrays as large bindless arrays. - std::vector b; - auto add = [&](uint32_t bind, VkDescriptorType t, uint32_t cnt) { - b.push_back({bind, t, cnt, VK_SHADER_STAGE_ALL, nullptr}); - }; - add(0, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 4096); add(1, VK_DESCRIPTOR_TYPE_SAMPLER, 1024); - add(2, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1); add(3, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1024); - add(4, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1024); add(5, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256); - add(6, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256); add(7, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256); - for (uint32_t i = 8; i <= 19; i++) add(i, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256); - VkDescriptorSetLayoutCreateInfo dli{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; - dli.bindingCount = uint32_t(b.size()); dli.pBindings = b.data(); + // Use the runtime's set-0 layout and sizing rules. The translator does not declare the runtime-only MS SRVs. + leonida::BindlessFeatures bindless{}; + std::function layout_supported; + if (vkGetDescriptorSetLayoutSupport) + layout_supported = [&](const leonida::BindlessFeatures& candidate) { + const leonida::bindless::SetLayout layout(candidate); + VkDescriptorSetLayoutSupport support{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_SUPPORT}; + vkGetDescriptorSetLayoutSupport(dev, &layout.info, &support); + return support.supported == VK_TRUE; + }; + if (!leonida::bindless::size_bindings(bindless, props2.properties.limits, indexing_limits, indexed, layout_supported) && + f12.descriptorBindingSampledImageUpdateAfterBind && f12.descriptorBindingStorageImageUpdateAfterBind && + f12.descriptorBindingStorageBufferUpdateAfterBind) { + bindless.update_after_bind = true; + leonida::bindless::size_bindings(bindless, props2.properties.limits, indexing_limits, indexed, layout_supported); + } + const leonida::bindless::SetLayout layout(bindless); VkDescriptorSetLayout dsl; - if (VkResult r = vkCreateDescriptorSetLayout(dev, &dli, nullptr, &dsl)) { std::fprintf(stderr, "layout %d\n", r); return 1; } + if (VkResult r = vkCreateDescriptorSetLayout(dev, &layout.info, nullptr, &dsl)) { + std::fprintf(stderr, "layout %d\n", r); + return 1; + } // Set 1 of --pc-tail-ubo shaders (docs/design.md): dynamic uniform block at binding 0 holding heap/code base. const VkDescriptorSetLayoutBinding tail_binding{0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1, VK_SHADER_STAGE_ALL, nullptr}; diff --git a/runtime/test/vk_store_test.cpp b/runtime/test/vk_store_test.cpp index 5567511d0b..59963e8842 100644 --- a/runtime/test/vk_store_test.cpp +++ b/runtime/test/vk_store_test.cpp @@ -1,6 +1,6 @@ // Headless Vulkan test for translated typed image stores and loads (runtime/test/shaders/cs_imgstore.asm and -// cs_imgload.asm). -// Usage: vk_store_test cs.spv [load|load-d16|words|signed-zero] +// cs_imgload*.asm). +// Usage: vk_store_test cs.spv [load|load-d16|load-mip|words|signed-zero] // The shader builds three T#s (word1 FORMAT = 56 rgba8 unorm, 20 r32 uint, 21 r32 sint) and stores to three 8x8 // images. The translator picks the float / uint / sint view (set 0, bindings 8 / 9 / 10 for 2D) from the FORMAT // field, and the bindless index from the descriptor hash table (binding 2). As in the runtime, each image has its @@ -9,6 +9,10 @@ // "load" (cs_imgload.asm): the uint and sint images are filled before the dispatch, and the shader loads both // texels with image_load and stores their sum into the sint image. The device is made without // shaderStorageImageReadWithoutFormat, and a module that declares StorageImageReadWithoutFormat fails (SHADER-151). +// "load-d16": check integer narrowing for packed image_load (cs_imgload_d16.asm) or image_sample_lz +// (cs_sample_lz_int_d16.asm), including saturation at the 16-bit boundaries. +// "load-mip": read level 1 through typed, two-level SRVs with both full-width and D16 fetches; write the checked +// results to level 0 through single-level storage views. The two mips start with different data. // "words" (cs_imgatomic.asm, cs_imgatomic3d.asm, cs_resinfo.asm): the uint and sint images are filled as for "load" // and a 4x4x4 r32 uint volume with 200 + i, and nothing is judged here: the 64 words of each are printed after the // dispatch (texel (x, y) at i = 8y + x, (x, y, z) at i = 16z + 4y + x) for check.py to compare. Three things are @@ -60,7 +64,7 @@ static void table_insert(std::vector& t, const uint32_t key[8], uint32 } int main(int argc, char** argv) { - if (argc < 2) { std::fprintf(stderr, "usage: vk_store_test cs.spv [load|load-d16|words|signed-zero]\n"); return 2; } + if (argc < 2) { std::fprintf(stderr, "usage: vk_store_test cs.spv [load|load-d16|load-mip|words|signed-zero]\n"); return 2; } gipa = load_vulkan(); if (!gipa) return 1; #define LOADI(name) auto name = reinterpret_cast(gipa(inst, #name)) @@ -121,8 +125,9 @@ int main(int argc, char** argv) { VkPhysicalDeviceFeatures2 f2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; f2.features.shaderStorageImageWriteWithoutFormat = VK_TRUE; // "load" mode (cs_imgload.asm): the sint image receives the sum of the two texels read back with image_load. + const bool load_mip = argc > 2 && !std::strcmp(argv[2], "load-mip"); const bool packed_load = argc > 2 && !std::strcmp(argv[2], "load-d16"); - const bool load_mode = packed_load || (argc > 2 && !std::strcmp(argv[2], "load")); + const bool load_mode = load_mip || packed_load || (argc > 2 && !std::strcmp(argv[2], "load")); // "words" mode: the two images filled as for "load"; the shader's results are whatever it leaves in them. const bool words_mode = argc > 2 && !std::strcmp(argv[2], "words"); const bool signed_zero = argc > 2 && !std::strcmp(argv[2], "signed-zero"); @@ -236,7 +241,8 @@ int main(int argc, char** argv) { // The volume of the 3D atomics: index 1 of the 3D arrays, behind a T# of the 2D images' pattern (k = 4). const uint32_t VOL = 4; { - uint32_t t[8] = {0x5000, fmts[1] << 20, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55}; + // The volume uses the D3D12 layer's whole-mip UAV tag (FirstWSlice=0, WSize=4). + uint32_t t[8] = {0x5000, fmts[1] << 20, 0x55, 0x55, 0x80000055, 0x55, 0x55, 0xd7801800}; table_insert(table, t, 1); } VkBuffer tb; void* tbp; @@ -244,10 +250,12 @@ int main(int argc, char** argv) { std::memcpy(tbp, table.data(), table.size() * 4); const uint32_t W = 8; - VkImage img[3]; VkImageView view[3]; + const uint32_t base_width = load_mip ? 2 * W : W, mip_count = load_mip ? 2 : 1; + VkImage img[3]; VkImageView view[3], sampled[3]; for (int k = 0; k < 3; k++) { VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; - ii.imageType = VK_IMAGE_TYPE_2D; ii.format = vkf[k]; ii.extent = {W, W, 1}; ii.mipLevels = 1; ii.arrayLayers = 1; + ii.imageType = VK_IMAGE_TYPE_2D; ii.format = vkf[k]; ii.extent = {base_width, base_width, 1}; + ii.mipLevels = mip_count; ii.arrayLayers = 1; ii.samples = VK_SAMPLE_COUNT_1_BIT; ii.tiling = VK_IMAGE_TILING_OPTIMAL; ii.usage = VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; @@ -261,6 +269,14 @@ int main(int argc, char** argv) { vi.image = img[k]; vi.viewType = VK_IMAGE_VIEW_TYPE_2D; vi.format = vkf[k]; vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; CHECK(vkCreateImageView(dev, &vi, nullptr, &view[k])); + sampled[k] = view[k]; + if (load_mip) { + VkImageViewUsageCreateInfo usage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO}; + usage.usage = VK_IMAGE_USAGE_SAMPLED_BIT; + vi.pNext = &usage; + vi.subresourceRange.levelCount = mip_count; + CHECK(vkCreateImageView(dev, &vi, nullptr, &sampled[k])); + } } VkImage wide; VkImageView wide_view; { @@ -328,10 +344,10 @@ int main(int argc, char** argv) { dai.descriptorPool = dp; dai.descriptorSetCount = 1; dai.pSetLayouts = &dsl; VkDescriptorSet ds; CHECK(vkAllocateDescriptorSets(dev, &dai, &ds)); VkDescriptorBufferInfo tbi{tb, 0, VK_WHOLE_SIZE}; - VkDescriptorImageInfo sii[N] = {{VK_NULL_HANDLE, view[0], VK_IMAGE_LAYOUT_GENERAL}, - {VK_NULL_HANDLE, view[0], VK_IMAGE_LAYOUT_GENERAL}, - {VK_NULL_HANDLE, view[1], VK_IMAGE_LAYOUT_GENERAL}, - {VK_NULL_HANDLE, view[2], VK_IMAGE_LAYOUT_GENERAL}, + VkDescriptorImageInfo sii[N] = {{VK_NULL_HANDLE, sampled[0], VK_IMAGE_LAYOUT_GENERAL}, + {VK_NULL_HANDLE, sampled[0], VK_IMAGE_LAYOUT_GENERAL}, + {VK_NULL_HANDLE, sampled[1], VK_IMAGE_LAYOUT_GENERAL}, + {VK_NULL_HANDLE, sampled[2], VK_IMAGE_LAYOUT_GENERAL}, {VK_NULL_HANDLE, wide_view, VK_IMAGE_LAYOUT_GENERAL}}; VkDescriptorImageInfo smpi{sampler, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_UNDEFINED}; VkDescriptorImageInfo dii[3][N]; @@ -383,7 +399,10 @@ int main(int argc, char** argv) { const uint32_t image_words = W * W * (signed_zero ? 4 : 1); VkBuffer rb[3]; void* rbp[3]; for (int k = 0; k < 3; k++) CHECK(make_buffer(image_words * 4, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &rb[k], &rbp[k])); - // Load and words modes: what the uint and sint images hold before the dispatch, texel (x, y) at i = 8y + x. + // Mip mode seeds level 0 with a decoy and level 1 with the typed inputs. Signed-zero probes + // all four RGBA32 components; the ordinary load and words modes seed integer views only. + const int first_fill = signed_zero || load_mip ? 0 : filled ? 1 : 3; + const uint32_t mip_offset = load_mip ? base_width * base_width : 0; // The last row of the D16 fixture ("load-d16" only) exercises both sides of each 16-bit boundary. struct PackedLoad { uint32_t u; int32_t s, sum; }; constexpr PackedLoad boundary[] = { @@ -391,18 +410,24 @@ int main(int argc, char** argv) { {0, 32768, 32767}, {0, -32768, -32768}, {0, -32769, -32768}, {65536, -32769, 32767}, }; static_assert(sizeof(boundary) / sizeof(boundary[0]) == W); - // Load/words modes seed the integer images. The signed-zero probe seeds every component of all three images. - const int first_fill = signed_zero ? 0 : filled ? 1 : 3; VkBuffer fill[3]{}; - for (int k = first_fill; k < 3; ++k) { - void* mapped; - CHECK(make_buffer(image_words * 4, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &fill[k], &mapped)); - auto* words = static_cast(mapped); - for (uint32_t i = 0; i < image_words; ++i) { - const bool edge = packed_load && i / W == W - 1; - if (signed_zero) words[i] = 0x39000000u + k * image_words + i; - else if (k == 1) words[i] = edge ? boundary[i % W].u : 100 + i; - else words[i] = static_cast(edge ? boundary[i % W].s : -2 * int32_t(i)); + if (first_fill < 3) { + for (int k = first_fill; k < 3; ++k) { + void* mapped; + const uint32_t count = mip_offset + image_words; + CHECK(make_buffer(count * 4, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &fill[k], &mapped)); + auto* words = static_cast(mapped); + for (uint32_t i = 0; i < mip_offset; ++i) words[i] = 0x12345678u; + for (uint32_t i = 0; i < image_words; ++i) { + const bool edge = packed_load && i / W == W - 1; + if (signed_zero) words[mip_offset + i] = 0x39000000u + k * image_words + i; + else if (k == 0) words[mip_offset + i] = + (i & 1 ? 0xffu : 0u) | (i & W ? 0xff00u : 0u) | 0xff000000u; + else if (k == 1) words[mip_offset + i] = edge ? boundary[i % W].u : + (load_mip ? 0x100000u : 0u) + 100u + i; + else words[mip_offset + i] = static_cast(edge ? boundary[i % W].s : + -2 * int32_t(i) - (load_mip ? 0x10000 : 0)); + } } } // The volume's fill and its read-back, used in words mode. @@ -426,7 +451,7 @@ int main(int argc, char** argv) { ib[k].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; ib[k].newLayout = VK_IMAGE_LAYOUT_GENERAL; ib[k].dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; ib[k].srcQueueFamilyIndex = ib[k].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - ib[k].subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + ib[k].subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, mip_count, 0, 1}; if (k >= first_fill) { // filled by a copy first ib[k].newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; ib[k].dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; } @@ -442,6 +467,7 @@ int main(int argc, char** argv) { VkImageMemoryBarrier vol_ib = ib[0]; vol_ib.image = vol; vol_ib.newLayout = VK_IMAGE_LAYOUT_GENERAL; vol_ib.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + vol_ib.subresourceRange.levelCount = 1; const VkImageSubresourceLayers vol_layers{VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; if (words_mode) { // filled by a copy first vol_ib.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; vol_ib.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; @@ -460,10 +486,16 @@ int main(int argc, char** argv) { 0, nullptr, 1, &vol_ib); } if (first_fill < 3) { + VkBufferImageCopy copies[2]{}; + for (uint32_t level = 0; level < mip_count; ++level) { + auto& copy = copies[level]; + copy.bufferOffset = level ? mip_offset * 4 : 0; + copy.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, level, 0, 1}; + copy.imageExtent = {base_width >> level, base_width >> level, 1}; + } for (int k = first_fill; k < 3; k++) { - VkBufferImageCopy bic{}; - bic.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; bic.imageExtent = {W, W, 1}; - vkCmdCopyBufferToImage(cmd, fill[k], img[k], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &bic); + vkCmdCopyBufferToImage(cmd, fill[k], img[k], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + mip_count, copies); ib[k].oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; ib[k].newLayout = VK_IMAGE_LAYOUT_GENERAL; ib[k].srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; ib[k].dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; @@ -485,6 +517,7 @@ int main(int argc, char** argv) { ib[k].oldLayout = VK_IMAGE_LAYOUT_GENERAL; ib[k].newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; ib[k].srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; ib[k].dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; + ib[k].subresourceRange.levelCount = 1; } vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 3, ib); @@ -546,6 +579,18 @@ int main(int argc, char** argv) { for (uint32_t x = 0; x < W; x++) { uint32_t i = y * W + x; const uint8_t* c = static_cast(rbp[0]) + 4 * i; + if (load_mip) { + const bool red = x & 1, green = y & 1; + const uint32_t packed_float = (red ? 0x3c00u : 0) | (green ? 0x3c000000u : 0); + const uint32_t u = 0x100000u + 100 + i, s = uint32_t(-2 * int32_t(i) - 0x10000); + // D16 saturates red to 65535 (UINT) or -32768 (SINT); the high half holds alpha = 1. + const uint32_t want_u = u + 0x0001ffffu + packed_float; + const uint32_t want_s = s + 0x00018000u; + if (c[0] != (red ? 255 : 0) || c[1] != (green ? 255 : 0) || c[2] || c[3]) bad[0]++; + if (static_cast(rbp[1])[i] != want_u) bad[1]++; + if (static_cast(rbp[2])[i] != want_s) bad[2]++; + continue; + } int er = int(std::lround(x / 7.0 * 255)), eg = int(std::lround(y / 7.0 * 255)); if (std::abs(c[0] - er) > 1 || std::abs(c[1] - eg) > 1 || std::abs(c[2] - 128) > 1 || c[3] != 255) bad[0]++; const bool edge = packed_load && y == W - 1; diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h index 0aca467878..ae9ba56f7c 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h @@ -104,6 +104,8 @@ class Device { bool sampler_filter_minmax = false; bool vertex_attribute_divisor = false; bool storage_buffer_8bit = false; // storageBuffer8BitAccess enabled + bool storage_image_extended_formats = false; // typed r8ui storage images + bool maintenance10 = false; // depth/stencil transfers on non-graphics families, per format bool conditional_rendering = false; // VK_EXT_conditional_rendering enabled, where available bool host_image_copy = false; // VK_EXT_host_image_copy and hostImageCopy enabled // VK_KHR_maintenance5 enabled, where VK_FORMAT_A8_UNORM_KHR can be sampled and blended as a colour attachment, as @@ -111,11 +113,16 @@ class Device { bool a8_render_target = false; // VK_EXT_external_memory_host is enabled when non-zero: its minImportedHostPointerAlignment. VkDeviceSize host_pointer_alignment = 0; + bool sliced_3d_uav = false; // imageSlicedViewOf3D and robustImageAccess enabled + bool robust_image_access = false; // create(true) only: VK_KHR (else EXT) swapchain_maintenance1 and its feature enabled, with the surface half on the // instance, so a vsync swapchain can switch to IMMEDIATE or FIFO_RELAXED per present. bool swapchain_maintenance1 = false; bool shader_fma = false; // VK_KHR_shader_fma and shaderFmaFloat32 enabled (OpFmaKHR, rdna2spirv.py --fma khr) bool occlusion_query_precise = false; // occlusionQueryPrecise enabled + bool prepare_on_bind=false; + bool first_use_backend_pipelines=false; + bool cold_graphics_compile = false; bool pipeline_statistics_query = false; // pipelineStatisticsQuery enabled bool request_debug_utils = false; // set before create(): enable VK_EXT_debug_utils when the loader has it bool request_buffer_device_address = false; // set before create(): enable bufferDeviceAddress where supported @@ -176,6 +183,17 @@ class Device { bool create(bool presentation = false) { return initialize(presentation) == DeviceStatus::ready; } DeviceStatus initialize(bool presentation = false) { + return initialize_device(presentation, false, true); + } + + // Headless UAV tests can request sliced views and opt out of legacy formatless storage image features. + DeviceStatus initialize(bool enable_sliced_3d_uav, bool enable_legacy_formatless_features) { + return initialize_device(false, enable_sliced_3d_uav, enable_legacy_formatless_features); + } + +private: + DeviceStatus initialize_device(bool presentation, bool enable_sliced_3d_uav, + bool enable_legacy_formatless_features) { const auto failure = [](const char* call, VkResult result) { std::fprintf(stderr, "%s failed (VkResult %d)\n", call, static_cast(result)); return DeviceStatus::failed; @@ -335,7 +353,9 @@ class Device { std::printf("device: %s%s%s\n", chosen.deviceName, v13_.core ? "" : " (Vulkan 1.2 + KHR extensions)", validation ? " (validation on)" : ""); - VkPhysicalDeviceVulkan11Features features11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES}; + VkPhysicalDeviceVulkan13Features features13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; + VkPhysicalDeviceVulkan11Features features11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, + v13_.core ? &features13 : nullptr}; VkPhysicalDeviceVulkan12Features features12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &features11}; VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &features12}; features2_of(physical, &features); @@ -375,8 +395,18 @@ class Device { subgroup.subgroup_size_control ? "on" : "off", subgroup.compute_full_subgroups ? "on" : "off"); // shaderDrawParameters, where available: translated vertex shaders will read BaseVertex and BaseInstance once PR 436 // (zero-based VS ids) is in; harmless before. + const char* compile_mode = std::getenv("LEONIDA_PIPELINE_COMPILE"); + const bool cache_only = compile_mode && std::strcmp(compile_mode, "cache-only") == 0; + v13_.enable_pipeline_cache_control = cache_only && v13_.core && v13_.pipeline_cache_control; + cold_graphics_compile = v13_.enable_pipeline_cache_control; + prepare_on_bind = compile_mode && std::strcmp(compile_mode, "on-demand") == 0; + first_use_backend_pipelines = prepare_on_bind || (compile_mode && std::strcmp(compile_mode, "first-use") == 0); VkPhysicalDeviceVulkan11Features enable11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, v13_.enable(conditional_rendering ? &enable_conditional : nullptr)}; + if (v13_.core) { + robust_image_access = features13.robustImageAccess == VK_TRUE; + static_cast(enable11.pNext)->robustImageAccess = robust_image_access; + } enable11.shaderDrawParameters = features11.shaderDrawParameters; VkPhysicalDeviceVulkan12Features enable12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &enable11}; enable12.timelineSemaphore = VK_TRUE; @@ -430,14 +460,19 @@ class Device { sharing_.push_back(f); } VkPhysicalDeviceFeatures enable{}; + storage_image_extended_formats = features.features.shaderStorageImageExtendedFormats == VK_TRUE; + enable.shaderStorageImageExtendedFormats = storage_image_extended_formats; enable.textureCompressionBC = features.features.textureCompressionBC; // BC uploads, where available enable.shaderInt64 = features.features.shaderInt64; // translated shaders declare Int64 (index features) bc = features.features.textureCompressionBC == VK_TRUE; enable.shaderSampledImageArrayDynamicIndexing = bindless; enable.shaderStorageImageArrayDynamicIndexing = bindless; + enable.shaderStorageImageReadWithoutFormat = + enable_legacy_formatless_features && features.features.shaderStorageImageReadWithoutFormat; + enable.shaderStorageImageWriteWithoutFormat = + enable_legacy_formatless_features && features.features.shaderStorageImageWriteWithoutFormat; enable.logicOp = features.features.logicOp; // d3d12_draw_test's logic-op draw, where available enable.geometryShader = features.features.geometryShader; // d3d12_geometry_test, where available - enable.shaderInt64 = features.features.shaderInt64; // translated shaders declare Int64 for their addresses const char* conditional_extension = VK_EXT_CONDITIONAL_RENDERING_EXTENSION_NAME; // VK_EXT_host_image_copy where the device has it, for the D3D12 layer's CPU texture copies. @@ -536,6 +571,22 @@ class Device { } #endif + const char* sliced_name = VK_EXT_IMAGE_SLICED_VIEW_OF_3D_EXTENSION_NAME; + VkPhysicalDeviceImageSlicedViewOf3DFeaturesEXT sliced{ + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_SLICED_VIEW_OF_3D_FEATURES_EXT}; + if (enable_sliced_3d_uav && robust_image_access && + std::any_of(extensions.begin(), extensions.end(), [&](const auto& e) { + return std::strcmp(e.extensionName, sliced_name) == 0; + })) { + VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &sliced}; + instance_fn("vkGetPhysicalDeviceFeatures2")(physical, &query); + sliced_3d_uav = sliced.imageSlicedViewOf3D == VK_TRUE; + if (sliced_3d_uav) { + sliced.pNext = *v13_.next(); + *v13_.next() = &sliced; + } + } + #ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME // VK_KHR_shader_fma where the device has it: translated shaders built with --fma khr use OpFmaKHR. VkPhysicalDeviceShaderFmaFeaturesKHR fma_features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_FMA_FEATURES_KHR}; @@ -605,6 +656,22 @@ class Device { if (a8_render_target) device_extensions.push_back(VK_KHR_MAINTENANCE_5_EXTENSION_NAME); #endif if (host_pointer_alignment) device_extensions.push_back(VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME); + if (sliced_3d_uav) device_extensions.push_back(sliced_name); +#ifdef VK_KHR_maintenance10 + VkPhysicalDeviceMaintenance10FeaturesKHR maint10{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_10_FEATURES_KHR}; + if (v13_.core && all_queue_types && std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { + return std::strcmp(e.extensionName, VK_KHR_MAINTENANCE_10_EXTENSION_NAME) == 0; + })) { + VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &maint10}; + instance_fn("vkGetPhysicalDeviceFeatures2")(physical, &query); + maintenance10 = maint10.maintenance10 == VK_TRUE; + if (maintenance10) { + maint10.pNext = *v13_.next(); + *v13_.next() = &maint10; + device_extensions.push_back(VK_KHR_MAINTENANCE_10_EXTENSION_NAME); + } + } +#endif const char* swapchain = "VK_KHR_swapchain"; if (presentation) device_extensions.push_back(swapchain); #if defined(VK_KHR_swapchain_maintenance1) @@ -655,6 +722,7 @@ class Device { return result == VK_SUCCESS ? DeviceStatus::ready : failure("vkCreateCommandPool", result); } +public: bool depth_format_usable(VkFormat format) const { VkFormatProperties properties{}; instance_fn("vkGetPhysicalDeviceFormatProperties")(physical, format, diff --git a/runtime/test/vulkan_scratch_test.cpp b/runtime/test/vulkan_scratch_test.cpp index 8ca6a819a3..90a3fa0c6a 100644 --- a/runtime/test/vulkan_scratch_test.cpp +++ b/runtime/test/vulkan_scratch_test.cpp @@ -37,6 +37,8 @@ struct FakeVulkan { int free_memory_calls = 0; int wait_idle_calls = 0; int get_counter_calls = 0; + VkSharingMode sharing_mode = VK_SHARING_MODE_EXCLUSIVE; + std::vector families; VkResult create_buffer_result = VK_SUCCESS; VkResult bind_result = VK_SUCCESS; @@ -52,6 +54,9 @@ const VkDevice k_device = make_handle(0x100); VKAPI_ATTR VkResult VKAPI_CALL fake_create_buffer( VkDevice, const VkBufferCreateInfo* info, const VkAllocationCallbacks*, VkBuffer* out) { ++g_vk->create_buffer_calls; + g_vk->sharing_mode = info->sharingMode; + if (info->queueFamilyIndexCount) + g_vk->families.assign(info->pQueueFamilyIndices, info->pQueueFamilyIndices + info->queueFamilyIndexCount); if (g_vk->create_buffer_result != VK_SUCCESS) return g_vk->create_buffer_result; const std::uintptr_t id = g_vk->next_buffer++; g_vk->live_buffers[id] = info->size; @@ -148,7 +153,7 @@ int main() { g_vk = &vk; constexpr VkDeviceSize k_4mib = 4u << 20; { - ScratchBuffers scratch(fake_get_device_proc, k_device, fake_allocate); + ScratchBuffers scratch(fake_get_device_proc, k_device, fake_allocate, {2, 5}); EXPECT(scratch.loaded()); VkBuffer buf = VK_NULL_HANDLE; @@ -157,6 +162,7 @@ int main() { EXPECT(vk.create_buffer_calls == 0); EXPECT(scratch.get(100, buf, off)); + EXPECT(vk.sharing_mode == VK_SHARING_MODE_CONCURRENT && vk.families == std::vector({2, 5})); const VkBuffer chunk1 = buf; EXPECT(chunk1 != VK_NULL_HANDLE && off == 0); EXPECT(vk.live_buffers[reinterpret_cast(chunk1)] == k_4mib); diff --git a/runtime/test/xbox_cbv_vector_test.cpp b/runtime/test/xbox_cbv_vector_test.cpp new file mode 100644 index 0000000000..3a62c2e8dc --- /dev/null +++ b/runtime/test/xbox_cbv_vector_test.cpp @@ -0,0 +1,55 @@ +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include +#include +using namespace d3d12test; +#define CHECK(x) do { if (!(x)) { std::fprintf(stderr,"line %d: %s\n",__LINE__,#x); return 1; } } while(0) +int main(int argc,char** argv) { + vktest::Device vk; + const auto status=vk.initialize(); + if(status==vktest::DeviceStatus::unavailable)return 77; + CHECK(status==vktest::DeviceStatus::ready); + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc=vk.instance_proc;info.instance=vk.instance;info.physical=vk.physical; + info.device=vk.device;info.queue=vk.queue;info.queue_family=vk.family;info.buffer_device_address=true; + ID3D12Device* dev=nullptr; + CHECK(SUCCEEDED(rt::d3d12::create_vulkan_device(info,IID_PPV_ARGS(&dev)))); + Ref xbox; + CHECK(SUCCEEDED(rt::d3d12_xs::create_device_proxy(dev,__uuidof(ID3D12Device),reinterpret_cast(&xbox.p),true))); + rt::d3d12::set_device_outer(dev,xbox.p); + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + auto desc=buffer_desc(256); + Ref constants; + CHECK(SUCCEEDED(dev->CreateCommittedResource(&heap,D3D12_HEAP_FLAG_NONE,&desc,D3D12_RESOURCE_STATE_COMMON,nullptr,IID_PPV_ARGS(&constants.p)))); + Ref descriptors; + D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,2,D3D12_DESCRIPTOR_HEAP_FLAG_NONE,0}; + CHECK(SUCCEEDED(dev->CreateDescriptorHeap(&hd,IID_PPV_ARGS(&descriptors.p)))); + auto dst=descriptors->GetCPUDescriptorHandleForHeapStart(); + const UINT stride=dev->GetDescriptorHandleIncrementSize(hd.Type); + D3D12_CONSTANT_BUFFER_VIEW_DESC cb{constants->GetGPUVirtualAddress(),256}; + CHECK(cb.BufferLocation && cb.BufferLocation<(8ull<<20)); + xbox->CreateConstantBufferView(&cb,dst); + dev->CreateConstantBufferView(&cb,{dst.ptr+stride}); + for (unsigned variant=0;variant<2;++variant) { + leonida::gfx10::BufferWords words{}; + std::memcpy(words.data(),reinterpret_cast(dst.ptr+variant*stride),sizeof(words)); + leonida::gfx10::Buffer decoded{}; + CHECK(leonida::gfx10::decode(words,decoded) && decoded.address==cb.BufferLocation); + CHECK(decoded.stride==(variant?0u:16u) && decoded.num_records==(variant?256u:16u)); + CHECK(decoded.oob_select==(variant?leonida::gfx10::OobSelect::raw:leonida::gfx10::OobSelect::structured_with_offset)); + if(argc==3) { + std::vector image(static_cast(cb.BufferLocation)+256); + std::memcpy(image.data()+64,words.data(),sizeof(words)); + for(unsigned row=0;row<16;++row)for(unsigned col=0;col<4;++col) { + const std::uint32_t value=100+10*row+col; + std::memcpy(image.data()+cb.BufferLocation+16*row+4*col,&value,4); + } + std::ofstream file(argv[1+variant],std::ios::binary);CHECK(file.write(reinterpret_cast(image.data()),image.size())); + } + } + CHECK(!vk.validation_errors()); + std::puts("Xbox CBV has sixteen complete 16-byte rows; byte-address view retains 256 bytes"); + return 0; +} diff --git a/runtime/test/xbox_d16s8_surface_test.cpp b/runtime/test/xbox_d16s8_surface_test.cpp new file mode 100644 index 0000000000..98f33a3c1c --- /dev/null +++ b/runtime/test/xbox_d16s8_surface_test.cpp @@ -0,0 +1,48 @@ +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include +#define CHECK(v) do { if(!(v)){std::fprintf(stderr,"line %d: %s\n",__LINE__,#v);return 1;} } while(0) +using namespace d3d12test; +int main() { + vktest::Device gpu;const auto status=gpu.initialize();if(status==vktest::DeviceStatus::unavailable)return 77; + CHECK(status==vktest::DeviceStatus::ready);rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc=gpu.instance_proc;info.instance=gpu.instance;info.physical=gpu.physical;info.device=gpu.device; + info.queue=gpu.queue;info.queue_family=gpu.family;info.buffer_device_address=true; + Ref dev;CHECK(SUCCEEDED(rt::d3d12::create_vulkan_device(info,IID_PPV_ARGS(&dev.p)))); + constexpr DXGI_FORMAT format=static_cast(118); constexpr UINT extent=32; + D3D12_RESOURCE_DESC tex{};tex.Dimension=D3D12_RESOURCE_DIMENSION_TEXTURE2D;tex.Width=extent;tex.Height=extent; + tex.DepthOrArraySize=1;tex.MipLevels=1;tex.Format=format;tex.SampleDesc.Count=1;tex.Flags=D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + const auto required=dev->GetResourceAllocationInfo(0,1,&tex);CHECK(required.SizeInBytes>0 && required.SizeInBytes!=~UINT64{0} && required.Alignment); + D3D12_FEATURE_DATA_FORMAT_INFO planes{format};CHECK(SUCCEEDED(dev->CheckFeatureSupport(D3D12_FEATURE_FORMAT_INFO,&planes,sizeof(planes))) && planes.PlaneCount==2); + D3D12_HEAP_PROPERTIES def{D3D12_HEAP_TYPE_DEFAULT},rd{D3D12_HEAP_TYPE_READBACK}; + D3D12_CLEAR_VALUE clear{};clear.Format=format;clear.DepthStencil={0.25f,0x3c}; + Ref texture,readback; + CHECK(SUCCEEDED(dev->CreateCommittedResource(&def,D3D12_HEAP_FLAG_NONE,&tex,D3D12_RESOURCE_STATE_DEPTH_WRITE,&clear,IID_PPV_ARGS(&texture.p)))); + D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp[2]{};UINT rows[2]{};UINT64 bytes[2]{},total=0; + dev->GetCopyableFootprints(&tex,0,2,0,fp,rows,bytes,&total); + CHECK(bytes[0]==extent*2 && bytes[1]==extent && rows[0]==extent && rows[1]==extent && total>0); + CHECK(fp[0].Footprint.Format==DXGI_FORMAT_R16_TYPELESS && fp[1].Footprint.Format==DXGI_FORMAT_R8_TYPELESS); + auto b=buffer_desc(total);CHECK(SUCCEEDED(dev->CreateCommittedResource(&rd,D3D12_HEAP_FLAG_NONE,&b,D3D12_RESOURCE_STATE_COPY_DEST,nullptr,IID_PPV_ARGS(&readback.p)))); + Ref dsv;D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_DSV,1,D3D12_DESCRIPTOR_HEAP_FLAG_NONE,0}; + CHECK(SUCCEEDED(dev->CreateDescriptorHeap(&hd,IID_PPV_ARGS(&dsv.p))));const auto handle=dsv->GetCPUDescriptorHandleForHeapStart(); + D3D12_DEPTH_STENCIL_VIEW_DESC view{};view.Format=format;view.ViewDimension=D3D12_DSV_DIMENSION_TEXTURE2D;dev->CreateDepthStencilView(texture.p,&view,handle); + Ref queue;Ref alloc;Ref list;Ref fence; + D3D12_COMMAND_QUEUE_DESC q{};CHECK(SUCCEEDED(dev->CreateCommandQueue(&q,IID_PPV_ARGS(&queue.p)))); + CHECK(SUCCEEDED(dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT,IID_PPV_ARGS(&alloc.p)))); + CHECK(SUCCEEDED(dev->CreateCommandList(0,D3D12_COMMAND_LIST_TYPE_DIRECT,alloc.p,nullptr,IID_PPV_ARGS(&list.p)))); + CHECK(SUCCEEDED(dev->CreateFence(0,D3D12_FENCE_FLAG_NONE,IID_PPV_ARGS(&fence.p)))); + const auto both=D3D12_CLEAR_FLAG_DEPTH|D3D12_CLEAR_FLAG_STENCIL;list->ClearDepthStencilView(handle,both,.25f,0x3c,0,nullptr); + D3D12_RECT rect{8,8,24,24};list->ClearDepthStencilView(handle,both,.75f,0xa5,1,&rect); + auto bar=transition(texture.p,D3D12_RESOURCE_STATE_DEPTH_WRITE,D3D12_RESOURCE_STATE_COPY_SOURCE);list->ResourceBarrier(1,&bar); + D3D12_TEXTURE_COPY_LOCATION from{};from.pResource=texture.p;from.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;from.SubresourceIndex=1; + D3D12_TEXTURE_COPY_LOCATION to{};to.pResource=readback.p;to.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;to.PlacedFootprint=fp[1]; + list->CopyTextureRegion(&to,0,0,0,&from,nullptr);CHECK(SUCCEEDED(list->Close())); + ID3D12CommandList* batch[]={list.p};queue->ExecuteCommandLists(1,batch);CHECK(SUCCEEDED(queue->Signal(fence.p,1))); + const auto end=GetTickCount64()+3000;while(fence->GetCompletedValue()<1 && GetTickCount64()GetCompletedValue()>=1); + void* mapped=nullptr;CHECK(SUCCEEDED(readback->Map(0,nullptr,&mapped)));const auto* pixels=static_cast(mapped)+fp[1].Offset; + for(unsigned y=0;y=8&&x<24&&y>=8&&y<24?0xa5:0x3c)); + readback->Unmap(0,nullptr);CHECK(!gpu.validation_errors()); + std::printf("Xbox D16+S8 allocation %llu; both plane footprints and all %u stencil pixels passed\n",(unsigned long long)required.SizeInBytes,extent*extent); + return 0; +} diff --git a/runtime/test/xbox_depth_storage_test.cpp b/runtime/test/xbox_depth_storage_test.cpp new file mode 100644 index 0000000000..9f33db608b --- /dev/null +++ b/runtime/test/xbox_depth_storage_test.cpp @@ -0,0 +1,243 @@ +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/title_va_alias.h" +#include +#include + +using namespace d3d12test; +#define VERIFY(expr) do { if (!(expr)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #expr); return 1; } } while (0) + +namespace { +void* leased_pages{}; +unsigned released_leases{}; +void* allocate_texture_pages(std::size_t bytes, std::uint64_t) { + leased_pages = VirtualAlloc(nullptr, bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); + if (leased_pages) leonida::title_va_aliases().add_title_memory(reinterpret_cast(leased_pages), bytes); + return leased_pages; +} +void release_texture_pages(void* p, std::uint64_t) { + leonida::title_va_aliases().remove_title_memory(reinterpret_cast(p)); + VirtualFree(p, 0, MEM_RELEASE); + ++released_leases; +} +int check_lease(ID3D12Device* dev, ID3D12Device* xbox) { + D3D12_RESOURCE_DESC shape{}; + shape.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + shape.Width = shape.Height = 256; + shape.DepthOrArraySize = shape.MipLevels = 1; + shape.Format = DXGI_FORMAT_R32G32_FLOAT; + shape.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + shape.SampleDesc.Count = 1; + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + Ref pc; + VERIFY(SUCCEEDED(dev->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &shape, D3D12_RESOURCE_STATE_COMMON, + nullptr, IID_PPV_ARGS(&pc.p)))); + VERIFY(pc->GetGPUVirtualAddress() == 0); + rt::d3d12_xs::set_descriptor_heap_allocator(allocate_texture_pages, release_texture_pages); + using Create = HRESULT(WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, UINT, const D3D12_RESOURCE_DESC*, + UINT, const D3D12_CLEAR_VALUE*, const IID*, void**); + const auto create = reinterpret_cast(slot(xbox, 76)); + { + Ref console; + VERIFY(SUCCEEDED(create(xbox, &heap, 0, &shape, 0, nullptr, &__uuidof(ID3D12Resource), + reinterpret_cast(&console.p)))); + VERIFY(leased_pages && console->GetGPUVirtualAddress() == reinterpret_cast(leased_pages)); + VERIFY(released_leases == 0); + auto* words = static_cast(leased_pages); + words[0] = 0x365f; + words[256 * 256 * 2 - 1] = 0x9814; + VERIFY(console->GetGPUVirtualAddress() == reinterpret_cast(leased_pages)); + } + VERIFY(released_leases == 1); + rt::d3d12_xs::set_descriptor_heap_allocator(nullptr, nullptr); + return 0; +} +} + +int main() { + vktest::Device gpu; + const auto status = gpu.initialize(); + if (status == vktest::DeviceStatus::unavailable) return 77; + VERIFY(status == vktest::DeviceStatus::ready); + const bool with_stencil = std::getenv("LEONIDA_TEST_D16S8_UAV") != nullptr; + constexpr auto xbox_d16s8 = static_cast(118); + rt::d3d12::VulkanDeviceInfo info{}; + info.bindless = gpu.bindless; + info.bindless_partially_bound = gpu.partially_bound; + info.get_instance_proc = gpu.instance_proc; + info.instance = gpu.instance; + info.physical = gpu.physical; + info.device = gpu.device; + info.queue = gpu.queue; + info.queue_family = gpu.family; + info.buffer_device_address = true; + ID3D12Device* dev{}; + VERIFY(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&dev)))); + constexpr UINT layers = 6, width = 32; + std::array original{0x1095, 0x568c, 0x242a, 0x93db, 0xb832, 0x0e69}; + D3D12_RESOURCE_DESC tex{}; + tex.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + tex.Width = tex.Height = 768; + tex.DepthOrArraySize = layers; + tex.MipLevels = 1; + tex.SampleDesc.Count = 1; + tex.Format = with_stencil ? xbox_d16s8 : DXGI_FORMAT_R16_TYPELESS; + tex.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + D3D12_CLEAR_VALUE clear{}; + clear.Format = with_stencil ? xbox_d16s8 : DXGI_FORMAT_D16_UNORM; + clear.DepthStencil.Depth = 1; + Ref depth; + VERIFY(dev->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &tex, D3D12_RESOURCE_STATE_DEPTH_WRITE, + &clear, IID_PPV_ARGS(&depth.p)) == E_INVALIDARG && !depth.p); + Ref proxy; + VERIFY(SUCCEEDED(rt::d3d12_xs::create_device_proxy(dev, __uuidof(ID3D12Device), + reinterpret_cast(&proxy.p), true))); + rt::d3d12::set_device_outer(dev, proxy.p); + VERIFY(check_lease(dev, proxy.p) == 0); + const auto allocation = dev->GetResourceAllocationInfo(0, 1, &tex); + VERIFY(allocation.SizeInBytes >= 768u * 768 * layers * 2 && allocation.SizeInBytes != UINT64_MAX); + using XboxCreate = HRESULT(WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, UINT, const D3D12_RESOURCE_DESC*, + UINT, const D3D12_CLEAR_VALUE*, const IID*, void**); + const auto create = reinterpret_cast(slot(proxy.p, 76)); + tex.Width = tex.Height = width; + if (with_stencil) { + VERIFY(SUCCEEDED(create(proxy.p, &heap, 0, &tex, D3D12_RESOURCE_STATE_DEPTH_WRITE, &clear, + &__uuidof(ID3D12Resource), reinterpret_cast(&depth.p)))); + } else { + VERIFY(SUCCEEDED(dev->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &tex, D3D12_RESOURCE_STATE_DEPTH_WRITE, + &clear, __uuidof(ID3D12Resource), nullptr))); + VERIFY(SUCCEEDED(dev->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &tex, D3D12_RESOURCE_STATE_DEPTH_WRITE, + &clear, IID_PPV_ARGS(&depth.p)))); + } + VERIFY(depth->GetDesc().Flags == tex.Flags); + Ref dsv, uav; + D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, layers}; + VERIFY(SUCCEEDED(dev->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&dsv.p)))); + hd.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; + hd.NumDescriptors = layers + 1; + VERIFY(SUCCEEDED(dev->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&uav.p)))); + const auto slot = [&](ID3D12DescriptorHeap* h, D3D12_DESCRIPTOR_HEAP_TYPE t, UINT i) { + auto handle = h->GetCPUDescriptorHandleForHeapStart(); + handle.ptr += i * dev->GetDescriptorHandleIncrementSize(t); + return handle; + }; + Ref queue; + Ref allocator; + Ref list; + Ref fence; + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + VERIFY(SUCCEEDED(dev->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + VERIFY(SUCCEEDED(dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + VERIFY(SUCCEEDED(dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, IID_PPV_ARGS(&list.p)))); + VERIFY(SUCCEEDED(dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprints[2 * layers]{}; + UINT64 total{}; + dev->GetCopyableFootprints(&tex, 0, with_stencil ? 2 * layers : layers, 0, footprints, nullptr, nullptr, &total); + auto buffer = buffer_desc(total); + D3D12_HEAP_PROPERTIES host{D3D12_HEAP_TYPE_READBACK}; + Ref readback; + VERIFY(SUCCEEDED(dev->CreateCommittedResource(&host, D3D12_HEAP_FLAG_NONE, &buffer, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&readback.p)))); + for (UINT i = 0; i < layers; ++i) { + const auto d = slot(dsv.p, D3D12_DESCRIPTOR_HEAP_TYPE_DSV, i); + D3D12_DEPTH_STENCIL_VIEW_DESC dv{}; + dv.Format = with_stencil ? xbox_d16s8 : DXGI_FORMAT_D16_UNORM; + dv.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DARRAY; + dv.Texture2DArray.FirstArraySlice = i; + dv.Texture2DArray.ArraySize = 1; + dev->CreateDepthStencilView(depth.p, &dv, d); + const auto flags = with_stencil ? D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL : D3D12_CLEAR_FLAG_DEPTH; + list->ClearDepthStencilView(d, flags, float(original[i]) / 65535.f, UINT8(0x30 + i), 0, nullptr); + D3D12_UNORDERED_ACCESS_VIEW_DESC uv{}; + uv.Format = DXGI_FORMAT_R16_UINT; + uv.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + uv.Texture2DArray.FirstArraySlice = i; + uv.Texture2DArray.ArraySize = 1; + dev->CreateUnorderedAccessView(depth.p, nullptr, &uv, slot(uav.p, hd.Type, i)); + } + // Mix legacy and enhanced transitions. Leave slice five entirely on the depth image. + D3D12_RECT rect{3, 4, 19, 26}; + for (UINT i = 0; i < layers - 1; ++i) { + D3D12_TEXTURE_BARRIER enhanced{}; + enhanced.SyncBefore = D3D12_BARRIER_SYNC_DEPTH_STENCIL; + enhanced.SyncAfter = D3D12_BARRIER_SYNC_CLEAR_UNORDERED_ACCESS_VIEW; + enhanced.AccessBefore = D3D12_BARRIER_ACCESS_DEPTH_STENCIL_WRITE; + enhanced.AccessAfter = D3D12_BARRIER_ACCESS_UNORDERED_ACCESS; + enhanced.LayoutBefore = D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE; + enhanced.LayoutAfter = D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS; + enhanced.pResource = depth.p; + enhanced.Subresources = {0, 1, i, 1, 0, 1}; + D3D12_BARRIER_GROUP group{D3D12_BARRIER_TYPE_TEXTURE, 1}; + group.pTextureBarriers = &enhanced; + auto legacy = transition(depth.p, D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + legacy.Transition.Subresource = i; + if (i % 2) list->Barrier(1, &group); else list->ResourceBarrier(1, &legacy); + const UINT values[4]{0x8040u + i}; + list->ClearUnorderedAccessViewUint({}, slot(uav.p, hd.Type, i), depth.p, values, 1, &rect); + std::swap(legacy.Transition.StateBefore, legacy.Transition.StateAfter); + std::swap(enhanced.SyncBefore, enhanced.SyncAfter); + std::swap(enhanced.AccessBefore, enhanced.AccessAfter); + std::swap(enhanced.LayoutBefore, enhanced.LayoutAfter); + if (i % 2) list->Barrier(1, &group); else list->ResourceBarrier(1, &legacy); + } + ID3D12Resource *raw_depth = depth.p, *raw_stencil = nullptr; + if (with_stencil) { + D3D12_UNORDERED_ACCESS_VIEW_DESC st{}; + st.Format = DXGI_FORMAT_R8_UINT; + st.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + st.Texture2DArray.ArraySize = layers; + st.Texture2DArray.PlaneSlice = 1; + dev->CreateUnorderedAccessView(depth.p, nullptr, &st, slot(uav.p, hd.Type, layers)); + const auto inspected_plane = [&](UINT index) -> ID3D12Resource* { + leonida::gfx10::ImageWords words{}; + std::memcpy(words.data(), reinterpret_cast(slot(uav.p,hd.Type,index).ptr), sizeof(words)); + leonida::gfx10::Image image{}; + if (!leonida::gfx10::decode(words,image)) return nullptr; + return reinterpret_cast(rt::d3d12::uav_image_resource(depth.p,image.address)); + }; + raw_depth = inspected_plane(0); + raw_stencil = inspected_plane(layers); + VERIFY(raw_depth && raw_stencil && raw_depth != depth.p && raw_stencil != raw_depth); + } + auto ready = transition(depth.p, D3D12_RESOURCE_STATE_DEPTH_WRITE, + with_stencil ? D3D12_RESOURCE_STATE_UNORDERED_ACCESS : D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &ready); + for (UINT i = 0; i < (with_stencil ? 2 * layers : layers); ++i) { + D3D12_TEXTURE_COPY_LOCATION from{}, to{}; + from.pResource = i < layers ? raw_depth : raw_stencil; from.SubresourceIndex = i % layers; + to.pResource = readback.p; to.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; to.PlacedFootprint = footprints[i]; + list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + } + VERIFY(SUCCEEDED(list->Close())); + ID3D12CommandList* batch[]{list.p}; + queue->ExecuteCommandLists(1, batch); + VERIFY(SUCCEEDED(queue->Signal(fence.p, 1))); + const auto end = GetTickCount64() + 5000; + while (fence->GetCompletedValue() < 1 && GetTickCount64() < end) Sleep(1); + VERIFY(fence->GetCompletedValue() == 1); + void* mapped{}; + VERIFY(SUCCEEDED(readback->Map(0, nullptr, &mapped))); + auto* bytes = static_cast(mapped); + for (UINT i = 0; i < layers; ++i) for (int y = 0; y < width; ++y) for (int x = 0; x < width; ++x) { + const auto offset = footprints[i].Offset + y * footprints[i].Footprint.RowPitch + x * 2; + const auto value = *reinterpret_cast(bytes + offset); + const bool changed = i < layers-1 && x >= rect.left && x < rect.right && y >= rect.top && y < rect.bottom; + const UINT expected = changed ? 0x8040u+i : original[i]; + if (value != expected) { + std::fprintf(stderr, "slice %u pixel (%d,%d) expected %04x got %04x\n", i, x, y, expected, value); + return 1; + } + } + if (with_stencil) { + for (UINT i=0; iUnmap(0, nullptr); + VERIFY(gpu.validation_errors() == 0); + std::printf("Depth D16 / storage R16_UINT, six layers and %u exact texels\n", width * width * layers); + return 0; +} diff --git a/runtime/test/xbox_gpu_label_test.cpp b/runtime/test/xbox_gpu_label_test.cpp new file mode 100644 index 0000000000..bbf5c8f474 --- /dev/null +++ b/runtime/test/xbox_gpu_label_test.cpp @@ -0,0 +1,59 @@ +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/gpu_label_memory.h" +#include +#include +#include + +#define CHECK(x) do { if(!(x)){std::fprintf(stderr,"line %d: %s\n",__LINE__,#x);return 1;} } while(0) +using namespace d3d12test; +namespace xs=rt::d3d12_xs; +struct Data { + void* addr=VirtualAlloc(nullptr,4096,MEM_RESERVE|MEM_COMMIT,PAGE_READWRITE); + void track() {auto a=reinterpret_cast(addr);leonida::label::memory().track(a,4096,a,true);} + ~Data(){if(addr){leonida::label::memory().release_heap(reinterpret_cast(addr));VirtualFree(addr,0,MEM_RELEASE);}} +}; +using Create=HRESULT(WINAPI*)(void*,const void*,ID3D12CommandAllocator*,ID3D12PipelineState*,const IID*,void**); +using Label=void(WINAPI*)(void*,std::uintptr_t,std::uint64_t,std::uint32_t,std::uint32_t); +int main() { + _putenv_s("LEONIDA_GPU_LABELS","1"); + vktest::Device gpu;auto status=gpu.initialize();if(status==vktest::DeviceStatus::unavailable)return 77; + CHECK(status==vktest::DeviceStatus::ready); + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc=gpu.instance_proc;info.instance=gpu.instance;info.physical=gpu.physical; + info.device=gpu.device;info.queue=gpu.queue;info.queue_family=gpu.family;info.buffer_device_address=true; + ID3D12Device* inner=nullptr;CHECK(SUCCEEDED(rt::d3d12::create_vulkan_device(info,IID_PPV_ARGS(&inner)))); + Ref device;CHECK(SUCCEEDED(xs::create_device_proxy(inner,__uuidof(ID3D12Device),reinterpret_cast(&device.p),true))); + rt::d3d12::set_device_outer(inner,device.p); + Ref queue;D3D12_COMMAND_QUEUE_DESC queue_desc{}; + CHECK(SUCCEEDED(inner->CreateCommandQueue(&queue_desc,IID_PPV_ARGS(&queue.p)))); + Ref allocator;CHECK(SUCCEEDED(inner->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT,IID_PPV_ARGS(&allocator.p)))); + std::uint64_t desc[4]{};Ref list; + CHECK(SUCCEEDED(reinterpret_cast(slot(device.p,73))(device.p,desc,allocator.p,nullptr,&__uuidof(ID3D12GraphicsCommandList),reinterpret_cast(&list.p)))); + CHECK(xs::is_list_proxy(list.p));auto* real=xs::list_proxy_real_list(list.p);CHECK(real); + Data live,stale;CHECK(live.addr && stale.addr);live.track();stale.track(); + const auto base=reinterpret_cast(live.addr),old=reinterpret_cast(stale.addr); + auto* values=static_cast(live.addr);auto* retired=static_cast(stale.addr); + const auto write32=reinterpret_cast