From baa202d241337ddf4bdf1f0e871a23a219f53dc2 Mon Sep 17 00:00:00 2001 From: Celegans12 <53881228+Celegans12@users.noreply.github.com> Date: Tue, 6 Oct 2026 06:32:01 +0200 Subject: [PATCH] feat(agc): implement 10_11_11 unorm images through 32-bit uint views GFX10 image format 30 (10_11_11_UNORM: X and Y are unorm11 in bits 0-21, Z is unorm10 in bits 22-31, per Mesa's gfx10 tables) has no Vulkan format, so its sampled and storage descriptors threw at decode. Format 30 now takes the R32_UINT route of 10_11_11_UINT: the driver binds the raw dwords as R32_UINT and the shader extracts each field and converts it with the buffer format helpers (NormalizeFormatComponent on loads, EmitFormatStoreComponent on stores); DST_SEL 1 reads 1.0f. Samples, gathers, LOD queries, 16-bit data and loads or stores whose DST_SEL names the missing W channel throw. Converted textures are now viewed with an identity component mapping, since the shader applies DST_SEL itself: a 10_11_11_UINT view whose X selector was not X lost the packed dword. DCC clear codes 0001 and 1110 of a converted texture throw instead of filling one R32_UINT channel. --- .../Graphics/include/TextureFormat.hpp | 1 + .../Graphics/src/DccMetadata.cpp | 3 + .../Graphics/src/ShaderResources.cpp | 11 +- .../Graphics/src/TextureFormat.cpp | 6 +- .../libSceAgcDriver/tests/TextureFormat.cpp | 30 ++ .../tests/execution/ImageConvertedUnorm.cpp | 295 ++++++++++++++++++ .../RdnaDecoder/src/RdnaDescriptorFormat.cpp | 5 +- .../SpirvBackend/src/SpirvImageEmitter.cpp | 46 ++- docs/dev/TechnicalDebt.md | 2 + 9 files changed, 387 insertions(+), 12 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/execution/ImageConvertedUnorm.cpp diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/TextureFormat.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/TextureFormat.hpp index b23f2f1da..aca377fc8 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/TextureFormat.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/TextureFormat.hpp @@ -14,6 +14,7 @@ VkFormat ResolveTextureFormat(std::uint32_t guestFormat); std::optional FindGuestTextureFormat(VkFormat format, std::uint32_t elementBytes); std::optional FindGuestColorTargetFormat(VkFormat format, std::uint32_t elementBytes); std::uint32_t BytesPerElement(std::uint32_t guestFormat); +bool IsConvertedTextureFormat(std::uint32_t guestFormat); bool IsBlockCompressed(std::uint32_t guestFormat); std::uint32_t BlockWidth(std::uint32_t guestFormat); std::uint32_t BlockHeight(std::uint32_t guestFormat); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/DccMetadata.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/DccMetadata.cpp index 1f8c2d1d8..463093477 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/DccMetadata.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/DccMetadata.cpp @@ -15,6 +15,8 @@ #include #include #include +#include +#include #include #include @@ -427,6 +429,7 @@ DccKeys textureClearKeys(const GuestTextureResource& resource, std::uint64_t gue if (resource.dccAddress == 0) return DccKeys::Uncompressed; const auto keys = readDccKeys(resource.dccAddress, guestBytes, memoized); if (keys == DccKeys::Uncompressed) return keys; + if (IsConvertedTextureFormat(resource.format) && (keys == DccKeys::Clear0001 || keys == DccKeys::Clear1110)) throw std::runtime_error(std::string("AGC graphics: DCC clear code ") + DccKeysName(keys) + " of converted texture format " + std::to_string(resource.format) + " is not implemented"); std::byte probe[16]{}; if (!IsDccClear(keys) || !FillDccClear(ResolveTextureFormat(resource.format), keys, resource.dccAlphaOnMsb, std::span(probe, std::min(sizeof(probe), BytesPerElement(resource.format))))) { static std::mutex reportedMutex; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index d6d69c35f..dd1147c6f 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -48,6 +48,11 @@ VkComponentSwizzle ComponentSwizzleFor(std::uint8_t dstSel) { } } +VkComponentMapping ViewComponents(const GuestTextureResource& resource) { + if (IsConvertedTextureFormat(resource.format)) return {VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G, VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A}; + return {ComponentSwizzleFor(resource.dstSelX), ComponentSwizzleFor(resource.dstSelY), ComponentSwizzleFor(resource.dstSelZ), ComponentSwizzleFor(resource.dstSelW)}; +} + // Sampled textures are reused across draws and dispatches while their guest bytes are unchanged; a // byte copy of the guest surface validates each reuse, so CPU or GPU writes to it force a re-upload. // The key is everything a lookup matches: the device, the eight descriptor words and the swizzle. @@ -1697,7 +1702,7 @@ bool ShaderResources::Revalidate(std::span shaders, ProofR for (std::uint32_t element = 0; element < binding.count; ++element) { const auto words = std::span(binding.guestDescriptor).subspan(static_cast(element) * elementWords, elementWords); const auto resource = DecodeTextureResource(words); - const VkComponentMapping components{ComponentSwizzleFor(resource.dstSelX), ComponentSwizzleFor(resource.dstSelY), ComponentSwizzleFor(resource.dstSelZ), ComponentSwizzleFor(resource.dstSelW)}; + const VkComponentMapping components = ViewComponents(resource); if (textureIndex >= textures.size() || cachedTexture(context, words, resource, components, 0, !binding.imageDepthCompare.empty() && binding.imageDepthCompare.at(element)) != textures[textureIndex]) return false; ++textureIndex; } @@ -2438,7 +2443,7 @@ bool ShaderResources::precollectImages() { record.decoded = true; if (record.sampled && !noRecords && words.size() == 8 && (binding.imageDepthCompare.empty() || !binding.imageDepthCompare.at(element))) { std::copy(words.begin(), words.end(), record.words.begin()); - record.components = {ComponentSwizzleFor(record.resource.dstSelX), ComponentSwizzleFor(record.resource.dstSelY), ComponentSwizzleFor(record.resource.dstSelZ), ComponentSwizzleFor(record.resource.dstSelW)}; + record.components = ViewComponents(record.resource); record.keys = TextureClearKeys(record.resource, record.guestBytes); auto& cache = Textures(); std::lock_guard lock(cache.mutex); @@ -2526,7 +2531,7 @@ void ShaderResources::resolveImageBinding(const ShaderRecompiler::DescriptorBind const auto resource = record != nullptr && record->decoded ? record->resource : DecodeTextureResource(words); const bool firstLayer = binding.imageShape == ShaderRecompiler::DescriptorImageShape::Image2D && resource.dimension == TextureDimension::k2DArray; if (!firstLayer && !MatchesGuestDimension(*binding.imageShape, resource.dimension)) throw std::runtime_error("AGC graphics: guest texture dimension disagrees with the shader's declared image shape (shape " + std::to_string(static_cast(*binding.imageShape)) + ", dimension " + std::to_string(static_cast(resource.dimension)) + ")"); - const VkComponentMapping components{ComponentSwizzleFor(resource.dstSelX), ComponentSwizzleFor(resource.dstSelY), ComponentSwizzleFor(resource.dstSelZ), ComponentSwizzleFor(resource.dstSelW)}; + const VkComponentMapping components = ViewComponents(resource); const auto guestBytes = record != nullptr && record->decoded ? record->guestBytes : DescribeSurface(resource).guestBytes; std::shared_ptr texture; if (record != nullptr && record->texture != nullptr) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/TextureFormat.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/TextureFormat.cpp index 62bde9b8c..108bdbe5d 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/TextureFormat.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/TextureFormat.cpp @@ -92,7 +92,7 @@ constexpr auto MakeFormatLookupTable() { constexpr auto kFormatLookupTable = MakeFormatLookupTable(); std::uint32_t remapGuestFormat(std::uint32_t guestFormat) { - return guestFormat == 34 ? 20 : guestFormat; + return guestFormat == 30 || guestFormat == 34 ? 20 : guestFormat; } const FormatEntry& findFormatEntry(std::uint32_t guestFormat) { @@ -119,6 +119,10 @@ std::uint32_t BytesPerElement(std::uint32_t guestFormat) { return findFormatEntry(guestFormat).bytesPerElement; } +bool IsConvertedTextureFormat(std::uint32_t guestFormat) { + return remapGuestFormat(guestFormat) != guestFormat; +} + std::optional FindGuestColorTargetFormat(VkFormat format, std::uint32_t elementBytes) { switch (format) { case VK_FORMAT_B8G8R8A8_UNORM: format = VK_FORMAT_R8G8B8A8_UNORM; break; diff --git a/core/libs/prx/libSceAgcDriver/tests/TextureFormat.cpp b/core/libs/prx/libSceAgcDriver/tests/TextureFormat.cpp index 6fa05cd45..3973bfa18 100644 --- a/core/libs/prx/libSceAgcDriver/tests/TextureFormat.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/TextureFormat.cpp @@ -1,5 +1,10 @@ #include "GraphicsTests.hpp" +#include "prx/libSceAgcDriver/Graphics/include/DccMetadata.hpp" +#include "prx/libSceAgcDriver/Graphics/include/GuestTextureResource.hpp" #include "prx/libSceAgcDriver/Graphics/include/TextureFormat.hpp" +#include "RdnaDecoder/RdnaDescriptorFormat.hpp" +#include +#include #include #include @@ -18,6 +23,23 @@ void reject(TAction action, std::string_view reason) { throw std::runtime_error(std::string("expected texture format rejection: ") + std::string(reason)); } +void convertedDccClearTests() { + alignas(64) std::array keys{}; + GuestTextureResource resource{}; + resource.dccAddress = reinterpret_cast(keys.data()); + const auto read = [&](std::uint32_t format, std::uint8_t key) { + keys.fill(key); + resource.format = format; + return TextureClearKeys(resource, keys.size() * 256u); + }; + for (const std::uint32_t format : {30u, 34u}) { + reject([&] { read(format, 0x40); }, "DCC clear code 0001 of converted texture format " + std::to_string(format)); + reject([&] { read(format, 0x80); }, "DCC clear code 1110 of converted texture format " + std::to_string(format)); + Require(read(format, 0x00) == DccKeys::Clear0000 && read(format, 0xc0) == DccKeys::Clear1111, "converted texture format " + std::to_string(format) + " must keep its 0000 and 1111 DCC clear codes"); + } + Require(read(20, 0x40) == DccKeys::Clear0001 && read(20, 0x80) == DccKeys::Clear1110, "format 20 must keep its 0001 and 1110 DCC clear codes"); +} + } void RunTextureFormatTests() { @@ -45,10 +67,18 @@ void RunTextureFormatTests() { Require(ResolveTextureFormat(34) == ResolveTextureFormat(20), "format 34 must remap to format 20"); Require(BytesPerElement(34) == BytesPerElement(20), "remapped format 34 must share the width of format 20"); + Require(ResolveTextureFormat(30) == ResolveTextureFormat(20), "format 30 must remap to format 20"); + Require(BytesPerElement(30) == 4u, "remapped format 30 must be four bytes wide"); + for (std::uint32_t format = 0; format < 512u; ++format) { + const auto remapped = static_cast(ShaderRecompiler::RemapTextureFormat(static_cast(format))); + if (remapped == format) continue; + Require(ResolveTextureFormat(format) == ResolveTextureFormat(remapped), "guest format " + std::to_string(format) + " must resolve like the format the recompiler remaps it to"); + } reject([] { ResolveTextureFormat(0); }, "unsupported guest texture format"); reject([] { ResolveTextureFormat(183); }, "unsupported guest texture format"); reject([] { ResolveTextureFormat(9999); }, "unsupported guest texture format"); reject([] { BytesPerElement(2); }, "unsupported guest texture format"); reject([] { IsBlockCompressed(200); }, "unsupported guest texture format"); + convertedDccClearTests(); } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageConvertedUnorm.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageConvertedUnorm.cpp new file mode 100644 index 000000000..376473101 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageConvertedUnorm.cpp @@ -0,0 +1,295 @@ +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" +#include "prx/libc/include/GuestAllocations.hpp" +#include "Recompiler.hpp" +#include "VulkanTestDevice.hpp" +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::Require; +using ShaderRecompiler::ShaderStage; + +constexpr std::uint32_t Threads = 32; +constexpr std::uint32_t LoadWidth = 2048; +constexpr std::uint32_t LoadGroups = LoadWidth / Threads; +constexpr std::uint32_t Type2D = 9; +constexpr std::uint32_t UnormFormat = 30; +constexpr std::uint32_t UintFormat = 34; +constexpr std::uint32_t SwizzleXYZ1 = 0x3acu; +constexpr std::uint32_t SwizzleXZY1 = 0x374u; +constexpr std::uint32_t SwizzleZYX1 = 0x32eu; +constexpr std::uint32_t SwizzleX011 = 0x244u; +constexpr std::uint32_t SwizzleYXZ1 = 0x3a5u; +constexpr std::uint32_t SwizzleXYZW = 0xfacu; +constexpr std::uint32_t D16 = 0x80000000u; +constexpr std::uint32_t DivisionUlps = 3; +constexpr std::size_t BlockBytes = 65536; +constexpr std::size_t RoundTripOffset = 16384; +constexpr std::size_t StoreOffset = 32768; +constexpr std::array PointSampler{0x00000092u, 0x00fff000u, 0u, 0u}; + +alignas(256) std::array Output{}; +alignas(256) std::array Input{}; + +constexpr std::array LoadCode(std::uint32_t dmask, std::uint32_t d16) { + return { + 0x7e080218u, 0x343c0885u, 0x4a3c3d00u, 0x34063c84u, 0x7e3e0280u, 0x7e140280u, 0x7e160280u, 0x7e180280u, + 0x7e1a0280u, 0xf0001008u | (dmask << 8u), 0x00010a1eu | d16, 0xbf8c3f70u, 0xe0781000u, 0x80000a03u, 0xbf810000u, + }; +} + +constexpr std::array StoreCode(std::uint32_t dmask, std::uint32_t d16) { + return { + 0x34060084u, 0xe0381000u, 0x80030a03u, 0x7e3c0300u, 0x7e3e0280u, 0xbf8c3f70u, 0xf0201008u | (dmask << 8u), 0x00010a1eu | d16, + 0xbf810000u, + }; +} + +constexpr std::array SamplerCode(std::uint32_t word0) { + return { + 0x34060084u, 0x7e280280u, 0x7e2a0280u, word0, 0x00610a14u, 0xbf8c3f70u, 0xe0781000u, 0x80000a03u, + 0xbf810000u, + }; +} + +alignas(256) constexpr std::array RoundTrip{ + 0x7e080218u, 0x343c0885u, 0x4a3c3d00u, 0x7e3e0280u, 0xf0001708u, 0x00010a1eu, 0xbf8c3f70u, 0xf0201708u, + 0x00040a1eu, 0xbf810000u, +}; + +alignas(256) constexpr auto LoadXyzw = LoadCode(0xfu, 0u); +alignas(256) constexpr auto LoadXyz = LoadCode(0x7u, 0u); +alignas(256) constexpr auto LoadXy = LoadCode(0x3u, 0u); +alignas(256) constexpr auto LoadD16 = LoadCode(0xfu, D16); +alignas(256) constexpr auto StoreXyz = StoreCode(0x7u, 0u); +alignas(256) constexpr auto StoreXz = StoreCode(0x5u, 0u); +alignas(256) constexpr auto StoreD16 = StoreCode(0x7u, D16); +alignas(256) constexpr auto SampleLz = SamplerCode(0xf09c0f08u); +alignas(256) constexpr auto Gather4Lz = SamplerCode(0xf11c0108u); +alignas(256) constexpr auto GetLod = SamplerCode(0xf1800308u); + +constexpr std::array StoreValues{ + 0x00000000u, 0x3f800000u, 0x3f000000u, 0x3eaaaaabu, 0x80000000u, 0xbf800000u, + 0x40000000u, 0x7f800000u, 0x7fc00000u, 0x000116c2u, 0x3f7fbe77u, +}; + +class GuestBlock { +public: + GuestBlock() { +#ifdef _WIN32 + block = static_cast(VirtualAlloc(nullptr, BlockBytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); +#else + block = static_cast(std::aligned_alloc(BlockBytes, BlockBytes)); +#endif + Require(block != nullptr, "image converted unorm: cannot allocate the guest block"); + GuestAllocations::Mutation().Add(block, BlockBytes, true, true); + } + + ~GuestBlock() { + GuestAllocations::Mutation().Remove(block); +#ifdef _WIN32 + VirtualFree(block, 0, MEM_RELEASE); +#else + std::free(block); +#endif + } + + GuestBlock(const GuestBlock&) = delete; + GuestBlock& operator=(const GuestBlock&) = delete; + + std::uint8_t* Data() { return block; } + +private: + std::uint8_t* block = nullptr; +}; + +std::string Hex(std::uint32_t value) { + char text[16]; + std::snprintf(text, sizeof(text), "0x%08x", value); + return text; +} + +std::array BufferDescriptor(const void* data, std::uint32_t bytes) { + const auto address = reinterpret_cast(data); + return {static_cast(address), static_cast((address >> 32u) & 0xffffu), bytes, 0x01016facu}; +} + +std::array TextureDescriptor(const void* data, std::uint32_t format, std::uint32_t swizzle, std::uint32_t width) { + const auto address = static_cast(reinterpret_cast(data)); + return { + static_cast(address >> 8u), + static_cast((address >> 40u) & 0xffu) | (format << 20u) | (((width - 1u) & 3u) << 30u), + (width - 1u) >> 2u, + swizzle | (Type2D << 28u), + 0u, + 0u, + 0u, + 0u, + }; +} + +std::uint32_t LoadTexel(std::uint32_t index) { + return index | ((2047u - index) << 11u) | ((index & 1023u) << 22u); +} + +std::uint32_t Field(std::uint32_t texel, std::uint32_t component) { + return component == 2u ? texel >> 22u : (texel >> (component * 11u)) & 2047u; +} + +struct Expected { + std::uint32_t bits; + std::uint32_t ulps; +}; + +Expected Selected(std::uint32_t texel, std::uint32_t swizzle, std::uint32_t component, bool unorm) { + const auto selector = (swizzle >> (component * 3u)) & 7u; + if (selector == 0u) return {0u, 0u}; + if (selector == 1u) return {unorm ? 0x3f800000u : 1u, 0u}; + const auto field = Field(texel, selector - 4u); + const auto maximum = selector == 6u ? 1023u : 2047u; + if (!unorm) return {field, 0u}; + return {std::bit_cast(static_cast(static_cast(field) / maximum)), field == 0u || field == maximum ? 0u : DivisionUlps}; +} + +std::uint32_t StoreField(std::uint32_t bits, std::uint32_t maximum) { + const auto value = std::bit_cast(bits); + if (!(value > 0.0f)) return 0u; + if (value >= 1.0f) return maximum; + return static_cast(std::nearbyint(static_cast(value) * maximum)); +} + +void Run(AgcDriver::VulkanDevice& device, std::span code, const std::array& texture, const std::array& extra, std::uint32_t groups, const std::array& target = {}) { + Output.fill(0xdeadbeefu); + std::vector userData(24, 0u); + const auto output = BufferDescriptor(Output.data(), static_cast(Output.size() * 4u)); + std::copy(output.begin(), output.end(), userData.begin()); + std::copy(texture.begin(), texture.end(), userData.begin() + 4); + std::copy(extra.begin(), extra.end(), userData.begin() + 12); + std::copy(target.begin(), target.end(), userData.begin() + 16); + const std::array memory{{{reinterpret_cast(code.data()), std::as_bytes(code)}}}; + const ShaderRecompiler::ShaderComputeStageInfo compute{{Threads, 1, 1}, 0u, {true, false, false}, false, 1}; + ShaderRecompiler::RecompileRequest request{ + {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, + {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, + device.Target(), + {0, 0, 0, 128} + }; + request.useCache = false; + const auto result = ShaderRecompiler::Recompile(request); + device.Dispatch(result, groups, 1, 1, {}, reinterpret_cast(code.data())); + device.WaitIdle(); +} + +void CheckLoad(AgcDriver::VulkanDevice& device, const std::uint8_t* texels, std::span code, std::uint32_t dmask, std::uint32_t format, std::uint32_t swizzle, const std::string& what) { + Run(device, code, TextureDescriptor(texels, format, swizzle, LoadWidth), {}, LoadGroups); + for (std::uint32_t index = 0; index < LoadWidth; ++index) { + std::uint32_t slot = 0; + for (std::uint32_t component = 0; component < 4u; ++component) { + if (((dmask >> component) & 1u) == 0u) continue; + const auto expected = Selected(LoadTexel(index), swizzle, component, format == UnormFormat); + const auto actual = Output[index * 4u + slot++]; + const auto distance = actual > expected.bits ? actual - expected.bits : expected.bits - actual; + Require(distance <= expected.ulps, what + ": texel " + std::to_string(index) + " component " + std::to_string(component) + " is " + Hex(actual) + ", expected " + Hex(expected.bits) + " within " + std::to_string(expected.ulps) + " ULP"); + } + } +} + +void CheckRoundTrip(AgcDriver::VulkanDevice& device, std::uint8_t* texels) { + auto* target = texels + RoundTripOffset; + std::fill(target, target + LoadWidth * 4u, static_cast(0xa5u)); + Run(device, RoundTrip, TextureDescriptor(texels, UnormFormat, SwizzleXYZ1, LoadWidth), {}, LoadGroups, TextureDescriptor(target, UnormFormat, SwizzleXYZ1, LoadWidth)); + AgcDriver::Graphics::StorageTexture::FlushPending(reinterpret_cast(target), LoadWidth * 4u, nullptr, "test"); + device.WaitIdle(); + for (std::uint32_t index = 0; index < LoadWidth; ++index) { + std::uint32_t actual = 0; + std::memcpy(&actual, target + index * 4u, 4u); + Require(actual == LoadTexel(index), "image_load then image_store: texel " + std::to_string(index) + " is " + Hex(actual) + ", expected " + Hex(LoadTexel(index))); + } +} + +void CheckStore(AgcDriver::VulkanDevice& device, std::uint8_t* texels, std::span code, std::uint32_t dmask, const std::string& what) { + std::fill(texels, texels + Threads * 4u, static_cast(0xa5u)); + Input.fill(0u); + std::array expected{}; + for (std::uint32_t tid = 0; tid < Threads; ++tid) { + const std::array values{StoreValues[tid % 11u], StoreValues[(tid + 4u) % 11u], StoreValues[(tid + 8u) % 11u]}; + std::uint32_t slot = 0; + for (std::uint32_t component = 0; component < 3u; ++component) { + if (((dmask >> component) & 1u) == 0u) continue; + Input[tid * 4u + slot++] = values[component]; + expected[tid] |= StoreField(values[component], component == 2u ? 1023u : 2047u) << (component * 11u); + } + } + Run(device, code, TextureDescriptor(texels, UnormFormat, SwizzleXYZ1, Threads), BufferDescriptor(Input.data(), static_cast(Input.size() * 4u)), 1); + AgcDriver::Graphics::StorageTexture::FlushPending(reinterpret_cast(texels), Threads * 4u, nullptr, "test"); + device.WaitIdle(); + for (std::uint32_t tid = 0; tid < Threads; ++tid) { + std::uint32_t actual = 0; + std::memcpy(&actual, texels + tid * 4u, 4u); + Require(actual == expected[tid], what + ": texel " + std::to_string(tid) + " is " + Hex(actual) + ", expected " + Hex(expected[tid])); + } +} + +void RequireRefused(AgcDriver::VulkanDevice& device, std::span code, const std::uint8_t* texels, std::uint32_t swizzle, const std::array& extra, const std::string& reason, const std::string& what) { + std::string refusal; + try { + Run(device, code, TextureDescriptor(texels, UnormFormat, swizzle, LoadWidth), extra, 1); + } catch (const std::exception& error) { + refusal = error.what(); + } + Require(refusal.find(reason) != std::string::npos, what + " of a 10_11_11_UNORM image was not refused: " + refusal); +} + +} + +int main() { + try { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + GuestBlock block; + auto* texels = block.Data(); + for (std::uint32_t index = 0; index < LoadWidth; ++index) { + const auto texel = LoadTexel(index); + std::memcpy(texels + index * 4u, &texel, 4u); + } + CheckLoad(*device, texels, LoadXyzw, 0xfu, UnormFormat, SwizzleXYZ1, "image_load dmask:0xf X Y Z 1"); + CheckLoad(*device, texels, LoadXy, 0x3u, UnormFormat, SwizzleXZY1, "image_load dmask:0x3 X Z Y 1"); + CheckLoad(*device, texels, LoadXyzw, 0xfu, UnormFormat, SwizzleZYX1, "image_load dmask:0xf Z Y X 1"); + CheckLoad(*device, texels, LoadXyzw, 0xfu, UnormFormat, SwizzleX011, "image_load dmask:0xf X 0 1 1"); + CheckLoad(*device, texels, LoadXyz, 0x7u, UintFormat, SwizzleYXZ1, "image_load of 10_11_11_UINT dmask:0x7 Y X Z 1"); + CheckRoundTrip(*device, texels); + CheckStore(*device, texels + StoreOffset, StoreXyz, 0x7u, "image_store dmask:0x7"); + CheckStore(*device, texels + StoreOffset, StoreXz, 0x5u, "image_store dmask:0x5"); + RequireRefused(*device, SampleLz, texels, SwizzleXYZ1, PointSampler, "samples or gathers a converted unorm image", "image_sample_lz"); + RequireRefused(*device, Gather4Lz, texels, SwizzleXYZ1, PointSampler, "samples or gathers a converted unorm image", "image_gather4_lz"); + RequireRefused(*device, GetLod, texels, SwizzleXYZ1, PointSampler, "queries the level of detail of a converted unorm image", "image_get_lod"); + RequireRefused(*device, LoadD16, texels, SwizzleXYZ1, {}, "converted unorm image with 16-bit data", "image_load d16"); + RequireRefused(*device, StoreD16, texels + StoreOffset, SwizzleXYZ1, BufferDescriptor(Input.data(), static_cast(Input.size() * 4u)), "converted unorm image with 16-bit data", "image_store d16"); + RequireRefused(*device, LoadXyzw, texels, SwizzleXYZW, {}, "selects a channel the converted image format does not have", "image_load with DST_SEL X Y Z W"); + RequireRefused(*device, StoreXyz, texels + StoreOffset, SwizzleXYZW, BufferDescriptor(Input.data(), static_cast(Input.size() * 4u)), "selects a channel the converted image format does not have", "image_store with DST_SEL X Y Z W"); + std::puts("image converted unorm tests passed"); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/core/shader/recompiler/RdnaDecoder/src/RdnaDescriptorFormat.cpp b/core/shader/recompiler/RdnaDecoder/src/RdnaDescriptorFormat.cpp index acc3b3135..2d68f1a1a 100644 --- a/core/shader/recompiler/RdnaDecoder/src/RdnaDescriptorFormat.cpp +++ b/core/shader/recompiler/RdnaDecoder/src/RdnaDescriptorFormat.cpp @@ -13,7 +13,7 @@ struct FormatInfo { bool sint32; }; -constexpr std::array kFormatInfoTable {{ +constexpr std::array kFormatInfoTable {{ {IrBufferFormat::Format8UNorm, true, false, false}, {IrBufferFormat::Format8SNorm, false, false, false}, {IrBufferFormat::Format8UInt, true, true, false}, @@ -34,6 +34,7 @@ constexpr std::array kFormatInfoTable {{ {IrBufferFormat::Format16_16UInt, true, true, false}, {IrBufferFormat::Format16_16SInt, true, false, true}, {IrBufferFormat::Format16_16Float, true, false, false}, + {IrBufferFormat::Format11_11_10UNorm, true, true, false}, {IrBufferFormat::Format11_11_10UInt, true, true, false}, {IrBufferFormat::Format11_11_10Float, true, false, false}, {IrBufferFormat::Format10_10_10_2UNorm, true, false, false}, @@ -118,7 +119,7 @@ IrTextureNumericClass SampledTextureNumericClass(IrBufferFormat format) { } IrBufferFormat RemapTextureFormat(IrBufferFormat format) { - return format == IrBufferFormat::Format11_11_10UInt ? IrBufferFormat::Format32UInt : format; + return format == IrBufferFormat::Format11_11_10UNorm || format == IrBufferFormat::Format11_11_10UInt ? IrBufferFormat::Format32UInt : format; } std::uint32_t DepthBitsTextureWidth(std::uint32_t word1, std::uint32_t word3) { diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp index 419bf78ed..30a34d432 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp @@ -417,24 +417,43 @@ SpirvBufferFormatInfo ImageConversionFormat(const ImageResource& image) { return {}; } const auto info = GetFormatInfo(format); - if (SampledTextureNumericClass(format) != IrTextureNumericClass::Uint || RemapTextureFormat(format) == format || info.type != SpirvFormatComponentType::Uint || !info.packedBitfield || info.byteSize != sizeof(std::uint32_t) || info.componentCount == 0u || info.componentCount > 4u) { - throw std::runtime_error("image conversion format is not a packed 32-bit unsigned integer format"); + if (SampledTextureNumericClass(format) != IrTextureNumericClass::Uint || RemapTextureFormat(format) == format || (info.type != SpirvFormatComponentType::Uint && info.type != SpirvFormatComponentType::Unorm) || !info.packedBitfield || info.byteSize != sizeof(std::uint32_t) || info.componentCount == 0u || info.componentCount > 4u) { + throw std::runtime_error("image conversion format is not a packed 32-bit unsigned integer or unorm format"); } return info; } +void RequireConvertedUnormAccess(SpirvValueEmitContext& ctx, const ImageEmitAccess& access, const SpirvBufferFormatInfo& info) { + if (access.mem.dataBits == 16u) { + ctx.Fail(access.inst, "reads or writes a converted unorm image with 16-bit data, which is not implemented"); + } + for (std::uint32_t component = 0; component < 4u; component++) { + const auto selector = (access.image.shaderSwizzle >> (component * 3u)) & 7u; + if (selector >= 4u && selector - 4u >= info.componentCount) { + ctx.Fail(access.inst, "selects a channel the converted image format does not have"); + } + } +} + std::uint32_t UnpackImageTexel(SpirvValueEmitContext& ctx, const ImageEmitAccess& access, std::uint32_t texel) { auto& state = ctx.state; const auto info = ImageConversionFormat(access.image); if (info.format == IrBufferFormat::Invalid) { return texel; } + const bool unorm = info.type == SpirvFormatComponentType::Unorm; + if (unorm) { + RequireConvertedUnormAccess(ctx, access, info); + } const auto packed = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, TypeU32(state), packed, texel, 0u); std::uint32_t components[4] = {ConstantU32(state, 0), ConstantU32(state, 0), ConstantU32(state, 0), ConstantU32(state, 0)}; for (std::uint32_t component = 0; component < info.componentCount; component++) { components[component] = state.module.AllocateId(); state.module.AddFunction(spv::OpBitFieldUExtract, TypeU32(state), components[component], packed, ConstantU32(state, info.componentBitOffset[component]), ConstantU32(state, info.componentBits[component])); + if (unorm) { + components[component] = NormalizeFormatComponent(state, info, component, components[component]); + } } for (std::uint32_t component = info.componentCount; component < 4u; component++) { components[component] = components[component % info.componentCount]; @@ -444,7 +463,7 @@ std::uint32_t UnpackImageTexel(SpirvValueEmitContext& ctx, const ImageEmitAccess for (std::uint32_t component = 0; component < 4u; component++) { const auto selector = (swizzle >> (component * 3u)) & 7u; if (selector == 1u) { - selected[component] = ConstantU32(state, 1u); + selected[component] = ConstantU32(state, FormattedConstantBits(info, SpirvFormattedSourceKind::One)); } else if (selector >= 4u) { selected[component] = components[selector - 4u]; } else { @@ -572,13 +591,22 @@ std::uint32_t PackImageTexel(SpirvValueEmitContext& ctx, const ImageEmitAccess& if (info.format == IrBufferFormat::Invalid) { return texel; } + const bool unorm = info.type == SpirvFormatComponentType::Unorm; + if (unorm) { + RequireConvertedUnormAccess(ctx, access, info); + } auto packed = ConstantU32(state, 0u); for (std::uint32_t component = 0; component < info.componentCount; component++) { const auto value = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, TypeU32(state), value, texel, component); - const auto maximum = ConstantU32(state, info.componentBits[component] == 32u ? UINT32_MAX : (1u << info.componentBits[component]) - 1u); - const auto within = Binary(state, spv::OpULessThan, TypeBool(state), value, maximum); - const auto clamped = Select(state, TypeU32(state), within, value, maximum); + auto clamped = value; + if (unorm) { + clamped = EmitFormatStoreComponent(state, info, component, value); + } else { + const auto maximum = ConstantU32(state, info.componentBits[component] == 32u ? UINT32_MAX : (1u << info.componentBits[component]) - 1u); + const auto within = Binary(state, spv::OpULessThan, TypeBool(state), value, maximum); + clamped = Select(state, TypeU32(state), within, value, maximum); + } const auto shifted = info.componentBitOffset[component] == 0u ? clamped : Binary(state, spv::OpShiftLeftLogical, TypeU32(state), clamped, ConstantU32(state, info.componentBitOffset[component])); packed = Binary(state, spv::OpBitwiseOr, TypeU32(state), packed, shifted); } @@ -695,6 +723,9 @@ void EmitQueryDimensionsOp(SpirvValueEmitContext& ctx, const ImageEmitAccess& ac void EmitQueryLodOp(SpirvValueEmitContext& ctx, const ImageEmitAccess& access) { auto& state = ctx.state; + if (ImageConversionFormat(access.image).type == SpirvFormatComponentType::Unorm) { + ctx.Fail(access.inst, "queries the level of detail of a converted unorm image, which is not implemented"); + } state.module.EmitCapability(spv::CapabilityImageQuery); const auto sampled = MakeSampledImage(state, access.mem.resource, access.mem.sampler, access.slot); const auto coord = CoordF32(ctx, access, 0, RdnaImageDimensionInfoFor(access.image.dimension).spatialComponents, AddressDimension(access).spatialComponents); @@ -795,6 +826,9 @@ SampleSetup MakeSampleSetup(SpirvValueEmitContext& ctx, const ImageEmitAccess& a if (dref && access.image.conversionFormat != IrBufferFormat::Invalid) { ctx.Fail(access.inst, "uses depth comparison with a packed integer image"); } + if (ImageConversionFormat(access.image).type == SpirvFormatComponentType::Unorm) { + ctx.Fail(access.inst, "samples or gathers a converted unorm image, which needs filtering in the shader and is not implemented"); + } const auto coord = CoordF32(ctx, access, layout.coord, dimensionInfo.coordinateComponents, AddressDimension(access).coordinateComponents); return {dimensionInfo, layout, access.image.numericClass, dref, coord}; } diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index 827cc3ae2..bf6bfd94b 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -193,6 +193,8 @@ Throughout the project, every function at every stage either **does exactly what - The [output modifier](../../core/shader/recompiler/Translation/src/TranslationContext/OperandAccess.cpp) (`mul:2`, `mul:4`, `div:2`) follows the hardware with the IEEE mode off and f32 denormals flushed, the LLVM graphics default; the shader's MODE register is not read, and the hardware ignores the modifier in the other modes. On f16 results it is ignored, as on the hardware while f16 denormals are enabled; with them flushed the hardware applies it. - [Comparison sampling of a color texture](../../core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp) (`image_sample_c`/`image_sample_c_lz` on a texture that is not R32 float or R16 unorm) is emulated in the shader, since Vulkan compares only depth formats: the red channel is fetched, compared and, for bilinear filtering, blended (compare, then filter). Only 2D and 2D array views, float/unorm/snorm formats, wrap, clamp-to-edge and clamp-to-border addressing (border red 0 for the black borders, 1 for opaque white) and point or bilinear filtering at one level are implemented; half-border addressing, the border color table, gradients, LOD bias, offsets, LOD clamps, gathers, other dimensions, anisotropy and mip filtering throw. Under bilinear filtering, taps past a clamp-to-border edge compare the border value and blend with the texel taps, so results near the edge depend on the filter weights. AMD documentation does not say how a color format's reference is handled: it is clamped to [0, 1] for unorm and [-1, 1] for snorm, as Vulkan does for unorm depth, and not clamped for float. Bilinear weights are full float, not the hardware's fixed-point subtexel weights - [libScePlayerInvitationDialog](../../core/libs/prx/libScePlayerInvitationDialog/libScePlayerInvitationDialog.cpp) simulates dialog completion without displaying UI or sending invitations, so `scePlayerInvitationDialogGetResult` reports `USER_CANCELED`; its parameter ABI remains unverified. The 40-byte result layout (error code, result, 32 reserved bytes) is taken from [SharpProspero](https://github.com/SvenGDK/SharpProspero/blob/main/src/SharpProspero/Interop/Dialog/PlayerInvitationDialog.cs) and the error codes from the other common dialogs, not confirmed on a title. +- [Converted unorm images](../../core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp) (10_11_11_UNORM, read and written through an R32_UINT view): samples, gathers, LOD queries, 16-bit data and a DST_SEL of the missing W channel throw. +- [Converted unorm image loads](../../core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp) divide by 2^n - 1 with the buffer format path's `OpFDiv`, which Vulkan allows to be up to 2.5 ULP off, so some drivers are not bit-exact. - [64-bit LDS atomics](../../core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvMemoryInstructions.cpp) (`ds_*_u64`, `ds_*_b64`, `ds_*_f64`) read and write the two dwords under a workgroup lock stored after the guest LDS, as LDS is a 32-bit array without 64-bit atomics. They are atomic with respect to each other only: 32-bit accesses to the same dwords issued concurrently are not ordered by the lock. 64-bit GDS atomics throw. `ds_min/max(_rtn)_f64` and `ds_cmpst(_rtn)_f64` follow the NaN and signed-zero rules measured for the f32 forms; the f64 forms were not measured on hardware. - [wcsrtombs_s](../../core/libs/prx/libc/src/Multibyte.cpp) (libc) follows the console's `libc.prx`, but a runtime-constraint violation only returns its error: the default handler there writes the message and a newline to `stderr` before returning, which is not done here. Conversion uses the C locale of `wcrtomb` (`MB_CUR_MAX` 1), so the path where a multibyte character does not fit the remaining space is not reached - [Thread exit destructors](../../core/libs/prx/libSceLibcInternal/Export.cpp) (libSceLibcInternal) run when a libkernel thread finishes; on the main or a host thread only `_sceLibcInternalThreadDtors` runs them, as `exit` does, else they are dropped