diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index be932f1e9c..0e3eef4653 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -411,6 +411,21 @@ What is implemented (all of it testable without the game): `ClearUnorderedAccessViewFloat` packs RGB9E5 with round-half-up (clamping negative/NaN to 0 and +Inf/overflow to 65408, bumping on 512) and `ClearUnorderedAccessViewUint` writes 0, matching WARP (`d3d12_r9g9b9e5_uav_test`, `d3d12_uav_clear_test`); + - R32_UINT and R9G9B9E5 views (D3D-RGB9E5-UINT-ALIAS-VIEW): on the title's device only, the one behind the Xbox-ABI + proxy (`set_device_outer`, which `D3D12XboxCreateDevice` calls), an `R32_UINT` texture and an + `R9G9B9E5_SHAREDEXP` one that allow unordered access take shader-resource views in each other's format. The + console title packs light as RGB9E5 bits into `R32_UINT` textures from compute shaders, which cannot store that + format, and samples them through `R9G9B9E5_SHAREDEXP` views of the same texture (sky, sky and light probes, + bounced light, cloud and sky volumes); the console allows that view, desktop D3D12 refuses it, and a device + without the proxy still does (the PC tests and the WARP parity comparisons use one). Such a texture is a + `MUTABLE_FORMAT` image with `{R32_UINT, E5B9G9R9_UFLOAT_PACK32}` in its format list, both formats of Vulkan's + 32-bit compatibility class (an `R32_UINT`-backed `R9G9B9E5` UAV texture already has that list); a view in the other + format is `SAMPLED_BIT` only, and its T# names `5_9_9_9_FLOAT` (132) or `32_UINT` (20) at the texture's own + address. Unordered-access views keep the PC rule (the title stores the words through `R32_UINT`; most GPUs have no + `E5B9G9R9` storage), and so do textures without unordered access, multisampled and reserved ones: a mutable image + may lose the driver's compression, so other `R32_UINT` textures keep a plain image. Found by comparing with + fxceless/victory-fork, a fork of VIctory that fixed the same black sky, probes and fog by pointing the sampled + texture at the written one; here one image takes both views (`d3d12_rgb9e5_alias_view_test`); - the descriptor shader samples `B5G5R5A1_UNORM` through a 2D SRV. Opaque and transparent red check bit 15, and mixed-channel texels check the five-bit color fields; - `B5G5R5A1_UNORM` with `ALLOW_UNORDERED_ACCESS` on a GPU whose `VK_FORMAT_A1R5G5B5_UNORM_PACK16` lacks @@ -3615,6 +3630,7 @@ to be recovered from call sites (or the NDA GDK headers, if a developer has acce | 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, 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**. | +| `R32_UINT` / `R9G9B9E5_SHAREDEXP` views of one texture | fxceless/victory-fork (third-party, a fork of VIctory): the title writes packed light as `R32_UINT` from compute and samples it through `R9G9B9E5_SHAREDEXP` views; with two host textures everything read was black | On the title's device (the one behind the proxy) a UAV texture of either format is a mutable image listing both, and takes SRVs in the other format; a device without the proxy keeps desktop D3D12's refusal. Not run on a retail title yet. Details in ยง3.2's format list. | | Device slot 74 | The retail title's boot under `gta6rt --run`: called as `(pointer, u32, pointer)` | **Stand-in.** `d3d12_xs_device.cpp` answers `S_OK` and does nothing, for a caller in an image the guest loader mapped; the PC slot 74 is `ShaderCacheControl`, which the call does not fit and which any other caller still gets. What the console method is, and what it should do, is **Open**. | | Command-allocator slot 9 | The retail title's boot under `gta6rt --run`: called past the 9-slot PC allocator, as `(function pointer, context, ...)`; `SetAllocatorCallbackX` is the name the commit that added it uses | **Stand-in.** The allocator proxy records the callback and its context (`allocator_proxy_callback`, `allocator_proxy_callback_context`) and answers `S_OK`. **Nothing calls the callback**: the Vulkan layer backs command buffers itself. Whether the title depends on being called back is **Open**. | | Device slot 81, queue `PresentX`/`SuspendX`/`ResumeX` | XCL (GPL-2.0-only, third-party): `GetFrameStatisticsX` at device slot 81, `PresentX` at queue slot 30 (older runtime layout) or 32 (newer); `SuspendX`/`ResumeX` slots unmeasured | `set_presentation_handler` forwards 78-81 and the queue routes to a presenter (`attach_xbox_presentation`; `gta6rt` creates no `XboxPresentation` yet). Without one, slot 81 answers `S_FALSE` with a zero count (no statistics yet) and the queue slots stay refused. Moved with `LEONIDA_XS_FRAME_STATISTICS_SLOT` (3..127) and `LEONIDA_XS_PRESENT_X_SLOT` (default 30); `SuspendX` and `ResumeX` are routed only when `LEONIDA_XS_SUSPEND_X_SLOT` / `LEONIDA_XS_RESUME_X_SLOT` are set (queue slots 19..127; two routes on one slot are refused with a log). | diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 1544671726..4346e13dde 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2104,6 +2104,29 @@ if(TARGET Vulkan::Headers) target_compile_definitions(d3d12_r9g9b9e5_uav_test PRIVATE LEONIDA_TEST_CS_R9G9B9E5_UAV_SPV="${LEONIDA_TEST_CS_R9G9B9E5_UAV}") endif() + # D3D-RGB9E5-UINT-ALIAS-VIEW: on the title's device (behind the Xbox-ABI proxy) R32_UINT and R9G9B9E5_SHAREDEXP + # UAV textures take SRVs in each other's format; compute stores packed words through an R32_UINT UAV and a second + # dispatch samples them through an R9G9B9E5 SRV of the same texture. A device without the proxy keeps refusing. + add_executable(d3d12_rgb9e5_alias_view_test test/d3d12_rgb9e5_alias_view_test.cpp) + target_link_libraries(d3d12_rgb9e5_alias_view_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_rgb9e5_alias_view_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_rgb9e5_alias_view_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_rgb9e5_alias_view COMMAND d3d12_rgb9e5_alias_view_test) + set_tests_properties(d3d12_rgb9e5_alias_view PROPERTIES SKIP_RETURN_CODE 77) + if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) + # The same store-then-sample shader as d3d12_r9g9b9e5_uav_test, compiled to an output of this test's own. + set(LEONIDA_TEST_CS_RGB9E5_ALIAS ${CMAKE_CURRENT_BINARY_DIR}/generated/cs_rgb9e5_alias_view.spv) + add_custom_command( + OUTPUT ${LEONIDA_TEST_CS_RGB9E5_ALIAS} + COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${LEONIDA_TEST_CS_RGB9E5_ALIAS} + ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_r9g9b9e5_uav.comp + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_r9g9b9e5_uav.comp + COMMENT "Compiling cs_r9g9b9e5_uav.comp for d3d12_rgb9e5_alias_view_test" + VERBATIM) + target_sources(d3d12_rgb9e5_alias_view_test PRIVATE ${LEONIDA_TEST_CS_RGB9E5_ALIAS}) + target_compile_definitions(d3d12_rgb9e5_alias_view_test PRIVATE + LEONIDA_TEST_CS_RGB9E5_ALIAS_SPV="${LEONIDA_TEST_CS_RGB9E5_ALIAS}") + endif() # Debug markers as VK_EXT_debug_utils labels, and private data on every object (D3D-24). add_executable(d3d12_debug_markers_test test/d3d12_debug_markers_test.cpp) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index f1217c2365..22f8359839 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -243,6 +243,10 @@ 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; + // A texture of the title's whose shader-resource views may also take the other format of the R32_UINT / + // R9G9B9E5_SHAREDEXP pair (DeviceState::rgb9e5_alias): E5B9G9R9 for an R32_UINT texture, R32_UINT for an + // R9G9B9E5 one. Its image is mutable and lists both. UNDEFINED for every other texture. + VkFormat alias = VK_FORMAT_UNDEFINED; }; // 96-bit textures are always RGBA32 images, even where the GPU has an RGB32 one (most have none with optimal @@ -526,6 +530,15 @@ struct TextureCreateInfo { format_list.viewFormatCount = 2; format_list.pViewFormats = view_formats.data(); info.pNext = &format_list; + } else if (format.alias) { + // R32_UINT and E5B9G9R9_UFLOAT_PACK32 are both in Vulkan's 32-bit compatibility class, so one mutable + // image takes views of both. Its own format keeps every usage; a view in the other one restricts itself + // to SAMPLED_BIT (bind_image). An R32_UINT-backed R9G9B9E5 UAV texture (above) already lists the pair. + info.flags |= VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT; + view_formats = {format.format, format.alias}; + format_list.viewFormatCount = 2; + format_list.pViewFormats = view_formats.data(); + info.pNext = &format_list; } } @@ -642,6 +655,16 @@ struct DeviceState { bool rgba8_srgb_uav_emulated = false; bool bgra8_srgb_uav_emulated = false; + // The title's device: its outer identity is the Xbox-ABI proxy (rt::d3d12::set_device_outer, which + // D3D12XboxCreateDevice calls). The console's R32_UINT / R9G9B9E5 views (rgb9e5_alias), which desktop D3D12 + // refuses, are made on it only; a device without the proxy (create_vulkan_device alone, as the PC tests and the + // WARP parity comparisons use it) keeps the PC rule. + bool title_device = false; + // Whether the GPU makes the mutable images rgb9e5_alias asks for: an R32_UINT one listing E5B9G9R9_UFLOAT_PACK32, + // and an E5B9G9R9 one (R9G9B9E5 UAV textures with native storage) listing R32_UINT. Read once at device creation. + bool rgb9e5_alias_uint = false; + bool rgb9e5_alias_e5 = false; + // Cached physical-device no-attachment sample counts for D3D12_OPTIONS19. UINT no_output_sample_counts = 0; std::uint32_t f16_half_top_location = 29; @@ -864,6 +887,50 @@ struct DeviceState { return image_format_properties2(info.physical, &query, &props) == VK_SUCCESS; } + // Whether a mutable `image` image with the usages a UAV texture gets (TextureCreateInfo) can list `view` too, and + // `view` can be sampled: what rgb9e5_alias needs for the pair. + bool probe_alias_pair(VkFormat image, VkFormat view) const { + if (!image_format_properties2 || !storage_usable(image) || !sampled_usable(image) || !sampled_usable(view)) + return false; + const VkFormat view_formats[2] = {image, view}; + VkImageFormatListCreateInfo list{VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO}; + list.viewFormatCount = 2; + list.pViewFormats = view_formats; + VkPhysicalDeviceImageFormatInfo2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2, &list}; + query.format = image; + query.type = VK_IMAGE_TYPE_2D; + query.tiling = VK_IMAGE_TILING_OPTIMAL; + query.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | + VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; + if (color_attachment_usable(image)) query.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; + query.flags = VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT; + VkImageFormatProperties2 props{VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2}; + return image_format_properties2(info.physical, &query, &props) == VK_SUCCESS; + } + + // D3D-RGB9E5-UINT-ALIAS-VIEW. The console title packs light as R9G9B9E5_SHAREDEXP bits into R32_UINT textures + // from compute shaders, which cannot store that format, and samples them through R9G9B9E5_SHAREDEXP + // shader-resource views of the same texture (sky, probes, bounced light, cloud and sky volumes). The console + // allows such a view; desktop D3D12 refuses it, and so does image_descriptor on a PC device. On the title's device + // a texture of the pair gets the other format as Format::alias: its image is mutable and lists both, and its SRVs + // may name either (image_descriptor). Only textures a shader can write and read (ALLOW_UNORDERED_ACCESS, no + // DENY_SHADER_RESOURCE, single-sampled) get it: the packed light is written by compute, and a mutable image may + // lose the driver's compression, so every other R32_UINT texture keeps its plain image. The reverse view (R32_UINT + // of an R9G9B9E5 UAV texture) costs nothing where the texture is already an R32_UINT-backed image (no E5B9G9R9 + // storage, as on NVIDIA). UNDEFINED: no alias. + VkFormat rgb9e5_alias(const D3D12_RESOURCE_DESC& desc, const Format& format) const { + if (!title_device || !(desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) || + (desc.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) || desc.SampleDesc.Count > 1) + return VK_FORMAT_UNDEFINED; + if (desc.Format == DXGI_FORMAT_R32_UINT && format.format == VK_FORMAT_R32_UINT && rgb9e5_alias_uint) + return VK_FORMAT_E5B9G9R9_UFLOAT_PACK32; + if (desc.Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP && + (format.uint_backed == VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 || + (format.format == VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 && rgb9e5_alias_e5))) + return VK_FORMAT_R32_UINT; + return VK_FORMAT_UNDEFINED; + } + // The limits apply to this exact combination of format, type, tiling, usage, create flags and pNext format list. HRESULT check_image_support(const VkImageCreateInfo& create) const { VkImageFormatProperties limits{}; @@ -967,8 +1034,17 @@ struct DeviceState { return VK_SAMPLE_COUNT_1_BIT; } - // The format a texture description is created with, D24S8 and R9G9B9E5 UAV fallbacks included. + // The format a texture description is created with, D24S8 and R9G9B9E5 UAV fallbacks and the title's R32_UINT / + // R9G9B9E5 alias included. Committed and placed creation and GetResourceAllocationInfo all ask here, so the size a + // placement is measured with is the size of the image made (reserved textures drop the alias: create_sparse_image). Format texture_format(const D3D12_RESOURCE_DESC& desc) const { + Format format = base_texture_format(desc); + if (format.format != VK_FORMAT_UNDEFINED) format.alias = rgb9e5_alias(desc, format); + return format; + } + + // texture_format without the alias. + Format base_texture_format(const D3D12_RESOURCE_DESC& desc) const { if (!xr_bias_compatible(desc)) return {}; if (desc.Format == DXGI_FORMAT_A8_UNORM && (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc.SampleDesc.Count != 1 || @@ -1167,9 +1243,11 @@ struct DeviceState { // 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. + // `alias_format`: the other format of a title texture's R32_UINT / R9G9B9E5 pair (Format::alias), or UNDEFINED. 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) { + bool allow_channel_cast = false, VkFormat uint_backed = VK_FORMAT_UNDEFINED, + VkFormat alias_format = VK_FORMAT_UNDEFINED) { namespace g = leonida::gfx10; std::lock_guard lock(descriptor_mutex); if (!bindless) return false; @@ -1201,6 +1279,11 @@ struct DeviceState { 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); + // A shader-resource T# in the other format of the pair (image_descriptor made it for SRVs only): R32_UINT has + // one channel and E5B9G9R9 three, so no channel-order match exists and the pair is named outright. + const bool alias_view = !stencil && !storage && alias_format != VK_FORMAT_UNDEFINED && + image.format == g::format_from_vulkan(alias_format); + if (alias_view) view_format = alias_format; VkFormat channels_format = view_format; // whose channels the T#'s swizzle selects from // A B4G4R4A4 render target stored as RGBA8 (no 4444 format renders on this device): a 16-bit view of the // 32-bit image is not allowed, so its 4_4_4_4 T# reads the RGBA8 image (which holds the logical R, G, B, A) @@ -1230,7 +1313,8 @@ struct DeviceState { 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) { + // The image's storage and attachment usages are its own format's; E5B9G9R9 has neither on most GPUs. + if (uint_backed || alias_view) { sampled_usage.usage = VK_IMAGE_USAGE_SAMPLED_BIT; view_info.pNext = &sampled_usage; } @@ -1891,6 +1975,7 @@ class Resource final } bool has_castable_formats() const { return !castable_formats_.empty(); } VkFormat uint_backed() const { return uint_backed_; } // Format::uint_backed + VkFormat alias_format() const { return alias_format_; } // Format::alias: the title's R32_UINT / R9G9B9E5 pair 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 @@ -2164,7 +2249,11 @@ class Resource final HRESULT create_sparse_image() { auto& vk = device_.context->vk; - const auto format = device_.texture_format(desc_); + auto format = device_.texture_format(desc_); + // A reserved texture keeps the PC rule for R32_UINT / R9G9B9E5 views: sparse residency on a mutable image is + // a combination nothing has measured yet, and whether the title packs light into reserved textures is not + // known. + format.alias = VK_FORMAT_UNDEFINED; TextureCreateInfo create(desc_, format, false); create.info.flags |= VK_IMAGE_CREATE_SPARSE_BINDING_BIT | VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT | VK_IMAGE_CREATE_SPARSE_ALIASED_BIT; @@ -2251,17 +2340,20 @@ class Resource final view_formats_ = castable; if (std::find(view_formats_.begin(), view_formats_.end(), format.format) == view_formats_.end()) view_formats_.push_back(format.format); - if (format.uint_backed) { - // An unsigned-backed UAV texture needs both its formats whatever the list names (TextureCreateInfo). - for (VkFormat pair : {format.format, format.uint_backed}) - if (std::find(view_formats_.begin(), view_formats_.end(), pair) == view_formats_.end()) - view_formats_.push_back(pair); - } + // An unsigned-backed UAV texture needs both its formats whatever the list names, and so does a texture + // of the title's R32_UINT / R9G9B9E5 pair (TextureCreateInfo). + for (VkFormat pair : {format.uint_backed, format.alias}) + if (pair && std::find(view_formats_.begin(), view_formats_.end(), pair) == view_formats_.end()) + view_formats_.push_back(pair); info.flags |= VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT; create.format_list.viewFormatCount = std::uint32_t(view_formats_.size()); create.format_list.pViewFormats = view_formats_.data(); - create.format_list.pNext = info.pNext; - info.pNext = &create.format_list; + // TextureCreateInfo may have chained this same list already (an unsigned-backed or aliased texture): + // chaining it again would point it at itself. + if (info.pNext != &create.format_list) { + create.format_list.pNext = info.pNext; + info.pNext = &create.format_list; + } } const std::uint32_t samples = info.samples; // Textures the CPU reads and writes (WriteToSubresource/ReadFromSubresource) copy on the host when they can. @@ -2367,6 +2459,7 @@ class Resource final binding.sampled_in_general = device_.bindless != nullptr; format_ = format.format; uint_backed_ = format.uint_backed; + alias_format_ = format.alias; aspects_ = format.aspects; image_address_ = device_.next_image_address.fetch_add(256); binding_ = binding; @@ -2717,6 +2810,7 @@ class Resource final std::vector view_formats_; // creation-time castable list; empty means no restriction std::vector castable_formats_; // the same list as the application gave it VkFormat uint_backed_ = VK_FORMAT_UNDEFINED; + VkFormat alias_format_ = VK_FORMAT_UNDEFINED; // Format::alias std::uint64_t image_address_ = 0; // what a T# names the texture by bool rgb96_ = false; VkImageAspectFlags aspects_ = 0; @@ -4781,9 +4875,9 @@ class ShaderCacheSession final std::shared_ptr store_; }; -// 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) { +// The T# of a view: what the shader gets to know about it, in the structure the console's shaders read. `storage`: +// an unordered-access view. False (with a log) for a view set 0 cannot show yet. +bool image_descriptor(const Resource& resource, const TextureView& view, bool storage, leonida::gfx10::Image& out) { namespace g = leonida::gfx10; const D3D12_RESOURCE_DESC& desc = resource.desc(); // Plane 1 of a depth-stencil texture is its stencil, viewed as X24_TYPELESS_G8_UINT (D24S8) or @@ -4835,7 +4929,13 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida // 4_4_4_4 as on the console, and bind_image views the RGBA8 image with the 4444 view's channels. const bool rgba8_4444 = desc.Format == DXGI_FORMAT_B4G4R4A4_UNORM && resource.format() == VK_FORMAT_R8G8B8A8_UNORM; if (rgba8_4444) named = VK_FORMAT_A4R4G4B4_UNORM_PACK16; - if (volume) { + // A shader-resource view of a title texture of the R32_UINT / R9G9B9E5_SHAREDEXP pair in the pair's other format + // (Format::alias, DeviceState::rgb9e5_alias): the image is mutable and lists it. Unordered-access views keep the + // PC rule: the title stores the packed words through R32_UINT, and most GPUs have no E5B9G9R9 storage. + const bool alias_view = !storage && !stencil && resource.alias_format() != VK_FORMAT_UNDEFINED && + ((desc.Format == DXGI_FORMAT_R32_UINT && view.format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP) || + (desc.Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP && view.format == DXGI_FORMAT_R32_UINT)); + if (volume && !alias_view) { 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) @@ -4881,7 +4981,9 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida log_once("view format from another typeless family (B8G8R8X8 and B8G8R8A8):", int(view.format)); return false; } - if ((view.format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP) != (desc.Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP)) { + // The PC rule, which desktop D3D12 applies; the console lifts it for the title's R32_UINT / R9G9B9E5 pair. + if ((view.format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP) != (desc.Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP) && + !alias_view) { log_once("incompatible R9G9B9E5 view format:", int(view.format)); return false; } @@ -4917,6 +5019,8 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida view_format = named; } else if (code && rgba8_4444) { view_format = resource.format(); + } else if (code && alias_view) { + view_format = named; // the other format of the pair, which the image lists (R32_UINT has no RGB channels) } else if (code) { view_format = g::vulkan_view_format(resource_format, code, resource.has_view_format_list()); } @@ -5179,6 +5283,8 @@ class Device final state_.probe_uint_backed_uav(VK_FORMAT_R8G8B8A8_SRGB, VK_FORMAT_R8G8B8A8_UNORM); state_.bgra8_srgb_uav_emulated = state_.probe_uint_backed_uav(VK_FORMAT_B8G8R8A8_SRGB, VK_FORMAT_B8G8R8A8_UNORM); + state_.rgb9e5_alias_uint = state_.probe_alias_pair(VK_FORMAT_R32_UINT, VK_FORMAT_E5B9G9R9_UFLOAT_PACK32); + state_.rgb9e5_alias_e5 = state_.probe_alias_pair(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, VK_FORMAT_R32_UINT); memory_properties(info.physical, &state_.memory); { char text[4] = {}; @@ -5673,7 +5779,11 @@ class Device final } bool bind_sampler(const leonida::gfx10::SamplerWords& words) { return state_.bind_sampler(words); } void own(const OwnedRuntime& owned) { owned_ = owned; } - void set_outer(IUnknown* outer) { outer_ = outer; } + // Set right after creation, before the title calls anything (D3D12XboxCreateDevice); DeviceState::title_device. + void set_outer(IUnknown* outer) { + outer_ = outer; + state_.title_device = rt::d3d12_xs::is_device_proxy(outer); + } UINT STDMETHODCALLTYPE GetNodeCount() override { return 1; } @@ -8631,11 +8741,11 @@ class Device final 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; + if (!image_descriptor(resource, view, storage, 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()); + resource.uint_backed(), resource.alias_format()); if (registered && resource.sparse_image()) state_.context->note_shader_image(resource.id()); if (leonida::gfx10::multisampled(image.type) && !registered) return; std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); diff --git a/runtime/test/d3d12_rgb9e5_alias_view_test.cpp b/runtime/test/d3d12_rgb9e5_alias_view_test.cpp new file mode 100644 index 0000000000..c49e5679e6 --- /dev/null +++ b/runtime/test/d3d12_rgb9e5_alias_view_test.cpp @@ -0,0 +1,592 @@ +// D3D-RGB9E5-UINT-ALIAS-VIEW: the console title packs light into R32_UINT textures as R9G9B9E5_SHAREDEXP bits from +// compute shaders, which cannot store that format, and samples them through R9G9B9E5_SHAREDEXP shader-resource views +// of the same texture (sky, sky and light probes, bounced light, cloud and sky volumes). Desktop D3D12 refuses such a +// view and so did the layer; the console allows it. On the title's device, the Vulkan device behind the Xbox-ABI proxy +// (rt::d3d12::set_device_outer), a texture of that pair that allows unordered access is a mutable image listing both +// formats, and takes a shader-resource view in the other one (docs/d3d12_vulkan.md, "R32_UINT and R9G9B9E5 views"). +// +// Exercises, on the title's device: +// 1. R32_UINT UAV textures from device slot 76 (committed, the title's call), CreatePlacedResource and a 3D +// committed one: an R9G9B9E5_SHAREDEXP SRV of each is a 5_9_9_9_FLOAT T# (132) that set 0 registered. An +// R9G9B9E5 UAV of the same texture, and an R9G9B9E5 SRV of an R32_UINT texture without unordered access, stay +// null descriptors. +// 2. The reverse: an R32_UINT SRV of an R9G9B9E5_SHAREDEXP UAV texture is a 32_UINT T# (20), registered; an +// R32_UINT UAV of it stays null. +// 3. A castable-format list as well (CreateCommittedResource3 with {R32_FLOAT}): R9G9B9E5 and R32_FLOAT SRVs. +// 4. On the GPU: one compute dispatch stores 16 packed R9G9B9E5 words through the R32_UINT UAV (set-0 storage +// bindings 9 and 4), a second samples them through the R9G9B9E5 SRV (binding 0), and every float equals +// uav_clear::decode of its word; CopyTextureRegion then reads the 16 words back unchanged. +// And on a device without the proxy (the PC path, which the WARP parity tests use): the same views stay null. +// +// Synthetic data only; no game files. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. +#include "vk_test_device.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/gfx10_descriptors.h" +#include "../src/uav_clear.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +namespace g = leonida::gfx10; + +// Device slot 76 as the title calls it: the PC CreateCommittedResource's arguments with the IID by pointer. +using XboxCreateResourceFn = HRESULT(WINAPI*)(void* device, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS, + const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_STATES, + const D3D12_CLEAR_VALUE*, const IID*, void**); + +void* slot(void* object, unsigned index) { return (*reinterpret_cast(object))[index]; } + +template +struct Ref { + T* p = nullptr; + ~Ref() { reset(); } + void reset() { + if (p) p->Release(); + p = nullptr; + } + T* operator->() const { return p; } +}; + +constexpr UINT kSize = 4; // every 2D texture here is 4x4: 16 texels, one dispatch of 16 lanes + +D3D12_RESOURCE_DESC texture(DXGI_FORMAT format, D3D12_RESOURCE_FLAGS flags, + D3D12_RESOURCE_DIMENSION dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D, + UINT16 depth = 1) { + D3D12_RESOURCE_DESC d{}; + d.Dimension = dimension; + d.Width = kSize; + d.Height = kSize; + d.DepthOrArraySize = depth; + d.MipLevels = 1; + d.Format = format; + d.SampleDesc.Count = 1; + d.Flags = flags; + return d; +} + +D3D12_SHADER_RESOURCE_VIEW_DESC srv(DXGI_FORMAT format, bool volume = false) { + D3D12_SHADER_RESOURCE_VIEW_DESC v{}; + v.Format = format; + v.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + if (volume) { + v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; + v.Texture3D.MipLevels = 1; + } else { + v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + v.Texture2D.MipLevels = 1; + } + return v; +} + +D3D12_UNORDERED_ACCESS_VIEW_DESC uav(DXGI_FORMAT format) { + D3D12_UNORDERED_ACCESS_VIEW_DESC v{}; + v.Format = format; + v.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; + return v; +} + +// CPU descriptor slots in a heap of the PC device behind the proxy; the proxy's view calls write them unchanged +// (the handles are not in a title-backed heap, so translate_cpu_descriptor_handle keeps them). +struct Slots { + Ref heap; + std::byte* base = nullptr; + UINT step = 0; + + bool create(ID3D12Device* device, UINT count) { + const D3D12_DESCRIPTOR_HEAP_DESC desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, count}; + if (FAILED(device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&heap.p)))) return false; + base = reinterpret_cast(heap->GetCPUDescriptorHandleForHeapStart().ptr); + step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + return base && step >= sizeof(g::ImageWords); + } + D3D12_CPU_DESCRIPTOR_HANDLE handle(UINT i) const { + return {reinterpret_cast(base + std::size_t(i) * step)}; + } + // The slot for a view call, filled with a pattern first so that a call which writes nothing does not pass for a + // null view. + D3D12_CPU_DESCRIPTOR_HANDLE at(UINT i) const { + std::memset(base + std::size_t(i) * step, 0xaa, step); + return handle(i); + } + g::ImageWords words(UINT i) const { + g::ImageWords w{}; + std::memcpy(w.data(), base + std::size_t(i) * step, sizeof(w)); + return w; + } + bool null(UINT i) const { + const auto* p = reinterpret_cast(base + std::size_t(i) * step); + return std::all_of(p, p + step, [](std::uint8_t b) { return b == 0; }); + } +}; + +// The T# in slot `i` decodes with GFX10 format `format` and is in set 0's hash table (not the fallback, index 0). +bool written_and_registered(ID3D12Device* device, const Slots& slots, UINT i, std::uint32_t format) { + const g::ImageWords words = slots.words(i); + g::Image image{}; + if (!g::decode(words, image) || image.format != format) { + std::fprintf(stderr, "slot %u: no T# of format %u (decoded %u)\n", i, format, unsigned(image.format)); + return false; + } + std::uint32_t key[8]; + std::memcpy(key, words.data(), sizeof(key)); + if (!rt::d3d12::bindless_hash_lookup(device, key)) { + std::fprintf(stderr, "slot %u: the T# is not in set 0's hash table\n", i); + return false; + } + return true; +} + +#ifdef LEONIDA_TEST_CS_RGB9E5_ALIAS_SPV +bool read_spirv(const char* path, std::vector& out) { + std::ifstream file(path, std::ios::binary | std::ios::ate); + if (!file) return false; + const auto size = file.tellg(); + if (size <= 0 || size % 4 != 0) return false; + out.resize(std::size_t(size) / 4); + file.seekg(0); + return bool(file.read(reinterpret_cast(out.data()), size)); +} + +// The push constants of test/glsl/cs_r9g9b9e5_uav.comp. +struct ShaderParams { + std::uint32_t tsharp[8]; + std::uint32_t ssharp[4]; + std::uint32_t mode; // 0: store packed words through the T#'s storage views; 1: sample through its sampled view + std::uint32_t width; + std::uint32_t height; + std::uint32_t pad; +}; + +// Stores `words` through the UAV T# (an R32_UINT storage view), then samples the texture through the SRV T# (an +// E5B9G9R9 sampled view of the same image) into `out`, four floats a texel. Both against the layer's set 0. +bool store_then_sample(vktest::Device& d, VkDescriptorSet set0, VkDescriptorSetLayout set0_layout, + const g::ImageWords& uav_words, const g::ImageWords& srv_words, const g::SamplerWords& sampler, + const std::array& words, std::array& out) { + std::vector code; + if (!read_spirv(LEONIDA_TEST_CS_RGB9E5_ALIAS_SPV, code)) return false; + void* in_ptr = nullptr; + void* out_ptr = nullptr; + const VkBuffer in_buf = d.buffer(sizeof(words), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &in_ptr); + const VkBuffer out_buf = d.buffer(sizeof(out), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &out_ptr); + if (!in_buf || !out_buf) return false; + std::memcpy(in_ptr, words.data(), sizeof(words)); + + const auto create_dsl = d.fn("vkCreateDescriptorSetLayout"); + const auto destroy_dsl = d.fn("vkDestroyDescriptorSetLayout"); + const auto create_pool = d.fn("vkCreateDescriptorPool"); + const auto destroy_pool = d.fn("vkDestroyDescriptorPool"); + const auto alloc_sets = d.fn("vkAllocateDescriptorSets"); + const auto update_sets = d.fn("vkUpdateDescriptorSets"); + const auto create_layout = d.fn("vkCreatePipelineLayout"); + const auto destroy_layout = d.fn("vkDestroyPipelineLayout"); + const auto create_module = d.fn("vkCreateShaderModule"); + const auto destroy_module = d.fn("vkDestroyShaderModule"); + const auto create_pipelines = d.fn("vkCreateComputePipelines"); + const auto destroy_pipeline = d.fn("vkDestroyPipeline"); + + VkDescriptorSetLayout set1_layout = VK_NULL_HANDLE; + VkDescriptorPool pool = VK_NULL_HANDLE; + VkPipelineLayout layout = VK_NULL_HANDLE; + VkShaderModule module = VK_NULL_HANDLE; + VkPipeline pipeline = VK_NULL_HANDLE; + const auto done = [&](bool ok) { + if (pipeline) destroy_pipeline(d.device, pipeline, nullptr); + if (module) destroy_module(d.device, module, nullptr); + if (layout) destroy_layout(d.device, layout, nullptr); + if (pool) destroy_pool(d.device, pool, nullptr); + if (set1_layout) destroy_dsl(d.device, set1_layout, nullptr); + return ok; + }; + + // Set 1: the packed words in, the sampled floats out. + const VkDescriptorSetLayoutBinding bindings[2] = { + {0, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}, + {1, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}}; + VkDescriptorSetLayoutCreateInfo set1_info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; + set1_info.bindingCount = 2; + set1_info.pBindings = bindings; + if (create_dsl(d.device, &set1_info, nullptr, &set1_layout) != VK_SUCCESS) return done(false); + const VkDescriptorPoolSize pool_size{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 2}; + VkDescriptorPoolCreateInfo pool_info{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; + pool_info.maxSets = 1; + pool_info.poolSizeCount = 1; + pool_info.pPoolSizes = &pool_size; + if (create_pool(d.device, &pool_info, nullptr, &pool) != VK_SUCCESS) return done(false); + VkDescriptorSetAllocateInfo alloc_info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; + alloc_info.descriptorPool = pool; + alloc_info.descriptorSetCount = 1; + alloc_info.pSetLayouts = &set1_layout; + VkDescriptorSet set1 = VK_NULL_HANDLE; + if (alloc_sets(d.device, &alloc_info, &set1) != VK_SUCCESS) return done(false); + const VkDescriptorBufferInfo buffers[2] = {{in_buf, 0, sizeof(words)}, {out_buf, 0, sizeof(out)}}; + VkWriteDescriptorSet writes[2]{}; + for (UINT i = 0; i < 2; ++i) { + writes[i] = {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}; + writes[i].dstSet = set1; + writes[i].dstBinding = i; + writes[i].descriptorCount = 1; + writes[i].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + writes[i].pBufferInfo = &buffers[i]; + } + update_sets(d.device, 2, writes, 0, nullptr); + + const VkDescriptorSetLayout set_layouts[2] = {set0_layout, set1_layout}; + const VkPushConstantRange range{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(ShaderParams)}; + VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + layout_info.setLayoutCount = 2; + layout_info.pSetLayouts = set_layouts; + layout_info.pushConstantRangeCount = 1; + layout_info.pPushConstantRanges = ⦥ + if (create_layout(d.device, &layout_info, nullptr, &layout) != VK_SUCCESS) return done(false); + VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + module_info.codeSize = code.size() * sizeof(std::uint32_t); + module_info.pCode = code.data(); + if (create_module(d.device, &module_info, nullptr, &module) != VK_SUCCESS) return done(false); + VkComputePipelineCreateInfo pipeline_info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; + pipeline_info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; + pipeline_info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; + pipeline_info.stage.module = module; + pipeline_info.stage.pName = "main"; + pipeline_info.layout = layout; + if (create_pipelines(d.device, VK_NULL_HANDLE, 1, &pipeline_info, nullptr, &pipeline) != VK_SUCCESS) + return done(false); + + const bool ok = d.run([&](VkCommandBuffer cb) { + const auto bind_pipeline = d.fn("vkCmdBindPipeline"); + const auto bind_sets = d.fn("vkCmdBindDescriptorSets"); + const auto push = d.fn("vkCmdPushConstants"); + const auto dispatch = d.fn("vkCmdDispatch"); + const auto barrier = d.fn("vkCmdPipelineBarrier"); + const VkDescriptorSet sets[2] = {set0, set1}; + bind_pipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline); + bind_sets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, layout, 0, 2, sets, 0, nullptr); + + ShaderParams store{}; + std::memcpy(store.tsharp, uav_words.data(), sizeof(store.tsharp)); + std::memcpy(store.ssharp, sampler.data(), sizeof(store.ssharp)); + store.mode = 0; + store.width = store.height = kSize; + push(cb, layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(store), &store); + dispatch(cb, 1, 1, 1); + VkMemoryBarrier written{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + written.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; + written.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; + barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, &written, 0, + nullptr, 0, nullptr); + + ShaderParams sample = store; + std::memcpy(sample.tsharp, srv_words.data(), sizeof(sample.tsharp)); + sample.mode = 1; + push(cb, layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(sample), &sample); + dispatch(cb, 1, 1, 1); + VkMemoryBarrier host{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + host.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; + host.dstAccessMask = VK_ACCESS_HOST_READ_BIT; + barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &host, 0, nullptr, 0, + nullptr); + return true; + }); + if (ok) std::memcpy(out.data(), out_ptr, sizeof(out)); + return done(ok); +} +#endif + +// Runs `record` on a fresh direct list of `device` and waits for it. +template +bool execute(ID3D12Device* device, Record&& record) { + Ref queue; + Ref allocator; + Ref list; + Ref fence; + const D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + if (FAILED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p))) || + FAILED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))) || + FAILED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, + IID_PPV_ARGS(&list.p))) || + FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))) + return false; + record(list.p); + if (FAILED(list->Close())) return false; + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + if (rt::d3d12::last_execute_result(queue.p) != leonida::ReplayResult::success) return false; + return SUCCEEDED(queue->Signal(fence.p, 1)) && SUCCEEDED(fence->SetEventOnCompletion(1, nullptr)); +} + +rt::d3d12::VulkanDeviceInfo device_info(const vktest::Device& d) { + 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 = d.buffer_device_address; + info.bindless = d.bindless; + 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; + return info; +} + +} // namespace + +int main() { + vktest::Device d; + d.request_buffer_device_address = true; // heaps, so placed textures, need the GPU address arena + const auto status = d.initialize(); + if (status == vktest::DeviceStatus::unavailable) return 77; + if (status != vktest::DeviceStatus::ready) return 1; + if (!d.bindless) { + std::printf("SKIP: the device has no bindless set 0, which the views are registered in\n"); + return 77; + } + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + constexpr auto uint32 = DXGI_FORMAT_R32_UINT; + constexpr auto rgb9e5 = DXGI_FORMAT_R9G9B9E5_SHAREDEXP; + constexpr auto unordered = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + constexpr std::uint32_t kFormat32Uint = 20, kFormat5999Float = 132; // GFX10_FORMAT_32_UINT, _5_9_9_9_FLOAT + D3D12_RESOURCE_ALLOCATION_INFO title_allocation{}, pc_allocation{}; + + { + // The title's device: the Vulkan device behind the Xbox-ABI proxy, as D3D12XboxCreateDevice makes it. + const rt::d3d12::VulkanDeviceInfo info = device_info(d); + 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); // the proxy now owns `inner` + Slots slots; + EXPECT(slots.create(inner, 16)); + + // 1. R32_UINT UAV textures: slot 76 (committed, the title's own call shape), placed, and a volume. + const IID resource_iid = __uuidof(ID3D12Resource); + D3D12_RESOURCE_DESC light_desc = texture(uint32, unordered); + light_desc.Layout = static_cast(0x101); // the Xbox tiled layout word slot 76 replaces + Ref light; + EXPECT(SUCCEEDED(reinterpret_cast(slot(device.p, 76))( + device.p, &default_heap, D3D12_HEAP_FLAG_NONE, &light_desc, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + nullptr, &resource_iid, reinterpret_cast(&light.p)))); + device->CreateUnorderedAccessView(light.p, nullptr, nullptr, slots.at(0)); + device->CreateShaderResourceView(light.p, nullptr, slots.at(1)); + const D3D12_SHADER_RESOURCE_VIEW_DESC packed_view = srv(rgb9e5); + device->CreateShaderResourceView(light.p, &packed_view, slots.at(2)); + EXPECT(written_and_registered(device.p, slots, 0, kFormat32Uint)); + EXPECT(written_and_registered(device.p, slots, 1, kFormat32Uint)); + EXPECT(written_and_registered(device.p, slots, 2, kFormat5999Float)); + g::Image own{}, packed{}; // one texture, two formats: the same address, RGB1 for the packed view + EXPECT(g::decode(slots.words(1), own) && g::decode(slots.words(2), packed)); + EXPECT(packed.address == own.address && packed.swizzle == g::channels_rgb); + const D3D12_UNORDERED_ACCESS_VIEW_DESC packed_store = uav(rgb9e5); + device->CreateUnorderedAccessView(light.p, nullptr, &packed_store, slots.at(3)); + EXPECT(slots.null(3)); // shaders store the words through R32_UINT; no typed R9G9B9E5 store is made up + + const D3D12_RESOURCE_DESC placed_desc = texture(uint32, unordered); + if (d.buffer_device_address) { // heaps live in the GPU address arena + D3D12_HEAP_DESC heap_desc{}; + heap_desc.SizeInBytes = 1 << 20; + heap_desc.Properties = default_heap; + heap_desc.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; + heap_desc.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES; + Ref heap; + EXPECT(SUCCEEDED(device->CreateHeap(&heap_desc, IID_PPV_ARGS(&heap.p)))); + Ref placed; + EXPECT(SUCCEEDED(device->CreatePlacedResource(heap.p, 0, &placed_desc, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, + IID_PPV_ARGS(&placed.p)))); + device->CreateShaderResourceView(placed.p, &packed_view, slots.at(4)); + EXPECT(written_and_registered(device.p, slots, 4, kFormat5999Float)); + } else { + std::printf("no bufferDeviceAddress, so no heaps: the placed texture was not checked\n"); + } + + const D3D12_RESOURCE_DESC volume_desc = texture(uint32, unordered, D3D12_RESOURCE_DIMENSION_TEXTURE3D, 4); + Ref volume; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &volume_desc, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, + IID_PPV_ARGS(&volume.p)))); + const D3D12_SHADER_RESOURCE_VIEW_DESC packed_volume = srv(rgb9e5, true); + device->CreateShaderResourceView(volume.p, &packed_volume, slots.at(5)); + EXPECT(written_and_registered(device.p, slots, 5, kFormat5999Float)); + + // Only textures a shader can write are listed with both formats; a plain R32_UINT texture keeps the PC rule. + const D3D12_RESOURCE_DESC plain_desc = texture(uint32, D3D12_RESOURCE_FLAG_NONE); + Ref plain; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &plain_desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&plain.p)))); + device->CreateShaderResourceView(plain.p, &packed_view, slots.at(6)); + EXPECT(slots.null(6)); + + // 2. The reverse: an R32_UINT SRV of an R9G9B9E5 UAV texture reads its raw bits. + D3D12_RESOURCE_DESC packed_desc = texture(rgb9e5, unordered); + Ref packed_texture; + EXPECT(SUCCEEDED(reinterpret_cast(slot(device.p, 76))( + device.p, &default_heap, D3D12_HEAP_FLAG_NONE, &packed_desc, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + nullptr, &resource_iid, reinterpret_cast(&packed_texture.p)))); + const D3D12_SHADER_RESOURCE_VIEW_DESC bits_view = srv(uint32); + device->CreateShaderResourceView(packed_texture.p, &bits_view, slots.at(7)); + EXPECT(written_and_registered(device.p, slots, 7, kFormat32Uint)); + const D3D12_UNORDERED_ACCESS_VIEW_DESC bits_store = uav(uint32); + device->CreateUnorderedAccessView(packed_texture.p, nullptr, &bits_store, slots.at(8)); + EXPECT(slots.null(8)); + + // 3. A castable-format list as well: both its format and the packed one are views. + Ref device10; + EXPECT(SUCCEEDED(inner->QueryInterface(IID_PPV_ARGS(&device10.p)))); + D3D12_RESOURCE_DESC1 listed_desc{}; + std::memcpy(&listed_desc, &placed_desc, sizeof(placed_desc)); + const DXGI_FORMAT castable[] = {DXGI_FORMAT_R32_FLOAT}; + Ref listed; + EXPECT(SUCCEEDED(device10->CreateCommittedResource3(&default_heap, D3D12_HEAP_FLAG_NONE, &listed_desc, + D3D12_BARRIER_LAYOUT_COMMON, nullptr, nullptr, 1, + castable, IID_PPV_ARGS(&listed.p)))); + device->CreateShaderResourceView(listed.p, &packed_view, slots.at(9)); + EXPECT(written_and_registered(device.p, slots, 9, kFormat5999Float)); + const D3D12_SHADER_RESOURCE_VIEW_DESC float_view = srv(DXGI_FORMAT_R32_FLOAT); + device->CreateShaderResourceView(listed.p, &float_view, slots.at(10)); + EXPECT(written_and_registered(device.p, slots, 10, 22)); // GFX10_FORMAT_32_FLOAT + title_allocation = inner->GetResourceAllocationInfo(0, 1, &placed_desc); + +#ifdef LEONIDA_TEST_CS_RGB9E5_ALIAS_SPV + // 4. On the GPU. The list's clear puts the texture in its unordered-access layout and brings set 0 up to date. + const UINT zero[4] = {}; + const g::ImageWords store_words = slots.words(0), sample_words = slots.words(2); + device->CreateUnorderedAccessView(light.p, nullptr, nullptr, slots.at(11)); + EXPECT(execute(inner, [&](ID3D12GraphicsCommandList* list) { + list->ClearUnorderedAccessViewUint({0}, slots.handle(11), light.p, zero, 0, nullptr); + })); + Ref sampler_heap; + const D3D12_DESCRIPTOR_HEAP_DESC sampler_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 1}; + EXPECT(SUCCEEDED(inner->CreateDescriptorHeap(&sampler_heap_desc, IID_PPV_ARGS(&sampler_heap.p)))); + D3D12_SAMPLER_DESC point{}; + point.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT; + point.AddressU = point.AddressV = point.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; + const D3D12_CPU_DESCRIPTOR_HANDLE sampler_slot = sampler_heap->GetCPUDescriptorHandleForHeapStart(); + device->CreateSampler(&point, sampler_slot); + g::SamplerWords sampler{}; + std::memcpy(sampler.data(), reinterpret_cast(sampler_slot.ptr), sizeof(sampler)); + // A second execute brings the sampler into set 0 too. + EXPECT(execute(inner, [](ID3D12GraphicsCommandList*) {})); + + // Shared exponents from 2^-24 to the largest finite value, and mantissas that tell the channels apart. + const std::array words = { + 0x94010040u, 0x79010100u, 0x80000100u, 0x80020000u, 0x84000000u, 0xb0080190u, 0xf80001ffu, 0xffffffffu, + 0x08000100u, 0x00000100u, 0x00000001u, 0x7556ab55u, 0x840e0501u, 0x98040100u, 0x00000000u, 0x88040280u, + }; + std::array sampled{}; + EXPECT(store_then_sample(d, rt::d3d12::bindless_set(device.p), rt::d3d12::bindless_set_layout(device.p), + store_words, sample_words, sampler, words, sampled)); + for (UINT i = 0; i < 16; ++i) { + leonida::uav_clear::Element element{}; + element.size = 4; + std::memcpy(element.bytes.data(), &words[i], 4); + VkClearColorValue want{}; + EXPECT(leonida::uav_clear::decode(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, element, want)); // RGB, alpha 1 + for (UINT c = 0; c < 4; ++c) { // exact: every value is a 9-bit mantissa times a power of two + const float got = sampled[i * 4 + c]; + if (got != want.float32[c]) { + std::fprintf(stderr, "texel %u channel %u: sampled %g, want %g (word 0x%08x)\n", i, c, got, + want.float32[c], words[i]); + return 1; + } + } + } + + // The same memory: the words the shader stored are what the R32_UINT texture holds. + Ref readback; + D3D12_RESOURCE_DESC readback_desc{}; + readback_desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + readback_desc.Width = 256 * kSize; + readback_desc.Height = 1; + readback_desc.DepthOrArraySize = 1; + readback_desc.MipLevels = 1; + readback_desc.SampleDesc.Count = 1; + readback_desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + EXPECT(SUCCEEDED(inner->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + EXPECT(execute(inner, [&](ID3D12GraphicsCommandList* list) { + D3D12_RESOURCE_BARRIER to_source{}; + to_source.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + to_source.Transition = {light.p, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE}; + list->ResourceBarrier(1, &to_source); + D3D12_TEXTURE_COPY_LOCATION to{readback.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + to.PlacedFootprint = {0, {uint32, kSize, kSize, 1, 256}}; + D3D12_TEXTURE_COPY_LOCATION from{light.p, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + })); + void* mapped = nullptr; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); + for (UINT i = 0; i < 16; ++i) { + std::uint32_t word = 0; + std::memcpy(&word, static_cast(mapped) + (i / kSize) * 256 + (i % kSize) * 4, 4); + if (word != words[i]) { + std::fprintf(stderr, "texel %u: the texture holds 0x%08x, the shader stored 0x%08x\n", i, word, + words[i]); + return 1; + } + } + readback->Unmap(0, nullptr); + std::printf("GPU: 16/16 packed words stored through the R32_UINT UAV sampled back through the R9G9B9E5 SRV " + "as their RGB9E5 floats, and read back unchanged\n"); +#else + std::printf("glslangValidator was not found at configure time: the GPU store-and-sample part did not run\n"); +#endif + } + + { + // 5. The PC path: a device without the proxy keeps the PC rule, so the WARP parity tests see what they did. + const rt::d3d12::VulkanDeviceInfo info = device_info(d); + Ref device; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p)))); + Slots slots; + EXPECT(slots.create(device.p, 4)); + const D3D12_RESOURCE_DESC light_desc = texture(uint32, unordered); + Ref light; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &light_desc, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, + IID_PPV_ARGS(&light.p)))); + const D3D12_SHADER_RESOURCE_VIEW_DESC packed_view = srv(rgb9e5); + device->CreateShaderResourceView(light.p, &packed_view, slots.at(0)); + EXPECT(slots.null(0)); + device->CreateShaderResourceView(light.p, nullptr, slots.at(1)); + EXPECT(written_and_registered(device.p, slots, 1, kFormat32Uint)); // its own format still is a view + const D3D12_RESOURCE_DESC packed_desc = texture(rgb9e5, unordered); + Ref packed_texture; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &packed_desc, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, + IID_PPV_ARGS(&packed_texture.p)))); + const D3D12_SHADER_RESOURCE_VIEW_DESC bits_view = srv(uint32); + device->CreateShaderResourceView(packed_texture.p, &bits_view, slots.at(2)); + EXPECT(slots.null(2)); + pc_allocation = device->GetResourceAllocationInfo(0, 1, &light_desc); + } + std::printf("4x4 R32_UINT UAV texture: %llu bytes on the title's device (both formats listed), %llu on a PC one\n", + static_cast(title_allocation.SizeInBytes), + static_cast(pc_allocation.SizeInBytes)); + + if (d.validation_errors()) { + std::fprintf(stderr, "%u Vulkan validation errors\n", d.validation_errors()); + return 1; + } + std::printf("d3d12_rgb9e5_alias_view_test: OK (0 validation errors)\n"); + return 0; +}