From fb12b1926065ab4fd4b4faa96c31a41c15adac4a Mon Sep 17 00:00:00 2001 From: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:15:28 +0800 Subject: [PATCH] perf(agc): replay direct draws to native multisample color targets Keep the image and a weak reference to each multisample attachment. Reacquire it through the live target registry to apply pending writes and clears and verify the image and view before recording. Retired or recreated attachments take the ordinary draw path. AI-assisted: Codex + GPT-6.2 Astra (xhigh) --- .../Execution/include/Recipe.hpp | 5 + .../Graphics/include/MultisampleTarget.hpp | 1 + .../prx/libSceAgcDriver/Graphics/src/Draw.cpp | 47 ++++++-- .../Graphics/src/MultisampleTarget.cpp | 27 ++++- .../libSceAgcDriver/tests/TargetStateMemo.cpp | 112 +++++++++++++++--- .../cmake/agc_driver_target_memo_tests.cmake | 9 +- 6 files changed, 169 insertions(+), 32 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Recipe.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Recipe.hpp index 3ab0d7e78df6..2d70813912cb 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Recipe.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Recipe.hpp @@ -70,12 +70,17 @@ enum class RecipeOutcome { Recorded, Rebuild }; // pipeline stages. Built at the end of a recorded, cacheable, reusable, non-indirect draw and // attached to the draw entry's matched stage variants; immutable. struct DrawRecipe { + struct MultisampleAttachment { + std::weak_ptr owner; + VkImage image; + }; VkDevice device = VK_NULL_HANDLE; std::weak_ptr templateRef; Graphics::ResourceCache::Key key; std::weak_ptr pipeline; std::weak_ptr framebuffer; std::vector> targets; + std::vector multisampleAttachments; std::vector targetViews; std::uint64_t passKey = 0; Graphics::VertexInputLayout vertexInput; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp index 8863a4d2f935..9e204005c8d8 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp @@ -112,6 +112,7 @@ std::vector ReadMultisampleTargetSamples_nid_no_patch(const Context& MultisampleColorSnapshot ReadMultisampleTargetColorSnapshot_nid_no_patch(const Context& context, const ColorTarget& target); VkImageView MultisampleTargetView(const Context& context, const ColorTarget& target, VkImage* image = nullptr); VkImageView MultisampleTargetView(const Context& context, const ColorTarget& target, std::shared_ptr& owner, VkImage* image = nullptr); +bool RepeatMultisampleTargetView(const Context& context, const ColorTarget& target, const std::shared_ptr& owner, VkImage image, VkImageView view); void PrepareMultisampleTargetForDraw_nid_no_patch(const Context& context, const ColorTarget& target); void KeepMultisampleTarget_nid_no_patch(const std::shared_ptr& owner); void MaterializeMultisampleTargetClear(const Context& context, const ColorTarget& target); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index f3b4b3ff611a..bc9d5c70de01 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -4700,14 +4700,19 @@ void recordPreparedDraw(const Context& context, const State& state, const Pm4::D // only a template the resource cache serves under this content key (reusable: no lease, // no copied writes, every direct region import- or mirror-served) of a direct draw, so a // hit's proof is the template's ProveCurrent and nothing needs completion work. - if (recipeOut != nullptr && DrawRecipes() && cacheable && !outcome.waited && args == nullptr && resources->Reusable() && !resources->SpaceReuse() && !multisampled && !pipeline->ReordersSamples()) { + if (recipeOut != nullptr && DrawRecipes() && cacheable && !outcome.waited && args == nullptr && resources->Reusable() && !resources->SpaceReuse() && !pipeline->ReordersSamples() && + (!multisampled || std::ranges::all_of(targets, &TargetBinding::multisampled))) { auto recipe = std::make_shared(); recipe->device = context.device; recipe->templateRef = resources; recipe->key = contentKey; recipe->pipeline = pipeline; recipe->framebuffer = framebuffer; - for (const auto& owner : owners) recipe->targets.emplace_back(owner); + if (multisampled) { + for (const auto& binding : targets) recipe->multisampleAttachments.push_back({binding.multisampleOwner, binding.multisampleImage}); + } else { + for (const auto& owner : owners) recipe->targets.emplace_back(owner); + } recipe->targetViews = targetViews; recipe->passKey = DrawRenderPassKey(context, state, targetViews); recipe->vertexInput = inputs.VertexLayout(); @@ -5171,7 +5176,9 @@ DrawRecipeOutcome DrawWithRecipe(const Context& context, const State& state, con if (recipe.hasDepth != state.depth.has_value()) return miss(DrawRecipeMiss::TargetGone); if (!ZeroVertexLayoutMatches(recipe.vertexInput, shaders.front().program->vertexAttributes)) return miss(DrawRecipeMiss::Proof); const std::size_t expectedViews = state.colors.size() + (recipe.hasDepth ? 1u : 0u); - Require(recipe.targets.size() == state.colors.size() && recipe.targetViews.size() == expectedViews, "draw recipe targets do not match the state"); + const bool multisampled = !recipe.multisampleAttachments.empty(); + const auto colorCount = multisampled ? recipe.multisampleAttachments.size() : recipe.targets.size(); + Require(colorCount == state.colors.size() && recipe.targetViews.size() == expectedViews, "draw recipe targets do not match the state"); const auto plan = planDraw(context, state, draw, shaders, &recipe, outcome, timer); DrawInputs inputs; if (plan.nothing) inputs.nothing = true; @@ -5190,20 +5197,37 @@ DrawRecipeOutcome DrawWithRecipe(const Context& context, const State& state, con if (ownsTargetMemo(memo) && (memo.colors.valid || memo.depth.valid)) noteTargetMemo(TargetMemoEvent::RecipeInvalidated); memo.Invalidate(); const bool passAttachments = PassAttachmentMemoEnabled(); - const bool verifyAttachments = passAttachments && VerifyPassAttachments() && [&] { + std::vector> multisampleOwners; + std::vector multisampleImages; + if (multisampled) { + multisampleOwners.reserve(state.colors.size()); + multisampleImages.reserve(state.colors.size()); + } + const bool verifyAttachments = passAttachments && !multisampled && VerifyPassAttachments() && [&] { InlineList, 8> ignored; return matchAttachmentMemo(context, state, ignored, recipe.targetViews); }(); InlineList, 8> targets; - const bool attachmentsFromMemo = passAttachments && !VerifyPassAttachments() && matchAttachmentMemo(context, state, targets, recipe.targetViews); + const bool attachmentsFromMemo = passAttachments && !multisampled && !VerifyPassAttachments() && matchAttachmentMemo(context, state, targets, recipe.targetViews); if (attachmentsFromMemo) { noteAttachments(AttachmentEvent::Hit); for (std::size_t index = 0; index < state.colors.size(); ++index) { if (state.colors[index].fmaskAddress != 0) GuardOneFragmentFmask(context, state.colors[index]); } } else { - for (std::size_t index = 0; index < recipe.targets.size(); ++index) { + for (std::size_t index = 0; index < colorCount; ++index) { timer.phase(PhaseSetup); + if (multisampled) { + const auto& color = state.colors[index]; + const auto& attachment = recipe.multisampleAttachments[index]; + auto owner = attachment.owner.lock(); + if (!RepeatMultisampleTargetView(context, color, owner, attachment.image, recipe.targetViews[index])) return miss(DrawRecipeMiss::TargetGone); + multisampleOwners.push_back(std::move(owner)); + multisampleImages.push_back(attachment.image); + targets.EmplaceBack(nullptr); + timer.phase(PhaseReadTarget); + continue; + } if (state.colors[index].fmaskAddress != 0) GuardOneFragmentFmask(context, state.colors[index]); auto stored = recipe.targets[index].lock(); if (stored == nullptr || !StorageImageCached(context, stored.get()) || !StorageImageServesKeys(*stored, SurfaceForTarget(state.colors[index]).dccAddress)) return miss(DrawRecipeMiss::TargetGone); @@ -5247,6 +5271,13 @@ DrawRecipeOutcome DrawWithRecipe(const Context& context, const State& state, con } const auto moved = resources->MovedReadOnlyBuffers(shaders, *recorder, &state.color); if (!moved.has_value()) return miss(DrawRecipeMiss::Buffers); + if (multisampled) { + const auto& sources = resources->MultisampleSources(); + for (const auto& color : state.colors) { + if (std::ranges::find(sources, color.surfaceAddress) != sources.end()) return miss(DrawRecipeMiss::Proof); + } + if (state.depth) RequireNoNativeDepthFeedback_nid_no_patch(context, *state.depth, resources->SampledTextures()); + } CheckBufferAliases(shaders, state.color, draw.indexAddress, inputs.indexBytes); if (recipe.hasDepth && writesDepthTarget(state)) NoteDepthSurfaceWrite(context, *state.depth); SharedResourceCache().Touch(recipe.key); @@ -5263,7 +5294,7 @@ DrawRecipeOutcome DrawWithRecipe(const Context& context, const State& state, con auto framebuffer = recipe.framebuffer.lock(); if (framebuffer == nullptr) { const auto stored = targets.Span(); - const std::vector> framebufferOwners(stored.begin(), stored.end()); + const auto framebufferOwners = multisampled ? multisampleOwners : std::vector>(stored.begin(), stored.end()); framebuffer = pipeline->AcquireFramebuffer(recipe.targetViews, framebufferOwners, state.renderExtent, state.renderLayers); } timer.phase(PhasePipeline); @@ -5275,6 +5306,8 @@ DrawRecipeOutcome DrawWithRecipe(const Context& context, const State& state, con record.moved = *moved; record.targetViews = recipe.targetViews; record.targets = targets.Span(); + record.multisampleTargets = std::move(multisampleOwners); + record.multisampleImages = std::move(multisampleImages); InlineList, 8> slices; for (const auto& color : state.colors) slices.EmplaceBack(color.arraySlice, color.arrayLastSlice != 0 ? color.layers : 1u); record.targetSlices = slices.Span(); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleTarget.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleTarget.cpp index 51f342f80974..f4f1539024fd 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleTarget.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleTarget.cpp @@ -1478,14 +1478,16 @@ bool holdHostOnly(const MultisampleTarget& target) { return true; } -MultisampleTarget& acquire(const Context& context, const ColorTarget& requested, std::optional initialClear = std::nullopt, std::shared_ptr initialUpload = {}, std::vector initialBaseline = {}) { +MultisampleTarget* acquireExisting(const Context& context, const ColorTarget& requested, const MultisampleTarget* expected = nullptr, VkImage expectedImage = VK_NULL_HANDLE) { discardRetiredTargets(); for (const auto& target : targets()) { if (!target->active->load(std::memory_order_acquire)) continue; if (target->context.device != context.device || !target->Serves(requested)) continue; auto use = requested; use.format = target->target.format; - if (recreated(target->target, use)) { + const bool recreate = recreated(target->target, use); + if (expected != nullptr && (target.get() != expected || target->image != expectedImage || recreate)) return nullptr; + if (recreate) { { std::unique_lock lock(guardedMutex()); if (!target->active->load(std::memory_order_acquire)) continue; @@ -1496,7 +1498,7 @@ MultisampleTarget& acquire(const Context& context, const ColorTarget& requested, target->use->hostOnly.store(true, std::memory_order_release); guard(context, use, target->active, target->metadataValid, target->use, target); target->ApplyFastClear(use); - return *target; + return target.get(); } { std::unique_lock lock(guardedMutex()); @@ -1522,8 +1524,13 @@ MultisampleTarget& acquire(const Context& context, const ColorTarget& requested, target->ApplyFastClear(use); collectFmaskWrites(target->target); stampUse(*target->use, target->target.address, guardedColorBytes(target->target)); - return *target; + return target.get(); } + return nullptr; +} + +MultisampleTarget& acquire(const Context& context, const ColorTarget& requested, std::optional initialClear = std::nullopt, std::shared_ptr initialUpload = {}, std::vector initialBaseline = {}) { + if (auto* existing = acquireExisting(context, requested)) return *existing; const auto& use = requested; auto target = std::make_shared(context, use, false, initialClear, std::move(initialUpload), std::move(initialBaseline)); target->Keep(); @@ -1953,6 +1960,18 @@ VkImageView MultisampleTargetView(const Context& context, const ColorTarget& tar return acquired.View(target.format); } +bool RepeatMultisampleTargetView(const Context& context, const ColorTarget& target, const std::shared_ptr& owner, VkImage image, VkImageView view) { + if (owner == nullptr || target.samples <= 1 || target.staged) return false; + storeEarlierStorageResults(target); + const DccPublication publication(target); + TargetsLock lock; + auto* existing = acquireExisting(context, target, static_cast(owner.get()), image); + if (existing == nullptr || existing->View(target.format) != view) return false; + existing->drawn = true; + ++existing->contents; + return true; +} + void KeepMultisampleTarget_nid_no_patch(const std::shared_ptr& owner) { std::static_pointer_cast(owner)->Keep(); } diff --git a/core/libs/prx/libSceAgcDriver/tests/TargetStateMemo.cpp b/core/libs/prx/libSceAgcDriver/tests/TargetStateMemo.cpp index 66cb7410687b..85666d86ea36 100644 --- a/core/libs/prx/libSceAgcDriver/tests/TargetStateMemo.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/TargetStateMemo.cpp @@ -175,21 +175,27 @@ State drawState(const ColorTarget& color, const DrawOptions& options) { return state; } -void draw(AgcDriver::VulkanDevice& device, const ColorTarget& color, const DrawOptions& options = {}) { +struct CoverShaders { ShaderRecompiler::RecompileResult vertex; - vertex.spirv = std::vector(std::begin(COVER_VERT_SPV), std::end(COVER_VERT_SPV)); - vertex.variantId = 1; ShaderRecompiler::RecompileResult fragment; - fragment.spirv = std::vector(std::begin(COVER_FRAG_SPV), std::end(COVER_FRAG_SPV)); - fragment.variantId = 2; - const std::array shaders{{ + const std::array stages{{ {ShaderRecompiler::ShaderStage::Vertex, &vertex, 0}, {ShaderRecompiler::ShaderStage::Fragment, &fragment, 0} }}; + CoverShaders() { + vertex.spirv = std::vector(std::begin(COVER_VERT_SPV), std::end(COVER_VERT_SPV)); + vertex.variantId = 1; + fragment.spirv = std::vector(std::begin(COVER_FRAG_SPV), std::end(COVER_FRAG_SPV)); + fragment.variantId = 2; + } +}; + +void draw(AgcDriver::VulkanDevice& device, const ColorTarget& color, const DrawOptions& options = {}) { + const CoverShaders cover; const auto state = drawState(color, options); std::lock_guard lock(AgcDriver::GuestMemory::GpuMutex()); if (options.prepareOnly) SetDrawStopAfterResolveForTest(DrawStopForTest::ReturnAfterResolve); - device.Draw(state, {0, 3, 0, 1, 0, false}, shaders); + device.Draw(state, {0, 3, 0, 1, 0, false}, cover.stages); } bool memoSwitchedOff() { @@ -1629,16 +1635,8 @@ void recipeViews(AgcDriver::VulkanDevice& device) { colorB.surfaceAddress = colorB.address; reset(device, colorA); reset(device, colorB); - ShaderRecompiler::RecompileResult vertex; - vertex.spirv = std::vector(std::begin(COVER_VERT_SPV), std::end(COVER_VERT_SPV)); - vertex.variantId = 1; - ShaderRecompiler::RecompileResult fragment; - fragment.spirv = std::vector(std::begin(COVER_FRAG_SPV), std::end(COVER_FRAG_SPV)); - fragment.variantId = 2; - const std::array shaders{{ - {ShaderRecompiler::ShaderStage::Vertex, &vertex, 0}, - {ShaderRecompiler::ShaderStage::Fragment, &fragment, 0} - }}; + const CoverShaders cover; + const auto& shaders = cover.stages; const auto stateA = drawState(colorA, {}); const auto stateB = drawState(colorB, {}); const AgcDriver::Pm4::DrawParameters params{0, 3, 0, 1, 0, false}; @@ -1680,8 +1678,86 @@ void recipeViews(AgcDriver::VulkanDevice& device) { expect(device, colorA, [](std::uint32_t x) { return leftOver(x, Old); }, "recipe draw after view change"); } -const std::array, 18> R3Scenarios{{ +void multisampleRecipe(AgcDriver::VulkanDevice& device) { + auto color = colorTarget(); + color.address = address(MultisampleStorage.data()); + color.surfaceAddress = color.address; + color.samples = color.coverageSamples = 4; + const auto bytes = MultisampledColorBytes(color); + Require(bytes <= MultisampleStorage.size(), "multisample recipe storage is too small"); + AgcDriver::GuestMemory::Write(color.address, std::vector(bytes)); + AgcDriver::GuestMemory::BumpCollectEpoch(); + auto state = drawState(color, {}); + state.blend.blendEnable = VK_TRUE; + state.blend.srcColorBlendFactor = VK_BLEND_FACTOR_CONSTANT_COLOR; + state.blend.dstColorBlendFactor = VK_BLEND_FACTOR_ONE; + state.blend.srcAlphaBlendFactor = VK_BLEND_FACTOR_CONSTANT_ALPHA; + state.blend.dstAlphaBlendFactor = VK_BLEND_FACTOR_ONE; + state.blends = {state.blend}; + state.blendConstants.fill(32.0f / 255.0f); + state.quadSampleMask.fill(0x5u); + + const CoverShaders cover; + const AgcDriver::Pm4::DrawParameters draw{0, 3, 0, 1, 0, false}; + std::shared_ptr recipe; + unsigned draws = 0; + { + std::lock_guard lock(AgcDriver::GuestMemory::GpuMutex()); + while (recipe == nullptr && draws < 3) { + device.Draw(state, draw, cover.stages, {}, &recipe); + ++draws; + } + Require(recipe != nullptr, "the native multisample color draw did not build a recipe"); + Require(device.DrawFromRecipe(state, draw, cover.stages, {}, recipe) == AgcDriver::RecipeOutcome::Recorded, + "the native multisample color draw did not replay"); + ++draws; + device.WaitIdle(); + } + const auto context = AgcDriver::VulkanDeviceTestAccess::ContextOf(device); + const auto samples = ReadMultisampleTargetSamples_nid_no_patch(context, color); + Require(samples.size() == Width * Height * color.samples * 4u, "multisample recipe readback size"); + for (unsigned pixel = 0; pixel < Width * Height; ++pixel) { + for (unsigned sample = 0; sample < color.samples; ++sample) { + std::uint32_t value; + std::memcpy(&value, samples.data() + (pixel * color.samples + sample) * sizeof(value), sizeof(value)); + const auto expected = pixel % Width < LeftWidth && (sample == 0 || sample == 2) ? 32u * draws * 0x01010101u : 0u; + Require(value == expected, "multisample recipe changed sample " + std::to_string(sample) + " at pixel " + std::to_string(pixel)); + } + } + const auto destination = colorTarget(); + reset(device, destination); + ColorMetadataPass resolve{}; + resolve.mode = ColorMetadataPass::Mode::Resolve; + resolve.source = color; + resolve.targets = {destination}; + device.ColorMetadataPass(resolve); + expect(device, destination, [&](unsigned x) { return x < LeftWidth ? 16u * draws * 0x01010101u : 0u; }, "multisample recipe resolve"); + + std::lock_guard lock(AgcDriver::GuestMemory::GpuMutex()); + device.WaitIdle(); + const auto alias = MultisampleColorTargetOver(color.address, static_cast(bytes)); + Require(alias.has_value(), "the multisample test target has no live owner"); + RetireMultisampleColorTarget(alias->active); + Require(device.DrawFromRecipe(state, draw, cover.stages, {}, recipe) == AgcDriver::RecipeOutcome::Rebuild, + "a recipe replayed a retired multisample attachment"); + std::shared_ptr replacement; + device.Draw(state, draw, cover.stages, {}, &replacement); + Require(replacement != nullptr, "the new multisample owner did not produce a replacement recipe"); + Require(device.DrawFromRecipe(state, draw, cover.stages, {}, recipe) == AgcDriver::RecipeOutcome::Rebuild, + "a recipe replayed a replacement owner at the same guest address"); + Require(device.DrawFromRecipe(state, draw, cover.stages, {}, replacement) == AgcDriver::RecipeOutcome::Recorded, + "the replacement owner's recipe did not record"); + device.WaitIdle(); + std::shared_ptr heldOwner; + MultisampleTargetView(context, color, heldOwner); + ClearMultisampleTargets(context.device); + Require(device.DrawFromRecipe(state, draw, cover.stages, {}, replacement) == AgcDriver::RecipeOutcome::Rebuild, + "a live framebuffer owner remained replayable after the target list was cleared"); +} + +const std::array, 19> R3Scenarios{{ {"memo-order", memoOrder}, + {"multisample-recipe", multisampleRecipe}, {"recipe-views", recipeViews}, {"untracked-dcc", untrackedDccClear}, {"untracked-cmask", untrackedCmaskClear}, diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_target_memo_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_target_memo_tests.cmake index 8f14bdb338fb..973bfe803099 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_target_memo_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_target_memo_tests.cmake @@ -83,13 +83,16 @@ if(BUILD_TESTING) endif() endforeach() add_test(NAME agc_driver_target_memo_recipe_views COMMAND agc_driver_target_memo_tests --r3 recipe-views) - set_tests_properties(agc_driver_target_memo_recipe_views PROPERTIES + add_test(NAME agc_driver_multisample_color_recipe COMMAND agc_driver_target_memo_tests --r3 multisample-recipe) + set_tests_properties(agc_driver_multisample_color_recipe agc_driver_target_memo_recipe_views PROPERTIES TIMEOUT 30 SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" - ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_DRAW_PIPELINE=1;APS5_PROFILE_DRAW=1" + ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_DRAW_PIPELINE=1") + set_property(TEST agc_driver_target_memo_recipe_views APPEND PROPERTY ENVIRONMENT APS5_PROFILE_DRAW=1) + set_tests_properties(agc_driver_target_memo_recipe_views PROPERTIES PASS_REGULAR_EXPRESSION "recipe views: pass attachment memo on.*target state memo tests passed" FAIL_REGULAR_EXPRESSION "differ from the full lookup") if(WIN32) - set_tests_properties(agc_driver_target_memo_recipe_views PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") + set_tests_properties(agc_driver_multisample_color_recipe agc_driver_target_memo_recipe_views PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() if(NOT WIN32) add_test(NAME agc_driver_target_memo_watched_imports COMMAND agc_driver_target_memo_tests)