diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp index 3e8477437ce2..c494ba7a0d02 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp @@ -1055,7 +1055,7 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { } try { require(result.pushConstants.size() <= pushBudget, "stage push constants exceed the pipeline push constant block"); - stages.push_back({program.binary.stage, &result, result.pushConstants.empty() ? 0u : pushCursorBytes, stageCaptures[i].registeredViews.get()}); + stages.push_back({program.binary.stage, &result, result.pushConstants.empty() ? 0u : pushCursorBytes, stageCaptures[i].registeredViews.get(), program.binary.codeAddress}); pushCursorBytes += static_cast(result.pushConstants.size()); } catch (...) { TraceMaterializationFailure(trace.token, submission, packetOffset, "push-constant-validation", completedSubdraws, std::current_exception()); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index 7a21630d1ece..e929b4d9d9f7 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -784,6 +784,7 @@ struct VulkanDevice::State { std::unique_ptr emptyBuffer; std::unique_ptr oversizedBuffer; std::unique_ptr atomicLockTable; + std::unique_ptr shaderSampleCounter; std::unique_ptr placeholderImages; std::unique_ptr textureCache; std::unique_ptr pipelineCache; @@ -1304,6 +1305,7 @@ struct VulkanDevice::State { emptyBuffer.reset(); oversizedBuffer.reset(); atomicLockTable.reset(); + shaderSampleCounter.reset(); placeholderImages.reset(); samplerCache.reset(); textureCache.reset(); @@ -2855,6 +2857,11 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) : const auto words = state->atomicLockTable->Bytes(); std::memset(words.data(), 0, words.size()); } + if (graphicsContext().bufferDeviceAddress) { + state->shaderSampleCounter = std::make_unique(graphicsContext(), sizeof(std::uint64_t), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT); + const auto words = state->shaderSampleCounter->Bytes(); + std::memset(words.data(), 0, words.size()); + } static const bool headlessPipelineCache = std::getenv("APS5_HEADLESS_PIPELINE_CACHE") != nullptr; state->pipelineCache = std::make_unique(graphicsContext(), state->properties, window != nullptr || compileOnly || headlessPipelineCache); if (!compileOnly) { @@ -5275,6 +5282,7 @@ Graphics::Context VulkanDevice::buildContext() const { context.nullDescriptors = state->shaderProfile != nullptr && state->shaderProfile->NullDescriptors(); context.bufferInt64Atomics = state->bufferInt64Atomics; context.atomicLockTable = state->atomicLockTable ? state->atomicLockTable->DeviceAddress() : 0; + context.shaderSampleCounter = state->shaderSampleCounter.get(); context.placeholderImages = state->placeholderImages.get(); context.viewportIndexLayer = state->viewportIndexLayer; context.imageFormatList = state->imageFormatList; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp index b5dc76f34500..3561fc5ea731 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp @@ -25,6 +25,7 @@ namespace AgcDriver::Graphics { +class Buffer; class TextureDetiler; class GpuColorTransfer; class BufferPool; @@ -328,6 +329,7 @@ struct Context { bool nullDescriptors = false; bool bufferInt64Atomics = false; VkDeviceAddress atomicLockTable = 0; + Buffer* shaderSampleCounter = nullptr; const PlaceholderImages* placeholderImages = nullptr; bool viewportIndexLayer = false; bool demoteToHelperInvocation = false; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineSpecialization.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineSpecialization.hpp index 730ad1bf7730..ef24cbe3472d 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineSpecialization.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineSpecialization.hpp @@ -52,10 +52,11 @@ class PipelineSpecialization { } } - PipelineSpecialization(const ShaderRecompiler::RecompileResult& shader, VkDeviceAddress atomicLockTable, std::uint32_t layerBase, std::uint32_t layerCount) : PipelineSpecialization(shader, atomicLockTable) { + PipelineSpecialization(const ShaderRecompiler::RecompileResult& shader, VkDeviceAddress atomicLockTable, VkDeviceAddress sampleCounter, std::uint32_t layerBase, std::uint32_t layerCount) : PipelineSpecialization(shader, atomicLockTable) { for (auto& constant : values) { if (constant.id == ShaderRecompiler::PipelineSpecialization::MeshLayerBase) constant.value = layerBase; if (constant.id == ShaderRecompiler::PipelineSpecialization::MeshLayerCount) constant.value = layerCount; + if (ShaderRecompiler::PipelineSpecialization::IsSampleCounter(constant.id)) constant.value = static_cast(sampleCounter >> (32u * (constant.id - ShaderRecompiler::PipelineSpecialization::SampleCounterBase))); } } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp index 9684625f6748..4c1843f814bd 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp @@ -417,6 +417,8 @@ class Recorder { std::uint64_t SamplesTotal(); bool DumpSamples(VkDeviceAddress target, std::uint64_t address = 0, std::uint32_t blocks = 0xffffu); void NoteSampledDraw(VkCommandBuffer commands); + void NoteShaderCountedDraw(VkCommandBuffer commands, std::uint64_t program = 0); + bool CountsShaderSamples() const; void NoteDrawTraceToken(std::uint64_t token) noexcept; void NoteFaultToken(AgcDriver::FaultToken token) noexcept; bool QueuesSampleDumps() const; @@ -574,6 +576,7 @@ class Recorder { // The function the flush hook calls, on the accessing thread (which may hold the GPU mutex), // when an access overlaps one of that thread's queued labels; it records them. Set once. static void SetQueuedLabelRecorder(void (*recorder)()); + static void RefuseGpuSampleCounterForTest(bool refuse); static void FailNextSubmitsForTest(unsigned count); static void FailNextDiscardRegistrationsForTest(unsigned count); // Whether the lock-free pending-write snapshot (open, in-flight and finishing batches) overlaps @@ -793,6 +796,7 @@ class Recorder { VkQueryPool handle; std::uint32_t slot = 0; std::uint64_t batch = 0; + VkBuffer counted = VK_NULL_HANDLE; }; static_assert(std::is_nothrow_move_constructible_v && std::is_nothrow_move_assignable_v); struct Batch { @@ -849,6 +853,8 @@ class Recorder { std::uint32_t segmentNext = 0; std::uint32_t segmentSlot = 0; bool segmentActive = false; + bool shaderSamples = false; + bool countingStarted = false; std::uint32_t queuedDumps = 0; std::vector timedKeys; std::vector timedBytes; @@ -979,9 +985,19 @@ class Recorder { void foldSegments(); void foldQueuedDumps(VkCommandBuffer commands, std::span writes, std::size_t first, std::size_t end, std::uint32_t& dumpIndex, std::uint32_t& consumed); void reserveSampleRestore(const Batch& batch); + void startCounting(); + void settleShaderSamples(); + void copySegment(VkCommandBuffer commands, const SampleSegment& segment, std::uint32_t index, std::uint32_t run = 1); + std::uint64_t segmentSamples(const SampleSegment& segment); + void traceShaderSamples(std::uint64_t dump, VkDeviceAddress target, std::uint64_t address, std::uint32_t blocks, std::size_t first); std::vector pendingSamples; std::uint64_t sampleBatches = 0; bool countingSamples = false; + bool shaderSamplesDirty = false; + std::shared_ptr shaderSlots; + std::uint32_t shaderSlotNext = 0; + std::uint64_t sampleDumps = 0; + std::vector shaderCountedPrograms; int meshArgumentState = 0; VkPipelineLayout meshArgumentLayout = VK_NULL_HANDLE; VkPipeline meshArgumentPipeline = VK_NULL_HANDLE; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp index 953db9bbf860..a59cd8536946 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp @@ -52,6 +52,7 @@ struct CompiledShader { const ShaderRecompiler::RecompileResult* program; std::uint32_t pushConstantOffset; const std::vector* registeredImageViews = nullptr; + std::uint64_t codeAddress = 0; }; inline std::uint32_t KeyedPushOffset(const CompiledShader& shader) { @@ -97,6 +98,12 @@ inline VkShaderStageFlags PushConstantStages(std::span sha return result; } +inline bool ShadersCountSamples(std::span shaders) { + return std::ranges::any_of(shaders, [](const CompiledShader& shader) { + return shader.stage == ShaderRecompiler::ShaderStage::Fragment && shader.program != nullptr && std::ranges::any_of(shader.program->specialization, [](const ShaderRecompiler::PipelineSpecializationConstant& constant) { return ShaderRecompiler::PipelineSpecialization::IsSampleCounter(constant.id); }); + }); +} + inline std::array AssemblePushConstants(std::span shaders) { static_assert(PipelinePushConstantBytes % 4 == 0 && PipelinePushConstantBytes / 4 <= 64 && PipelinePushSlotBytes / 4 < 64, "the occupied mask holds one bit per DWORD of the block"); std::array result{}; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/State.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/State.hpp index d627be3287ba..cb7fc80fc390 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/State.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/State.hpp @@ -96,6 +96,10 @@ struct ColorTarget { std::uint16_t stagedMask = 0; VkFormat stagedFormat = VK_FORMAT_UNDEFINED; + bool UnclampedBlend() const { + return packing == ShaderRecompiler::ColorExportPacking::None && partialWriteMask == UnclampedBlendMask; + } + bool operator==(const ColorTarget& other) const { return address == other.address && extent.width == other.extent.width && extent.height == other.extent.height && format == other.format && bytes == other.bytes && componentMapping == other.componentMapping && tileMode == other.tileMode && elementBytes == other.elementBytes && @@ -298,6 +302,7 @@ struct ReversedBlend { ReversedBlend TranslateReversedBlend(std::uint32_t blendControl, std::uint8_t componentMapping, VkFormat format, bool forceDestinationAlphaOne, const std::array& constants); std::size_t CmaskBytes(std::uint32_t width, std::uint32_t height); std::uint32_t ColorWriteMask(const Registers& context); +VkFormat ColorTargetDccClearFormat(const ColorTarget& color); GuestTextureResource SurfaceForTarget(const ColorTarget& color); GuestTextureResource ArraySurfaceForTarget(const ColorTarget& color); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/DccMetadata.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/DccMetadata.cpp index 01fe49620a57..f73d7fa5432a 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/DccMetadata.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/DccMetadata.cpp @@ -411,6 +411,7 @@ bool LayoutFor(VkFormat format, Layout& layout) { case VK_FORMAT_R16G16_SINT: layout = {2, {16, 16}, Kind::Sint}; return true; case VK_FORMAT_R16G16_SFLOAT: layout = {2, {16, 16}, Kind::Float}; return true; case VK_FORMAT_B10G11R11_UFLOAT_PACK32: layout = {3, {11, 11, 10}, Kind::Float}; return true; + case VK_FORMAT_R4G4B4A4_UNORM_PACK16: layout = {4, {4, 4, 4, 4}, Kind::Unorm}; return true; case VK_FORMAT_A2B10G10R10_UNORM_PACK32: case VK_FORMAT_A2R10G10B10_UNORM_PACK32: layout = {4, {10, 10, 10, 2}, Kind::Unorm}; return true; case VK_FORMAT_A2B10G10R10_UINT_PACK32: layout = {4, {10, 10, 10, 2}, Kind::Uint}; return true; case VK_FORMAT_R8G8B8A8_UNORM: case VK_FORMAT_R8G8B8A8_SRGB: case VK_FORMAT_B8G8R8A8_UNORM: case VK_FORMAT_B8G8R8A8_SRGB: layout = {4, {8, 8, 8, 8}, Kind::Unorm}; return true; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index ab9bd7695e03..6dc482ab6c6e 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -479,7 +479,7 @@ std::array clearTexel(const ColorTarget& color, DccKeys keys) { Require(elementBytes <= sizeof(color.clearWords), "the DCC register clear of a texel over 64 bits is not modeled"); std::memcpy(texel.data(), color.clearWords.data(), elementBytes); } else { - Require(FillDccClear(color.format, keys, color.dccAlphaOnMsb, std::span(texel.data(), elementBytes)), "the target's format has no encoding of its DCC clear code"); + Require(FillDccClear(ColorTargetDccClearFormat(color), keys, color.dccAlphaOnMsb, std::span(texel.data(), elementBytes)), "the target's format has no encoding of its DCC clear code"); } return texel; } @@ -526,14 +526,28 @@ void storeSingleTexels(const Context& context, const ColorTarget& color) { MarkDccUncompressed(context, color.dccAddress, color.bytes, colorKeyCount(color, color.bytes)); } +bool clearNeedsTargetLayout(const ColorTarget& color, DccKeys keys) { + return ColorTargetDccClearFormat(color) != color.format && (keys == DccKeys::Clear0001 || keys == DccKeys::Clear1110); +} + void materializeRegisterClear(const Context& context, const ColorTarget& color, StorageTexture& resident) { if (color.dccAddress == 0 || resident.Descriptor().dccAddress != color.dccAddress) return; - if (ProvedCurrentDccKeys(color.dccAddress, color.bytes, resident.TargetKeyProof()) != DccKeys::ClearRegister) return; + const auto provedKeys = ProvedCurrentDccKeys(color.dccAddress, color.bytes, resident.TargetKeyProof()); + const auto keyBytes = static_cast(color.bytes / 256); + if (clearNeedsTargetLayout(color, provedKeys)) { + if (auto* recorder = Recorder::Active(); keyBytes != 0 && recorder != nullptr && recorder->PendingWriteOverlaps(color.dccAddress, keyBytes)) { + Recorder::CountSync(2); + recorder->SyncThrough(color.dccAddress, keyBytes); + } + storeClearTexels(context, color, clearTexel(color, DccKeys::ClearRegister)); + resident.Refresh(); + return; + } + if (provedKeys != DccKeys::ClearRegister) return; const auto texel = clearTexel(color, DccKeys::ClearRegister); const char* refusal = nullptr; const bool pendingKeysKnown = KnownPendingDccKeys(color.dccAddress, color.bytes) == DccKeys::ClearRegister; bool cleared = clearToTexel(resident, texel, color.elementBytes, refusal, pendingKeysKnown); - const auto keyBytes = static_cast(color.bytes / 256); if (!cleared && keyBytes != 0) { if (auto* recorder = Recorder::Active(); recorder != nullptr && recorder->PendingWriteOverlaps(color.dccAddress, keyBytes)) { Recorder::CountSync(2); @@ -1787,6 +1801,8 @@ struct DrawInputs { std::uint32_t meshLayerStride = 0; std::vector restartTable; std::uint32_t expandedIndexCount = 0; + bool shaderCountsSamples = false; + std::uint64_t countingProgram = 0; const VertexInputLayout& VertexLayout() const { return retainedVertexInput != nullptr ? *retainedVertexInput : vertexInput; } }; @@ -1980,9 +1996,13 @@ DrawInputs prepareDrawInputs(const Context& context, const State& state, const P if (draw.indexed) GuestMemory::CheckRange(reinterpret_cast(draw.indexAddress), static_cast(indexBytes), draw.indexSize); APS5_LOG_CHARS_OUT_DEBUG("Index buffer range OK"); if (draw.indexed) RequireNoMultisampleTarget(draw.indexAddress, static_cast(indexBytes), "an index buffer read", DepthReadCause::Reuse); - if (state.pixelKill && !state.pixelEarlyZ && std::ranges::any_of(state.colors, [](const ColorTarget& color) { return color.partialWriteMask != 0; })) { + inputs.shaderCountsSamples = ShadersCountSamples(shaders); + if (inputs.shaderCountsSamples) inputs.countingProgram = std::ranges::find(shaders, ShaderRecompiler::ShaderStage::Fragment, &CompiledShader::stage)->codeAddress; + if (inputs.shaderCountsSamples || (state.pixelKill && !state.pixelEarlyZ && std::ranges::any_of(state.colors, [](const ColorTarget& color) { return color.partialWriteMask != 0; }))) { const auto* recorder = Recorder::Active(); - Require(recorder == nullptr || !recorder->CountingSamples(), "a partial write of a packed color target merges inside the pixel shader after early depth and stencil tests, which a shader that kills pixels under late tests cannot use while occlusion queries count samples: the early tests would count the pixels it kills"); + Require(recorder == nullptr || !recorder->CountingSamples() || !inputs.shaderCountsSamples || state.samples == 1u, "a partial write of a packed color target that merges inside the pixel shader and kills pixels under late tests cannot be drawn to a multisampled target while occlusion queries count samples: a merge into a multisampled target runs the pixel shader once per sample, and the shader sample counter's count of those invocations is not verified against the occlusion queries"); + Require(recorder == nullptr || !recorder->CountingSamples() || !inputs.shaderCountsSamples || std::ranges::none_of(state.colors, [](const ColorTarget& color) { return color.coverageSamples > 1u; }), "a partial write of a packed color target that merges inside the pixel shader and kills pixels under late tests cannot be drawn to a color target with several coverage samples while occlusion queries count samples: the shader sample counter counts surviving invocations, not covered samples"); + Require(recorder == nullptr || !recorder->CountingSamples() || (inputs.shaderCountsSamples && recorder->CountsShaderSamples()), "a partial write of a packed color target merges inside the pixel shader after early depth and stencil tests, so a shader that kills pixels under late tests counts its own samples while occlusion queries count samples, which needs the device's shader sample counter and the GPU occlusion counter"); } timer.phase(PhaseValidate); timing.Mark("validate"); @@ -2585,7 +2605,8 @@ void CompactIndirectListRestart(const Context& context, const Pm4::DrawParameter // GPU-side indirect draw from `argumentBuffer` or the CPU-read records with the driver's rules. bool recordDrawCommandsImpl(const Context& context, VkCommandBuffer commands, const State& state, const Pm4::DrawParameters& draw, const DrawInputs& inputs, const IndirectRecord* indirect, VkBuffer argumentBuffer, VkDeviceSize argumentOffset, const DrawTraceContext* trace, std::uint32_t& subdraw, std::optional pieceFirstIndex = std::nullopt) { bool emitted = false; - if (context.recorder != nullptr) context.recorder->NoteSampledDraw(commands); + if (context.recorder != nullptr && inputs.shaderCountsSamples) context.recorder->NoteShaderCountedDraw(commands, inputs.countingProgram); + else if (context.recorder != nullptr) context.recorder->NoteSampledDraw(commands); const auto recorded = [&](std::uint32_t index) { if (trace != nullptr && context.recorder != nullptr) { context.recorder->NoteDrawTraceToken(trace->token); @@ -4406,7 +4427,7 @@ bool prepareDraw(const Context& context, const State& state, const Pm4::DrawPara if (keys == DccKeys::ClearRegister) { const auto texel = clearTexel(color, keys); for (std::size_t offset = 0; offset + color.elementBytes <= pixels.size(); offset += color.elementBytes) std::memcpy(pixels.data() + offset, texel.data(), color.elementBytes); - } else if (!FillDccClear(color.format, keys, color.dccAlphaOnMsb, pixels)) { + } else if (!FillDccClear(ColorTargetDccClearFormat(color), keys, color.dccAlphaOnMsb, pixels)) { static std::set> reported; if (reported.size() < 32 && reported.insert({color.address, static_cast(keys)}).second) std::fprintf(stderr, "[gpu] color target 0x%llx (VkFormat %d) has %s DCC keys; its stored texels are used\n", static_cast(color.address), static_cast(color.format), DccKeysName(keys)); if (binding.gpuTiling) std::memcpy(pixels.data(), binding.original.data(), binding.original.size()); @@ -5598,7 +5619,7 @@ void RunColorMetadataPass(const Context& context, const ColorMetadataPass& pass) const auto resident = metadataPassResident(context, color); if (resident != nullptr) { const char* refusal = nullptr; - const bool current = keys == DccKeys::ClearRegister ? clearToTexel(*resident, texel, color.elementBytes, refusal, true) : StorageTexture::FindPending(color.address, color.bytes) == resident || resident->UploadedKeys() == keys; + const bool current = keys == DccKeys::ClearRegister ? clearToTexel(*resident, texel, color.elementBytes, refusal, true) : StorageTexture::FindPending(color.address, color.bytes) == resident || (!clearNeedsTargetLayout(color, keys) && resident->UploadedKeys() == keys); if (current) { resident->MarkDirty(); MarkDccUncompressed(context, color.dccAddress, color.bytes, colorKeyCount(color, color.bytes)); @@ -5610,6 +5631,7 @@ void RunColorMetadataPass(const Context& context, const ColorMetadataPass& pass) if (materializeMipClear(context, color, chain)) continue; } storeClearTexels(context, color, texel); + if (resident != nullptr && clearNeedsTargetLayout(color, keys)) resident->Refresh(); } } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestTextureResource.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestTextureResource.cpp index 93c3beb94abe..685507658fef 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestTextureResource.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestTextureResource.cpp @@ -437,7 +437,8 @@ std::array EncodeTextureResource(const GuestTextureResource& r const bool array = resource.dimension == TextureDimension::k2DArray; Require(((resource.dimension == TextureDimension::k2D || array) && resource.samples == 1u) || (multisampled && resource.samples >= 2u && resource.samples <= 16u && std::has_single_bit(resource.samples)), "only 2D, 2D array and multisampled 2D surfaces have a texture descriptor encoding"); Require(resource.mipCount >= 1u && resource.mipCount <= 16u && (resource.allocatedMipCount == 0u || resource.allocatedMipCount == resource.mipCount) && resource.baseLevel <= resource.lastLevel && resource.lastLevel < resource.mipCount && (array ? resource.baseArray <= resource.depthOrLastArray && resource.depthOrLastArray <= 0x1fffu : resource.depthOrLastArray == 0u && resource.baseArray == 0u), "the surface's mip levels or array slices have no texture descriptor encoding"); - Require((!multisampled || resource.mipCount == 1u) && resource.dccAddress == 0u && resource.minLod == 0u && !resource.iterate256 && resource.bcSwizzle == 0u && resource.linearPitch == 0u, "only single-level multisampled surfaces and surfaces without metadata have a texture descriptor encoding"); + Require((!multisampled || (resource.mipCount == 1u && resource.dccAddress == 0u)) && resource.minLod == 0u && !resource.iterate256 && resource.bcSwizzle == 0u && resource.linearPitch == 0u, "only single-level multisampled surfaces without metadata and single-sample surfaces without metadata other than DCC keys have a texture descriptor encoding"); + Require((resource.dccAddress & 0xffu) == 0u && (resource.dccAddress >> 8u) <= 0xffffffffffull, "the surface's DCC key address has no texture descriptor encoding"); Require(resource.width >= 1u && resource.width <= 0x4000u && resource.height >= 1u && resource.height <= 0x4000u && resource.format < 0x200u, "the surface's extent or format has no texture descriptor encoding"); const auto xorMask = resource.tileMode == TextureTileMode::kS4KBX || resource.tileMode == TextureTileMode::kD4KBX ? 0xfffull : 0xffffull; Require(XorSwizzleMode(resource.tileMode) != 0 ? (resource.baseAddress & xorMask) == 0 && (resource.pipeBankXor & ~xorMask) == 0 : resource.pipeBankXor == 0, "the surface's pipe and bank XOR has no texture descriptor encoding"); @@ -470,6 +471,11 @@ std::array EncodeTextureResource(const GuestTextureResource& r words[3] = resource.dstSelX | (resource.dstSelY << 3u) | (resource.dstSelZ << 6u) | (resource.dstSelW << 9u) | (resource.baseLevel << 12u) | (lastLevel << 16u) | (tileMode << 20u) | ((multisampled ? 14u : array ? 13u : 9u) << 28u); words[4] = resource.depthOrLastArray | (resource.baseArray << 16u); words[5] = (multisampled ? sampleLevel : resource.mipCount - 1u) << 4u; + if (resource.dccAddress != 0u) { + const auto keys = resource.dccAddress >> 8u; + words[6] = (resource.dccPipeAligned ? 1u << 19u : 0u) | (1u << 21u) | (resource.dccAlphaOnMsb ? 1u << 22u : 0u) | (static_cast(keys & 0xffu) << 24u); + words[7] = static_cast(keys >> 8u); + } return words; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp index c7df37045285..84455d15694d 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp @@ -409,7 +409,7 @@ ColorWriteMasks channelWriteMasks(const State& state, std::spanDeviceAddress() : 0u, state.meshLayerBase, state.meshLayerCount); stages[i].pSpecializationInfo = specializations.back().Info(); } if (std::ranges::any_of(shaders, [](const CompiledShader& shader) { return shader.program != nullptr && !shader.program->stencilReferences.empty(); })) { @@ -1099,7 +1099,7 @@ Pipeline::Pipeline(const Context& context, const State& state, const VertexInput std::vector firstChannels(state.blends.begin(), state.blends.end()); std::vector secondChannels(state.blends.begin(), state.blends.end()); for (const auto& merged : state.colors) { - if (merged.partialWriteMask != UnclampedBlendMask) continue; + if (!merged.UnclampedBlend()) continue; for (auto* channels : {&firstChannels, &secondChannels}) channels->at(merged.exportIndex) = {}; } if (alternateAlpha) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp index 2fa30af0d3f8..8faf99eb2b82 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp @@ -214,7 +214,28 @@ constexpr std::uint32_t DumpFoldCapacity = 1024; constexpr std::uint32_t SampleDumpBytes = 15 * 16 + 8; constexpr VkDeviceSize DumpListOffset = 16 + 8 * SegmentFoldCapacity; constexpr std::uint32_t SampleDumpPushBytes = 40; +constexpr std::uint32_t ShaderSampleSlots = 256; +constexpr std::size_t ShaderSampleTracePrograms = 8; std::atomic dumpsQueued{0}, dumpsQueuedInPass{0}, dumpsAtOnce{0}, segmentsClosed{0}, dumpFolds{0}, capacityFolds{0}; +std::atomic traceShaderSamplesLeft{[] { + const char* text = std::getenv("APS5_TRACE_SHADER_SAMPLES"); + return text != nullptr ? static_cast(std::strtoll(text, nullptr, 10)) : std::int64_t{0}; +}()}; + +bool TracingShaderSamples() { + return traceShaderSamplesLeft.load(std::memory_order_relaxed) > 0; +} + +std::string CountedProgramList(std::span programs) { + if (programs.empty()) return " none"; + std::string text; + for (const auto program : programs) { + char entry[24]; + std::snprintf(entry, sizeof(entry), " 0x%llx", static_cast(program)); + text += entry; + } + return text; +} struct SamplePoolCache { VkDevice device; @@ -581,6 +602,7 @@ bool ProcTable() { AgcDriver::Mutex labelTableMutex; std::atomic injectedSubmitFailures{0}; std::atomic injectedDiscardRegistrationFailures{0}; +std::atomic refusedGpuSampleCounter{false}; Recorder* labelTableOwner = nullptr; // The ranges of the calling worker's queued labels (NoteQueuedLabel, cleared by // ForgetQueuedLabels): the flush hook, on the same thread, has them recorded before an access that @@ -2937,7 +2959,7 @@ void Recorder::KeepStorePagePool(std::unique_ptr pool) { void Recorder::CountSamples() { GuestMemory::AssertGpuLockHeld("Recorder::CountSamples"); gpuSampleCounter(); - countingSamples = true; + startCounting(); if (segmentMode() || open == nullptr || open->samples != VK_NULL_HANDLE) return; if (open->renderPass.open) endOpenRenderPass(PassBreak::Samples); beginSamples(*open); @@ -2948,16 +2970,74 @@ std::uint64_t Recorder::SamplesTotal() { if (segmentMode() && !Idle()) Sync(); std::uint64_t total = 0; std::memcpy(&total, sampleCounter->Bytes().data(), sizeof(total)); + std::uint64_t hardware = 0, shader = 0; + std::size_t hardwareSegments = 0, shaderReads = 0; for (const auto& segment : pendingSamples) { - std::uint64_t samples = 0; - Check(context.Function("vkGetQueryPoolResults")(context.device, segment.handle, segment.slot, 1, sizeof(samples), &samples, sizeof(samples), VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT), "vkGetQueryPoolResults occlusion"); - total += samples; + const bool counted = segment.counted != VK_NULL_HANDLE; + (counted ? shader : hardware) += segmentSamples(segment); + ++(counted ? shaderReads : hardwareSegments); } pendingSamples.clear(); + if (shaderSamplesDirty && context.shaderSampleCounter != nullptr) { + const auto counted = context.shaderSampleCounter->Bytes().first(sizeof(std::uint64_t)); + std::uint64_t samples = 0; + std::memcpy(&samples, counted.data(), sizeof(samples)); + if (countingSamples) { + shader += samples; + ++shaderReads; + } + std::memset(counted.data(), 0, counted.size()); + shaderSamplesDirty = false; + } + total += hardware + shader; std::memcpy(sampleCounter->Bytes().data(), &total, sizeof(total)); + const auto dump = sampleDumps++; + if (TracingShaderSamples()) { + if (shaderReads != 0 && traceShaderSamplesLeft.fetch_sub(1, std::memory_order_relaxed) > 0) { + std::fprintf(stderr, "[shader samples] dump %llu (CPU total): occlusion query segments %llu samples in %zu, shader counter %llu samples in %zu reads, total %llu, counted programs%s\n", static_cast(dump), static_cast(hardware), hardwareSegments, static_cast(shader), shaderReads, static_cast(total), CountedProgramList(shaderCountedPrograms).c_str()); + } + shaderCountedPrograms.clear(); + } return total; } +std::uint64_t Recorder::segmentSamples(const SampleSegment& segment) { + std::uint64_t samples = 0; + if (segment.counted != VK_NULL_HANDLE) { + const auto slots = static_cast(segment.pool.get())->Bytes(); + std::memcpy(&samples, slots.data() + sizeof(samples) * segment.slot, sizeof(samples)); + return samples; + } + Check(context.Function("vkGetQueryPoolResults")(context.device, segment.handle, segment.slot, 1, sizeof(samples), &samples, sizeof(samples), VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT), "vkGetQueryPoolResults occlusion"); + return samples; +} + +void Recorder::traceShaderSamples(std::uint64_t dump, VkDeviceAddress target, std::uint64_t address, std::uint32_t blocks, std::size_t first) { + auto programs = std::move(shaderCountedPrograms); + shaderCountedPrograms.clear(); + const auto begin = pendingSamples.begin() + static_cast(std::min(first, pendingSamples.size())); + if (std::none_of(begin, pendingSamples.end(), [](const SampleSegment& segment) { return segment.counted != VK_NULL_HANDLE; })) return; + if (traceShaderSamplesLeft.fetch_sub(1, std::memory_order_relaxed) <= 0) return; + const auto enabled = blocks & 0xffffu; + const auto word = address != 0 && enabled != 0u ? address + 16u * static_cast(std::countr_zero(enabled)) : 0u; + open->completions.push_back([this, dump, target, address, word, segments = std::vector(begin, pendingSamples.end()), programs = std::move(programs)] { + std::uint64_t hardware = 0, shader = 0; + std::size_t hardwareSegments = 0, shaderReads = 0; + for (const auto& segment : segments) { + const bool counted = segment.counted != VK_NULL_HANDLE; + (counted ? shader : hardware) += segmentSamples(segment); + ++(counted ? shaderReads : hardwareSegments); + } + char written[48] = "unreadable"; + if (word != 0 && GuestMemory::Accessible(reinterpret_cast(word), 2 * sizeof(std::uint32_t))) { + std::array value{}; + std::memcpy(value.data(), reinterpret_cast(word), sizeof(value)); + std::snprintf(written, sizeof(written), "%llu%s", static_cast(value[0] | (static_cast(value[1] & 0x7fffffffu) << 32u)), (value[1] & 0x80000000u) != 0u ? "" : " (not ready)"); + } + std::fprintf(stderr, "[shader samples] dump %llu (GPU) to 0x%llx (device 0x%llx): occlusion query segments %llu samples in %zu, shader counter %llu samples in %zu reads, total written %s, counted programs%s\n", static_cast(dump), static_cast(address), static_cast(target), static_cast(hardware), hardwareSegments, static_cast(shader), shaderReads, written, CountedProgramList(programs).c_str()); + }); +} + void Recorder::NoteSampledDraw(VkCommandBuffer commands) { if (open == nullptr) return; if (segmentMode()) { @@ -2967,6 +3047,54 @@ void Recorder::NoteSampledDraw(VkCommandBuffer commands) { if (open->sampleActive) open->samplesDrawn = true; } +void Recorder::NoteShaderCountedDraw(VkCommandBuffer commands, std::uint64_t program) { + if (context.shaderSampleCounter == nullptr) return; + shaderSamplesDirty = true; + if (TracingShaderSamples() && shaderCountedPrograms.size() < ShaderSampleTracePrograms && std::ranges::find(shaderCountedPrograms, program) == shaderCountedPrograms.end()) shaderCountedPrograms.push_back(program); + if (open == nullptr) return; + open->shaderSamples = true; + if (countingSamples && segmentMode() && commands == open->commands && open->segmentActive) endSegment(*open); +} + +bool Recorder::CountsShaderSamples() const { + return context.shaderSampleCounter != nullptr && segmentMode(); +} + +void Recorder::startCounting() { + if (!countingSamples) { + settleShaderSamples(); + shaderCountedPrograms.clear(); + } + countingSamples = true; +} + +void Recorder::settleShaderSamples() { + if (!shaderSamplesDirty || context.shaderSampleCounter == nullptr || !segmentMode()) return; + const auto commands = Commands(); + const auto counter = context.shaderSampleCounter->Handle(); + recordBarrier(commands, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT); + std::uint32_t barriers = 2; + if (countingSamples) { + if (shaderSlots == nullptr || shaderSlotNext == ShaderSampleSlots) { + shaderSlots = std::make_shared(context, sizeof(std::uint64_t) * ShaderSampleSlots, VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT); + shaderSlotNext = 0; + } + const auto slot = shaderSlotNext++; + const VkBufferCopy region{0, sizeof(std::uint64_t) * static_cast(slot), sizeof(std::uint64_t)}; + context.Function("vkCmdCopyBuffer")(commands, counter, shaderSlots->Handle(), 1, ®ion); + recordBarrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0); + ++barriers; + reserveSampleRestore(*open); + pendingSamples.push_back({shaderSlots, VK_NULL_HANDLE, slot, open->sampleBatch, shaderSlots->Handle()}); + } + context.Function("vkCmdFillBuffer")(commands, counter, 0, sizeof(std::uint64_t), 0u); + recordBarrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_HOST_READ_BIT); + CountBarriers(CommandClass::Copy, barriers); + open->shaderSamples = true; + if (!countingSamples) open->countingStarted = true; + shaderSamplesDirty = false; +} + void Recorder::NoteDrawTraceToken(std::uint64_t token) noexcept { if (token == 0 || open == nullptr) return; try { @@ -2992,7 +3120,7 @@ void Recorder::NoteFaultToken(AgcDriver::FaultToken token) noexcept { bool Recorder::gpuSampleCounter() { if (sampleCounterState != 0) return sampleCounterState > 0; sampleCounterState = -1; - if (!context.bufferDeviceAddress) return false; + if (!context.bufferDeviceAddress || refusedGpuSampleCounter.load(std::memory_order_relaxed)) return false; VkShaderModule module = VK_NULL_HANDLE; try { sampleCounter = std::make_unique(context, DumpListOffset + 16 * DumpFoldCapacity, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT); @@ -3202,16 +3330,25 @@ void Recorder::endSegment(Batch& batch) { void Recorder::copySegments(VkCommandBuffer commands, std::uint32_t count) { Require(count <= pendingSamples.size() && count <= SegmentFoldCapacity, "occlusion segments exceed the fold capacity"); - const auto copy = function(cmdCopyQueryPoolResults, "vkCmdCopyQueryPoolResults"); for (std::uint32_t i = 0; i < count;) { const auto& first = pendingSamples[i]; std::uint32_t run = 1; - while (i + run < count && pendingSamples[i + run].handle == first.handle && pendingSamples[i + run].slot == first.slot + run) ++run; - copy(commands, first.handle, first.slot, run, sampleCounter->Handle(), 16 + 8 * static_cast(i), 8, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); + while (first.counted == VK_NULL_HANDLE && i + run < count && pendingSamples[i + run].handle == first.handle && pendingSamples[i + run].slot == first.slot + run) ++run; + copySegment(commands, first, i, run); i += run; } } +void Recorder::copySegment(VkCommandBuffer commands, const SampleSegment& segment, std::uint32_t index, std::uint32_t run) { + const auto target = 16 + 8 * static_cast(index); + if (segment.counted != VK_NULL_HANDLE) { + const VkBufferCopy region{sizeof(std::uint64_t) * static_cast(segment.slot), target, sizeof(std::uint64_t)}; + context.Function("vkCmdCopyBuffer")(commands, segment.counted, sampleCounter->Handle(), 1, ®ion); + return; + } + function(cmdCopyQueryPoolResults, "vkCmdCopyQueryPoolResults")(commands, segment.handle, segment.slot, run, sampleCounter->Handle(), target, 8, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); +} + void Recorder::reserveSampleRestore(const Batch& batch) { const auto needed = pendingSamples.size() + batch.foldedSamples.size() + 1; if (needed > pendingSamples.capacity()) pendingSamples.reserve(std::max(needed, 2 * pendingSamples.capacity())); @@ -3301,7 +3438,6 @@ void Recorder::endSamples(Batch& batch) { void Recorder::foldSamples(Batch& batch, VkDeviceAddress target, std::uint32_t blocks) { const auto commands = batch.commands; - const auto copy = function(cmdCopyQueryPoolResults, "vkCmdCopyQueryPoolResults"); const auto push = function(cmdPushConstants, "vkCmdPushConstants"); const auto dispatch = function(cmdDispatch, "vkCmdDispatch"); const auto bindCompute = context.ComputeBinding(); @@ -3311,7 +3447,7 @@ void Recorder::foldSamples(Batch& batch, VkDeviceAddress target, std::uint32_t b if (done != 0) recordBarrier(commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT); for (std::uint32_t i = 0; i < count; ++i) { const auto& segment = pendingSamples[done + i]; - copy(commands, segment.handle, segment.slot, 1, sampleCounter->Handle(), 16 + 8 * i, 8, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); + copySegment(commands, segment, i); if (segment.pool != nullptr) batch.kept.push_back(segment.pool); } done += count; @@ -3348,12 +3484,21 @@ void Recorder::foldSamples(Batch& batch, VkDeviceAddress target, std::uint32_t b bool Recorder::DumpSamples(VkDeviceAddress target, std::uint64_t address, std::uint32_t blocks) { GuestMemory::AssertGpuLockHeld("Recorder::DumpSamples"); if (target == 0 || !gpuSampleCounter()) return false; - countingSamples = true; + startCounting(); flushDeferredDispatch(); + const auto dump = sampleDumps++; if (segmentMode()) { ensureOpen(); + settleShaderSamples(); if (address != 0 && LabelRunsPerBatch() && pendingSamples.size() < SegmentFoldCapacity && open->queuedDumps < DumpFoldCapacity) { if (open->segmentActive) endSegment(*open); + if (TracingShaderSamples()) { + std::size_t first = 0; + for (const auto& earlier : open->run.queued) { + if (earlier.dumpTarget != 0) first = earlier.dumpSegments; + } + traceShaderSamples(dump, target, address, blocks, first); + } if (open->renderPass.open) dumpsQueuedInPass.fetch_add(1, std::memory_order_relaxed); if (open->run.queued.empty()) storeRuns.fetch_add(1, std::memory_order_relaxed); auto& queued = open->run.queued.emplace_back(); @@ -3367,6 +3512,7 @@ bool Recorder::DumpSamples(VkDeviceAddress target, std::uint64_t address, std::u } FlushStores(); Commands(); + if (TracingShaderSamples()) traceShaderSamples(dump, target, address, blocks, 0); foldSamples(*open, target, blocks); dumpsAtOnce.fetch_add(1, std::memory_order_relaxed); return true; @@ -4947,6 +5093,10 @@ bool Recorder::SubmitHeld() const { return submitHold != VK_NULL_HANDLE || (heldSerial != 0 && unsignaled(heldSerial)); } +void Recorder::RefuseGpuSampleCounterForTest(bool refuse) { + refusedGpuSampleCounter.store(refuse, std::memory_order_relaxed); +} + void Recorder::FailNextSubmitsForTest(unsigned count) { injectedSubmitFailures.store(count, std::memory_order_relaxed); } @@ -5627,6 +5777,8 @@ void Recorder::finish(std::unique_ptr batch, bool wait, int source, bool } void Recorder::discard(std::unique_ptr batch) noexcept { + if (batch->shaderSamples) shaderSamplesDirty = true; + if (batch->countingStarted) countingSamples = false; std::erase_if(pendingSamples, [&](const SampleSegment& sample) { return sample.batch == batch->sampleBatch; }); std::erase_if(batch->foldedSamples, [&](const SampleSegment& sample) { return sample.batch == batch->sampleBatch; }); if (pendingSamples.size() + batch->foldedSamples.size() <= pendingSamples.capacity()) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp index 3c0d4e0602a0..37669e8e57ed 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp @@ -176,7 +176,7 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi Require(compiled.program != nullptr, "missing compiled shader"); const auto& shader = *compiled.program; PipelineSpecialization::Validate(shader); - const bool atomicLockTable = std::ranges::any_of(shader.specialization, [](const ShaderRecompiler::PipelineSpecializationConstant& constant) { return ShaderRecompiler::PipelineSpecialization::IsAtomicLockTable(constant.id); }); + const bool pipelineAddress = std::ranges::any_of(shader.specialization, [](const ShaderRecompiler::PipelineSpecializationConstant& constant) { return ShaderRecompiler::PipelineSpecialization::IsPipelineAddress(constant.id); }); const auto stage = compiled.stage; const bool vertex = stage == Stage::Vertex || stage == Stage::Local; const bool fragment = stage == Stage::Fragment; @@ -371,7 +371,7 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi terminateExtension = true; break; } - Require(extension == "SPV_KHR_float_controls" || (fmaFloat16 && extension == "SPV_KHR_fma") || (imageInt64Atomics && extension == "SPV_EXT_shader_image_int64") || (atomicLockTable && extension == "SPV_KHR_physical_storage_buffer") || (viewportIndexLayer && extension == "SPV_EXT_shader_viewport_index_layer") || (fragment && demoteToHelperInvocation && extension == "SPV_EXT_demote_to_helper_invocation") || (mesh && (extension == "SPV_EXT_mesh_shader" || extension == "SPV_KHR_physical_storage_buffer")) || (fragment && !primitiveLocations.empty() && extension == "SPV_EXT_mesh_shader") || (fragment && !shader.stencilReferences.empty() && extension == "SPV_KHR_physical_storage_buffer") || (geometry && state.tessellationCapture && extension == "SPV_KHR_physical_storage_buffer") || ((descriptorIndexing || runtimeDescriptorArray) && extension == "SPV_EXT_descriptor_indexing") || extension == "SPV_KHR_8bit_storage" || (shader.bdaAbiVersion == ShaderRecompiler::BdaAbi::Version && extension == "SPV_KHR_physical_storage_buffer"), "unsupported SPIR-V extension"); + Require(extension == "SPV_KHR_float_controls" || (fmaFloat16 && extension == "SPV_KHR_fma") || (imageInt64Atomics && extension == "SPV_EXT_shader_image_int64") || (pipelineAddress && extension == "SPV_KHR_physical_storage_buffer") || (viewportIndexLayer && extension == "SPV_EXT_shader_viewport_index_layer") || (fragment && demoteToHelperInvocation && extension == "SPV_EXT_demote_to_helper_invocation") || (mesh && (extension == "SPV_EXT_mesh_shader" || extension == "SPV_KHR_physical_storage_buffer")) || (fragment && !primitiveLocations.empty() && extension == "SPV_EXT_mesh_shader") || (fragment && !shader.stencilReferences.empty() && extension == "SPV_KHR_physical_storage_buffer") || (geometry && state.tessellationCapture && extension == "SPV_KHR_physical_storage_buffer") || ((descriptorIndexing || runtimeDescriptorArray) && extension == "SPV_EXT_descriptor_indexing") || extension == "SPV_KHR_8bit_storage" || (shader.bdaAbiVersion == ShaderRecompiler::BdaAbi::Version && extension == "SPV_KHR_physical_storage_buffer"), "unsupported SPIR-V extension"); break; } case spv::OpTerminateInvocation: diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp index 133031a465f8..eeb1db74de50 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp @@ -1129,6 +1129,7 @@ DecodedColorFormat DecodeColorFormatRaw(std::uint32_t format, std::uint32_t numb throw std::runtime_error("AGC graphics: unsupported color format " + std::to_string(format) + " number type " + std::to_string(number) + " component swap " + std::to_string(swap)); }; const bool alternate = swap == 1; + const auto rgbaMapping = static_cast(alternate ? 0xc6u : swap == 2 ? 0x1bu : swap == 3 ? 0x93u : 0xe4u); const auto single = [&](VkFormat vkFormat, std::uint32_t bytes) { return DecodedColorFormat{vkFormat, bytes, static_cast((0xe4u & ~3u) | swap)}; }; if (swap > 1 && format != 1 && format != 2 && format != 4 && format != 7 && format != 10 && format != 12 && format != 16 && format != 19) return fail(); switch (format) { @@ -1192,14 +1193,12 @@ DecodedColorFormat DecodeColorFormatRaw(std::uint32_t format, std::uint32_t numb if (number == floating) return {VK_FORMAT_R32G32_SFLOAT, 8}; if (number == uint) return {VK_FORMAT_R32G32_UINT, 8}; return fail(); - case 12: { - const auto reversed = static_cast(alternate ? 0xc6u : swap == 2 ? 0x1bu : swap == 3 ? 0x93u : 0xe4u); - if (number == floating) return {VK_FORMAT_R16G16B16A16_SFLOAT, 8, reversed}; - if (number == unorm) return {VK_FORMAT_R16G16B16A16_UNORM, 8, reversed}; - if (number == snorm) return {VK_FORMAT_R16G16B16A16_SNORM, 8, reversed}; - if (number == uint) return {VK_FORMAT_R16G16B16A16_UINT, 8, reversed}; + case 12: + if (number == floating) return {VK_FORMAT_R16G16B16A16_SFLOAT, 8, rgbaMapping}; + if (number == unorm) return {VK_FORMAT_R16G16B16A16_UNORM, 8, rgbaMapping}; + if (number == snorm) return {VK_FORMAT_R16G16B16A16_SNORM, 8, rgbaMapping}; + if (number == uint) return {VK_FORMAT_R16G16B16A16_UINT, 8, rgbaMapping}; return fail(); - } case 14: if (swap != 0) return fail(); if (number == floating) return {VK_FORMAT_R32G32B32A32_SFLOAT, 16}; @@ -1212,8 +1211,8 @@ DecodedColorFormat DecodeColorFormatRaw(std::uint32_t format, std::uint32_t numb if (swap != 0 || number != unorm) return fail(); return {VK_FORMAT_A1R5G5B5_UNORM_PACK16, 2, 0xc6u}; case 19: - if (swap != 2 || number != unorm) return fail(); - return {VK_FORMAT_R16_UINT, 2, 0x1bu, ShaderRecompiler::ColorExportPacking::Unorm4_4_4_4}; + if (swap > 3 || number != unorm) return fail(); + return {VK_FORMAT_R16_UINT, 2, rgbaMapping, ShaderRecompiler::ColorExportPacking::Unorm4_4_4_4}; default: return fail(); } @@ -2131,9 +2130,50 @@ State DecodeState(const QueueState& queue, bool vertexWorkgroup) { } state.blendEnable = ((blend >> 30u) & 1u) != 0 && (read(cx, 0x31c + slot * 0xfu) & 0x10000u) == 0; Require(!state.blendEnable || !color.uintExport, "blending into an unsigned integer target is unsupported"); + const bool nibbles = color.packing == ShaderRecompiler::ColorExportPacking::Unorm4_4_4_4; + const bool opaqueDestination = state.blendEnable && (read(cx, 0x31d + slot * 0xfu) & 0x20000u) != 0; + const auto alpha = (blend & 0x20000000u) != 0 ? blend >> 16u : blend; + if (state.blendEnable && nibbles) { + const auto replaces = [opaqueDestination](std::uint32_t equation, auto opaqueFactor) { + auto source = blendFactor(equation & 0x1fu); + auto destination = blendFactor((equation >> 8u) & 0x1fu); + if (opaqueDestination) { + source = opaqueFactor(source); + destination = opaqueFactor(destination); + } + return source == VK_BLEND_FACTOR_ONE && destination == VK_BLEND_FACTOR_ZERO && blendOp((equation >> 5u) & 7u) == VK_BLEND_OP_ADD; + }; + if (((exportedMask & 7u) == 0u || replaces(blend, colorFactorWithOpaqueDestination)) && + ((exportedMask & 8u) == 0u || replaces(alpha, alphaFactorWithOpaqueDestination))) state.blendEnable = VK_FALSE; + } + if (state.blendEnable && nibbles) { + namespace Packing = ShaderRecompiler::Packed4444Blend; + const auto info = read(cx, 0x31c + slot * 0xfu); + char detail[96]; + std::snprintf(detail, sizeof(detail), " (CB_COLOR_INFO 0x%08x, CB_BLEND%u_CONTROL 0x%08x)", info, slot, blend); + const std::string where = detail; + Require((info & 0x8000u) != 0, "blending unclamped color into a 4_4_4_4 unorm target is not implemented" + where); + Require(color.samples == 1u && LogicOpFromRop(result.colorRop) == VK_LOGIC_OP_COPY, "blending into a multisampled 4_4_4_4 unorm target or under a color logic operation is not implemented" + where); + const auto equation = [&](std::uint32_t control, bool writes, auto opaqueFactor) { + if (!writes) return 1u; + const auto operation = blendOp((control >> 5u) & 7u); + if (operation == VK_BLEND_OP_MIN || operation == VK_BLEND_OP_MAX) return static_cast(operation) << 8u; + auto source = blendFactor(control & 0x1fu); + auto destination = blendFactor((control >> 8u) & 0x1fu); + if (opaqueDestination) { + source = opaqueFactor(source); + destination = opaqueFactor(destination); + } + Require(Packing::SupportsFactor(source) && Packing::SupportsFactor(destination), "blending into a 4_4_4_4 unorm target with a constant or dual-source factor is not implemented" + where); + return Packing::EncodeEquation(source, destination, operation); + }; + const auto rgbEquation = equation(blend, (exportedMask & 7u) != 0u, colorFactorWithOpaqueDestination); + const auto alphaEquation = equation(alpha, (exportedMask & 8u) != 0u, alphaFactorWithOpaqueDestination); + color.mergeBlend = Packing::Encode(mapping, rgbEquation, alphaEquation); + state.blendEnable = VK_FALSE; + } const bool reversed = mapping == 0x1bu || mapping == 0x93u; if (state.blendEnable) { - const bool opaqueDestination = (read(cx, 0x31d + slot * 0xfu) & 0x20000u) != 0; const auto recordBlendConstant = [&](std::uint32_t channel, float value) { Require((requiredBlendMask & (1u << channel)) == 0 || requiredBlendConstants[channel] == value, "color targets require conflicting blend constants after component swap"); requiredBlendConstants[channel] = value; @@ -2156,7 +2196,6 @@ State DecodeState(const QueueState& queue, bool vertexWorkgroup) { state.srcColorBlendFactor = blendFactor(blend & 0x1fu); state.dstColorBlendFactor = blendFactor((blend >> 8u) & 0x1fu); state.colorBlendOp = blendOp((blend >> 5u) & 7u); - const auto alpha = (blend & 0x20000000u) != 0 ? blend >> 16u : blend; state.srcAlphaBlendFactor = blendFactor(alpha & 0x1fu); state.dstAlphaBlendFactor = blendFactor((alpha >> 8u) & 0x1fu); state.alphaBlendOp = blendOp((alpha >> 5u) & 7u); @@ -2198,14 +2237,13 @@ State DecodeState(const QueueState& queue, bool vertexWorkgroup) { const std::string packed = std::string(color.packing == ShaderRecompiler::ColorExportPacking::Float11_11_10 ? "an " : "a ") + PackedColorTargetName(color.packing); const auto slotExport = (exportFormat >> (4u * color.exportIndex)) & 0xfu; if (slotExport == 5 || slotExport == 6) throw std::runtime_error("AGC graphics: color export format " + std::to_string(slotExport) + " into " + packed + " target is unsupported"); - if (state.srcColorBlendFactor == VK_BLEND_FACTOR_ONE && state.dstColorBlendFactor == VK_BLEND_FACTOR_ZERO && state.colorBlendOp == VK_BLEND_OP_ADD) state.blendEnable = VK_FALSE; + if (!nibbles && state.srcColorBlendFactor == VK_BLEND_FACTOR_ONE && state.dstColorBlendFactor == VK_BLEND_FACTOR_ZERO && state.colorBlendOp == VK_BLEND_OP_ADD) state.blendEnable = VK_FALSE; const bool floating = color.packing == ShaderRecompiler::ColorExportPacking::Float11_11_10; if (floating && state.blendEnable) { color.mergeBlend = PackedBlendControl(blend); state.blendEnable = VK_FALSE; } Require(!state.blendEnable, "blending into " + packed + " color target is unsupported"); - const bool nibbles = color.packing == ShaderRecompiler::ColorExportPacking::Unorm4_4_4_4; const std::uint32_t packedMask = nibbles ? 0xfu : 7u; Require(nibbles || floating || (exportedMask & packedMask) == packedMask, "partial writes of " + packed + " color target are unsupported"); if ((exportedMask & packedMask) != packedMask || color.mergeBlend != 0u) { @@ -2252,7 +2290,7 @@ State DecodeState(const QueueState& queue, bool vertexWorkgroup) { Require(color.samples == 1u && color.packing == ShaderRecompiler::ColorExportPacking::None, "blending unclamped normalized color into a multisampled or packed color target is not implemented" + where); Require(!reversed && mapping != 0xecu, "blending unclamped normalized color into a color target with a reversed or alternate component order is not implemented" + where); Require(!(secondSource(state.srcColorBlendFactor) || secondSource(state.dstColorBlendFactor) || secondSource(state.srcAlphaBlendFactor) || secondSource(state.dstAlphaBlendFactor)), "dual-source blending of unclamped normalized color is not implemented" + where); - Require(std::ranges::none_of(result.colors, [&](const ColorTarget& other) { return &other != &color && other.partialWriteMask != 0 && other.partialWriteMask != UnclampedBlendMask; }), "blending unclamped normalized color cannot join a partial write of a packed color target in one draw" + where); + Require(std::ranges::none_of(result.colors, [&](const ColorTarget& other) { return &other != &color && other.partialWriteMask != 0 && !other.UnclampedBlend(); }), "blending unclamped normalized color cannot join a partial write of a packed color target in one draw" + where); Require(!SignedNormalizedFormat(color.format) || (state.colorWriteMask & NormalizedChannelMask(color.format)) == NormalizedChannelMask(color.format), "blending unclamped signed normalized color with a write mask that skips a component is not implemented, since the shader rewrites the skipped component through a float and the code -128 would become -127" + where); color.partialWriteMask = UnclampedBlendMask; } @@ -2340,6 +2378,7 @@ ColorTarget StagedMergeTarget(const ColorTarget& staged) { } GuestTextureResource TargetMergeSurface(const ColorTarget& color) { + Require(color.arrayLastSlice == 0u || color.dccAddress == 0u, "a merge into a 2D array color target with DCC keys is not implemented: the merge surface starts at the array, the keys at the viewed slice"); auto surface = color.arrayLastSlice != 0u ? ArraySurfaceForTarget(color) : SurfaceForTarget(color); if (color.samples > 1u) { Require(surface.baseAddress == color.surfaceAddress && surface.dimension == TextureDimension::k2D && surface.mipCount == 1u, "a merged multisampled color target does not start at its single-level surface"); @@ -2381,7 +2420,7 @@ std::vector ExportTargetMerges(const State& state merge.descriptor = EncodeTextureResource(TargetMergeSurface(color)); merge.depthStencilWrites = DepthStencilWrites(state); merge.depthStencilTests = DepthStencilTests(state); - if (color.partialWriteMask != UnclampedBlendMask) continue; + if (!color.UnclampedBlend()) continue; const auto& attachment = state.blends.at(color.exportIndex); auto& blend = merge.blend; blend.enabled = true; @@ -2481,6 +2520,10 @@ std::uint32_t GuestFormatFor(VkFormat format, std::uint32_t elementBytes) { } +VkFormat ColorTargetDccClearFormat(const ColorTarget& color) { + return color.packing == ShaderRecompiler::ColorExportPacking::Unorm4_4_4_4 ? VK_FORMAT_R4G4B4A4_UNORM_PACK16 : color.format; +} + GuestTextureResource SurfaceForTarget(const ColorTarget& color) { static const bool residentLinear = std::getenv("APS5_NO_RESIDENT_LINEAR") == nullptr; Require((residentLinear && color.tileMode == ColorTileMode::Linear) || !ColorTileModeIsLinear(color.tileMode), "linear color targets are not resident"); @@ -2721,7 +2764,19 @@ ColorTarget DecodeColorBuffer(const Registers& cx, std::uint32_t slot, bool allo color.format = decoded.format; color.componentMapping = decoded.componentMapping; color.packing = decoded.packing; - if (WordPacked(color.packing) && (info & 0x10000000u) != 0) throw std::runtime_error("AGC graphics: DCC-compressed " + std::string(PackedColorTargetName(color.packing)) + " color targets are unsupported"); + if (WordPacked(color.packing) && (info & 0x10000000u) != 0 && (color.packing != ShaderRecompiler::ColorExportPacking::Unorm4_4_4_4 || color.samples > 1u || color.mipCount > 1u)) { + char detail[192]; + std::snprintf(detail, sizeof(detail), " (CB_COLOR_INFO 0x%08x, CB_COLOR_ATTRIB 0x%08x, CB_COLOR_ATTRIB3 0x%08x, %ux%u, %u mips, %u samples)", info, attrib, attrib3, color.surfaceExtent.width, color.surfaceExtent.height, color.mipCount, color.samples); + const char* kind = color.packing != ShaderRecompiler::ColorExportPacking::Unorm4_4_4_4 ? "" : color.samples > 1u ? "multisampled " : "mipmapped "; + throw std::runtime_error("AGC graphics: DCC-compressed " + std::string(kind) + PackedColorTargetName(color.packing) + " color targets are unsupported" + detail); + } + if (WordPacked(color.packing) && (info & 0x10000000u) != 0) { + static bool reported = false; + if (!reported) { + reported = true; + std::fprintf(stderr, "[gpu] first DCC %s color target 0x%llx: CB_COLOR_INFO 0x%08x, CB_COLOR_ATTRIB 0x%08x, CB_COLOR_ATTRIB3 0x%08x, %ux%u, %u mips, view mip %u, slices %u-%u\n", PackedColorTargetName(color.packing), static_cast(color.address), info, attrib, attrib3, color.surfaceExtent.width, color.surfaceExtent.height, color.mipCount, viewMip, slice, lastSlice); + } + } Require(color.packing != ShaderRecompiler::ColorExportPacking::Unorm10_11_11 || (info & 0x00040000u) == 0, "truncating (ROUND_MODE) 10_11_11 unorm color targets are unsupported"); Require(color.packing != ShaderRecompiler::ColorExportPacking::Unorm4_4_4_4 || (info & 0x00040000u) == 0, "truncating (ROUND_MODE) 4_4_4_4 unorm color targets are unsupported"); for (std::uint32_t word = 0; word < 2; ++word) { @@ -2781,7 +2836,7 @@ ColorTarget DecodeColorBuffer(const Registers& cx, std::uint32_t slot, bool allo const auto dccBase = ((dccHigh == cx.end() ? 0ull : static_cast(dccHigh->second & 0xffu)) << 40u) | (static_cast(read(cx, 0x325 + stride)) << 8u); if (maxMip == 0) { color.dccAddress = dccBase; - color.dccAlphaOnMsb = DccAlphaOnMsb(color.format, swap); + color.dccAlphaOnMsb = DccAlphaOnMsb(ColorTargetDccClearFormat(color), swap); color.dccPipeAligned = ((attrib3 >> 30u) & 1u) != 0; if (sliceBytes != 0) color.dccAddress += slice * (color.dccPipeAligned ? DccKeyCount(ColorTextureTileMode(color.tileMode), color.elementBytes, color.surfaceExtent.width, color.surfaceExtent.height, sliceBytes) : DccKeyBytes(sliceBytes)); if (color.samples > 1) { @@ -2791,7 +2846,7 @@ ColorTarget DecodeColorBuffer(const Registers& cx, std::uint32_t slot, bool allo } } else if (!volume && color.arrayLastSlice == 0 && slice == 0) { color.chainDccAddress = dccBase; - color.dccAlphaOnMsb = DccAlphaOnMsb(color.format, swap); + color.dccAlphaOnMsb = DccAlphaOnMsb(ColorTargetDccClearFormat(color), swap); color.dccPipeAligned = ((attrib3 >> 30u) & 1u) != 0; if (color.dccPipeAligned && ColorTextureTileMode(color.tileMode) == TextureTileMode::kR64KBX && !RuntimeSwitches::Set(RuntimeSwitch::NoDccMipFastClear)) { if (const auto offset = DccMipKeyOffset(color.surfaceExtent.width, color.surfaceExtent.height, color.elementBytes, color.mipCount, std::min(firstTailLevel, color.mipCount), color.mip)) color.dccAddress = dccBase + *offset; diff --git a/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp b/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp index 2bace0853428..85b3fde5bc8a 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp @@ -2021,6 +2021,49 @@ void UnclampedNormalizedColorTests() { queue.context[0x1e0] = blending; state = DecodeState(queue); Require(state.colors.at(0).partialWriteMask == AgcDriver::Graphics::UnclampedBlendMask && AgcDriver::Graphics::ExportTargetMerges(state).at(0).blend.snorm, "an unclamped SNORM target that blends was not routed to the pixel shader as signed"); + auto keyed = target(0x1000000cu); + keyed.context[0x325] = 0x1234; + keyed.context[0x1e0] = blending; + state = DecodeState(keyed); + const auto keyedSurface = AgcDriver::Graphics::DecodeTextureResource(AgcDriver::Graphics::ExportTargetMerges(state).at(0).descriptor); + const auto keyedTarget = AgcDriver::Graphics::SurfaceForTarget(state.colors.at(0)); + Require(state.colors.at(0).partialWriteMask == AgcDriver::Graphics::UnclampedBlendMask && state.colors.at(0).dccAddress == 0x123400u && keyedSurface.dccAddress == 0x123400u && keyedSurface.dccAlphaOnMsb == state.colors.at(0).dccAlphaOnMsb && keyedSurface.dccPipeAligned == state.colors.at(0).dccPipeAligned && keyedSurface.baseAddress == keyedTarget.baseAddress && keyedSurface.format == keyedTarget.format && keyedSurface.mipCount == 1u, "an unclamped blend into a DCC 8_8 UNORM target (CB_COLOR_INFO 0x1000000c) did not merge through a descriptor that carries the target's keys"); + { + constexpr std::uint32_t mipSide = 128; + constexpr std::size_t mipBlockAlignment = 65536; + constexpr std::size_t mipKeysOffset = std::size_t{1} << 19u; + std::vector mipBlock(mipBlockAlignment + 2 * mipKeysOffset); + const auto mipAddress = (reinterpret_cast(mipBlock.data()) + mipBlockAlignment - 1) / mipBlockAlignment * mipBlockAlignment; + const auto mipKeys = mipAddress + mipKeysOffset; + auto chain = target(0x1000000cu); + chain.context[0x318] = static_cast(mipAddress >> 8u); + chain.context[0x390] = static_cast(mipAddress >> 40u); + chain.context[0x325] = static_cast(mipKeys >> 8u); + chain.context[0x3a8] = static_cast(mipKeys >> 40u); + chain.context[0x3b0] = (3u << 28u) | ((mipSide - 1u) << 14u) | (mipSide - 1u); + chain.context[0x3b8] |= (static_cast(AgcDriver::Graphics::ColorTileMode::RenderTarget) << 14u) | (1u << 30u); + chain.context[0x31b] = 1u << 26u; + chain.context[0x1e0] = blending; + state = DecodeState(chain); + const auto& viewed = state.colors.at(0); + const auto mipSurface = AgcDriver::Graphics::DecodeTextureResource(AgcDriver::Graphics::ExportTargetMerges(state).at(0).descriptor); + Require(viewed.partialWriteMask == AgcDriver::Graphics::UnclampedBlendMask && viewed.mip == 1u && viewed.mipCount == 4u && viewed.chainDccAddress == mipKeys && mipSurface.dccAddress == mipKeys && mipSurface.baseAddress == mipAddress && mipSurface.mipCount == 4u && mipSurface.baseLevel == 1u && mipSurface.lastLevel == 1u && mipSurface.dccPipeAligned, "an unclamped blend into mip 1 of a mipmapped DCC 8_8 UNORM target did not merge through a descriptor of that mip that carries the chain's keys"); + for (const std::uint32_t slice : {0u, 1u}) { + auto layered = target(0x1000000cu); + layered.context[0x318] = static_cast(mipAddress >> 8u); + layered.context[0x390] = static_cast(mipAddress >> 40u); + layered.context[0x325] = static_cast(mipKeys >> 8u); + layered.context[0x3a8] = static_cast(mipKeys >> 40u); + layered.context[0x3b0] = ((mipSide - 1u) << 14u) | (mipSide - 1u); + layered.context[0x3b8] |= (static_cast(AgcDriver::Graphics::ColorTileMode::RenderTarget) << 14u) | (1u << 30u) | 3u; + layered.context[0x31b] = slice | (slice << 13u); + layered.context[0x1e0] = blending; + const auto arrayState = DecodeState(layered); + const auto& layer = arrayState.colors.at(0); + Require(layer.partialWriteMask == AgcDriver::Graphics::UnclampedBlendMask && layer.arrayLastSlice == 3u && layer.arraySlice == slice && layer.dccAddress >= mipKeys, "an unclamped blend into slice " + std::to_string(slice) + " of a four-slice DCC 8_8 UNORM array did not decode with its keys"); + expectFailure([&] { static_cast(AgcDriver::Graphics::ExportTargetMerges(arrayState)); }, "a merge into a 2D array color target with DCC keys is not implemented"); + } + } auto unsignedMasked = target(0x0000000cu); unsignedMasked.context[0x1e0] = blending; unsignedMasked.context[0x8e] = 0x1u; @@ -3988,6 +4031,34 @@ void metadataPassTests() { Require(AgcDriver::Graphics::FillDccClear(tenBitPass->targets[0].format, clear.keys, tenBitPass->targets[0].dccAlphaOnMsb, std::as_writable_bytes(std::span(copied))) && std::ranges::all_of(copied, [&](std::uint32_t word) { return word == clear.texel; }), "a copied " + name + " target under " + clear.code + " keys was not filled with its 10/10/10/2 texel"); } } + for (const std::uint32_t swap : {0u, 1u, 2u, 3u}) { + auto nibbles = queue; + nibbles.context[0x31c] = (nibbles.context[0x31c] & ~0x187cu) | (19u << 2u) | (swap << 11u); + nibbles.context[0x323] = 0x7c3a; + const auto nibblePass = DecodeColorMetadataPass(nibbles); + const bool alphaOnMsb = swap < 2u; + Require(nibblePass.has_value() && nibblePass->targets.size() == 1 && nibblePass->targets[0].format == VK_FORMAT_R16_UINT && nibblePass->targets[0].packing == ShaderRecompiler::ColorExportPacking::Unorm4_4_4_4 && nibblePass->targets[0].dccAddress == keysAddress && nibblePass->targets[0].dccAlphaOnMsb == alphaOnMsb, "the metadata pass target of a DCC 4_4_4_4 unorm target with component swap " + std::to_string(swap) + " changed"); + const auto nibbleBytes = static_cast(nibblePass->targets[0].bytes); + Require(nibbleBytes != 0 && nibbleBytes <= colorMemory.size() && nibbleBytes % 256u == 0 && nibbleBytes / 256u <= dccKeys.size(), "the 4_4_4_4 unorm metadata pass target does not fit the test surface"); + const auto alphaWord = static_cast(alphaOnMsb ? 0xf000u : 0x000fu); + struct NibbleClear { + std::uint8_t key; + std::uint16_t word; + const char* code; + }; + for (const auto& clear : {NibbleClear{0x00, 0x0000u, "0000"}, NibbleClear{0x40, alphaWord, "0001"}, NibbleClear{0x80, static_cast(~alphaWord), "1110"}, NibbleClear{0xc0, 0xffffu, "1111"}, NibbleClear{0x20, 0x7c3au, "register"}, NibbleClear{0xff, 0x5a5au, "uncompressed"}}) { + std::memset(colorMemory.data(), 0x5a, colorMemory.size()); + dccKeys.fill(clear.key); + AgcDriver::Graphics::RunColorMetadataPass(context, *nibblePass); + bool filled = true; + for (std::size_t offset = 0; offset < nibbleBytes; offset += 2) { + std::uint16_t word = 0; + std::memcpy(&word, colorMemory.data() + offset, 2); + filled = filled && word == clear.word; + } + Require(filled && std::all_of(dccKeys.begin(), dccKeys.begin() + static_cast(nibbleBytes / 256u), [](std::uint8_t key) { return key == 0xff; }), std::string("a ") + clear.code + " fast clear of a 4_4_4_4 unorm target with component swap " + std::to_string(swap) + " was not eliminated into its four nibbles"); + } + } constexpr std::uint32_t tiledSide = 128; constexpr std::size_t tiledBytes = tiledSide * tiledSide * 4; @@ -12857,6 +12928,75 @@ void unorm4_4_4_4TargetTests() { const auto packings = AgcDriver::Graphics::ExportPackings(state); Require(packings[0] == ColorExportPacking::Unorm4_4_4_4 && std::all_of(packings.begin() + 1, packings.end(), [](ColorExportPacking packing) { return packing == ColorExportPacking::None; }), "export 0 did not carry the 4_4_4_4 unorm packing"); Require(state.color.partialWriteMask == 0u && state.blends[0].colorWriteMask == 0xfu && AgcDriver::Graphics::ExportTargetMerges(state).empty(), "a full write of a 4_4_4_4 unorm target merged into the target"); + + { + auto blending = queue; + blending.context[0x31c] = (blending.context.at(0x31c) & ~((3u << 11u) | 0x10000u)) | (1u << 11u); + blending.context[0x8e] = 0xfu; + blending.context[0x1e0] = 0x61010001u; + const auto both = AgcDriver::Graphics::DecodeState(blending); + const auto merge = AgcDriver::Graphics::ExportTargetMerges(both).at(0); + namespace Packing = ShaderRecompiler::Packed4444Blend; + const auto replace = Packing::EncodeEquation(VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ZERO, VK_BLEND_OP_ADD); + const auto add = Packing::EncodeEquation(VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE, VK_BLEND_OP_ADD); + Require(!both.blend.blendEnable && both.blend.colorWriteMask == 0u && merge.mask == 0xffffu && !merge.blend.enabled && + merge.packing == ColorExportPacking::Unorm4_4_4_4 && merge.blendControl == Packing::Encode(0xc6u, replace, add), + "a full 4_4_4_4 blend did not use its own packed target and separate alpha equation"); + + blending.context[0x8e] = 7u; + const auto rgbOnly = AgcDriver::Graphics::DecodeState(blending); + Require(!rgbOnly.blend.blendEnable && rgbOnly.color.partialWriteMask == 0x0fffu, "a 4_4_4_4 write that excludes alpha must replace RGB and preserve the alpha nibble"); + + blending.context[0x8e] = 0xfu; + blending.context[0x1e0] = 0x60010001u; + Require(!AgcDriver::Graphics::DecodeState(blending).blend.blendEnable, "a 4_4_4_4 replacement equation must disable blending"); + + blending.context[0x31d] = 0x20000u; + blending.context[0x1e0] = 0x67060001u; + Require(!AgcDriver::Graphics::DecodeState(blending).blend.blendEnable, "a 4_4_4_4 replacement equation with an opaque destination must disable blending"); + } + + { + auto alphaOnly = queue; + alphaOnly.context[0x31c] &= ~((3u << 11u) | 0x10000u); + alphaOnly.context[0x8e] = 8u; + alphaOnly.context[0x1e0] = 0x60010504u; + const auto result = AgcDriver::Graphics::DecodeState(alphaOnly); + Require(!result.blend.blendEnable && result.color.partialWriteMask == 0xf000u, "an alpha-only 4_4_4_4 replacement must ignore the RGB blend equation"); + + alphaOnly.context[0x8e] = 0xfu; + const auto all = AgcDriver::Graphics::DecodeState(alphaOnly); + const auto merge = AgcDriver::Graphics::ExportTargetMerges(all).at(0); + namespace Packing = ShaderRecompiler::Packed4444Blend; + const auto over = Packing::EncodeEquation(VK_BLEND_FACTOR_SRC_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, VK_BLEND_OP_ADD); + const auto replace = Packing::EncodeEquation(VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ZERO, VK_BLEND_OP_ADD); + Require(merge.mask == 0xffffu && merge.blendControl == Packing::Encode(0xe4u, over, replace), "4_4_4_4 RGB blend lost its separate alpha replacement"); + + alphaOnly.context[0x31c] &= ~0x8000u; + expectFailure([&] { AgcDriver::Graphics::DecodeState(alphaOnly); }, "blending unclamped color into a 4_4_4_4 unorm target"); + alphaOnly.context[0x31c] |= 0x8000u; + alphaOnly.context[0x1e0] = 0x4000050du; + expectFailure([&] { AgcDriver::Graphics::DecodeState(alphaOnly); }, "with a constant or dual-source factor"); + } + + { + auto replacement = queue; + replacement.context[0x1e0] = 0x40000001u; + for (const auto& [swap, mapping] : {std::pair{2u, 0x1bu}, std::pair{3u, 0x93u}}) { + replacement.context[0x31c] = (replacement.context.at(0x31c) & ~((3u << 11u) | 0x10000u)) | (swap << 11u); + const auto result = AgcDriver::Graphics::DecodeState(replacement); + Require(!result.blend.blendEnable && result.color.componentMapping == mapping, "a reversed 4_4_4_4 replacement must keep its component order and bypass blending"); + } + replacement.context[0x1e0] = 0x61010001u; + const auto blended = AgcDriver::Graphics::DecodeState(replacement); + const auto merge = AgcDriver::Graphics::ExportTargetMerges(blended).at(0); + namespace Packing = ShaderRecompiler::Packed4444Blend; + const auto replace = Packing::EncodeEquation(VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ZERO, VK_BLEND_OP_ADD); + const auto add = Packing::EncodeEquation(VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE, VK_BLEND_OP_ADD); + Require(merge.blendControl == Packing::Encode(0x93u, replace, add) && !blended.dualSourceBlend, + "the reversed packed blend lost its component order or used the two-source attachment path"); + } + auto changed = queue; for (const auto& [targetMask, wordMask] : {std::pair{1u, 0xf000u}, std::pair{7u, 0xfff0u}, std::pair{8u, 0x000fu}, std::pair{0xau, 0x0f0fu}}) { changed.context[0x8e] = targetMask; @@ -13147,15 +13287,72 @@ void unorm4_4_4_4TargetTests() { unmergedCounting.context.pixel->targetMerges = {}; static_cast(ShaderRecompiler::Recompile(unmergedCounting)); } - for (const auto& [number, swap] : {std::pair{1u, 2u}, std::pair{4u, 2u}, std::pair{0u, 0u}, std::pair{0u, 1u}, std::pair{0u, 3u}}) { + for (const auto& [swap, redMask] : {std::pair{0u, 0x000fu}, std::pair{1u, 0x0f00u}, std::pair{2u, 0xf000u}, std::pair{3u, 0x00f0u}}) { + changed = queue; + changed.context[0x31c] = (changed.context[0x31c] & ~(3u << 11u)) | (swap << 11u); + changed.context[0x8e] = 1u; + const auto partial = AgcDriver::Graphics::DecodeState(changed); + Require(partial.color.partialWriteMask == redMask, "a red-only 4_4_4_4 write selected the wrong nibble for component swap " + std::to_string(swap)); + } + for (const auto number : {1u, 4u}) { + changed = queue; + changed.context[0x31c] |= number << 8u; + expectFailure([&] { AgcDriver::Graphics::DecodeState(changed); }, "unsupported color format 19 number type " + std::to_string(number) + " component swap 2"); + } + for (const auto& [swap, alphaOnMsb] : {std::pair{0u, true}, std::pair{1u, true}, std::pair{2u, false}, std::pair{3u, false}}) { changed = queue; - changed.context[0x31c] = (changed.context[0x31c] & ~((7u << 8u) | (3u << 11u))) | (number << 8u) | (swap << 11u); - expectFailure([&] { AgcDriver::Graphics::DecodeState(changed); }, "unsupported color format 19 number type " + std::to_string(number) + " component swap " + std::to_string(swap)); + changed.context[0x31c] = (changed.context[0x31c] & ~(3u << 11u)) | (swap << 11u) | 0x10000000u; + changed.context[0x325] = 0x1234; + const auto keyed = AgcDriver::Graphics::DecodeState(changed); + Require(keyed.color.format == VK_FORMAT_R16_UINT && keyed.color.packing == ColorExportPacking::Unorm4_4_4_4 && keyed.color.dccAddress == 0x123400u && keyed.color.dccAlphaOnMsb == alphaOnMsb, "a DCC 4_4_4_4 unorm target with component swap " + std::to_string(swap) + " lost its keys or the side its alpha nibble is on"); + Require(AgcDriver::Graphics::ColorTargetDccClearFormat(keyed.color) == VK_FORMAT_R4G4B4A4_UNORM_PACK16 && AgcDriver::Graphics::SurfaceForTarget(keyed.color).dccAddress == 0x123400u, "a DCC 4_4_4_4 unorm target does not expand its clear codes over four nibbles, or its resident surface lost the keys"); + struct NibbleClear { + AgcDriver::Graphics::DccKeys keys; + std::uint16_t word; + }; + const auto alphaWord = static_cast(alphaOnMsb ? 0xf000u : 0x000fu); + for (const auto& clear : {NibbleClear{AgcDriver::Graphics::DccKeys::Clear0000, 0x0000u}, NibbleClear{AgcDriver::Graphics::DccKeys::Clear0001, alphaWord}, NibbleClear{AgcDriver::Graphics::DccKeys::Clear1110, static_cast(~alphaWord)}, NibbleClear{AgcDriver::Graphics::DccKeys::Clear1111, 0xffffu}}) { + std::array words{}; + words.fill(0x5a5au); + Require(AgcDriver::Graphics::FillDccClear(AgcDriver::Graphics::ColorTargetDccClearFormat(keyed.color), clear.keys, keyed.color.dccAlphaOnMsb, std::as_writable_bytes(std::span(words))) && std::ranges::all_of(words, [&](std::uint16_t word) { return word == clear.word; }), std::string("a ") + AgcDriver::Graphics::DccKeysName(clear.keys) + " clear of a 4_4_4_4 unorm target with component swap " + std::to_string(swap) + " did not fill its nibbles"); + } + auto blended = changed; + blended.context[0x8e] = 0xfu; + blended.context[0x1e0] = 0x40000504u; + const auto blendedState = AgcDriver::Graphics::DecodeState(blended); + const auto blendedMerges = AgcDriver::Graphics::ExportTargetMerges(blendedState); + Require(blendedMerges.size() == 1u && blendedState.color.mergeBlend != 0u && blendedMerges[0].mask == 0xffffu && blendedMerges[0].blendControl == blendedState.color.mergeBlend, "a source-over blend into a DCC 4_4_4_4 unorm target with component swap " + std::to_string(swap) + " did not merge in the pixel shader"); + const auto blendedSurface = AgcDriver::Graphics::DecodeTextureResource(blendedMerges[0].descriptor); + const auto expectedSurface = AgcDriver::Graphics::TargetMergeSurface(blendedState.color); + Require(blendedSurface.dccAddress == 0x123400u && blendedSurface.dccAlphaOnMsb == alphaOnMsb && blendedSurface.dccPipeAligned == expectedSurface.dccPipeAligned && blendedSurface.baseAddress == expectedSurface.baseAddress && blendedSurface.format == expectedSurface.format && blendedSurface.tileMode == expectedSurface.tileMode && blendedSurface.width == expectedSurface.width && blendedSurface.height == expectedSurface.height, "the merge descriptor of a blended DCC 4_4_4_4 unorm target with component swap " + std::to_string(swap) + " lost the target's DCC keys"); + } + { + constexpr std::uint32_t mipSide = 128; + constexpr std::size_t mipBlockAlignment = 65536; + constexpr std::size_t mipKeysOffset = std::size_t{1} << 19u; + std::vector mipBlock(mipBlockAlignment + 2 * mipKeysOffset); + const auto mipAddress = (reinterpret_cast(mipBlock.data()) + mipBlockAlignment - 1) / mipBlockAlignment * mipBlockAlignment; + const auto mipKeys = mipAddress + mipKeysOffset; + for (const std::uint32_t swap : {0u, 1u, 2u, 3u}) { + changed = queue; + changed.context[0x31c] = (changed.context[0x31c] & ~(3u << 11u)) | (swap << 11u) | 0x10000000u; + changed.context[0x318] = static_cast(mipAddress >> 8u); + changed.context[0x390] = static_cast(mipAddress >> 40u); + changed.context[0x325] = static_cast(mipKeys >> 8u); + changed.context[0x3a8] = static_cast(mipKeys >> 40u); + changed.context[0x3b0] = (3u << 28u) | ((mipSide - 1u) << 14u) | (mipSide - 1u); + changed.context[0x3b8] |= (static_cast(AgcDriver::Graphics::ColorTileMode::RenderTarget) << 14u) | (1u << 30u); + expectFailure([&] { static_cast(AgcDriver::Graphics::DecodeColorBuffer(changed.context, 0)); }, "DCC-compressed mipmapped 4_4_4_4 unorm color targets"); + changed.context[0x31c] &= ~0x10000000u; + const auto plain = AgcDriver::Graphics::DecodeColorBuffer(changed.context, 0); + Require(plain.format == VK_FORMAT_R16_UINT && plain.mipCount == 4u && plain.dccAddress == 0 && plain.chainDccAddress == 0, "a mipmapped 4_4_4_4 unorm target without DCC with component swap " + std::to_string(swap) + " was refused or kept keys"); + } } changed = queue; changed.context[0x31c] |= 0x10000000u; changed.context[0x325] = 0x1234; - expectFailure([&] { AgcDriver::Graphics::DecodeState(changed); }, "DCC-compressed 4_4_4_4 unorm color targets"); + changed.context[0x31d] = (changed.context.at(0x31d) & ~0x3f000u) | (1u << 12u) | (1u << 15u); + expectFailure([&] { AgcDriver::Graphics::DecodeState(changed); }, "DCC-compressed multisampled 4_4_4_4 unorm color targets"); changed = queue; changed.context[0x31c] |= 0x40000u; expectFailure([&] { AgcDriver::Graphics::DecodeState(changed); }, "truncating (ROUND_MODE) 4_4_4_4 unorm color targets"); diff --git a/core/libs/prx/libSceAgcDriver/tests/GuestTextureResource.cpp b/core/libs/prx/libSceAgcDriver/tests/GuestTextureResource.cpp index 10899b86a53e..18b7ee3fafc5 100644 --- a/core/libs/prx/libSceAgcDriver/tests/GuestTextureResource.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/GuestTextureResource.cpp @@ -876,5 +876,56 @@ void RunGuestTextureResourceTests() { Require(oneDGeometry.layers == 4u && oneDGeometry.layers == twoDGeometry.layers && oneDGeometry.layerBytes == twoDGeometry.layerBytes && oneDGeometry.guestBytes == twoDGeometry.guestBytes && oneDGeometry.mips.size() == twoDGeometry.mips.size() && oneDGeometry.mips[0].tiledSize == twoDGeometry.mips[0].tiledSize && oneDGeometry.mips[0].pitchBytes == twoDGeometry.mips[0].pitchBytes, "a PS4 1D array was not laid out like the height-1 2D array the PS4 tile mode table describes"); } + GuestTextureResource keyed{}; + keyed.baseAddress = 0x12340000u; + keyed.width = 2560u; + keyed.height = 1440u; + keyed.mipCount = 1u; + keyed.tileMode = TextureTileMode::kR64KBX; + keyed.dimension = TextureDimension::k2D; + keyed.format = 11u; + keyed.dstSelX = 4u; + keyed.dstSelY = 5u; + keyed.dstSelZ = 6u; + keyed.dstSelW = 7u; + for (const auto& [alphaOnMsb, pipeAligned] : {std::pair{true, true}, std::pair{false, false}}) { + keyed.dccAddress = 0xfb6d000000ull + (alphaOnMsb ? 0x1200u : 0x3400u); + keyed.dccAlphaOnMsb = alphaOnMsb; + keyed.dccPipeAligned = pipeAligned; + const auto words = EncodeTextureResource(keyed); + const auto decoded = DecodeTextureResource(words); + Require(decoded.dccAddress == keyed.dccAddress && decoded.dccAlphaOnMsb == alphaOnMsb && decoded.dccPipeAligned == pipeAligned && decoded.fmaskCmaskAddress == 0u && decoded.baseAddress == keyed.baseAddress && decoded.width == keyed.width && decoded.height == keyed.height && decoded.format == keyed.format && decoded.tileMode == keyed.tileMode && decoded.dimension == keyed.dimension, "an encoded texture descriptor with DCC keys did not decode to the same keys and surface"); + } + keyed.dccAddress = 0x12345680u; + reject([&] { static_cast(EncodeTextureResource(keyed)); }, "DCC key address has no texture descriptor encoding"); + keyed.dccAddress = 0x123400u; + keyed.dimension = TextureDimension::k2DMsaa; + keyed.samples = 2u; + reject([&] { static_cast(EncodeTextureResource(keyed)); }, "single-level multisampled surfaces without metadata"); + keyed.samples = 1u; + keyed.dimension = TextureDimension::k2DArray; + keyed.depthOrLastArray = 5u; + keyed.baseArray = 2u; + keyed.dccAddress = 0xfb6d005600ull; + keyed.dccAlphaOnMsb = false; + keyed.dccPipeAligned = true; + const auto keyedArray = DecodeTextureResource(EncodeTextureResource(keyed)); + Require(keyedArray.dimension == TextureDimension::k2DArray && keyedArray.depthOrLastArray == 5u && keyedArray.baseArray == 2u && keyedArray.dccAddress == keyed.dccAddress && !keyedArray.dccAlphaOnMsb && keyedArray.dccPipeAligned && keyedArray.baseAddress == keyed.baseAddress, "an encoded 2D array texture descriptor with DCC keys did not decode to the same slices and keys"); + keyed.dimension = TextureDimension::k2D; + keyed.depthOrLastArray = 0u; + keyed.baseArray = 0u; + keyed.mipCount = 4u; + keyed.baseLevel = 2u; + keyed.lastLevel = 2u; + const auto keyedMip = DecodeTextureResource(EncodeTextureResource(keyed)); + Require(keyedMip.mipCount == 4u && keyedMip.baseLevel == 2u && keyedMip.lastLevel == 2u && keyedMip.dccAddress == keyed.dccAddress && keyedMip.width == keyed.width && keyedMip.height == keyed.height && keyedMip.baseAddress == keyed.baseAddress, "an encoded texture descriptor of one mip of a chain with DCC keys did not decode to the same levels and keys"); + keyed.mipCount = 1u; + keyed.baseLevel = 0u; + keyed.lastLevel = 0u; + keyed.dccAddress = 0xfedcba987600ull; + Require(DecodeTextureResource(EncodeTextureResource(keyed)).dccAddress == keyed.dccAddress, "an encoded texture descriptor with DCC keys above 2^40 did not decode to the same key address"); + keyed.dccAddress = 0x1000000000000ull; + reject([&] { static_cast(EncodeTextureResource(keyed)); }, "DCC key address has no texture descriptor encoding"); + RunRememberedRejectionTests(); } diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_packed_unorm4444_dcc_target_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_packed_unorm4444_dcc_target_tests.cmake new file mode 100644 index 000000000000..1396c19b3941 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_packed_unorm4444_dcc_target_tests.cmake @@ -0,0 +1,9 @@ +target_include_directories(agc_driver_packed_unorm4444_dcc_target_tests PRIVATE $) +if(BUILD_TESTING) + add_test(NAME agc_driver_packed_unorm4444_dcc_target_no_resident COMMAND agc_driver_packed_unorm4444_dcc_target_tests) + set_tests_properties(agc_driver_packed_unorm4444_dcc_target_no_resident PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_NO_RESIDENT_TARGETS=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 30) + if(WIN32) + set_tests_properties(agc_driver_packed_unorm4444_dcc_target_no_resident PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_packed_unorm4444_partial_write_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_packed_unorm4444_partial_write_tests.cmake index d6904e9ecde6..bba530326d82 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_packed_unorm4444_partial_write_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_packed_unorm4444_partial_write_tests.cmake @@ -1 +1,17 @@ target_include_directories(agc_driver_packed_unorm4444_partial_write_tests PRIVATE $) +if(BUILD_TESTING) + add_test(NAME agc_driver_packed_unorm4444_partial_write_no_gpu_counter COMMAND agc_driver_packed_unorm4444_partial_write_tests no-gpu-counter) + set_tests_properties(agc_driver_packed_unorm4444_partial_write_no_gpu_counter PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 30) + add_test(NAME agc_driver_packed_unorm4444_partial_write_discarded_start COMMAND agc_driver_packed_unorm4444_partial_write_tests discarded-start) + set_tests_properties(agc_driver_packed_unorm4444_partial_write_discarded_start PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 30) + add_test(NAME agc_driver_packed_unorm4444_partial_write_multisampled_kill COMMAND agc_driver_packed_unorm4444_partial_write_tests multisampled-kill) + set_tests_properties(agc_driver_packed_unorm4444_partial_write_multisampled_kill PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 30) + add_test(NAME agc_driver_packed_unorm4444_partial_write_coverage_kill COMMAND agc_driver_packed_unorm4444_partial_write_tests coverage-kill) + set_tests_properties(agc_driver_packed_unorm4444_partial_write_coverage_kill PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 30) + add_test(NAME agc_driver_packed_unorm4444_partial_write_sample_mask_kill COMMAND agc_driver_packed_unorm4444_partial_write_tests sample-mask-kill) + set_tests_properties(agc_driver_packed_unorm4444_partial_write_sample_mask_kill PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 30) + if(WIN32) + set_tests_properties(agc_driver_packed_unorm4444_partial_write_no_gpu_counter agc_driver_packed_unorm4444_partial_write_discarded_start agc_driver_packed_unorm4444_partial_write_multisampled_kill agc_driver_packed_unorm4444_partial_write_coverage_kill agc_driver_packed_unorm4444_partial_write_sample_mask_kill PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/PackedUnorm4444ColorTarget.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/PackedUnorm4444ColorTarget.cpp index 85326136cf85..4615d41f2f85 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/PackedUnorm4444ColorTarget.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/PackedUnorm4444ColorTarget.cpp @@ -30,6 +30,7 @@ #include #include #include +#include #include namespace { @@ -43,7 +44,7 @@ constexpr std::uint32_t Width = 256; constexpr std::uint32_t Height = 128; constexpr std::uint32_t ScissorWidth = 128; constexpr std::size_t BlockBytes = 65536; -constexpr std::uint32_t Unorm4_4_4_4Info = 0x8000u | (19u << 2u) | (2u << 11u); +constexpr std::uint32_t Unorm4_4_4_4Info = 0x8000u | (19u << 2u); constexpr std::uint32_t LinearAttrib3 = 0x09000000u; constexpr std::uint32_t Float32Export = 9; constexpr std::uint32_t Float16Export = 4; @@ -152,17 +153,17 @@ struct Block { std::uint8_t* data = nullptr; }; -AgcDriver::Graphics::ColorTarget DecodeTarget(const Block& block, std::uint32_t attrib3) { +AgcDriver::Graphics::ColorTarget DecodeTarget(const Block& block, std::uint32_t attrib3, std::uint32_t swap) { AgcDriver::Registers cx; cx[0x318] = static_cast(block.Address() >> 8u); cx[0x31b] = 0; - cx[0x31c] = Unorm4_4_4_4Info; + cx[0x31c] = Unorm4_4_4_4Info | (swap << 11u); cx[0x31d] = 0; cx[0x3b0] = ((Width - 1u) << 14u) | (Height - 1u); cx[0x3b8] = attrib3; cx[0x390] = static_cast(block.Address() >> 40u); auto color = AgcDriver::Graphics::DecodeColorBuffer(cx, 0); - Require(color.format == VK_FORMAT_R16_UINT && color.elementBytes == 2 && color.componentMapping == 0x1bu && color.packing == ShaderRecompiler::ColorExportPacking::Unorm4_4_4_4 && color.bytes == block.bytes, "the 4_4_4_4 unorm target did not decode as a packed R16_UINT target"); + Require(color.format == VK_FORMAT_R16_UINT && color.elementBytes == 2 && color.packing == ShaderRecompiler::ColorExportPacking::Unorm4_4_4_4 && color.bytes == block.bytes, "the 4_4_4_4 unorm target did not decode as a packed R16_UINT target"); return color; } @@ -275,7 +276,7 @@ std::string Describe(std::array rgba) { void TargetTests(AgcDriver::VulkanDevice& device, Block& block, std::uint32_t attrib3, ColorTileMode mode, const char* kind) { const ColorTargetLayout layout(Width, Height, mode, 2); Require(layout.Bytes() == block.bytes, "the test surface size disagrees with its layout"); - const auto color = DecodeTarget(block, attrib3); + const auto color = DecodeTarget(block, attrib3, 2u); auto before = Fill(block); const float nan = std::numeric_limits::quiet_NaN(); const float infinity = std::numeric_limits::infinity(); @@ -311,6 +312,11 @@ void TargetTests(AgcDriver::VulkanDevice& device, Block& block, std::uint32_t at ExpectSurface(device, block, layout, before, golden.word, std::string("an FP16_ABGR export of ") + Describe(golden.rgba) + " into a " + kind + " 4_4_4_4 unorm target"); before = ReadBack(device, block); } + const auto distinctChannels = Float32Program({1.0f / 15.0f, 2.0f / 15.0f, 7.0f / 15.0f, 14.0f / 15.0f}); + for (const auto& [swap, word] : {std::pair{1u, 0xe127u}, std::pair{0u, 0xe721u}, std::pair{3u, 0x721eu}}) { + Draw(device, DecodeTarget(block, attrib3, swap), Float32Export, distinctChannels); + ExpectSurface(device, block, layout, before, word, "a 4_4_4_4 unorm target with component swap " + std::to_string(swap)); + } } } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/PackedUnorm4444DccTarget.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/PackedUnorm4444DccTarget.cpp new file mode 100644 index 000000000000..e0d81d27ddf6 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/PackedUnorm4444DccTarget.cpp @@ -0,0 +1,538 @@ +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp" +#include "prx/libSceAgcDriver/Graphics/include/ColorTargetLayout.hpp" +#include "prx/libSceAgcDriver/Graphics/include/DccMetadata.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "prx/libSceAgcDriver/Graphics/include/ShaderInputState.hpp" +#include "prx/libSceAgcDriver/Graphics/include/State.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" +#include "prx/libc/include/GuestAllocations.hpp" +#include "prx/libc/include/GuestArena.hpp" +#include "prx/libc/include/GuestWriteWatch.hpp" +#include "Recompiler.hpp" +#include "Optimization/ResourceProgram.hpp" +#include "VulkanTestDevice.hpp" +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#else +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::ColorTargetLayout; +using AgcDriver::Graphics::ColorTileMode; +using AgcDriver::Graphics::DccKeys; +using AgcDriver::Graphics::Require; +using ShaderRecompiler::ShaderStage; + +constexpr std::uint32_t Width = 256; +constexpr std::uint32_t Height = 128; +constexpr std::uint32_t ScissorWidth = 128; +constexpr std::size_t BlockBytes = 65536; +constexpr std::size_t KeyBytes = BlockBytes / 256; +constexpr std::uint32_t Unorm4_4_4_4Info = 0x8000u | (19u << 2u); +constexpr std::uint32_t DccEnable = 0x10000000u; +constexpr std::uint32_t TiledAttrib3 = 0x4dc6c000u; +constexpr std::uint32_t Float32Export = 9; +constexpr std::uint16_t RegisterWord = 0x7c3a; + +alignas(256) constexpr std::array VertexCode{ + 0xe0382000, 0x80000005, 0xbf8c3f70, 0xf80008cf, 0x03020100, 0xbf810000, +}; + +constexpr std::array, 3> Triangle{{ + {-1.0f, -1.0f, 0.5f, 1.0f}, {3.0f, -1.0f, 0.5f, 1.0f}, {-1.0f, 3.0f, 0.5f, 1.0f} +}}; + +alignas(256) std::array, 4> Programs{}; +std::size_t programCount = 0; + +std::span Float32Program(std::array rgba) { + Require(programCount < Programs.size(), "too many test programs"); + auto& code = Programs[programCount++]; + std::size_t at = 0; + for (std::uint32_t vgpr = 0; vgpr < 4u; ++vgpr) { + code[at++] = 0x7e0002ffu | ((4u + vgpr) << 17u); + code[at++] = std::bit_cast(rgba[vgpr]); + } + code[at++] = 0xf800180fu; + code[at++] = 0x07060504u; + code[at++] = 0xbf810000u; + return std::span(code.data(), at); +} + +struct Block { + explicit Block(std::size_t bytes) : bytes(bytes), watched(AgcDriver::GuestMemory::WriteWatched()) { +#ifdef _WIN32 + if (watched) { + data = static_cast(GuestArena::GuestArenaAllocate_nid_postfix(bytes, BlockBytes)); + GuestArena::GuestArenaCommit_nid_postfix(data, bytes, PAGE_READWRITE, bytes); + } else { + data = static_cast(VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + } +#else + if (watched) { + void* raw = mmap(nullptr, bytes + BlockBytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + Require(raw != MAP_FAILED, "cannot map the test block"); + const auto begin = reinterpret_cast(raw); + const auto aligned = (begin + BlockBytes - 1) & ~(static_cast(BlockBytes) - 1); + if (aligned != begin) munmap(raw, aligned - begin); + if (aligned + bytes != begin + bytes + BlockBytes) munmap(reinterpret_cast(aligned + bytes), begin + BlockBytes - aligned); + data = reinterpret_cast(aligned); + GuestWriteWatch::GuestWriteWatchRegister_nid_postfix(data, bytes); + } else { + data = static_cast(std::aligned_alloc(BlockBytes, bytes)); + } +#endif + Require(data != nullptr, "cannot allocate the test block"); + Require(!watched || AgcDriver::GuestMemory::Watched(Address(), bytes), "the test block is not write-watched"); + GuestAllocations::Mutation mutation; + mutation.Add(data, bytes, true, true, true); + } + ~Block() { + AgcDriver::Graphics::StorageTexture::FlushPending(Address(), bytes, nullptr, "test release"); + { + GuestAllocations::Mutation mutation; + mutation.Remove(data); + } +#ifdef _WIN32 + if (watched) { + GuestArena::GuestArenaReset_nid_postfix(data, bytes); + GuestArena::GuestArenaRelease_nid_postfix(data, bytes); + } else { + VirtualFree(data, 0, MEM_RELEASE); + } +#else + if (watched) { + munmap(data, bytes); + GuestWriteWatch::GuestWriteWatchUnregister_nid_postfix(data, bytes); + } else { + std::free(data); + } +#endif + } + Block(const Block&) = delete; + Block& operator=(const Block&) = delete; + std::uint64_t Address() const { return reinterpret_cast(data); } + std::size_t bytes; + bool watched; + std::uint8_t* data = nullptr; +}; + +AgcDriver::Registers TargetRegisters(const Block& block, const Block& keys, std::uint32_t swap) { + AgcDriver::Registers cx; + cx[0x318] = static_cast(block.Address() >> 8u); + cx[0x31b] = 0; + cx[0x31c] = Unorm4_4_4_4Info | DccEnable | (swap << 11u); + cx[0x31d] = 0; + cx[0x323] = RegisterWord; + cx[0x324] = 0; + cx[0x325] = static_cast(keys.Address() >> 8u); + cx[0x3a8] = static_cast(keys.Address() >> 40u); + cx[0x3b0] = ((Width - 1u) << 14u) | (Height - 1u); + cx[0x3b8] = TiledAttrib3; + cx[0x390] = static_cast(block.Address() >> 40u); + return cx; +} + +AgcDriver::Graphics::ColorTarget DecodeTarget(const Block& block, const Block& keys, std::uint32_t swap) { + auto color = AgcDriver::Graphics::DecodeColorBuffer(TargetRegisters(block, keys, swap), 0); + Require(color.format == VK_FORMAT_R16_UINT && color.elementBytes == 2 && color.packing == ShaderRecompiler::ColorExportPacking::Unorm4_4_4_4 && color.tileMode == ColorTileMode::RenderTarget && color.bytes == block.bytes, "the DCC 4_4_4_4 unorm target did not decode as a packed R16_UINT target"); + Require(color.samples == 1 && color.dccAddress == keys.Address() && color.dccAlphaOnMsb == (swap < 2u), "the DCC 4_4_4_4 unorm target with component swap " + std::to_string(swap) + " lost its keys or the side its alpha nibble is on"); + Require(AgcDriver::Graphics::ColorTargetDccClearFormat(color) == VK_FORMAT_R4G4B4A4_UNORM_PACK16 && AgcDriver::Graphics::SurfaceForTarget(color).dccAddress == keys.Address(), "the DCC 4_4_4_4 unorm target does not expand its clear codes over four nibbles, or its resident surface lost the keys"); + return color; +} + +void Draw(AgcDriver::VulkanDevice& device, AgcDriver::Graphics::ColorTarget color, std::uint32_t exportFormat, std::span pixelCode, const std::function& beforeDraw = {}) { + if (color.mergeBlend != 0u) color.partialWriteMask = AgcDriver::Graphics::PackedWriteMask(color.componentMapping, 0xfu); + const bool merged = color.partialWriteMask != 0u; + const auto target = device.Target(); + constexpr std::uint32_t waveSize = 64; + std::vector vertexUserData(4, 0u); + const auto address = reinterpret_cast(Triangle.data()); + const std::array vertexBuffer{static_cast(address), static_cast((address >> 32u) & 0xffffu) | (16u << 16u), static_cast(Triangle.size()), 0x01016facu}; + std::copy(vertexBuffer.begin(), vertexBuffer.end(), vertexUserData.begin()); + const std::array vertexMemory{{{reinterpret_cast(VertexCode.data()), std::as_bytes(std::span(VertexCode))}}}; + ShaderRecompiler::RecompileRequest vertex{ + {ShaderStage::Vertex, reinterpret_cast(VertexCode.data()), VertexCode, 0, {}}, + {waveSize, 0, vertexUserData, std::nullopt, std::nullopt, ShaderRecompiler::ShaderVertexStageInfo{}, vertexMemory}, + target, + {0, 0, 0, 64} + }; + vertex.useCache = false; + const auto vertexResult = ShaderRecompiler::Recompile(vertex); + const auto vertexPush = static_cast(vertexResult.pushConstants.size()); + + AgcDriver::Graphics::State state{}; + state.stages = {AgcDriver::Graphics::ShaderPath::Vertex, 0u, waveSize, waveSize, std::nullopt, std::nullopt}; + state.colors = {color}; + state.color = color; + state.hasColorTarget = true; + state.renderExtent = {Width, Height}; + state.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + state.viewport = {0, static_cast(Height), static_cast(Width), -static_cast(Height), 0, 1}; + state.negativeOneToOne = false; + state.scissor = {{0, 0}, {ScissorWidth, Height}}; + state.cullMode = VK_CULL_MODE_NONE; + state.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; + VkPipelineColorBlendAttachmentState blend{}; + blend.colorWriteMask = merged ? 0u : VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; + state.blends = {blend}; + state.blend = blend; + state.blendConstants = {}; + + const auto codeAddress = reinterpret_cast(pixelCode.data()); + const AgcDriver::Registers context{{0x1b6, 0x8000}, {0x1b3, 0}, {0x1b4, 0}, {0x203, 0}, {0x1c5, exportFormat}}; + const std::array pixelMemory{{{codeAddress, std::as_bytes(pixelCode)}}}; + ShaderRecompiler::RecompileRequest fragment{ + {ShaderStage::Fragment, codeAddress, pixelCode, 0, {}}, + {waveSize, 0, {}, std::nullopt, AgcDriver::Graphics::DecodePixelStageInfo(context, {}), std::nullopt, pixelMemory}, + target, + PixelPushLayout(vertexPush, target) + }; + const auto handle = ShaderRecompiler::PrepareShader(fragment); + AgcDriver::DriverDetail::ShaderSnapshot snapshot{codeAddress, 0, 1, {pixelCode.begin(), pixelCode.end()}, {}}; + snapshot.prepared->entries.push_back({0, handle}); + fragment.shader.code = snapshot.code; + fragment.context.pixel = AgcDriver::Graphics::DecodePixelStageInfo(context, AgcDriver::Graphics::ExportMappings(state)); + fragment.context.pixel->targetExportPacking = AgcDriver::Graphics::ExportPackings(state); + fragment.context.pixel->targetMerges = AgcDriver::Graphics::ExportTargetMerges(state); + Require(fragment.context.pixel->targetMerges.size() == (merged ? 1u : 0u) && (!merged || (fragment.context.pixel->targetMerges.front().mask == color.partialWriteMask && fragment.context.pixel->targetMerges.front().blendControl == color.mergeBlend && AgcDriver::Graphics::DecodeTextureResource(fragment.context.pixel->targetMerges.front().descriptor).dccAddress == color.dccAddress)), "the draw's target merge disagrees with its blend or lost the target's DCC keys"); + const ShaderRecompiler::SrtRuntime runtime{}; + const auto invocation = AgcDriver::DriverDetail::InvocationFor(snapshot, 0, fragment); + const auto pixelResult = invocation.Materialize(*invocation.Capture(runtime)); + const std::array shaders{{ + {ShaderStage::Vertex, &vertexResult, 0}, + {ShaderStage::Fragment, pixelResult.get(), PixelPushOffset(vertexPush, target)} + }}; + const AgcDriver::Pm4::DrawParameters draw{0, static_cast(Triangle.size()), 0, 1, 0, false}; + if (!beforeDraw) { + device.Draw(state, draw, shaders); + return; + } + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + beforeDraw(); + device.Draw(state, draw, shaders); +} + +std::vector ReadBack(AgcDriver::VulkanDevice& device, const Block& block) { + AgcDriver::Graphics::StorageTexture::FlushPending(block.Address(), block.bytes, nullptr, "test read-back"); + device.WaitIdle(); + std::vector stored(block.bytes / 2u); + AgcDriver::GuestMemory::Read(block.Address(), std::as_writable_bytes(std::span(stored)), 1); + return stored; +} + +void ExpectSurface(AgcDriver::VulkanDevice& device, const Block& block, const ColorTargetLayout& layout, const std::vector& before, std::uint32_t word, const std::string& what) { + const auto stored = ReadBack(device, block); + for (std::uint32_t y = 0; y < Height; ++y) { + for (std::uint32_t x = 0; x < Width; ++x) { + const auto index = layout.Offset(x, y) / 2u; + const bool inside = x < ScissorWidth; + const std::uint32_t expected = inside ? word : before[index]; + if (stored[index] == expected) continue; + char detail[160]; + std::snprintf(detail, sizeof(detail), ": pixel (%u, %u) %s the scissor holds 0x%04x, expected 0x%04x", x, y, inside ? "inside" : "outside", stored[index], expected); + throw std::runtime_error(what + detail); + } + } +} + +std::vector Fill(Block& block, std::uint32_t seed) { + std::vector words(block.bytes / 2u); + for (std::size_t index = 0; index < words.size(); ++index) words[index] = static_cast(((index + seed) * 0x9e3779b9u) >> 11u); + std::memcpy(block.data, words.data(), block.bytes); + return words; +} + +struct KeyCase { + std::uint8_t key; + DccKeys keys; + const char* code; +}; + +constexpr std::array KeyCases{{ + {0xff, DccKeys::Uncompressed, "uncompressed"}, + {0x00, DccKeys::Clear0000, "0000"}, + {0x40, DccKeys::Clear0001, "0001"}, + {0x80, DccKeys::Clear1110, "1110"}, + {0xc0, DccKeys::Clear1111, "1111"}, + {0x20, DccKeys::ClearRegister, "register"}, +}}; + +std::vector FillUnderKeys(Block& block, Block& keys, const KeyCase& item, std::uint32_t swap, std::uint32_t seed) { + auto before = Fill(block, seed); + std::memset(keys.data, item.key, KeyBytes); + const auto alphaWord = static_cast(swap < 2u ? 0xf000u : 0x000fu); + switch (item.keys) { + case DccKeys::Clear0000: std::fill(before.begin(), before.end(), static_cast(0x0000u)); break; + case DccKeys::Clear0001: std::fill(before.begin(), before.end(), alphaWord); break; + case DccKeys::Clear1110: std::fill(before.begin(), before.end(), static_cast(~alphaWord)); break; + case DccKeys::Clear1111: std::fill(before.begin(), before.end(), static_cast(0xffffu)); break; + case DccKeys::ClearRegister: std::fill(before.begin(), before.end(), RegisterWord); break; + default: break; + } + return before; +} + +constexpr std::array OneChannelDifferentCases{{ + {0x40, DccKeys::Clear0001, "0001"}, + {0x80, DccKeys::Clear1110, "1110"}, +}}; + +std::uint16_t AlphaWord(std::uint32_t swap) { + return static_cast(swap < 2u ? 0xf000u : 0x000fu); +} + +std::uint16_t ClearWord(DccKeys keys, std::uint32_t swap) { + return keys == DccKeys::Clear0001 ? AlphaWord(swap) : static_cast(~AlphaWord(swap)); +} + +void RequireUncompressedKeys(const Block& keys, const std::string& what) { + std::array after{}; + AgcDriver::GuestMemory::Read(keys.Address(), std::as_writable_bytes(std::span(after)), 1); + Require(std::all_of(after.begin(), after.end(), [](std::uint8_t key) { return key == 0xff; }), what + " left compressed DCC keys"); +} + +void DrawAndStore(AgcDriver::VulkanDevice& device, Block& block, Block& keys, const AgcDriver::Graphics::ColorTarget& color, std::span pixelCode, std::uint32_t seed) { + Fill(block, seed); + std::memset(keys.data, 0xff, KeyBytes); + Draw(device, color, Float32Export, pixelCode); + static_cast(ReadBack(device, block)); +} + +void ClearTests(AgcDriver::VulkanDevice& device, Block& block, Block& keys, std::span> swaps, std::span distinctChannels) { + const ColorTargetLayout layout(Width, Height, ColorTileMode::RenderTarget, 2); + Require(layout.Bytes() == block.bytes && block.bytes / 256u == KeyBytes && keys.bytes >= KeyBytes, "the test surface or its keys disagree with the target's layout"); + std::uint32_t seed = 0; + for (const auto& [swap, drawn] : swaps) { + for (int round = 0; round < 2; ++round) { + for (const auto& item : KeyCases) { + const auto before = FillUnderKeys(block, keys, item, swap, ++seed); + const auto color = DecodeTarget(block, keys, swap); + Draw(device, color, Float32Export, distinctChannels); + const std::string what = std::string("a draw into a 4_4_4_4 unorm target with component swap ") + std::to_string(swap) + " under " + item.code + " DCC keys (round " + std::to_string(round) + ")"; + ExpectSurface(device, block, layout, before, drawn, what); + RequireUncompressedKeys(keys, what); + } + } + } +} + +void MetadataPassTests(AgcDriver::VulkanDevice& device, Block& block, Block& keys, std::span> swaps, std::span distinctChannels) { + const ColorTargetLayout layout(Width, Height, ColorTileMode::RenderTarget, 2); + std::uint32_t seed = 1000; + for (const auto& [swap, drawn] : swaps) { + for (const auto mode : {AgcDriver::Graphics::ColorMetadataPass::Mode::EliminateFastClear, AgcDriver::Graphics::ColorMetadataPass::Mode::DccDecompress}) { + for (const auto& item : OneChannelDifferentCases) { + const auto color = DecodeTarget(block, keys, swap); + DrawAndStore(device, block, keys, color, distinctChannels, ++seed); + std::memset(keys.data, item.key, KeyBytes); + AgcDriver::Graphics::ColorMetadataPass pass{}; + pass.mode = mode; + pass.targets = {color}; + device.ColorMetadataPass(pass); + const auto word = ClearWord(item.keys, swap); + const std::vector cleared(block.bytes / 2u, word); + const std::string what = std::string(mode == AgcDriver::Graphics::ColorMetadataPass::Mode::EliminateFastClear ? "a fast-clear eliminate" : "a DCC decompress") + " of a drawn 4_4_4_4 unorm target with component swap " + std::to_string(swap) + " under " + item.code + " DCC keys"; + ExpectSurface(device, block, layout, cleared, word, what); + RequireUncompressedKeys(keys, what); + Draw(device, color, Float32Export, distinctChannels); + ExpectSurface(device, block, layout, cleared, drawn, what + ", then a draw"); + } + } + } +} + +bool PendingKeyFillTests(AgcDriver::VulkanDevice& device, Block& block, Block& keys, std::span> swaps, std::span distinctChannels) { + const ColorTargetLayout layout(Width, Height, ColorTileMode::RenderTarget, 2); + std::uint32_t seed = 2000; + for (const auto& [swap, drawn] : swaps) { + for (const auto& item : OneChannelDifferentCases) { + const auto color = DecodeTarget(block, keys, swap); + DrawAndStore(device, block, keys, color, distinctChannels, ++seed); + const std::string what = std::string("a second draw into a 4_4_4_4 unorm target with component swap ") + std::to_string(swap) + " after a pending GPU fill of its DCC keys with " + item.code; + const std::uint32_t word = item.key * 0x01010101u; + const std::array pattern{word, word, word, word}; + bool recorded = true; + Draw(device, color, Float32Export, distinctChannels, [&] { + recorded = device.FillBuffer(keys.Address(), KeyBytes, pattern); + Require(!recorded || AgcDriver::Graphics::DccKeyWritersPending(keys.Address(), KeyBytes), what + ": the recorded fill is not a pending key writer"); + }); + if (!recorded) return false; + ExpectSurface(device, block, layout, std::vector(block.bytes / 2u, ClearWord(item.keys, swap)), drawn, what); + RequireUncompressedKeys(keys, what); + } + } + return true; +} + +std::uint16_t BlendedWord(std::uint16_t stored, std::uint8_t mapping, const std::array& rgba, bool additive) { + const float alpha = std::clamp(rgba[3], 0.0f, 1.0f); + std::uint32_t word = 0; + for (std::uint32_t field = 0; field < 4u; ++field) { + const auto component = (mapping >> (2u * field)) & 3u; + const float source = std::clamp(rgba[component], 0.0f, 1.0f); + const float destination = static_cast((stored >> (4u * field)) & 0xfu) / 15.0f; + const float blended = component == 3u || additive ? source + destination : source * alpha + destination * (1.0f - alpha); + word |= static_cast(std::nearbyint(std::clamp(blended, 0.0f, 1.0f) * 15.0f)) << (4u * field); + } + return static_cast(word); +} + +void ExpectBlended(AgcDriver::VulkanDevice& device, const Block& block, const ColorTargetLayout& layout, const std::vector& before, std::uint8_t mapping, const std::array& rgba, bool additive, const std::string& what) { + const auto stored = ReadBack(device, block); + for (std::uint32_t y = 0; y < Height; ++y) { + for (std::uint32_t x = 0; x < Width; ++x) { + const auto index = layout.Offset(x, y) / 2u; + const bool inside = x < ScissorWidth; + const std::uint32_t expected = inside ? BlendedWord(before[index], mapping, rgba, additive) : before[index]; + if (stored[index] == expected) continue; + char detail[192]; + std::snprintf(detail, sizeof(detail), ": pixel (%u, %u) %s the scissor holds 0x%04x, expected 0x%04x (stored before 0x%04x)", x, y, inside ? "inside" : "outside", stored[index], expected, before[index]); + throw std::runtime_error(what + detail); + } + } +} + +AgcDriver::Graphics::ColorTarget BlendedTarget(const Block& block, const Block& keys, std::uint32_t swap, bool additive) { + namespace Packing = ShaderRecompiler::Packed4444Blend; + const auto over = Packing::EncodeEquation(VK_BLEND_FACTOR_SRC_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, VK_BLEND_OP_ADD); + const auto add = Packing::EncodeEquation(VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE, VK_BLEND_OP_ADD); + auto color = DecodeTarget(block, keys, swap); + color.mergeBlend = Packing::Encode(color.componentMapping, additive ? add : over, add); + return color; +} + +std::uint32_t BlendTests(AgcDriver::VulkanDevice& device, Block& block, Block& keys, std::span swaps, const std::array& rgba, std::span pixelCode) { + const ColorTargetLayout layout(Width, Height, ColorTileMode::RenderTarget, 2); + std::uint32_t seed = 0x100; + std::uint32_t draws = 0; + for (const auto swap : swaps) { + const bool additive = (swap & 1u) != 0u; + for (const auto& item : KeyCases) { + const auto before = FillUnderKeys(block, keys, item, swap, ++seed); + const auto color = BlendedTarget(block, keys, swap, additive); + Draw(device, color, Float32Export, pixelCode); + const std::string what = std::string("a ") + (additive ? "ONE/ONE" : "SRC_ALPHA/ONE_MINUS_SRC_ALPHA") + " blend into a 4_4_4_4 unorm target with component swap " + std::to_string(swap) + " under " + item.code + " DCC keys"; + ExpectBlended(device, block, layout, before, color.componentMapping, rgba, additive, what); + RequireUncompressedKeys(keys, what); + ++draws; + } + } + return draws; +} + +void NonResidentBlendRefusal(AgcDriver::VulkanDevice& device, Block& block, Block& keys, std::span pixelCode) { + static_cast(FillUnderKeys(block, keys, KeyCases.front(), 0u, 0x200u)); + try { + Draw(device, BlendedTarget(block, keys, 0u, false), Float32Export, pixelCode); + } catch (const std::exception& error) { + Require(std::string(error.what()).find("merged into its resident image") != std::string::npos, std::string("a blend into a non-resident DCC 4_4_4_4 unorm target was refused for another reason: ") + error.what()); + return; + } + throw std::runtime_error("a blend into a non-resident DCC 4_4_4_4 unorm target, which merges only into a resident image, was drawn"); +} + +std::uint32_t PartialWriteTests(AgcDriver::VulkanDevice& device, Block& block, Block& keys, std::span> swaps, std::span distinctChannels) { + const ColorTargetLayout layout(Width, Height, ColorTileMode::RenderTarget, 2); + std::uint32_t seed = 0x300; + std::uint32_t draws = 0; + for (const auto& [swap, drawn] : swaps) { + for (const auto& item : KeyCases) { + const auto before = FillUnderKeys(block, keys, item, swap, ++seed); + auto color = DecodeTarget(block, keys, swap); + color.partialWriteMask = AgcDriver::Graphics::PackedWriteMask(color.componentMapping, 0x5u); + const auto mask = color.partialWriteMask; + Draw(device, color, Float32Export, distinctChannels); + const std::string what = std::string("a partial write of red and blue into a 4_4_4_4 unorm target with component swap ") + std::to_string(swap) + " under " + item.code + " DCC keys"; + const auto stored = ReadBack(device, block); + for (std::uint32_t y = 0; y < Height; ++y) { + for (std::uint32_t x = 0; x < Width; ++x) { + const auto index = layout.Offset(x, y) / 2u; + const bool inside = x < ScissorWidth; + const std::uint32_t expected = inside ? (before[index] & ~mask) | (drawn & mask) : before[index]; + if (stored[index] == expected) continue; + char detail[192]; + std::snprintf(detail, sizeof(detail), ": pixel (%u, %u) %s the scissor holds 0x%04x, expected 0x%04x (stored before 0x%04x)", x, y, inside ? "inside" : "outside", stored[index], expected, before[index]); + throw std::runtime_error(what + detail); + } + } + RequireUncompressedKeys(keys, what); + ++draws; + } + } + return draws; +} + +void RefusalTests(const Block& block, const Block& keys) { + auto cx = TargetRegisters(block, keys, 2u); + cx[0x31d] = (1u << 12u) | (1u << 15u); + try { + static_cast(AgcDriver::Graphics::DecodeColorBuffer(cx, 0)); + } catch (const std::exception& error) { + Require(std::string(error.what()).find("DCC-compressed multisampled 4_4_4_4 unorm color targets") != std::string::npos, std::string("a multisampled DCC 4_4_4_4 unorm target was refused for another reason: ") + error.what()); + return; + } + throw std::runtime_error("a multisampled DCC 4_4_4_4 unorm target, whose clears are not modeled, was accepted"); +} + +} + +int main() { + try { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + const auto surfaceBytes = ColorTargetLayout(Width, Height, ColorTileMode::RenderTarget, 2).Bytes(); + Block alphaHigh(surfaceBytes); + Block alphaHighKeys(BlockBytes); + Block alphaLow(surfaceBytes); + Block alphaLowKeys(BlockBytes); + RefusalTests(alphaHigh, alphaHighKeys); + const auto distinctChannels = Float32Program({1.0f / 15.0f, 2.0f / 15.0f, 7.0f / 15.0f, 14.0f / 15.0f}); + constexpr std::array, 2> alphaHighSwaps{{{0u, 0xe721u}, {1u, 0xe127u}}}; + constexpr std::array, 2> alphaLowSwaps{{{2u, 0x127eu}, {3u, 0x721eu}}}; + ClearTests(*device, alphaHigh, alphaHighKeys, alphaHighSwaps, distinctChannels); + ClearTests(*device, alphaLow, alphaLowKeys, alphaLowSwaps, distinctChannels); + MetadataPassTests(*device, alphaHigh, alphaHighKeys, alphaHighSwaps, distinctChannels); + MetadataPassTests(*device, alphaLow, alphaLowKeys, alphaLowSwaps, distinctChannels); + const bool filled = PendingKeyFillTests(*device, alphaHigh, alphaHighKeys, alphaHighSwaps, distinctChannels) && PendingKeyFillTests(*device, alphaLow, alphaLowKeys, alphaLowSwaps, distinctChannels); + const char* const fills = filled ? "" : "; the pending key fill cases did not run: the device records no GPU fill of the keys"; + constexpr std::array blendedChannels{1.25f, 0.2f, 7.0f / 15.0f, 0.6f}; + const auto blendedProgram = Float32Program(blendedChannels); + if (std::getenv("APS5_NO_RESIDENT_TARGETS") != nullptr) { + NonResidentBlendRefusal(*device, alphaHigh, alphaHighKeys, blendedProgram); + std::printf("DCC 4_4_4_4 unorm color target tests passed; a blend into a non-resident target was refused%s\n", fills); + return 0; + } + constexpr std::array alphaHighBlendSwaps{0u, 1u}; + constexpr std::array alphaLowBlendSwaps{2u, 3u}; + const auto blended = BlendTests(*device, alphaHigh, alphaHighKeys, alphaHighBlendSwaps, blendedChannels, blendedProgram) + BlendTests(*device, alphaLow, alphaLowKeys, alphaLowBlendSwaps, blendedChannels, blendedProgram); + const auto partial = PartialWriteTests(*device, alphaHigh, alphaHighKeys, alphaHighSwaps, distinctChannels) + PartialWriteTests(*device, alphaLow, alphaLowKeys, alphaLowSwaps, distinctChannels); + std::printf("DCC 4_4_4_4 unorm color target tests passed, with %u blended draws and %u partial writes through the pixel-interlock merge%s\n", blended, partial, fills); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/PackedUnorm4444PartialWrite.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/PackedUnorm4444PartialWrite.cpp index 09cb138925ed..a6c79e90103b 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/PackedUnorm4444PartialWrite.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/PackedUnorm4444PartialWrite.cpp @@ -21,6 +21,7 @@ #else #include #endif +#include #include #include #include @@ -29,10 +30,12 @@ #include #include #include +#include #include #include #include #include +#include #include namespace { @@ -46,7 +49,7 @@ constexpr std::uint32_t Width = 256; constexpr std::uint32_t Height = 128; constexpr std::uint32_t ScissorWidth = 128; constexpr std::size_t BlockBytes = 65536; -constexpr std::uint32_t Unorm4_4_4_4Info = 0x8000u | (19u << 2u) | (2u << 11u); +constexpr std::uint32_t Unorm4_4_4_4Info = 0x8000u | (19u << 2u); constexpr std::uint32_t TiledAttrib3 = 0x4dc6c000u; constexpr std::uint32_t Float32Export = 9; constexpr std::uint32_t Float16Export = 4; @@ -54,8 +57,11 @@ constexpr std::uint32_t PositionInputs = 0x300u; constexpr std::uint32_t DepthInput = 0x400u; constexpr std::uint32_t LateKill = 0x40u; constexpr std::array CheckerboardKill{0x7e040f00u, 0x7e060f01u, 0x3a040702u, 0x36040481u, 0x7da40480u}; +constexpr std::array StripeKill{0x7e040f00u, 0x36040482u, 0x7da40480u}; +constexpr std::uint64_t SampleReady = 1ull << 63u; +constexpr std::size_t SampleDumpStride = 256; -enum class Kill { None, BeforeExport, AfterExport }; +enum class Kill { None, BeforeExport, AfterExport, Stripes, MaskExport }; alignas(256) constexpr std::array VertexCode{ 0xe0382000, 0x80000005, 0xbf8c3f70, 0xf80008cf, 0x03020100, 0xbf810000, @@ -90,9 +96,12 @@ std::span Program(const std::array& vgprs Require(programCount < Programs.size(), "too many test programs"); auto& code = Programs[programCount++]; std::size_t at = 0; - if (kill == Kill::BeforeExport) { + if (kill == Kill::BeforeExport || kill == Kill::MaskExport) { for (const auto word : CheckerboardKill) code[at++] = word; } + if (kill == Kill::Stripes) { + for (const auto word : StripeKill) code[at++] = word; + } for (std::uint32_t vgpr = 0; vgpr < (compressed ? 2u : 4u); ++vgpr) { code[at++] = 0x7e0002ffu | ((4u + vgpr) << 17u); code[at++] = vgprs[vgpr]; @@ -104,6 +113,10 @@ std::span Program(const std::array& vgprs code[at++] = 0xf8001890u; code[at++] = 0u; } else { + if (kill == Kill::MaskExport) { + code[at++] = 0xf8000084u; + code[at++] = 0x07060504u; + } code[at++] = compressed ? 0xf8001c0fu : 0xf800180fu; code[at++] = compressed ? 0x00000504u : 0x07060504u; } @@ -145,6 +158,8 @@ struct DrawSetup { std::span> vertices = Triangle; std::uint64_t depth = 0; bool depthWrite = false; + VkCompareOp depthCompare = VK_COMPARE_OP_LESS; + std::uint32_t samples = 1u; }; struct Block { @@ -205,17 +220,17 @@ struct Block { std::uint8_t* data = nullptr; }; -AgcDriver::Graphics::ColorTarget DecodeTarget(const Block& block) { +AgcDriver::Graphics::ColorTarget DecodeTarget(const Block& block, std::uint32_t swap) { AgcDriver::Registers cx; cx[0x318] = static_cast(block.Address() >> 8u); cx[0x31b] = 0; - cx[0x31c] = Unorm4_4_4_4Info; + cx[0x31c] = Unorm4_4_4_4Info | (swap << 11u); cx[0x31d] = 0; cx[0x3b0] = ((Width - 1u) << 14u) | (Height - 1u); cx[0x3b8] = TiledAttrib3; cx[0x390] = static_cast(block.Address() >> 40u); auto color = AgcDriver::Graphics::DecodeColorBuffer(cx, 0); - Require(color.format == VK_FORMAT_R16_UINT && color.componentMapping == 0x1bu && color.packing == ShaderRecompiler::ColorExportPacking::Unorm4_4_4_4 && color.tileMode == ColorTileMode::RenderTarget && color.bytes == block.bytes, "the tiled 4_4_4_4 unorm target did not decode as a packed R16_UINT target"); + Require(color.format == VK_FORMAT_R16_UINT && color.packing == ShaderRecompiler::ColorExportPacking::Unorm4_4_4_4 && color.tileMode == ColorTileMode::RenderTarget && color.bytes == block.bytes, "the tiled 4_4_4_4 unorm target did not decode as a packed R16_UINT target"); return color; } @@ -237,8 +252,8 @@ std::uint32_t Draw(AgcDriver::VulkanDevice& device, AgcDriver::Graphics::ColorTa const auto vertexResult = ShaderRecompiler::Recompile(vertex); const auto vertexPush = static_cast(vertexResult.pushConstants.size()); - const bool partial = exportedMask != 0xfu; - color.partialWriteMask = partial ? AgcDriver::Graphics::PackedWriteMask(color.componentMapping, exportedMask) : 0u; + const bool mergeTarget = exportedMask != 0xfu || color.mergeBlend != 0u; + color.partialWriteMask = mergeTarget ? AgcDriver::Graphics::PackedWriteMask(color.componentMapping, exportedMask) : 0u; AgcDriver::Graphics::State state{}; state.stages = {AgcDriver::Graphics::ShaderPath::Vertex, 0u, waveSize, waveSize, std::nullopt, std::nullopt}; state.colors = {color}; @@ -252,16 +267,17 @@ std::uint32_t Draw(AgcDriver::VulkanDevice& device, AgcDriver::Graphics::ColorTa state.cullMode = VK_CULL_MODE_NONE; state.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; VkPipelineColorBlendAttachmentState blend{}; - blend.colorWriteMask = partial ? 0u : VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; + blend.colorWriteMask = mergeTarget ? 0u : VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; state.blends = {blend}; state.blend = blend; state.blendConstants = {}; + state.samples = setup.samples; state.pixelKill = (setup.shaderControl & LateKill) != 0u; if (setup.depth != 0) { state.depth = AgcDriver::Graphics::DepthTarget{setup.depth, 0, {Width, Height}, VK_FORMAT_D32_SFLOAT, 1.0f, 0, 0, false}; state.depthTest = true; state.depthWrite = setup.depthWrite; - state.depthCompare = VK_COMPARE_OP_LESS; + state.depthCompare = setup.depthCompare; } const auto codeAddress = reinterpret_cast(pixelCode.data()); @@ -281,15 +297,19 @@ std::uint32_t Draw(AgcDriver::VulkanDevice& device, AgcDriver::Graphics::ColorTa fragment.context.pixel->targetExportPacking = AgcDriver::Graphics::ExportPackings(state); fragment.context.pixel->targetMerges = AgcDriver::Graphics::ExportTargetMerges(state); Require(fragment.context.pixel->pixelKillEnable == ((setup.shaderControl & LateKill) != 0u) && !fragment.context.pixel->earlyZ && std::ranges::all_of(fragment.context.pixel->targetMerges, [&](const ShaderRecompiler::TargetMerge& merge) { return merge.depthStencilWrites == (setup.depth != 0 && setup.depthWrite); }), "the draw's pixel kill under late tests or its depth and stencil writes did not decode"); - Require(fragment.context.pixel->targetMerges.size() == (partial ? 1u : 0u) && (!partial || fragment.context.pixel->targetMerges.front().mask == color.partialWriteMask), "the draw's target merge disagrees with its write mask"); + Require(fragment.context.pixel->targetMerges.size() == (mergeTarget ? 1u : 0u) && + (!mergeTarget || (fragment.context.pixel->targetMerges.front().mask == color.partialWriteMask && + fragment.context.pixel->targetMerges.front().blendControl == color.mergeBlend)), "the draw's target merge disagrees with its write mask or blend"); const ShaderRecompiler::SrtRuntime runtime{}; const auto invocation = AgcDriver::DriverDetail::InvocationFor(snapshot, 0, fragment); const auto pixelResult = invocation.Materialize(*invocation.Capture(runtime)); const bool registered = pixelResult->variantId == ShaderRecompiler::GetPreparedArtifact(*handle).variantId; - Require(registered != partial, partial ? "the merging draw reused the registered pixel shader" : "the full write did not use the registered pixel shader"); + Require(registered != mergeTarget, mergeTarget ? "the merging draw reused the registered pixel shader" : "the full write did not use the registered pixel shader"); + const bool counts = std::ranges::any_of(pixelResult->specialization, [](const ShaderRecompiler::PipelineSpecializationConstant& constant) { return ShaderRecompiler::PipelineSpecialization::IsSampleCounter(constant.id); }); + Require(counts == (mergeTarget && (setup.shaderControl & LateKill) != 0u), counts ? "a pixel shader that does not merge and kill under late tests counts its samples" : "the pixel shader of a merge that kills under late tests does not count its samples"); const std::array shaders{{ {ShaderStage::Vertex, &vertexResult, 0}, - {ShaderStage::Fragment, pixelResult.get(), PixelPushOffset(vertexPush, target)} + {ShaderStage::Fragment, pixelResult.get(), PixelPushOffset(vertexPush, target), nullptr, codeAddress} }}; const AgcDriver::Pm4::DrawParameters draw{0, static_cast(setup.vertices.size()), 0, 1, 0, false}; device.Draw(state, draw, shaders); @@ -326,6 +346,27 @@ std::vector Fill(Block& block, std::uint32_t seed) { return words; } +void BlendedWrites(AgcDriver::VulkanDevice& device, Block& block, const ColorTargetLayout& layout) { + namespace Packing = ShaderRecompiler::Packed4444Blend; + const auto rgb = Packing::EncodeEquation(VK_BLEND_FACTOR_SRC_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, VK_BLEND_OP_ADD); + const auto alphaAdd = Packing::EncodeEquation(VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE, VK_BLEND_OP_ADD); + const auto alphaSubtract = Packing::EncodeEquation(VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE, VK_BLEND_OP_REVERSE_SUBTRACT); + const auto pixelCode = Float32Program({1.25f, 0.8f, std::numeric_limits::quiet_NaN(), 0.4f}); + auto color = DecodeTarget(block, 1u); + color.mergeBlend = Packing::Encode(color.componentMapping, rgb, alphaAdd); + std::vector before(block.bytes / 2u, 0xc369u); + std::memcpy(block.data, before.data(), block.bytes); + Require(Draw(device, color, 0xfu, Float32Export, pixelCode) == 0xffffu, "a fully blended target must merge its entire packed word"); + ExpectSurface(device, block, layout, before, 0xf885u, 0xffffu, "source-over RGB and additive alpha in the alternate component order"); + + color = DecodeTarget(block, 3u); + color.mergeBlend = Packing::Encode(color.componentMapping, rgb, alphaSubtract); + std::fill(before.begin(), before.end(), 0x963cu); + std::memcpy(block.data, before.data(), block.bytes); + Require(Draw(device, color, 0x9u, Float32Export, pixelCode) == 0x00ffu, "the reversed packed blend must write only its red and alpha fields"); + ExpectSurface(device, block, layout, before, 0x0086u, 0x00ffu, "a reversed-order partial blend with independent alpha subtraction"); +} + struct Case { std::uint32_t mask; std::uint32_t wordMask; @@ -424,26 +465,6 @@ void DepthRejection(AgcDriver::VulkanDevice& device, Block& block, const ColorTa ExpectWords(device, block, layout, expected, before, "an X merge at z 0.25 in front of every stored depth"); } -void CountedKill(AgcDriver::VulkanDevice& device, Block& block, const ColorTargetLayout& layout, const AgcDriver::Graphics::ColorTarget& color) { - { - std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); - auto* recorder = AgcDriver::Graphics::Recorder::Active(); - Require(recorder != nullptr, "the test device has no command recorder to count samples"); - recorder->CountSamples(); - } - const auto before = Fill(block, 501u); - const std::array rgba{0.6f, 0.2f, 0.8f, 0.4f}; - std::string refusal; - try { - DrawCase(device, color, 0x1u, 0xf000u, Float32Export, Float32Program(rgba, Kill::BeforeExport), {PositionInputs, LateKill}); - } catch (const std::exception& error) { - refusal = error.what(); - } - Require(refusal.find("while occlusion queries count samples") != std::string::npos, "a merge that kills under late tests drew while occlusion queries count samples" + (refusal.empty() ? std::string() : ": " + refusal)); - DrawCase(device, color, 0x1u, 0xf000u, Float32Export, Float32Program(rgba)); - ExpectSurface(device, block, layout, before, Packed(rgba), 0xf000u, "a merged X write that kills nothing while occlusion queries count samples"); -} - void ExpectKilled(AgcDriver::VulkanDevice& device, const Block& block, const ColorTargetLayout& layout, const std::vector& before, std::uint32_t word, std::uint32_t wordMask, const std::string& what) { const auto stored = ReadBack(device, block); for (std::uint32_t y = 0; y < Height; ++y) { @@ -465,10 +486,307 @@ std::string Describe(std::uint32_t mask, std::array rgba) { return text; } +AgcDriver::Graphics::Recorder& TestRecorder() { + auto* recorder = AgcDriver::Graphics::Recorder::Active(); + Require(recorder != nullptr, "the test device has no command recorder to count samples"); + return *recorder; } -int main() { +class SampleMarks { +public: + SampleMarks(AgcDriver::VulkanDevice& device, bool gpu) : device(device), gpu(gpu) {} + + bool Mark() { + std::lock_guard lock(AgcDriver::GuestMemory::GpuMutex()); + if (gpu) { + Require(SampleDumpStride * (marks + 1u) <= dumps.bytes, "too many occlusion counter dumps for the dump block"); + if (!device.DumpSamplesOnGpu(dumps.Address() + SampleDumpStride * marks, 1u)) return false; + } else { + auto& recorder = TestRecorder(); + recorder.CountSamples(); + totals.push_back(recorder.SamplesTotal()); + } + ++marks; + return true; + } + + std::vector Counts() { + if (!gpu) return totals; + AgcDriver::Graphics::StorageTexture::FlushPending(dumps.Address(), dumps.bytes, nullptr, "test occlusion dump read-back"); + device.WaitIdle(); + std::vector words(dumps.bytes / sizeof(std::uint64_t)); + AgcDriver::GuestMemory::Read(dumps.Address(), std::as_writable_bytes(std::span(words)), 8); + std::vector counts; + for (std::size_t mark = 0; mark < marks; ++mark) { + const auto word = words[mark * SampleDumpStride / sizeof(std::uint64_t)]; + Require((word & SampleReady) != 0, "occlusion counter dump " + std::to_string(mark) + " has no ready bit"); + counts.push_back(word & ~SampleReady); + } + return counts; + } + +private: + AgcDriver::VulkanDevice& device; + bool gpu; + Block dumps{BlockBytes}; + std::size_t marks = 0; + std::vector totals; +}; + +struct CountedInterval { + const char* what; + std::uint64_t hardware; + std::uint64_t shader; +}; + +void ExpectCounts(SampleMarks& marks, std::span intervals, bool precise, const char* path, bool fresh) { + const auto counts = marks.Counts(); + Require(counts.size() == intervals.size() + 1u, "the occlusion counter was not read around every counted draw"); + Require(!fresh || counts.front() == 0u, std::string("the first read through ") + path + " counted " + std::to_string(counts.front()) + " samples, so the killing merges drawn before counting started were not dropped"); + for (std::size_t index = 0; index < intervals.size(); ++index) { + const auto& interval = intervals[index]; + Require(counts[index + 1u] >= counts[index], std::string("the occlusion counter went backwards over ") + interval.what); + const auto counted = counts[index + 1u] - counts[index]; + if (interval.hardware == 0u || precise) { + if (counted == interval.hardware + interval.shader) continue; + } else if (counted > interval.shader) { + continue; + } + char detail[480]; + std::snprintf(detail, sizeof(detail), "%s counted %llu samples through %s, expected %llu (%llu by the occlusion queries, %llu by the merging pixel shader)", interval.what, static_cast(counted), path, static_cast(interval.hardware + interval.shader), static_cast(interval.hardware), static_cast(interval.shader)); + throw std::runtime_error(detail); + } +} + +std::size_t CountedKill(AgcDriver::VulkanDevice& device, Block& block, Block& depth, const ColorTargetLayout& layout, const AgcDriver::Graphics::ColorTarget& color, bool gpu) { + const std::array nearer{0.6f, 0.2f, 0.8f, 0.4f}; + const std::array behind{0.0f, 1.0f, 1.0f, 1.0f}; + const std::array front{1.0f, 2.0f / 15.0f, 13.0f / 15.0f, 0.0f}; + const std::array last{0.0f, 0.0f, 0.0f, 7.0f / 15.0f}; + const std::array probe{1.0f, 0.0f, 0.0f, 1.0f / 15.0f}; + DrawCase(device, color, 0xfu, 0xffffu, Float32Export, Float32Program(behind), {0u, 0u, TriangleAt(1.0f), depth.Address(), true, VK_COMPARE_OP_ALWAYS}); + static_cast(ReadBack(device, block)); + SampleMarks marks(device, gpu); + const char* path = gpu ? "occlusion counter dumps on the GPU" : "the CPU sample total"; + if (!marks.Mark()) { + std::printf("skipped %s: the device refused the dump block\n", path); + return 0; + } + const bool precise = device.graphicsContext().occlusionQueryPrecise; + const auto before = Fill(block, gpu ? 701u : 702u); + auto expected = before; + const auto inside = [](std::uint32_t x) { return x < ScissorWidth; }; + const auto checker = [&](std::uint32_t x, std::uint32_t y) { return inside(x) && ((x ^ y) & 1u) == 0u; }; + const auto stripes = [&](std::uint32_t x, std::uint32_t y) { return inside(x) && !checker(x, y) && (x & 2u) == 0u; }; + const auto expect = [&](const auto& select, std::uint32_t word, std::uint32_t wordMask) { + std::uint64_t pixels = 0; + for (std::uint32_t y = 0; y < Height; ++y) { + for (std::uint32_t x = 0; x < Width; ++x) { + if (!select(x, y)) continue; + auto& stored = expected[layout.Offset(x, y) / 2u]; + stored = static_cast((stored & ~wordMask) | (word & wordMask)); + ++pixels; + } + } + return pixels; + }; + std::vector intervals; + DrawCase(device, color, 0xfu, 0xffffu, Float32Export, Float32Program(nearer, Kill::BeforeExport), {PositionInputs, LateKill, TriangleAt(0.5f), depth.Address(), true}); + intervals.push_back({"a full write at z 0.5 that kills a checkerboard and writes depth", expect(checker, Packed(nearer), 0xffffu), 0u}); + Require(marks.Mark(), std::string("the occlusion counter could not be read again through ") + path); + DrawCase(device, color, 0x1u, 0xf000u, Float32Export, Float32Program(behind, Kill::Stripes), {PositionInputs, LateKill, TriangleAt(0.75f), depth.Address(), false}); + intervals.push_back({"an X merge at z 0.75 behind the checkerboard's depth that kills every other column pair", 0u, expect(stripes, Packed(behind), 0xf000u)}); + Require(marks.Mark(), std::string("the occlusion counter could not be read again through ") + path); + DrawCase(device, color, 0x6u, 0x0ff0u, Float32Export, Float32Program(front, Kill::BeforeExport), {PositionInputs, LateKill, TriangleAt(0.25f), depth.Address(), false}); + const auto killing = expect(checker, Packed(front), 0x0ff0u); + DrawCase(device, color, 0x8u, 0x000fu, Float32Export, Float32Program(last), {0u, 0u, TriangleAt(0.25f), depth.Address(), false}); + intervals.push_back({"a Y and Z merge at z 0.25 that kills a checkerboard, then a W merge that kills nothing", expect([&](std::uint32_t x, std::uint32_t) { return inside(x); }, Packed(last), 0x000fu), killing}); + Require(marks.Mark(), std::string("the occlusion counter could not be read again through ") + path); + DrawCase(device, color, 0x1u, 0xf000u, Float32Export, Float32Program(probe), {0u, 0u, TriangleAt(0.75f), depth.Address(), false}); + intervals.push_back({"an X merge at z 0.75 that only the pixels the first draw killed pass", expect([&](std::uint32_t x, std::uint32_t y) { return inside(x) && !checker(x, y); }, Packed(probe), 0xf000u), 0u}); + Require(marks.Mark(), std::string("the occlusion counter could not be read again through ") + path); + ExpectWords(device, block, layout, expected, before, std::string("killing merges with depth tests counted through ") + path); + + namespace Packing = ShaderRecompiler::Packed4444Blend; + auto blended = DecodeTarget(block, 1u); + blended.mergeBlend = Packing::Encode(blended.componentMapping, Packing::EncodeEquation(VK_BLEND_FACTOR_SRC_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, VK_BLEND_OP_ADD), Packing::EncodeEquation(VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE, VK_BLEND_OP_ADD)); + const std::vector uniform(block.bytes / 2u, 0xc369u); + std::memcpy(block.data, uniform.data(), block.bytes); + Require(Draw(device, blended, 0xfu, Float32Export, Float32Program({1.25f, 0.8f, std::numeric_limits::quiet_NaN(), 0.4f}, Kill::BeforeExport), {PositionInputs, LateKill}) == 0xffffu, "a blend that kills under late tests did not merge the whole packed word"); + intervals.push_back({"a blend of the whole packed word without depth or stencil tests that kills a checkerboard", 0u, static_cast(ScissorWidth) * Height / 2u}); + Require(marks.Mark(), std::string("the occlusion counter could not be read again through ") + path); + ExpectKilled(device, block, layout, uniform, 0xf885u, 0xffffu, std::string("a killing blend counted through ") + path); + + const std::array under{4.0f / 15.0f, 9.0f / 15.0f, 2.0f / 15.0f, 12.0f / 15.0f}; + const std::array larger{10.0f / 15.0f, 3.0f / 15.0f, 6.0f / 15.0f, 5.0f / 15.0f}; + const std::array over{1.0f / 15.0f, 14.0f / 15.0f, 8.0f / 15.0f, 3.0f / 15.0f}; + const auto mixed = Fill(block, gpu ? 703u : 704u); + expected = mixed; + const auto maximum = [&](const auto& select, std::uint32_t word) { + std::uint64_t pixels = 0; + for (std::uint32_t y = 0; y < Height; ++y) { + for (std::uint32_t x = 0; x < Width; ++x) { + if (!select(x, y)) continue; + auto& stored = expected[layout.Offset(x, y) / 2u]; + std::uint32_t merged = 0; + for (std::uint32_t shift = 0; shift < 16u; shift += 4u) merged |= std::max((static_cast(stored) >> shift) & 0xfu, (word >> shift) & 0xfu) << shift; + stored = static_cast(merged); + ++pixels; + } + } + return pixels; + }; + DrawCase(device, color, 0xfu, 0xffffu, Float32Export, Float32Program(under)); + const auto ordinary = expect([&](std::uint32_t x, std::uint32_t) { return inside(x); }, Packed(under), 0xffffu); + auto maximal = color; + maximal.mergeBlend = Packing::Encode(maximal.componentMapping, Packing::EncodeEquation(VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE, VK_BLEND_OP_MAX), Packing::EncodeEquation(VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE, VK_BLEND_OP_MAX)); + Require(Draw(device, maximal, 0xfu, Float32Export, Float32Program(larger, Kill::BeforeExport), {PositionInputs, LateKill}) == 0xffffu, "a MAX blend that kills under late tests did not merge the whole packed word"); + const auto survivors = maximum(checker, Packed(larger)); + DrawCase(device, color, 0xfu, 0xffffu, Float32Export, Float32Program(over, Kill::Stripes), {PositionInputs, LateKill, TriangleAt(0.75f), depth.Address(), false}); + const auto behindDepth = expect(stripes, Packed(over), 0xffffu); + intervals.push_back({"a full write, a MAX blend of the whole packed word without depth or stencil tests that kills a checkerboard, then a full write at z 0.75 that kills every other column pair", ordinary + behindDepth, survivors}); + Require(marks.Mark(), std::string("the occlusion counter could not be read again through ") + path); + ExpectWords(device, block, layout, expected, mixed, std::string("a killing MAX blend between two full writes counted through ") + path); + + constexpr std::uint64_t seed = 0xfffff000u; + std::memcpy(block.data, uniform.data(), block.bytes); + device.WaitIdle(); + { + std::lock_guard lock(AgcDriver::GuestMemory::GpuMutex()); + auto* counter = device.graphicsContext().shaderSampleCounter; + Require(counter != nullptr, "the device has no shader sample counter to seed"); + const auto words = counter->Bytes().first(sizeof(std::uint64_t)); + std::uint64_t current = 1; + std::memcpy(¤t, words.data(), sizeof(current)); + Require(current == 0u, std::string("the shader sample counter held ") + std::to_string(current) + " after a read through " + path + ", which should have zeroed it"); + std::memcpy(words.data(), &seed, sizeof(seed)); + } + Require(Draw(device, blended, 0xfu, Float32Export, Float32Program({1.25f, 0.8f, std::numeric_limits::quiet_NaN(), 0.4f}, Kill::BeforeExport), {PositionInputs, LateKill}) == 0xffffu, "a blend that kills under late tests did not merge the whole packed word"); + intervals.push_back({"the killing blend again after the shader counter's low word was set to 0xfffff000, so its count carries into the high word", 0u, seed + static_cast(ScissorWidth) * Height / 2u}); + Require(marks.Mark(), std::string("the occlusion counter could not be read again through ") + path); + ExpectKilled(device, block, layout, uniform, 0xf885u, 0xffffu, std::string("a killing blend over a seeded shader counter counted through ") + path); + ExpectCounts(marks, intervals, precise, path, gpu); + return intervals.size(); +} + +void WithoutGpuCounter(AgcDriver::VulkanDevice& device, Block& block, const ColorTargetLayout& layout, const AgcDriver::Graphics::ColorTarget& color) { + const std::array rgba{0.6f, 0.2f, 0.8f, 0.4f}; + const auto before = Fill(block, 801u); + const auto mask = DrawCase(device, color, 0x1u, 0xf000u, Float32Export, Float32Program(rgba, Kill::BeforeExport), {PositionInputs, LateKill}); + ExpectKilled(device, block, layout, before, Packed(rgba), mask, "a killing merge drawn before counting on a device without the GPU occlusion counter"); + SampleMarks marks(device, false); + Require(marks.Mark(), "the CPU sample total could not be read without the GPU occlusion counter"); + const auto counts = marks.Counts(); + Require(counts.size() == 1u && counts.front() == 0u, "the CPU sample total counted " + std::to_string(counts.front()) + " samples of a killing merge drawn before counting started, on a device without the GPU occlusion counter"); + bool refused = false; + try { + DrawCase(device, color, 0x1u, 0xf000u, Float32Export, Float32Program(rgba, Kill::BeforeExport), {PositionInputs, LateKill}); + } catch (const std::exception& error) { + refused = std::string(error.what()).find("needs the device's shader sample counter and the GPU occlusion counter") != std::string::npos; + } + Require(refused, "a killing merge was not refused while counting on a device without the GPU occlusion counter"); + Require(marks.Mark(), "the CPU sample total could not be read after the refusal"); + const auto after = marks.Counts(); + Require(after.size() == 2u && after.back() == 0u, "the CPU sample total counted " + std::to_string(after.back()) + " samples after a refused draw, on a device without the GPU occlusion counter"); +} + +void MultisampledKillWhileCounting(AgcDriver::VulkanDevice& device, Block& block, const ColorTargetLayout& layout, const AgcDriver::Graphics::ColorTarget& color) { + const std::array rgba{0.6f, 0.2f, 0.8f, 0.4f}; + SampleMarks marks(device, false); + Require(marks.Mark(), "the CPU sample total could not be read before a multisampled killing merge"); + bool refused = false; + try { + DrawCase(device, color, 0x1u, 0xf000u, Float32Export, Float32Program(rgba, Kill::BeforeExport), {PositionInputs, LateKill, Triangle, 0u, false, VK_COMPARE_OP_LESS, 4u}); + } catch (const std::exception& error) { + refused = std::string(error.what()).find("cannot be drawn to a multisampled target while occlusion queries count samples") != std::string::npos; + } + Require(refused, "a killing merge to a multisampled target was not refused while counting"); + const auto before = Fill(block, 1001u); + const auto mask = DrawCase(device, color, 0x1u, 0xf000u, Float32Export, Float32Program(rgba, Kill::BeforeExport), {PositionInputs, LateKill}); + Require(marks.Mark(), "the CPU sample total could not be read after the single-sample killing merge"); + ExpectKilled(device, block, layout, before, Packed(rgba), mask, "a single-sample killing merge drawn after a refused multisampled one"); + const auto counts = marks.Counts(); + const std::uint64_t expected = static_cast(ScissorWidth) * Height / 2u; + Require(counts.size() == 2u && counts.back() - counts.front() == expected, "the CPU sample total counted " + std::to_string(counts.back() - counts.front()) + " samples around a refused multisampled killing merge and a single-sample one, expected " + std::to_string(expected)); +} + +void RefusedWhileCounting(AgcDriver::VulkanDevice& device, Block& block, const ColorTargetLayout& layout, const AgcDriver::Graphics::ColorTarget& color, const AgcDriver::Graphics::ColorTarget& refused, std::span refusedProgram, std::uint32_t refusedControl, const char* needle, const std::string& what) { + const std::array rgba{0.6f, 0.2f, 0.8f, 0.4f}; + SampleMarks marks(device, false); + Require(marks.Mark(), "the CPU sample total could not be read before " + what); + bool thrown = false; + std::string message = "no exception"; + try { + DrawCase(device, refused, 0x1u, 0xf000u, Float32Export, refusedProgram, {PositionInputs, refusedControl}); + } catch (const std::exception& error) { + message = error.what(); + thrown = message.find(needle) != std::string::npos; + } + Require(thrown, what + " was not refused while counting: " + message.substr(0, 300)); + const auto before = Fill(block, 1101u); + const auto mask = DrawCase(device, color, 0x1u, 0xf000u, Float32Export, Float32Program(rgba, Kill::BeforeExport), {PositionInputs, LateKill}); + Require(marks.Mark(), "the CPU sample total could not be read after the plain killing merge"); + ExpectKilled(device, block, layout, before, Packed(rgba), mask, "a plain killing merge drawn after " + what); + const auto counts = marks.Counts(); + const std::uint64_t expected = static_cast(ScissorWidth) * Height / 2u; + Require(counts.size() == 2u && counts.back() - counts.front() == expected, "the CPU sample total counted " + std::to_string(counts.back() - counts.front()) + " samples around " + what + " and a plain killing merge, expected " + std::to_string(expected)); +} + +void CoverageSamplesKillWhileCounting(AgcDriver::VulkanDevice& device, Block& block, const ColorTargetLayout& layout, const AgcDriver::Graphics::ColorTarget& color) { + const std::array rgba{0.6f, 0.2f, 0.8f, 0.4f}; + auto eqaa = color; + eqaa.coverageSamples = 2u; + RefusedWhileCounting(device, block, layout, color, eqaa, Float32Program(rgba, Kill::BeforeExport), LateKill, "a color target with several coverage samples", "a killing merge to a one-fragment target with several coverage samples"); +} + +void SampleMaskKillWhileCounting(AgcDriver::VulkanDevice& device, Block& block, const ColorTargetLayout& layout, const AgcDriver::Graphics::ColorTarget& color) { + const std::array rgba{0.6f, 0.2f, 0.8f, 0.4f}; + RefusedWhileCounting(device, block, layout, color, color, Float32Program(rgba, Kill::MaskExport), LateKill | 0x100u, "exports depth, stencil or coverage", "a killing merge whose pixel shader exports a sample mask"); +} + +void DiscardedCountStart(AgcDriver::VulkanDevice& device, Block& block, const ColorTargetLayout& layout, const AgcDriver::Graphics::ColorTarget& color) { + const std::array rgba{0.6f, 0.2f, 0.8f, 0.4f}; + auto before = Fill(block, 901u); + auto mask = DrawCase(device, color, 0x1u, 0xf000u, Float32Export, Float32Program(rgba, Kill::BeforeExport), {PositionInputs, LateKill}); + ExpectKilled(device, block, layout, before, Packed(rgba), mask, "a killing merge drawn before counting started"); + { + std::lock_guard lock(AgcDriver::GuestMemory::GpuMutex()); + auto& recorder = TestRecorder(); + recorder.CountSamples(); + AgcDriver::Graphics::Recorder::FailNextSubmitsForTest(1u); + bool failed = false; + try { + recorder.Submit(); + } catch (const std::runtime_error&) { + failed = true; + } + AgcDriver::Graphics::Recorder::FailNextSubmitsForTest(0u); + Require(failed, "the batch that started counting was submitted past an injected failure"); + } + device.WaitIdle(); + SampleMarks marks(device, false); + Require(marks.Mark(), "the CPU sample total could not be read after the batch that started counting was discarded"); + before = Fill(block, 902u); + mask = DrawCase(device, color, 0x1u, 0xf000u, Float32Export, Float32Program(rgba, Kill::BeforeExport), {PositionInputs, LateKill}); + Require(marks.Mark(), "the CPU sample total could not be read after a counted killing merge"); + ExpectKilled(device, block, layout, before, Packed(rgba), mask, "a killing merge drawn after the batch that started counting was discarded"); + const auto counts = marks.Counts(); + Require(counts.size() == 2u, "the CPU sample total was not read twice"); + Require(counts.front() == 0u, "the CPU sample total counted " + std::to_string(counts.front()) + " samples drawn before counting started, after the batch that reset the shader counter was discarded"); + const std::uint64_t expected = static_cast(ScissorWidth) * Height / 2u; + Require(counts.back() - counts.front() == expected, "a counted killing merge counted " + std::to_string(counts.back() - counts.front()) + " samples, expected " + std::to_string(expected) + ", after the batch that started counting was discarded"); +} + +} + +int main(int argc, char** argv) { try { + const bool discardedStart = argc > 1 && std::strcmp(argv[1], "discarded-start") == 0; + const bool withoutGpuCounter = argc > 1 && std::strcmp(argv[1], "no-gpu-counter") == 0; + const bool multisampledKill = argc > 1 && std::strcmp(argv[1], "multisampled-kill") == 0; + const bool coverageKill = argc > 1 && std::strcmp(argv[1], "coverage-kill") == 0; + const bool maskKill = argc > 1 && std::strcmp(argv[1], "sample-mask-kill") == 0; + if (withoutGpuCounter) AgcDriver::Graphics::Recorder::RefuseGpuSampleCounterForTest(true); const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; if (!TargetHasCapability(device->Target(), spv::CapabilityFragmentShaderPixelInterlockEXT)) { @@ -481,7 +799,34 @@ int main() { } const ColorTargetLayout layout(Width, Height, ColorTileMode::RenderTarget, 2); Block block(layout.Bytes()); - const auto color = DecodeTarget(block); + Block countedDepth(static_cast(Width) * Height * 4u); + const auto color = DecodeTarget(block, 2u); + if (withoutGpuCounter) { + WithoutGpuCounter(*device, block, layout, color); + std::puts("4_4_4_4 unorm partial write test passed without the GPU occlusion counter: a killing merge drawn before counting is not counted, and one drawn while counting is refused"); + return 0; + } + if (coverageKill) { + CoverageSamplesKillWhileCounting(*device, block, layout, color); + std::puts("4_4_4_4 unorm partial write test passed with a killing merge to a target with several coverage samples: it is refused while counting, and a plain one after it counts its samples"); + return 0; + } + if (maskKill) { + SampleMaskKillWhileCounting(*device, block, layout, color); + std::puts("4_4_4_4 unorm partial write test passed with a killing merge that exports a sample mask: the shader is refused when it is compiled, and a plain one after it counts its samples"); + return 0; + } + if (multisampledKill) { + MultisampledKillWhileCounting(*device, block, layout, color); + std::puts("4_4_4_4 unorm partial write test passed with a multisampled killing merge while counting: it is refused before it is counted, and a single-sample one after it counts its samples"); + return 0; + } + if (discardedStart) { + DiscardedCountStart(*device, block, layout, color); + std::puts("4_4_4_4 unorm partial write test passed with the batch that started counting discarded: samples drawn before counting never count, and a counted killing merge after it does"); + return 0; + } + BlendedWrites(*device, block, layout); Require(AgcDriver::Graphics::PackedWriteMask(color.componentMapping, 1u) == 0xf000u && AgcDriver::Graphics::PackedWriteMask(color.componentMapping, 8u) == 0x000fu && AgcDriver::Graphics::PackedWriteMask(color.componentMapping, 5u) == 0xf0f0u, "the export components did not map to the guest nibbles (X in 15..12, W in 3..0)"); const std::array cases{{ {0x1u, 0xf000u, {1.0f, 0.0f, 0.0f, 0.0f}}, @@ -525,8 +870,15 @@ int main() { SameDrawOverdraw(*device, block, layout, color, 0.2f, 0.8f, 401u); SameDrawOverdraw(*device, block, layout, color, 0.8f, 0.2f, 402u); DepthRejection(*device, block, layout, color); - CountedKill(*device, block, layout, color); - std::printf("4_4_4_4 unorm partial write tests passed: %zu masked draws, 3 back-to-back sequences, 4 checkerboard-killing draws, 2 same-draw overdraws of 16 layers, a depth-rejected merge and a refused killing merge while samples are counted, into a %ux%u tiled target, the killed, rejected and unscissored pixels kept\n", cases.size() + 1u, Width, Height); + const auto dumped = CountedKill(*device, block, countedDepth, layout, color, true); + const auto totalled = CountedKill(*device, block, countedDepth, layout, color, false); + const auto red = Float32Program({1.0f, 0.0f, 0.0f, 0.0f}); + for (const auto& [swap, redMask] : {std::pair{1u, 0x0f00u}, std::pair{0u, 0x000fu}, std::pair{3u, 0x00f0u}}) { + before = Fill(block, 601u + swap); + DrawCase(*device, DecodeTarget(block, swap), 1u, redMask, Float32Export, red); + ExpectSurface(*device, block, layout, before, redMask, redMask, "a red-only 4_4_4_4 write with component swap " + std::to_string(swap)); + } + std::printf("4_4_4_4 unorm partial write tests passed: %zu masked draws, 3 back-to-back sequences, 4 checkerboard-killing draws, 2 same-draw overdraws of 16 layers, a depth-rejected merge, %zu occlusion intervals around killing merges counted by GPU dumps and %zu by the CPU total (hardware intervals %s), into a %ux%u tiled target, the killed, rejected and unscissored pixels kept\n", cases.size() + 4u, dumped, totalled, device->graphicsContext().occlusionQueryPrecise ? "exact" : "nonzero", Width, Height); return 0; } catch (const std::exception& error) { std::cerr << error.what() << '\n'; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/UnclampedNormalizedBlend.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/UnclampedNormalizedBlend.cpp index ddcb97536cd7..0457ba319155 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/UnclampedNormalizedBlend.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/UnclampedNormalizedBlend.cpp @@ -2,6 +2,7 @@ #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp" #include "prx/libSceAgcDriver/Graphics/include/ColorTargetLayout.hpp" +#include "prx/libSceAgcDriver/Graphics/include/DccMetadata.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" #include "prx/libSceAgcDriver/Graphics/include/ShaderInputState.hpp" @@ -62,6 +63,8 @@ constexpr std::uint32_t Unorm8888Info = 10u << 2u; constexpr std::uint32_t Snorm8888Info = (10u << 2u) | (1u << 8u); constexpr std::uint32_t Unorm88Info = 3u << 2u; constexpr std::uint32_t TiledAttrib3 = 0x4dc6c000u; +constexpr std::uint32_t DccEnable = 0x10000000u; +constexpr std::uint32_t RegisterTexel = 0x5a3c9612u; constexpr std::uint32_t Float32Export = 9; constexpr std::uint32_t PositionInputs = 0x300u; constexpr std::uint32_t DepthInput = 0x400u; @@ -291,8 +294,9 @@ void Draw(AgcDriver::VulkanDevice& device, std::span targets, std: const auto& merges = fragment.context.pixel->targetMerges; Require(merges.size() == targets.size() && std::ranges::all_of(merges, [&](const ShaderRecompiler::TargetMerge& merge) { const auto& entry = targets[static_cast(&merge - merges.data())]; - return merge.blend.enabled && merge.mask == AgcDriver::Graphics::UnclampedBlendMask && merge.target == entry.color.exportIndex && merge.blend.snorm == entry.blend.snorm; - }), "the draw's target merges do not describe one unclamped blend per target"); + const auto surface = AgcDriver::Graphics::DecodeTextureResource(merge.descriptor); + return merge.blend.enabled && merge.mask == AgcDriver::Graphics::UnclampedBlendMask && merge.target == entry.color.exportIndex && merge.blend.snorm == entry.blend.snorm && surface.dccAddress == entry.color.dccAddress && (entry.color.dccAddress == 0u || (surface.dccAlphaOnMsb == entry.color.dccAlphaOnMsb && surface.dccPipeAligned == entry.color.dccPipeAligned)); + }), "the draw's target merges do not describe one unclamped blend per target with the target's DCC keys"); const ShaderRecompiler::SrtRuntime runtime{}; const auto invocation = AgcDriver::DriverDetail::InvocationFor(snapshot, 0, fragment); const auto pixelResult = invocation.Materialize(*invocation.Capture(runtime)); @@ -548,6 +552,74 @@ void Overdraw(AgcDriver::VulkanDevice& device, Block& block, const ColorTargetLa [&](const std::array& was) { return was; }); } +std::size_t KeyedTargetTests(AgcDriver::VulkanDevice& device) { + const ColorTargetLayout layout(Width, Height, ColorTileMode::RenderTarget, 4); + Block alignedBlock(layout.Bytes()); + Block alignedKeys(BlockBytes); + Block unalignedBlock(layout.Bytes()); + Block unalignedKeys(BlockBytes); + constexpr std::uint8_t PastKeys = 0x5a; + constexpr VkColorComponentFlags All = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; + const Case blend{"SRC_ALPHA, ONE_MINUS_SRC_ALPHA for color and ONE, ONE_MINUS_SRC_ALPHA for alpha with an out-of-range source", {VK_BLEND_FACTOR_SRC_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, VK_BLEND_OP_ADD, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, VK_BLEND_OP_ADD, All, {}, false}, {1.25f, -0.25f, 0.5f, 0.5f}, true}; + struct KeyedCase { + std::uint8_t key; + const char* code; + bool cleared; + std::array texel; + }; + constexpr std::array cases{{ + {0xff, "uncompressed", false, {}}, + {0x00, "0000", true, {0x00, 0x00, 0x00, 0x00}}, + {0x40, "0001", true, {0x00, 0x00, 0x00, 0xff}}, + {0x80, "1110", true, {0xff, 0xff, 0xff, 0x00}}, + {0xc0, "1111", true, {0xff, 0xff, 0xff, 0xff}}, + {0x20, "register", true, {static_cast(RegisterTexel), static_cast(RegisterTexel >> 8u), static_cast(RegisterTexel >> 16u), static_cast(RegisterTexel >> 24u)}}, + }}; + const auto program = Float32Program(blend.rgba); + std::uint32_t seed = 601; + std::size_t draws = 0; + for (const bool pipeAligned : {true, false}) { + Block& block = pipeAligned ? alignedBlock : unalignedBlock; + Block& keys = pipeAligned ? alignedKeys : unalignedKeys; + AgcDriver::Registers cx; + cx[0x318] = static_cast(block.Address() >> 8u); + cx[0x31b] = 0; + cx[0x31c] = Unorm8888Info | DccEnable; + cx[0x31d] = 0; + cx[0x323] = RegisterTexel; + cx[0x324] = 0; + cx[0x325] = static_cast(keys.Address() >> 8u); + cx[0x3a8] = static_cast(keys.Address() >> 40u); + cx[0x3b0] = ((Width - 1u) << 14u) | (Height - 1u); + cx[0x3b8] = pipeAligned ? TiledAttrib3 : TiledAttrib3 & ~(1u << 30u); + cx[0x390] = static_cast(block.Address() >> 40u); + const auto color = AgcDriver::Graphics::DecodeColorBuffer(cx, 0); + const auto keyCount = AgcDriver::Graphics::DccKeyCount(AgcDriver::Graphics::SurfaceForTarget(color), color.bytes); + const std::string target = std::string("a one-mip DCC 8_8_8_8 UNORM target with ") + (pipeAligned ? "pipe-aligned" : "unaligned") + " keys"; + Require(color.format == VK_FORMAT_R8G8B8A8_UNORM && color.packing == ShaderRecompiler::ColorExportPacking::None && color.bytes == block.bytes && color.dccAddress == keys.Address() && color.dccAlphaOnMsb && color.dccPipeAligned == pipeAligned && keyCount != 0u && keyCount < keys.bytes, target + " did not decode with its keys, their alignment and its alpha on the last channel"); + for (const auto& item : cases) { + auto before = Fill(block, seed++); + std::memset(keys.data, item.key, keyCount); + std::memset(keys.data + keyCount, PastKeys, keys.bytes - keyCount); + if (item.cleared) { + for (std::size_t at = 0; at + 4u <= before.size(); at += 4u) std::copy(item.texel.begin(), item.texel.end(), before.begin() + static_cast(at)); + } + Draw(device, color, blend.blend, Float32Export, program); + const std::string what = std::string("unclamped blend ") + blend.name + " into " + target + " under " + item.code + " DCC keys"; + const auto outcome = Expect(device, block, layout, before, false, blend.blend.writeMask, what, + [&](const std::array& was) { return Blended(blend.blend, blend.rgba, was, false); }, + [&](const std::array& was) { return Blended(blend.blend, blend.rgba, was, true); }); + Require(outcome.distinguished, what + " does not differ from Vulkan's clamped blend, so it cannot catch a clamping approximation"); + std::vector after(keys.bytes); + AgcDriver::GuestMemory::Read(keys.Address(), std::as_writable_bytes(std::span(after)), 1); + Require(std::all_of(after.begin(), after.begin() + static_cast(keyCount), [](std::uint8_t key) { return key == 0xffu; }), what + " left compressed DCC keys"); + Require(std::all_of(after.begin() + static_cast(keyCount), after.end(), [](std::uint8_t key) { return key == PastKeys; }), what + " changed the bytes after its " + std::to_string(keyCount) + " DCC keys"); + ++draws; + } + } + return draws; +} + } int main() { @@ -626,7 +698,8 @@ int main() { RecoveryAtImageCreation::armed = true; }); Require(RecoveryAtImageCreation::recoveries == 1u && RecoveryAtImageCreation::storageBytes != 0u, "the release at MRT1's image creation did not evict MRT0's resident image"); - std::printf("unclamped normalized color blend tests passed: %zu UNORM draws, %zu SNORM draws, 2 same-draw overdraws of 16 layers, 3 draws blending two targets each (1 with a texture cache release at MRT1's image creation), 1 refusal without pixel interlock\n", unormCases.size(), snormCases.size()); + const auto keyed = KeyedTargetTests(*device); + std::printf("unclamped normalized color blend tests passed: %zu UNORM draws, %zu SNORM draws, 2 same-draw overdraws of 16 layers, 3 draws blending two targets each (1 with a texture cache release at MRT1's image creation), %zu draws into a DCC target, 1 refusal without pixel interlock\n", unormCases.size(), snormCases.size(), keyed); return 0; } catch (const std::exception& error) { std::cerr << error.what() << '\n'; diff --git a/core/shader/recompiler/CMakeLists.txt b/core/shader/recompiler/CMakeLists.txt index dd4fa9d77c37..3123cf9954f4 100644 --- a/core/shader/recompiler/CMakeLists.txt +++ b/core/shader/recompiler/CMakeLists.txt @@ -289,6 +289,8 @@ function(add_shader_recompiler target runtimeTarget) FmaskLayoutOf IsFmaskTextureFormat PipelineSpecialization::IsAtomicLockTable + PipelineSpecialization::IsPipelineAddress + PipelineSpecialization::IsSampleCounter PipelineSpecialization::IsWorkgroupOffset PipelineSpecialization::WorkgroupOffsetBase PipelineSpecialization::WorkgroupOffsetWords diff --git a/core/shader/recompiler/PipelineSpecialization.hpp b/core/shader/recompiler/PipelineSpecialization.hpp index 184c3a25379a..9a959aba2c67 100644 --- a/core/shader/recompiler/PipelineSpecialization.hpp +++ b/core/shader/recompiler/PipelineSpecialization.hpp @@ -45,6 +45,8 @@ inline constexpr std::uint32_t WorkgroupOffsetBase = 8241u; inline constexpr std::uint32_t WorkgroupOffsetWords = 3u; inline constexpr std::uint32_t AtomicLockTableBase = 8244u; inline constexpr std::uint32_t AtomicLockTableWords = 2u; +inline constexpr std::uint32_t SampleCounterBase = 8246u; +inline constexpr std::uint32_t SampleCounterWords = 2u; inline constexpr std::uint32_t HeapCountBase = 8256u; inline constexpr std::uint32_t MipCountBase = 8320u; inline constexpr std::uint32_t StoreQuantizeBase = 12288u; @@ -81,6 +83,14 @@ inline constexpr bool IsAtomicLockTable(std::uint32_t id) { return id >= AtomicLockTableBase && id < AtomicLockTableBase + AtomicLockTableWords; } +inline constexpr bool IsSampleCounter(std::uint32_t id) { + return id >= SampleCounterBase && id < SampleCounterBase + SampleCounterWords; +} + +inline constexpr bool IsPipelineAddress(std::uint32_t id) { + return IsAtomicLockTable(id) || IsSampleCounter(id); +} + } } diff --git a/core/shader/recompiler/Recompiler.cpp b/core/shader/recompiler/Recompiler.cpp index 01d6735d7826..3fcfafd96541 100644 --- a/core/shader/recompiler/Recompiler.cpp +++ b/core/shader/recompiler/Recompiler.cpp @@ -1082,9 +1082,9 @@ std::vector specializeWords(const CompiledShaderArtifact& artifac cursor += count; continue; } - if (PipelineSpecialization::IsAtomicLockTable(words[cursor + 3u])) { - if (supplied.contains(words[cursor + 3u])) throw std::runtime_error("the atomic lock table is supplied with the pipeline, not prepared"); - if (!retained.insert(words[cursor + 1u]).second) throw std::runtime_error("duplicate atomic lock table specialization"); + if (PipelineSpecialization::IsPipelineAddress(words[cursor + 3u])) { + if (supplied.contains(words[cursor + 3u])) throw std::runtime_error("the atomic lock table and the sample counter are supplied with the pipeline, not prepared"); + if (!retained.insert(words[cursor + 1u]).second) throw std::runtime_error("duplicate pipeline address specialization"); cursor += count; continue; } @@ -1264,7 +1264,7 @@ SpecializedSpirv buildSpecializedModule(const CompiledShaderArtifact& artifact, if (op == spv::OpDecorate && count == 4u && materialized[cursor + 2u] == spv::DecorationDescriptorSet && (materialized[cursor + 3u] == PixelFunctionLdsDescriptorSet || materialized[cursor + 3u] == MeshWindowDescriptorSet || (compute && materialized[cursor + 3u] == WorkgroupMemoryDescriptorSet))) ldsBuffers.insert(materialized[cursor + 1u]); if (op == spv::OpDecorate && count == 4u && materialized[cursor + 2u] == spv::DecorationSpecId) { const auto id = materialized[cursor + 3u]; - if (!PipelineSpecialization::IsDispatchSupplied(id) && !PipelineSpecialization::IsAtomicLockTable(id)) module->specialization.push_back({id, supplied.at(id)}); + if (!PipelineSpecialization::IsDispatchSupplied(id) && !PipelineSpecialization::IsPipelineAddress(id)) module->specialization.push_back({id, supplied.at(id)}); } if (op == spv::OpVariable && count >= 4u && !ldsBuffers.contains(materialized[cursor + 2u])) { if (const auto found = bindingNumbers.find(materialized[cursor + 2u]); found != bindingNumbers.end()) module->bindings.push_back(found->second); @@ -1517,12 +1517,12 @@ void dumpFinalSpirv(const RecompileRequest& request, const RecompileResult& resu std::fprintf(stderr, "==== SPIR-V 0x%s written to %s\n", address, path); } -bool declaresAtomicLockTable(std::span words) { +bool declaresSpecialization(std::span words, bool (*selected)(std::uint32_t)) { for (std::size_t cursor = 5; cursor < words.size();) { const auto count = words[cursor] >> 16u; const auto op = static_cast(words[cursor] & 0xffffu); if (count == 0u || op == spv::OpFunction) break; - if (op == spv::OpDecorate && count == 4u && cursor + 3u < words.size() && words[cursor + 2u] == spv::DecorationSpecId && PipelineSpecialization::IsAtomicLockTable(words[cursor + 3u])) return true; + if (op == spv::OpDecorate && count == 4u && cursor + 3u < words.size() && words[cursor + 2u] == spv::DecorationSpecId && selected(words[cursor + 3u])) return true; cursor += count; } return false; @@ -1724,9 +1724,12 @@ RecompileResult materializeResult(const CompiledVariant& variant, const Recompil for (std::uint32_t component = 0; component < PipelineSpecialization::WorkgroupOffsetWords; ++component) result.specialization.push_back({PipelineSpecialization::WorkgroupOffsetBase + component, 0u}); result.specialization.push_back({PipelineSpecialization::StorePages, 0u}); } - if (declaresAtomicLockTable(artifact.spirv.Words())) { + if (declaresSpecialization(artifact.spirv.Words(), PipelineSpecialization::IsAtomicLockTable)) { for (std::uint32_t word = 0; word < PipelineSpecialization::AtomicLockTableWords; ++word) result.specialization.push_back({PipelineSpecialization::AtomicLockTableBase + word, 0u}); } + if (declaresSpecialization(artifact.spirv.Words(), PipelineSpecialization::IsSampleCounter)) { + for (std::uint32_t word = 0; word < PipelineSpecialization::SampleCounterWords; ++word) result.specialization.push_back({PipelineSpecialization::SampleCounterBase + word, 0u}); + } if (!artifact.stencilReferences.empty()) { if (artifact.stencilReferenceDword * sizeof(std::uint32_t) != result.pushConstants.size() || result.pushConstants.size() + sizeof(std::uint32_t) > request.layout.pushConstantSizeBytes) throw std::runtime_error("stencil replay push constant lies outside the stage range"); result.pushConstants.resize(result.pushConstants.size() + sizeof(std::uint32_t)); diff --git a/core/shader/recompiler/Recompiler.hpp b/core/shader/recompiler/Recompiler.hpp index 06eb92f190f6..d6ac2bcb3c65 100644 --- a/core/shader/recompiler/Recompiler.hpp +++ b/core/shader/recompiler/Recompiler.hpp @@ -178,6 +178,31 @@ inline constexpr std::uint32_t One = 3u; } +namespace Packed4444Blend { + +inline constexpr std::uint32_t Enabled = 1u << 30u; +inline constexpr std::uint32_t EquationMask = 0x7ffu; +inline constexpr std::uint32_t AlphaShift = 11u; +inline constexpr std::uint32_t MappingShift = 22u; + +constexpr std::uint32_t EncodeEquation(std::uint32_t source, std::uint32_t destination, std::uint32_t operation) { + return source | (destination << 4u) | (operation << 8u); +} + +constexpr std::uint32_t Encode(std::uint32_t mapping, std::uint32_t color, std::uint32_t alpha) { + return Enabled | (mapping << MappingShift) | (alpha << AlphaShift) | color; +} + +constexpr bool SupportsFactor(std::uint32_t factor) { + return factor <= 9u || factor == 14u; +} + +constexpr bool ValidEquation(std::uint32_t equation) { + return SupportsFactor(equation & 0xfu) && SupportsFactor((equation >> 4u) & 0xfu) && (equation >> 8u) <= 4u; +} + +} + struct TargetBlend { bool enabled = false; bool snorm = false; diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterHelpers.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterHelpers.hpp index e1b3dff6bfeb..62830df73cb1 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterHelpers.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterHelpers.hpp @@ -104,6 +104,8 @@ DppTargetLane EmitDppTargetLane(SpirvEmitterState& state, std::uint32_t control) std::uint32_t InputVariableForKind(const SpirvEmitterState& state, StageInputKind kind); bool OrderedPixelShader(const SpirvEmitterState& state); void FlushColorTargetMerge(SpirvEmitterState& state); +bool CountsSurvivingSamples(const SpirvEmitterState& state); +void EmitSurvivingSampleCount(SpirvEmitterState& state); const SpirvInputBinding* SpirvInputBindingForParameter(const SpirvEmitterState& state, std::uint32_t location); std::uint32_t EmitVertexParameterComponentU32(SpirvEmitterState& state, const SpirvInputBinding& input, std::uint32_t component); std::uint32_t EmitInputComponentU32(SpirvEmitterState& state, StageInputKind kind, std::uint32_t component); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvFlowEmitter.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvFlowEmitter.cpp index a83996375544..061769a041cb 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvFlowEmitter.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvFlowEmitter.cpp @@ -126,6 +126,7 @@ void EmitReturnTerminator(SpirvValueEmitContext& ctx) { const auto differs = Binary(state, spv::OpBitwiseAnd, TypeU32(state), Binary(state, spv::OpBitwiseXor, TypeU32(state), reference, expected), checked); EmitKillIfBoolFalse(state, Binary(state, spv::OpIEqual, TypeBool(state), differs, ConstantU32(state, 0u))); } + EmitSurvivingSampleCount(state); EmitReturnReleasingScratch(state); } diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvModuleSetup.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvModuleSetup.cpp index 9874c4ca11af..6cd7f94d1bb6 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvModuleSetup.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvModuleSetup.cpp @@ -370,7 +370,7 @@ void DefineModule(SpirvEmitterState& state) { DefineTessellationExecutionModes(state); } state.entryLabel = state.module.AllocateId(); - EmitBaseHeader(state.module, state.program, state.stencilReplayLateStore || state.requirements.imageAtomicLocks || state.requirements.bufferAtomicLocks); + EmitBaseHeader(state.module, state.program, state.stencilReplayLateStore || state.requirements.imageAtomicLocks || state.requirements.bufferAtomicLocks || CountsSurvivingSamples(state)); for (const auto capability : state.requirements.capabilities) { state.module.EmitCapability(capability); } @@ -523,7 +523,7 @@ void DefineModule(SpirvEmitterState& state) { state.module.AddExecutionMode(state.mainFunc, spv::ExecutionModeStencilRefReplacingEXT); } const bool merge = !pixel.merges.empty(); - const std::string mergeName = merge && pixel.merges.front().blend.enabled ? "blending into an unclamped normalized color target" : merge && pixel.merges.front().blendControl != 0u ? "blending into an 11_11_10 float color target" : "a partial write of a packed color target"; + const std::string mergeName = merge && pixel.merges.front().blend.enabled ? "blending into an unclamped normalized color target" : merge && pixel.merges.front().blendControl != 0u ? "blending into a packed color target" : "a partial write of a packed color target"; if (merge && (state.depthVariable != 0 || state.stencilRefVariable != 0 || pixel.psDepthExportEnable || pixel.psSampleMaskExportEnable || pixel.psStencilRefExportEnable || pixel.psAlphaToCoverage || pixel.QuadMasked() || (pixel.psPixelKillEnable && !pixel.psEarlyZ && pixel.mergeDepthStencilWrites))) { throw std::runtime_error(mergeName + " merges inside the pixel shader after early depth and stencil tests, which a shader that kills pixels under late tests of a draw writing depth or stencil, exports depth, stencil or coverage, or runs with a quad sample mask cannot use"); } diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvModuleEmitter.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvModuleEmitter.cpp index 7f3c010346ff..763490190731 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvModuleEmitter.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvModuleEmitter.cpp @@ -699,6 +699,38 @@ void MergeBlendTarget(SpirvEmitterState& state, std::size_t entry, std::uint32_t state.module.AddFunction(spv::OpStore, state.mergePendingVariables[entry], ConstantU32(state, 1u)); } +std::uint32_t Blend4444Color(SpirvEmitterState& state, const TargetMerge& merge, std::uint32_t color, std::uint32_t stored) { + namespace Packing = Packed4444Blend; + const auto mapping = merge.blendControl >> Packing::MappingShift; + const auto componentAt = [mapping](std::uint32_t field) { return (mapping >> (2u * field)) & 3u; }; + const auto low = ConstantF32Value(state, 0.0f); + const auto high = ConstantF32Value(state, 1.0f); + const auto format = GetFormatInfo(IrBufferFormat::Format4_4_4_4UNorm); + std::array source{}; + std::array destination{}; + for (std::uint32_t field = 0; field < 4u; ++field) { + const auto component = componentAt(field); + source[component] = BlendGlsl(state, GLSLstd450NMin, BlendGlsl(state, GLSLstd450NMax, BlendComponent(state, color, field), low), high); + const auto nibble = EmitAndConstant(state, EmitBinaryU32(state, spv::OpShiftRightLogical, stored, ConstantU32(state, 4u * field)), 0xfu); + destination[component] = Unary(state, spv::OpBitcast, TypeF32(state), NormalizeFormatComponent(state, format, field, nibble)); + } + TargetBlend blend{}; + std::array result{}; + for (std::uint32_t field = 0; field < 4u; ++field) { + const auto component = componentAt(field); + result[field] = low; + if ((merge.mask & (0xfu << (4u * field))) == 0u) continue; + const bool alpha = component == 3u; + const auto equation = (merge.blendControl >> (alpha ? Packing::AlphaShift : 0u)) & Packing::EquationMask; + const auto sourceFactor = BlendFactor(state, blend, equation & 0xfu, component, alpha, source, destination); + const auto destinationFactor = BlendFactor(state, blend, (equation >> 4u) & 0xfu, component, alpha, source, destination); + result[field] = BlendEquation(state, equation >> 8u, sourceFactor, destinationFactor, source[component], destination[component]); + } + const auto merged = state.module.AllocateId(); + state.module.AddFunction(spv::OpCompositeConstruct, TypeF32Vector(state, 4u), merged, result[0], result[1], result[2], result[3]); + return merged; +} + void MergeColorTarget(SpirvEmitterState& state, std::size_t entry, std::uint32_t color) { const auto& merge = PixelInfo(state).merges[entry]; if (merge.blend.enabled) return MergeBlendTarget(state, entry, color); @@ -707,9 +739,11 @@ void MergeColorTarget(SpirvEmitterState& state, std::size_t entry, std::uint32_t state.module.AddFunction(spv::OpCompositeExtract, TypeU32(state), stored, EmitStorageImageRead(state, resource, coord, sample), 0u); const bool floating = merge.packing == ColorExportPacking::Float11_11_10; if (!floating && merge.packing != ColorExportPacking::Unorm4_4_4_4) FailEmit("a color target merge into an unsupported packing"); - if (merge.blendControl != 0u && !floating) FailEmit("a blending color target merge into a target other than 11_11_10 float"); const auto format = floating ? IrBufferFormat::Format10_11_11Float : IrBufferFormat::Format4_4_4_4UNorm; - const auto word = PackExport(state, format, merge.blendControl != 0u ? BlendPackedColor(state, format, color, stored, merge.blendControl) : color); + if (merge.blendControl != 0u) { + color = floating ? BlendPackedColor(state, format, color, stored, merge.blendControl) : Blend4444Color(state, merge, color, stored); + } + const auto word = PackExport(state, format, color); const auto kept = EmitBinaryU32(state, spv::OpBitwiseAnd, stored, ConstantU32(state, ~merge.mask)); const auto merged = EmitOrU32(state, kept, EmitBinaryU32(state, spv::OpBitwiseAnd, word, ConstantU32(state, merge.mask))); state.module.AddFunction(spv::OpStore, state.mergeValueVariables[entry], merged); @@ -1105,6 +1139,48 @@ void FlushColorTargetMerge(SpirvEmitterState& state) { for (std::size_t entry = 0; entry < state.mergePendingVariables.size(); ++entry) FlushTargetMerge(state, entry); } +bool CountsSurvivingSamples(const SpirvEmitterState& state) { + if (state.program.Resources().stage != IrShaderStage::Pixel || state.inputInfo.pixel == nullptr) return false; + const auto& pixel = *state.inputInfo.pixel; + return !pixel.merges.empty() && pixel.psPixelKillEnable && !pixel.psEarlyZ; +} + +void EmitSurvivingSampleCount(SpirvEmitterState& state) { + if (!CountsSurvivingSamples(state)) return; + const auto u32 = TypeU32(state); + const auto u64 = TypeScalarU64(state); + const auto widen = [&](std::uint32_t value) { return Unary(state, spv::OpUConvert, u64, value); }; + const auto low = state.module.SpecializationConstant(u32, PipelineSpecialization::SampleCounterBase, 0u); + const auto high = state.module.SpecializationConstant(u32, PipelineSpecialization::SampleCounterBase + 1u, 0u); + const auto address = Binary(state, spv::OpBitwiseOr, u64, widen(low), Binary(state, spv::OpShiftLeftLogical, u64, widen(high), ConstantU32(state, 32u))); + const auto device = ConstantU32(state, spv::ScopeDevice); + const auto relaxed = ConstantU32(state, spv::MemorySemanticsMaskNone); + const auto add = [&](std::uint32_t word) { + const auto pointer = state.module.AllocateId(); + state.module.AddFunction(spv::OpConvertUToPtr, TypePhysicalU32Pointer(state), pointer, word); + const auto previous = state.module.AllocateId(); + state.module.AddFunction(spv::OpAtomicIAdd, u32, previous, pointer, device, relaxed, ConstantU32(state, 1u)); + return previous; + }; + auto counts = EmitCompareU32Constant(state, spv::OpINotEqual, EmitOrU32(state, low, high), 0u); + if (state.pixelValidMaskVariable != 0u) { + const auto valid = state.module.AllocateId(); + state.module.AddFunction(spv::OpLoad, u32, valid, state.pixelValidMaskVariable); + counts = Binary(state, spv::OpLogicalAnd, TypeBool(state), counts, EmitCompareU32Constant(state, spv::OpINotEqual, valid, 0u)); + } + if (const auto helperVariable = InputVariableForKind(state, StageInputKind::HelperInvocation); helperVariable != 0u) { + const auto helper = state.module.AllocateId(); + state.module.AddFunction(spv::OpLoad, TypeBool(state), helper, helperVariable); + counts = Binary(state, spv::OpLogicalAnd, TypeBool(state), counts, Unary(state, spv::OpLogicalNot, TypeBool(state), helper)); + } + EmitIfCondition(state, counts, [&] { + const auto previous = add(address); + EmitIfCondition(state, EmitCompareU32Constant(state, spv::OpIEqual, previous, 0xffffffffu), [&] { + add(Binary(state, spv::OpIAdd, u64, address, widen(ConstantU32(state, 4u)))); + }); + }); +} + namespace { std::uint32_t MeshArray(SpirvEmitterState& state, std::uint32_t storage, std::uint32_t type, std::uint32_t count) { @@ -2153,6 +2229,7 @@ void EmitProgram(SpirvEmitterState& state) { state.module.AddFunction(spv::OpKill); EmitLabel(state, mergeLabel); } + EmitSurvivingSampleCount(state); EmitReturnReleasingScratch(state); } else { StructuredFunctionState functionState; diff --git a/core/shader/recompiler/Translation/src/ShaderInputInfoBuilder.cpp b/core/shader/recompiler/Translation/src/ShaderInputInfoBuilder.cpp index ced2679b346e..870b42d331bf 100644 --- a/core/shader/recompiler/Translation/src/ShaderInputInfoBuilder.cpp +++ b/core/shader/recompiler/Translation/src/ShaderInputInfoBuilder.cpp @@ -179,7 +179,19 @@ ShaderStageInputInfo BuildShaderStageInputInfo(ShaderStageKind stage, const Gues const auto& first = pixel.targetMerges.front(); if (merge.mask == 0u || merge.target >= 8u || std::ranges::count(pixel.targetMerges, merge.target, &TargetMerge::target) != 1 || (merge.samples != 1u && merge.samples != 2u && merge.samples != 4u && merge.samples != 8u) || merge.samples != first.samples || merge.depthStencilWrites != first.depthStencilWrites || merge.depthStencilTests != first.depthStencilTests) throw std::runtime_error("ShaderInputInfoBuilder: invalid color target merge"); if (merge.blend.enabled ? merge.packing != ColorExportPacking::None : merge.packing != ColorExportPacking::Unorm4_4_4_4 && merge.packing != ColorExportPacking::Float11_11_10) throw std::runtime_error("ShaderInputInfoBuilder: a color target merge into an unsupported packing"); - if (merge.blendControl != 0u && merge.packing != ColorExportPacking::Float11_11_10) throw std::runtime_error("ShaderInputInfoBuilder: a blending color target merge into a target other than 11_11_10 float"); + if (merge.blendControl != 0u && merge.packing != ColorExportPacking::Float11_11_10) { + namespace Packing = Packed4444Blend; + const auto control = merge.blendControl; + const auto mapping = (control >> Packing::MappingShift) & 0xffu; + std::uint32_t components = 0; + for (std::uint32_t i = 0; i < 4u; ++i) components |= 1u << ((mapping >> (2u * i)) & 3u); + if (merge.packing != ColorExportPacking::Unorm4_4_4_4 || merge.samples != 1u || (merge.mask & ~0xffffu) != 0u || + (control & 0xc0000000u) != Packing::Enabled || components != 0xfu || + !Packing::ValidEquation(control & Packing::EquationMask) || + !Packing::ValidEquation((control >> Packing::AlphaShift) & Packing::EquationMask)) { + throw std::runtime_error("ShaderInputInfoBuilder: invalid packed color target blend"); + } + } if ((merge.layered && (merge.samples != 1u || merge.lastSlice < merge.firstSlice)) || (!merge.layered && (merge.firstSlice != 0u || merge.lastSlice != 0u))) throw std::runtime_error("ShaderInputInfoBuilder: a color target merge into a multisampled array, a slice range that ends before it starts, or slices of an unlayered target"); const auto& blend = merge.blend; if (blend.enabled && (merge.samples != 1u || blend.colorSource > 14u || blend.colorDestination > 14u || blend.alphaSource > 14u || blend.alphaDestination > 14u || blend.colorOperation > 4u || blend.alphaOperation > 4u || blend.writeMask > 0xfu)) throw std::runtime_error("ShaderInputInfoBuilder: invalid color target blend"); diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index e0df0fa5b35e..d3a5ebdd991c 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -661,6 +661,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_TRACE_TRIGGER_FILE` | native Unicode path on Windows, UTF-8 path elsewhere | `core/libs/prx/libSceAgcDriver/Execution/include/PerformanceTrace.hpp` | unset | additionally waits for a regular file before opening the frames/seconds trace window; the original start remains a lower bound, and the full duration begins when the window opens. Use a unique initially absent path, then create the file after verifying the scene. Use a local filesystem path: the presenter checks file metadata under the trace mutex, so slow or network metadata access can stall presentation. Checks occur on presents at most once per 250 ms while waiting; an existing file opens at the original lower bound. The file is not removed, read, or checked again after opening. Requires `APS5_TRACE_FRAMES` or `APS5_TRACE_SECONDS`; empty paths, existing nonregular files and filesystem errors are rejected. | | `APS5_TRACE_SHADER_CORRELATION` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp` | | traces shader selection and preparation failure tokens through draw batches (requires `APS5_CAPTURE_TRACE`) | | `APS5_TRACE_SHADER_REGS` | string | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp` | | prints a shader's registers for one hex program address, or `all` | +| `APS5_TRACE_SHADER_SAMPLES` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | 0 | prints one `[shader samples]` line for each of the first n occlusion counter reads (GPU dumps and CPU totals) that fold the sample count of a merging draw that kills under late tests: the read's index and dump address, the samples of the occlusion query segments and of the shader counter, the total written, and the code addresses of the counted pixel shaders. A GPU dump's line is printed when its batch completes | | `APS5_TRACE_SHADOW` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/UnitShadow.cpp` | | prints the first n shadow publishes, the first 64 seeds, every evict and retire | | `APS5_TRACE_SKIPS` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderDiagnostics.cpp` | | reports each distinct shader skip once with or without it; set, a repeat of an already reported skip is also logged as `again`, cut to 100 characters | | `APS5_TRACE_STAGING` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | | prints every distinct staged range once, with its size and whether an atomic element lies in it | diff --git a/docs/dev/debt/changes/agc-4444-color-blend.md b/docs/dev/debt/changes/agc-4444-color-blend.md new file mode 100644 index 000000000000..cc58fa10f8e9 --- /dev/null +++ b/docs/dev/debt/changes/agc-4444-color-blend.md @@ -0,0 +1,9 @@ +# libSceAgcDriver + +## change [Packed color target merges with another merged target] + +- [Packed color target merges with another merged target](../../../core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp) (libSceAgcDriver) - a blend or partial write of a 4_4_4_4 UNORM or 11_11_10 float target, throws when another color target of the draw also merges in the pixel shader (a second packed merge, staged or not, or an unclamped normalized blend), and so does any draw whose merged color targets share memory. + +## add Functional + +- [4_4_4_4 UNORM blending](../../../core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp) (libSceAgcDriver) - single-sample targets use the ordered pixel-interlock merge, with clamped source values, independent color and alpha equations, and nearest-even export packing. Constant and dual-source factors, unclamped or multisampled blending, and blending together with a color logic operation still require separate implementations. Console blend precision for this format is unmeasured. diff --git a/docs/dev/debt/changes/agc-dcc-4444-color-targets.md b/docs/dev/debt/changes/agc-dcc-4444-color-targets.md new file mode 100644 index 000000000000..9c4ecd198584 --- /dev/null +++ b/docs/dev/debt/changes/agc-dcc-4444-color-targets.md @@ -0,0 +1,5 @@ +# libSceAgcDriver + +## add Functional + +- [DCC 4_4_4_4 color targets](../../../core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp) (libSceAgcDriver) - not measured on a console. Multisampled and mipmapped DCC 4_4_4_4 UNORM targets throw. The resident R16_UINT image of a one-sample, one-mip target expands the 0001 and 1110 clear codes as one channel (0xffff and 0, not four nibbles): a draw or a CB fast-clear eliminate or DCC decompress that binds the target first stores the four-nibble clear into its texels, but a storage or sampled use of that image before then sees the one-channel value, and a write through it keeps that value. A read of the surface as a 4_4_4_4 texture (B4G4R4A4_UNORM_PACK16) under 0001, 1110 or 1111 keys reads the stored texels instead of the clear value. diff --git a/docs/dev/debt/changes/agc-merge-dcc-descriptor.md b/docs/dev/debt/changes/agc-merge-dcc-descriptor.md new file mode 100644 index 000000000000..70b498f16604 --- /dev/null +++ b/docs/dev/debt/changes/agc-merge-dcc-descriptor.md @@ -0,0 +1,5 @@ +# libSceAgcDriver + +## add Functional + +- [Pixel-interlock merges into DCC color targets](../../../core/libs/prx/libSceAgcDriver/Graphics/src/GuestTextureResource.cpp) (libSceAgcDriver) - not measured on a console. A merge into a multisampled DCC target or into a 2D array DCC target throws. A merge into one mip of a mipmapped DCC target keeps the gaps of mipmapped DCC color targets and is checked through its descriptor only. As for targets without DCC, a merge throws when its target has no resident image (`APS5_NO_RESIDENT_TARGETS`, a proxied target or an unrecorded draw). A one-sample merge binds a descriptor that carries the keys' address, alpha position and pipe alignment, so the descriptor names the same keys as the resident image the merge stores into. diff --git a/docs/dev/debt/changes/agc-merge-kill-sample-count.md b/docs/dev/debt/changes/agc-merge-kill-sample-count.md new file mode 100644 index 000000000000..6d4e344d52e1 --- /dev/null +++ b/docs/dev/debt/changes/agc-merge-kill-sample-count.md @@ -0,0 +1,11 @@ +# shader + +## change [Packed color target merges (4_4_4_4 partial writes, 11_11_10 float blending), refused draws] + +- [Packed color target merges (4_4_4_4 partial writes, 11_11_10 float blending), refused draws](../../../core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvModuleSetup.cpp) (shader recompiler) - a merge into a one-sample target throws when its shader exports depth, stencil or a sample mask, uses alpha-to-coverage or a quad sample mask, kills pixels under late tests in a draw that writes depth or stencil (a depth write, or a stencil test with a nonzero write mask and a non-keep operation), or writes guest memory (stores, atomics, GDS) under late tests in a draw with a depth, stencil or depth-bounds test, as the forced early tests would drop the writes of rejected pixels. On an RTX 4070 SUPER (driver 610.88) a fragment killed after early tests still wrote depth, and `FragDepth` was ignored with `EarlyFragmentTests`, so the depth write cannot move after the shader there. + +# libSceAgcDriver + +## add Functional + +- [Occlusion counts of merging draws that kill under late tests](../../../core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp) (libSceAgcDriver) - not measured on a console. A draw that merges a packed color target in the pixel shader and kills pixels under late tests runs with early tests, so it is left out of the occlusion queries and its pixel shader adds one sample for each invocation that survives the kill (a pixel of a one-sample target) to a device counter; the recorder copies that counter into the sample total before each counter dump and zeroes it. That the console counts these draws' samples after the kill follows the late-test order of `DB_SHADER_CONTROL`. A dump that follows such a draw inside a render pass ends the pass. Such a draw throws while samples are counted when its target is multisampled (the merge runs the pixel shader once per sample, so the counter very likely matches, but that is not verified against the occlusion queries) or is a one-fragment target with several coverage samples (one invocation covers several samples and the counter counts invocations). A pixel shader that exports a sample mask cannot merge a packed color target at all: it is refused when it is compiled. Without the GPU occlusion counter (no buffer device address, or its compute pipelines failed) such a draw throws while samples are counted.