mirror of
https://github.com/boykopovar/AnyPS5.git
synced 2026-10-10 01:28:44 +02:00
Merge pull request #76 from boykopovar/fix/frame-flicking
Fix/frame flicking ## Summary Fixed corrupted frames caused by guest input buffers being overwritten before GPU execution. ## Cause Draws referenced mutable guest memory. The CPU could overwrite an input buffer after the draw was recorded but before the GPU consumed it. ## Detection Instrumentation compared input-buffer contents at draw recording and GPU execution. Corrupted frames contained mismatches in buffers used by affected draws; adjacent correct frames did not. ## Changes The recorder now creates per-draw copies of read-only CPU input buffers and keeps them alive until GPU completion. Each draw uses descriptors referencing its preserved data. Buffers with pending GPU writes remain on the existing path and are not copied from CPU memory.
This commit is contained in:
@@ -0,0 +1,95 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <fstream>
|
||||
#include <mutex>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
namespace AgcDriver {
|
||||
|
||||
class CaptureTrace {
|
||||
public:
|
||||
static bool Enabled() {
|
||||
static const bool enabled = std::getenv("APS5_CAPTURE_TRACE") != nullptr;
|
||||
return enabled;
|
||||
}
|
||||
|
||||
template<typename... TArgs>
|
||||
static void Log(const char* format, TArgs... args) {
|
||||
if (!Enabled()) return;
|
||||
std::array<char, 2048> line{};
|
||||
const auto size = std::snprintf(line.data(), line.size(), format, args...);
|
||||
if (size < 0 || static_cast<std::size_t>(size) >= line.size()) throw std::runtime_error("Capture trace event exceeds 2047 bytes");
|
||||
static CaptureTrace& trace = instance();
|
||||
trace.append(std::string(line.data(), static_cast<std::size_t>(size)));
|
||||
}
|
||||
|
||||
private:
|
||||
static CaptureTrace& instance() {
|
||||
static CaptureTrace trace;
|
||||
return trace;
|
||||
}
|
||||
|
||||
CaptureTrace() {
|
||||
output.exceptions(std::ios::badbit | std::ios::failbit);
|
||||
output.open("capture-trace.log", std::ios::binary);
|
||||
worker = std::thread([this] { run(); });
|
||||
}
|
||||
|
||||
~CaptureTrace() {
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
stopping = true;
|
||||
}
|
||||
changed.notify_one();
|
||||
worker.join();
|
||||
}
|
||||
|
||||
void append(std::string line) {
|
||||
const auto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - start).count();
|
||||
std::lock_guard lock(mutex);
|
||||
if (pending.size() + line.size() + 64 > 16 * 1024 * 1024) throw std::runtime_error("Capture trace queue exceeded 16 MiB");
|
||||
pending += std::to_string(++sequence) + " " + std::to_string(elapsed) + "us " + line + "\n";
|
||||
if (line.starts_with("blit ")) flushRequested = true;
|
||||
if (pending.size() >= 65536 || flushRequested) changed.notify_one();
|
||||
}
|
||||
|
||||
void run() {
|
||||
try {
|
||||
for (;;) {
|
||||
std::string batch;
|
||||
{
|
||||
std::unique_lock lock(mutex);
|
||||
changed.wait_for(lock, std::chrono::milliseconds(100), [this] { return stopping || flushRequested || pending.size() >= 65536; });
|
||||
if (stopping && pending.empty()) return;
|
||||
batch.swap(pending);
|
||||
flushRequested = false;
|
||||
}
|
||||
if (batch.empty()) continue;
|
||||
output.write(batch.data(), static_cast<std::streamsize>(batch.size()));
|
||||
output.flush();
|
||||
}
|
||||
} catch (const std::exception& error) {
|
||||
std::fprintf(stderr, "Capture trace failed: %s\n", error.what());
|
||||
std::terminate();
|
||||
}
|
||||
}
|
||||
|
||||
std::ofstream output;
|
||||
std::mutex mutex;
|
||||
std::condition_variable changed;
|
||||
std::string pending;
|
||||
std::thread worker;
|
||||
std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
|
||||
unsigned long long sequence = 0;
|
||||
bool stopping = false;
|
||||
bool flushRequested = false;
|
||||
};
|
||||
|
||||
}
|
||||
@@ -21,6 +21,7 @@ public:
|
||||
// Fills the source image from another image of the same extent (any blittable format, layout
|
||||
// unchanged), leaving the source image ready to blit or read back.
|
||||
void RecordBlitInto(VkCommandBuffer commands, VkImage image, VkImageLayout layout, VkFilter filter);
|
||||
void RecordBlitInto(VkCommandBuffer commands, VkImage image, VkImageLayout layout, VkFilter filter, std::uint32_t width, std::uint32_t height);
|
||||
// Copies the source image's texels (tightly packed rows of its format) into a host-readable buffer
|
||||
// and makes them visible to the host once the submission completes.
|
||||
void RecordReadback(VkCommandBuffer commands, VkBuffer destination);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
#include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp"
|
||||
#include "prx/libSceAgcDriver/Execution/include/Driver.hpp"
|
||||
#include "prx/libSceAgcDriver/Execution/include/PerformanceTimer.hpp"
|
||||
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
|
||||
@@ -5621,6 +5622,7 @@ private:
|
||||
const auto opcode = (header >> 8u) & 0xffu;
|
||||
// Names this packet for the flush hook's sync attribution ([hooksync]); the flip is 0xffff.
|
||||
GuestMemory::SetCurrentPacket(header == FlipPacketHeader ? 0xffffu : opcode, submission.queue);
|
||||
CaptureTrace::Log("packet submission=%llu queue=%x offset=%zu header=%08x words=%zu", static_cast<unsigned long long>(submission.serial), submission.queue, cursor, header, packet.size());
|
||||
// Pending labels and full batches go to the GPU before this packet's own work starts
|
||||
// (see flushBetweenPackets); labels themselves only check the deadline, so a label
|
||||
// group shares one submission. Timed on its own, before the packet's timer starts.
|
||||
@@ -5930,6 +5932,7 @@ private:
|
||||
frame->IncludeSubmission(submission.serial, now, now, now, true);
|
||||
frame->SetFlip(submission.serial, cursor, now, now);
|
||||
frame->NoteFlipBatches(batchesAtFlip, unsignaledAtFlip);
|
||||
CaptureTrace::Log("flip frame=%llu submission=%llu offset=%zu batch=%llu unsignaled=%llu", static_cast<unsigned long long>(frameSerial), static_cast<unsigned long long>(submission.serial), cursor, static_cast<unsigned long long>(batchesAtFlip), static_cast<unsigned long long>(unsignaledAtFlip));
|
||||
submission.flips.at(cursor)->GpuReady(frame);
|
||||
} else if (opcode == 0x15) {
|
||||
timed(&WorkerProfile::dispatchMs, [&] { tolerate("dispatch", [&] { dispatch(queue, packet, submission); }); });
|
||||
@@ -5994,6 +5997,7 @@ private:
|
||||
std::string rejected;
|
||||
const auto verdict = draw(queue, packet, submission, rejected);
|
||||
drawn = verdict == DrawVerdict::Drawn;
|
||||
CaptureTrace::Log("draw submission=%llu queue=%x offset=%zu target=%llx mask=%x verdict=%d reason=%.256s", static_cast<unsigned long long>(submission.serial), submission.queue, cursor, static_cast<unsigned long long>(color), readRegister(queue.context, 0x8e), static_cast<int>(verdict), rejected.c_str());
|
||||
if (verdict == DrawVerdict::Rejected) {
|
||||
skipped(rejected);
|
||||
countSkip(Graphics::DrawSkip::Prechecked);
|
||||
@@ -6003,6 +6007,7 @@ private:
|
||||
std::fprintf(stderr, "[draw] target 0x%llx mask 0x%x ok\n",static_cast<unsigned long long>(color), readRegister(queue.context, 0x8e));
|
||||
}
|
||||
} catch (const std::exception& error) {
|
||||
CaptureTrace::Log("draw-error submission=%llu offset=%zu reason=%.256s", static_cast<unsigned long long>(submission.serial), cursor, error.what());
|
||||
skipped(error.what());
|
||||
countSkip(Graphics::DrawSkip::Thrown);
|
||||
}
|
||||
|
||||
@@ -79,7 +79,12 @@ void PresentationScaler::RecordUpload(VkCommandBuffer commands, VkBuffer uploadB
|
||||
}
|
||||
|
||||
void PresentationScaler::RecordBlitInto(VkCommandBuffer commands, VkImage image, VkImageLayout layout, VkFilter filter) {
|
||||
RecordBlitInto(commands, image, layout, filter, sourceWidth, sourceHeight);
|
||||
}
|
||||
|
||||
void PresentationScaler::RecordBlitInto(VkCommandBuffer commands, VkImage image, VkImageLayout layout, VkFilter filter, std::uint32_t width, std::uint32_t height) {
|
||||
Graphics::Require(sourceImage != VK_NULL_HANDLE && image != VK_NULL_HANDLE, "presentation image is unavailable");
|
||||
Graphics::Require(width != 0 && height != 0, "presentation blit extent must be non-zero");
|
||||
const auto pipelineBarrier = context.Function<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier");
|
||||
VkImageMemoryBarrier barrier{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};
|
||||
barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
|
||||
@@ -92,9 +97,9 @@ void PresentationScaler::RecordBlitInto(VkCommandBuffer commands, VkImage image,
|
||||
pipelineBarrier(commands, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier);
|
||||
VkImageBlit blit{};
|
||||
blit.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
|
||||
blit.srcOffsets[1] = {static_cast<std::int32_t>(sourceWidth), static_cast<std::int32_t>(sourceHeight), 1};
|
||||
blit.srcOffsets[1] = {static_cast<std::int32_t>(width), static_cast<std::int32_t>(height), 1};
|
||||
blit.dstSubresource = blit.srcSubresource;
|
||||
blit.dstOffsets[1] = blit.srcOffsets[1];
|
||||
blit.dstOffsets[1] = {static_cast<std::int32_t>(sourceWidth), static_cast<std::int32_t>(sourceHeight), 1};
|
||||
context.Function<PFN_vkCmdBlitImage>("vkCmdBlitImage")(commands, image, layout, sourceImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, filter);
|
||||
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
|
||||
barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
#include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp"
|
||||
#include "BdaAbi.hpp"
|
||||
#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp"
|
||||
#include "prx/libSceAgcDriver/Execution/include/PerformanceTimer.hpp"
|
||||
@@ -20,6 +21,9 @@
|
||||
#endif
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <charconv>
|
||||
#include <condition_variable>
|
||||
#include <fstream>
|
||||
#include <cstdlib>
|
||||
#include <mutex>
|
||||
#include <SDL_loadso.h>
|
||||
@@ -58,7 +62,70 @@ void require(bool condition, const char* reason) {
|
||||
// go. APS5_NO_RESOURCE_CACHE=1 builds every dispatch's resources as before.
|
||||
using ResourceCache = Graphics::ResourceCache;
|
||||
|
||||
void WriteFrameBmp(int index, std::uint32_t fullWidth, std::uint32_t fullHeight, std::span<const std::byte> full);
|
||||
std::uint32_t DumpScale();
|
||||
void WriteFrameBmp(int index, std::uint32_t fullWidth, std::uint32_t fullHeight, std::span<const std::byte> full, std::uint32_t scale);
|
||||
|
||||
class FrameDumpWriter {
|
||||
public:
|
||||
~FrameDumpWriter() {
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
stopping = true;
|
||||
}
|
||||
changed.notify_one();
|
||||
if (worker.joinable()) worker.join();
|
||||
}
|
||||
|
||||
void Enqueue(int index, std::uint32_t width, std::uint32_t height, std::uint32_t scale, std::vector<std::byte> pixels) {
|
||||
std::lock_guard lock(mutex);
|
||||
require(!stopping, "frame dump writer has stopped");
|
||||
require(pixels.size() <= maxBytes - queuedBytes, "frame dump queue exceeded 64 MiB");
|
||||
if (!worker.joinable()) worker = std::thread([this] { run(); });
|
||||
const auto bytes = pixels.size();
|
||||
pending.push_back({index, width, height, scale, std::move(pixels)});
|
||||
queuedBytes += bytes;
|
||||
changed.notify_one();
|
||||
}
|
||||
|
||||
private:
|
||||
struct Frame {
|
||||
int index;
|
||||
std::uint32_t width;
|
||||
std::uint32_t height;
|
||||
std::uint32_t scale;
|
||||
std::vector<std::byte> pixels;
|
||||
};
|
||||
|
||||
void run() {
|
||||
try {
|
||||
for (;;) {
|
||||
std::deque<Frame> batch;
|
||||
{
|
||||
std::unique_lock lock(mutex);
|
||||
changed.wait(lock, [this] { return stopping || !pending.empty(); });
|
||||
if (pending.empty() && stopping) return;
|
||||
batch.swap(pending);
|
||||
}
|
||||
for (const auto& frame : batch) {
|
||||
WriteFrameBmp(frame.index, frame.width, frame.height, frame.pixels, frame.scale);
|
||||
std::lock_guard lock(mutex);
|
||||
queuedBytes -= frame.pixels.size();
|
||||
}
|
||||
}
|
||||
} catch (const std::exception& error) {
|
||||
std::fprintf(stderr, "[gpu] frame dump writer failed: %s\n", error.what());
|
||||
std::terminate();
|
||||
}
|
||||
}
|
||||
|
||||
static constexpr std::size_t maxBytes = 64 * 1024 * 1024;
|
||||
std::mutex mutex;
|
||||
std::condition_variable changed;
|
||||
std::deque<Frame> pending;
|
||||
std::thread worker;
|
||||
std::size_t queuedBytes = 0;
|
||||
bool stopping = false;
|
||||
};
|
||||
|
||||
// The [present] line's counters (see the header); mutated under State::presentMutex.
|
||||
VulkanDevice::PresentStatistics presentCounters{};
|
||||
@@ -175,6 +242,10 @@ struct VulkanDevice::State {
|
||||
VkCommandBuffer commands = VK_NULL_HANDLE;
|
||||
std::shared_ptr<void> kept;
|
||||
std::unique_ptr<Graphics::Buffer> dumpBuffer;
|
||||
std::unique_ptr<PresentationScaler> dumpScaler;
|
||||
std::uint32_t dumpWidth = 0;
|
||||
std::uint32_t dumpHeight = 0;
|
||||
std::uint32_t dumpScale = 1;
|
||||
bool dumpRecorded = false;
|
||||
int dumpIndex = 0;
|
||||
std::uint32_t imageIndex = 0;
|
||||
@@ -207,7 +278,7 @@ struct VulkanDevice::State {
|
||||
bool queuePending = false;
|
||||
std::uint32_t queueIndex = 0;
|
||||
int nextDumpIndex = 0;
|
||||
std::thread dumpWriter;
|
||||
FrameDumpWriter dumpWriter;
|
||||
|
||||
template<typename TFunction>
|
||||
TFunction InstanceFunction(const char* name) const {
|
||||
@@ -358,17 +429,14 @@ struct VulkanDevice::State {
|
||||
}
|
||||
|
||||
void WriteFrameDump(const PresentSlot& slot) {
|
||||
require(slot.dumpBuffer != nullptr && scaler != nullptr, "frame dump was not recorded");
|
||||
// The readback buffer is reused by the slot's next dump, so its bytes are copied out before
|
||||
// the writer thread (one at a time) downscales and writes them.
|
||||
require(slot.dumpBuffer != nullptr, "frame dump was not recorded");
|
||||
std::vector<std::byte> full(slot.dumpBuffer->Bytes().begin(), slot.dumpBuffer->Bytes().end());
|
||||
if (dumpWriter.joinable()) dumpWriter.join();
|
||||
const auto index = slot.dumpIndex;
|
||||
const auto width = scaler->SourceWidth();
|
||||
const auto height = scaler->SourceHeight();
|
||||
const auto width = slot.dumpWidth;
|
||||
const auto height = slot.dumpHeight;
|
||||
static const auto start = std::chrono::steady_clock::now();
|
||||
std::fprintf(stderr, "[gpu] frame_%03d.bmp: %ux%u display read back on the GPU at %.1f s\n", index, width, height, std::chrono::duration<double>(std::chrono::steady_clock::now() - start).count());
|
||||
dumpWriter = std::thread([index, width, height, pixels = std::move(full)] { WriteFrameBmp(index, width, height, pixels); });
|
||||
dumpWriter.Enqueue(index, width, height, slot.dumpScale, std::move(full));
|
||||
}
|
||||
|
||||
// Blocks on the fence, or polls it every 50 us with APS5_PRESENT_POLL_FENCE=1 (the difference
|
||||
@@ -402,8 +470,10 @@ struct VulkanDevice::State {
|
||||
}
|
||||
if (recorder) SettleRetired(true);
|
||||
}
|
||||
if (dumpWriter.joinable()) dumpWriter.join();
|
||||
for (auto& slot : presentSlots) slot.dumpBuffer.reset();
|
||||
for (auto& slot : presentSlots) {
|
||||
slot.dumpBuffer.reset();
|
||||
slot.dumpScaler.reset();
|
||||
}
|
||||
// Results still in the unit shadows reach guest memory before the device goes; the
|
||||
// slabs (kept by the publishing batch) are freed by the recorder's teardown.
|
||||
if (recorder) {
|
||||
@@ -1542,15 +1612,19 @@ namespace {
|
||||
std::uint32_t DumpScale() {
|
||||
static const std::uint32_t scale = [] {
|
||||
const char* value = std::getenv("APS5_DUMP_SCALE");
|
||||
const int parsed = value ? std::atoi(value) : 4;
|
||||
return static_cast<std::uint32_t>(parsed > 0 ? parsed : 1);
|
||||
if (value == nullptr) return std::uint32_t{4};
|
||||
std::uint32_t parsed = 0;
|
||||
const auto end = value + std::strlen(value);
|
||||
const auto result = std::from_chars(value, end, parsed);
|
||||
require(result.ec == std::errc{} && result.ptr == end && parsed > 0 && parsed <= 16384, "APS5_DUMP_SCALE must be between 1 and 16384");
|
||||
return parsed;
|
||||
}();
|
||||
return scale;
|
||||
}
|
||||
|
||||
// frame_<index>.bmp: every DumpScale()-th pixel of a BGRA8 image, 32-bit top-down.
|
||||
void WriteFrameBmp(int index, std::uint32_t fullWidth, std::uint32_t fullHeight, std::span<const std::byte> full) {
|
||||
const auto scale = DumpScale();
|
||||
void WriteFrameBmp(int index, std::uint32_t fullWidth, std::uint32_t fullHeight, std::span<const std::byte> full, std::uint32_t scale) {
|
||||
require(scale != 0 && full.size() == static_cast<std::size_t>(fullWidth) * fullHeight * 4, "invalid frame dump pixels");
|
||||
const std::uint32_t width = (fullWidth + scale - 1) / scale;
|
||||
const std::uint32_t height = (fullHeight + scale - 1) / scale;
|
||||
std::vector<std::byte> pixels(static_cast<std::size_t>(width) * height * 4);
|
||||
@@ -1559,16 +1633,19 @@ void WriteFrameBmp(int index, std::uint32_t fullWidth, std::uint32_t fullHeight,
|
||||
}
|
||||
char name[32];
|
||||
std::snprintf(name, sizeof(name), "frame_%03d.bmp", index);
|
||||
if (std::FILE* file = std::fopen(name, "wb")) {
|
||||
{
|
||||
std::ofstream file;
|
||||
file.exceptions(std::ios::failbit | std::ios::badbit);
|
||||
file.open(name, std::ios::binary);
|
||||
const std::uint32_t imageBytes = width * height * 4;
|
||||
const std::uint32_t header[13] = {0, 0, 54, 40, width, static_cast<std::uint32_t>(-static_cast<std::int32_t>(height)), 1u | (32u << 16u), 0, imageBytes, 2835, 2835, 0, 0};
|
||||
const std::uint16_t magic = 0x4d42;
|
||||
const std::uint32_t fileBytes = 54 + imageBytes;
|
||||
std::fwrite(&magic, 2, 1, file);
|
||||
std::fwrite(&fileBytes, 4, 1, file);
|
||||
std::fwrite(header + 1, 4, 12, file);
|
||||
std::fwrite(pixels.data(), 1, pixels.size(), file);
|
||||
std::fclose(file);
|
||||
file.write(reinterpret_cast<const char*>(&magic), 2);
|
||||
file.write(reinterpret_cast<const char*>(&fileBytes), 4);
|
||||
file.write(reinterpret_cast<const char*>(header + 1), 48);
|
||||
file.write(reinterpret_cast<const char*>(pixels.data()), static_cast<std::streamsize>(pixels.size()));
|
||||
file.close();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1668,7 +1745,7 @@ bool VulkanDevice::PresentDisplayBuffer(const DisplayBuffer& buffer) {
|
||||
if (dumps.dumped < dumps.limit) {
|
||||
if (dumps.cpu) {
|
||||
const auto full = ReadDisplayBuffer(buffer);
|
||||
WriteFrameBmp(dumps.dumped++, buffer.width, buffer.height, full);
|
||||
WriteFrameBmp(dumps.dumped++, buffer.width, buffer.height, full, DumpScale());
|
||||
} else {
|
||||
state->nextDumpIndex = dumps.dumped++;
|
||||
dumpFrame = true;
|
||||
@@ -1679,6 +1756,7 @@ bool VulkanDevice::PresentDisplayBuffer(const DisplayBuffer& buffer) {
|
||||
lastReport = std::chrono::steady_clock::now();
|
||||
std::fprintf(stderr, "[flip] %llu presents from the resident image (%llu refreshed first), through guest memory: %llu not pending, %llu unsuitable; %llu GPU frame dumps\n", static_cast<unsigned long long>(residentPresents), static_cast<unsigned long long>(refreshedPresents), static_cast<unsigned long long>(notPending), static_cast<unsigned long long>(unsuitable), static_cast<unsigned long long>(gpuDumps));
|
||||
}
|
||||
CaptureTrace::Log("present dump=%d address=%llx width=%u height=%u resident=%d generation=%llu", dumpFrame ? state->nextDumpIndex : -1, static_cast<unsigned long long>(buffer.address), buffer.width, buffer.height, resident != nullptr, static_cast<unsigned long long>(resident ? resident->Generation() : 0));
|
||||
if (!present(buffer.width, buffer.height, true, {}, &buffer, resident, filter, dumpFrame)) {
|
||||
// A dropped frame (swapchain out of date) keeps the dump numbering contiguous.
|
||||
if (dumpFrame) --dumps.dumped;
|
||||
@@ -1739,9 +1817,7 @@ bool VulkanDevice::present(std::uint32_t width, std::uint32_t height, bool opaqu
|
||||
require(index < state->images.size() && index < state->rendered.size(), "acquired image index is out of range");
|
||||
auto& rendered = state->rendered[index];
|
||||
const bool clearOnly = pixels.empty() && display == nullptr;
|
||||
// A resident image is blitted straight to the swapchain; a frame dump goes through the
|
||||
// scaler's BGRA8 image so the readback has one format.
|
||||
const bool direct = resident != nullptr && !dumpFrame;
|
||||
const bool direct = resident != nullptr;
|
||||
// The scaler's source image, the color transfer's staging and the upload buffer are single
|
||||
// objects an in-flight blit through them may still read: the paths using or re-creating them
|
||||
// wait for every slot first. The game path did so before taking the mutex
|
||||
@@ -1763,6 +1839,7 @@ bool VulkanDevice::present(std::uint32_t width, std::uint32_t height, bool opaqu
|
||||
SubmitRecorded(false);
|
||||
std::chrono::steady_clock::time_point lastSubmittedAt{};
|
||||
const std::uint64_t batchesAtBlit = state->recorder ? state->recorder->NewestSubmitted(&lastSubmittedAt) : 0;
|
||||
CaptureTrace::Log("blit dump=%d batch=%llu slot=%zu image=%u direct=%d", dumpFrame ? state->nextDumpIndex : -1, static_cast<unsigned long long>(batchesAtBlit), state->presentCursor, index, direct);
|
||||
timing.Mark("pixel_upload");
|
||||
APS5_LOG_OUT_DEBUG("present source=%s bytes=%zu", pixels.empty() ? "clear" : "pixels", pixels.size());
|
||||
auto commands = slot.commands;
|
||||
@@ -1848,6 +1925,15 @@ bool VulkanDevice::present(std::uint32_t width, std::uint32_t height, bool opaqu
|
||||
Graphics::Recorder::CountBarriers(CommandClass::PresentBlit);
|
||||
if (direct) PresentationScaler::RecordBlitFrom(graphicsContext(), commands, resident->Image(), VK_IMAGE_LAYOUT_GENERAL, width, height, residentFilter, barrier.image, state->extent.width, state->extent.height);
|
||||
else state->scaler->RecordBlit(commands, barrier.image, state->extent.width, state->extent.height);
|
||||
if (dumpFrame && direct) {
|
||||
const auto scale = DumpScale();
|
||||
slot.dumpWidth = (width + scale - 1) / scale;
|
||||
slot.dumpHeight = (height + scale - 1) / scale;
|
||||
slot.dumpScale = 1;
|
||||
if (!slot.dumpScaler) slot.dumpScaler = std::make_unique<PresentationScaler>(graphicsContext(), VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_B8G8R8A8_UNORM);
|
||||
slot.dumpScaler->EnsureSourceImage(slot.dumpWidth, slot.dumpHeight);
|
||||
slot.dumpScaler->RecordBlitInto(commands, resident->Image(), VK_IMAGE_LAYOUT_GENERAL, VK_FILTER_NEAREST, width, height);
|
||||
}
|
||||
if (resident != nullptr) {
|
||||
// Later batches write the image again (the next frame into this buffer, a refresh): they
|
||||
// start after the blit has read it.
|
||||
@@ -1857,9 +1943,14 @@ bool VulkanDevice::present(std::uint32_t width, std::uint32_t height, bool opaqu
|
||||
Graphics::Recorder::CountBarriers(CommandClass::PresentBlit);
|
||||
}
|
||||
if (dumpFrame) {
|
||||
const auto dumpBytes = static_cast<std::size_t>(state->scaler->SourceWidth()) * state->scaler->SourceHeight() * 4;
|
||||
if (!direct) {
|
||||
slot.dumpWidth = state->scaler->SourceWidth();
|
||||
slot.dumpHeight = state->scaler->SourceHeight();
|
||||
slot.dumpScale = DumpScale();
|
||||
}
|
||||
const auto dumpBytes = static_cast<std::size_t>(slot.dumpWidth) * slot.dumpHeight * 4;
|
||||
if (!slot.dumpBuffer || slot.dumpBuffer->Bytes().size() != dumpBytes) slot.dumpBuffer = std::make_unique<Graphics::Buffer>(graphicsContext(), dumpBytes, VK_BUFFER_USAGE_TRANSFER_DST_BIT);
|
||||
state->scaler->RecordReadback(commands, slot.dumpBuffer->Handle());
|
||||
(direct ? slot.dumpScaler : state->scaler)->RecordReadback(commands, slot.dumpBuffer->Handle());
|
||||
}
|
||||
}
|
||||
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
|
||||
@@ -1938,8 +2029,7 @@ VulkanDevice::PresentStatistics VulkanDevice::PresentCounts() {
|
||||
bool VulkanDevice::PresentWaitsForSlots(const DisplayBuffer* buffer) const {
|
||||
if (buffer == nullptr || !state->SharedSlotInFlight()) return false;
|
||||
if (buffer->tilingMode == 1) return true;
|
||||
const auto& dumps = Dumps();
|
||||
if ((dumps.dumped < dumps.limit && !dumps.cpu) || NoResidentPresent()) return true;
|
||||
if (NoResidentPresent()) return true;
|
||||
VkFilter filter = VK_FILTER_LINEAR;
|
||||
bool pending = false;
|
||||
if (PresentableResident(graphicsContext(), *buffer, filter, pending) == nullptr) return true;
|
||||
|
||||
@@ -101,6 +101,20 @@ public:
|
||||
ShaderResources& operator=(const ShaderResources&) = delete;
|
||||
VkDescriptorSetLayout Layout() const;
|
||||
void Bind(VkCommandBuffer commands, VkPipelineBindPoint bindPoint, VkPipelineLayout layout) const;
|
||||
struct DrawBindings {
|
||||
DrawBindings() = default;
|
||||
DrawBindings(const DrawBindings&) = delete;
|
||||
DrawBindings& operator=(const DrawBindings&) = delete;
|
||||
struct Snapshot {
|
||||
std::uint64_t address;
|
||||
std::shared_ptr<Buffer> buffer;
|
||||
};
|
||||
DescriptorCache* cache = nullptr;
|
||||
DescriptorCache::SetAllocation allocation;
|
||||
std::vector<Snapshot> snapshots;
|
||||
~DrawBindings();
|
||||
};
|
||||
std::shared_ptr<DrawBindings> PrepareDrawBindings(Recorder& recorder) const;
|
||||
void WriteBack();
|
||||
// Deferred completion: MarkGpuWrites registers the results the recorded work leaves on the GPU
|
||||
// (storage images stay there; buffer ranges are noted so CPU reads wait); WriteBackBuffers runs
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
#include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp"
|
||||
#include "prx/libSceAgcDriver/Graphics/include/TextureFormat.hpp"
|
||||
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
|
||||
#include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp"
|
||||
#include "prx/libSceAgcDriver/Execution/include/PerformanceTimer.hpp"
|
||||
#include "prx/libc/include/General.hpp"
|
||||
#include "Optimization/include/Optimization/ShaderStageInputInfo.hpp"
|
||||
@@ -998,6 +999,83 @@ struct RecordedDraw {
|
||||
// attachments with nothing recorded between them share one pass; the host-write and host-read
|
||||
// barriers are implicit in the submission and the fence. Then the kept objects, the completion
|
||||
// work and, for a waited-for draw, the recorder sync.
|
||||
bool CaptureInputsEnabled() {
|
||||
static const bool enabled = std::getenv("APS5_CAPTURE_INPUTS") != nullptr;
|
||||
Require(!enabled || CaptureTrace::Enabled(), "APS5_CAPTURE_INPUTS requires APS5_CAPTURE_TRACE");
|
||||
return enabled;
|
||||
}
|
||||
|
||||
void captureInputs(const Context& context, Recorder& recorder, VkCommandBuffer commands, const ShaderResources& resources, const std::shared_ptr<ShaderResources::DrawBindings>& bindings, std::uint64_t target) {
|
||||
struct Sample {
|
||||
std::uint64_t address;
|
||||
std::size_t offset;
|
||||
std::vector<std::byte> expected;
|
||||
VkBuffer source;
|
||||
VkDeviceSize sourceOffset;
|
||||
};
|
||||
static unsigned long long nextDraw = 0;
|
||||
const auto draw = ++nextDraw;
|
||||
const auto batch = static_cast<unsigned long long>(recorder.Submissions() + 1);
|
||||
std::vector<Sample> samples;
|
||||
std::size_t total = 0;
|
||||
const auto addSample = [&](std::uint64_t address, std::size_t bytes, VkBuffer source, VkDeviceSize offset, const std::byte* expected) {
|
||||
if (bytes == 0 || bytes > 512) return;
|
||||
Require(offset % 4 == 0 && bytes % 4 == 0, "capture input is not aligned for a Vulkan buffer copy");
|
||||
Require(total + bytes <= 65536, "capture inputs exceed 64 KiB per draw");
|
||||
Sample sample{address, total, std::vector<std::byte>(bytes), source, offset};
|
||||
std::memcpy(sample.expected.data(), expected, bytes);
|
||||
total += bytes;
|
||||
samples.push_back(std::move(sample));
|
||||
};
|
||||
if (bindings != nullptr) {
|
||||
for (const auto& snapshot : bindings->snapshots) {
|
||||
const auto bytes = snapshot.buffer->Bytes();
|
||||
addSample(snapshot.address, bytes.size(), snapshot.buffer->Handle(), 0, bytes.data());
|
||||
}
|
||||
}
|
||||
for (const auto& [begin, end] : resources.InPlaceReads()) {
|
||||
Require(end >= begin, "invalid capture input range");
|
||||
const auto bytes = static_cast<std::size_t>(end - begin);
|
||||
if (bytes == 0 || bytes > 512) continue;
|
||||
if (bindings != nullptr && std::any_of(bindings->snapshots.begin(), bindings->snapshots.end(), [&](const auto& snapshot) { return snapshot.address < end && begin < snapshot.address + snapshot.buffer->Bytes().size(); })) continue;
|
||||
if (resources.WritesOverlap(begin, bytes) || recorder.PendingWriteOverlaps(begin, bytes)) {
|
||||
CaptureTrace::Log("input-skip draw=%llu batch=%llu address=%llx bytes=%zu reason=gpu-writer", draw, batch, static_cast<unsigned long long>(begin), bytes);
|
||||
continue;
|
||||
}
|
||||
const auto* imported = HostImportFor(context, begin, bytes);
|
||||
Require(imported != nullptr, "capture input has no host import");
|
||||
addSample(begin, bytes, imported->buffer, begin - imported->base, reinterpret_cast<const std::byte*>(begin));
|
||||
}
|
||||
CaptureTrace::Log("input-capture draw=%llu batch=%llu target=%llx ranges=%zu bytes=%zu", draw, batch, static_cast<unsigned long long>(target), samples.size(), total);
|
||||
if (samples.empty()) return;
|
||||
auto readback = std::make_shared<Buffer>(context, total, VK_BUFFER_USAGE_TRANSFER_DST_BIT);
|
||||
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT);
|
||||
const auto copy = context.Function<PFN_vkCmdCopyBuffer>("vkCmdCopyBuffer");
|
||||
for (const auto& sample : samples) {
|
||||
const VkBufferCopy region{sample.sourceOffset, sample.offset, sample.expected.size()};
|
||||
copy(commands, sample.source, readback->Handle(), 1, ®ion);
|
||||
}
|
||||
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT, VK_ACCESS_HOST_READ_BIT | VK_ACCESS_SHADER_READ_BIT);
|
||||
recorder.OnComplete([draw, batch, target, readback, samples = std::move(samples)] {
|
||||
const auto actual = readback->Bytes();
|
||||
std::size_t differences = 0;
|
||||
for (const auto& sample : samples) {
|
||||
std::size_t changed = 0;
|
||||
for (std::size_t index = 0; index < sample.expected.size(); ++index) {
|
||||
const auto gpu = actual[sample.offset + index];
|
||||
if (sample.expected[index] == gpu) continue;
|
||||
if (changed < 16) CaptureTrace::Log("input-byte draw=%llu batch=%llu address=%llx offset=%zu cpu=%02x gpu=%02x", draw, batch, static_cast<unsigned long long>(sample.address), index, std::to_integer<unsigned>(sample.expected[index]), std::to_integer<unsigned>(gpu));
|
||||
++changed;
|
||||
}
|
||||
if (changed != 0) {
|
||||
++differences;
|
||||
CaptureTrace::Log("input-mismatch draw=%llu batch=%llu target=%llx address=%llx bytes=%zu changed=%zu", draw, batch, static_cast<unsigned long long>(target), static_cast<unsigned long long>(sample.address), sample.expected.size(), changed);
|
||||
}
|
||||
}
|
||||
CaptureTrace::Log("input-result draw=%llu batch=%llu ranges=%zu mismatched=%zu", draw, batch, samples.size(), differences);
|
||||
});
|
||||
}
|
||||
|
||||
void recordDraw(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span<const CompiledShader> shaders, DrawInputs& inputs, RecordedDraw& record, DrawOutcome& outcome, DrawTimer& timer, double& ownWaitedMs) {
|
||||
auto* recorder = record.recorder;
|
||||
auto& resources = *record.resources;
|
||||
@@ -1030,10 +1108,13 @@ void recordDraw(const Context& context, const State& state, const Pm4::DrawParam
|
||||
if (recorder->HasQueuedKeyStores() && (resources.HoldsLease() || recorder->AnyQueuedKeyStore(touches))) recorder->FlushKeyStores();
|
||||
// A queued label store over such memory likewise (Recorder::RecordStore).
|
||||
if (recorder->HasQueuedStores() && (resources.HoldsLease() || recorder->AnyQueuedStore(touches))) recorder->FlushStores();
|
||||
const bool continued = !readsTarget && !gpuIndirect && recorder->ContinuesRenderPass(passKey);
|
||||
const auto drawBindings = resources.PrepareDrawBindings(*recorder);
|
||||
const bool capture = CaptureInputsEnabled();
|
||||
const bool continued = !capture && !readsTarget && !gpuIndirect && recorder->ContinuesRenderPass(passKey);
|
||||
outcome.passContinued = continued;
|
||||
outcome.passBegun = !continued;
|
||||
const auto commands = continued ? recorder->CommandsInRenderPass() : recorder->Commands();
|
||||
if (capture) captureInputs(context, *recorder, commands, resources, drawBindings, record.targets.empty() || record.targets.front() == nullptr ? 0 : record.targets.front()->Descriptor().baseAddress);
|
||||
// The draw's [gputime] class range: from its first barrier to the pass's trailing barrier (a
|
||||
// continued draw lies inside its pass's range).
|
||||
const auto drawTiming = !continued ? recorder->BeginGpuTiming(CommandClass::Draw) : Recorder::NoTiming;
|
||||
@@ -1065,7 +1146,12 @@ void recordDraw(const Context& context, const State& state, const Pm4::DrawParam
|
||||
record.pipeline->Begin(commands, *record.framebuffer, state.renderExtent, state.viewport, state.scissor);
|
||||
}
|
||||
APS5_LOG_CHARS_OUT_DEBUG("Pipeline Begin OK");
|
||||
resources.Bind(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, record.pipeline->Layout());
|
||||
if (drawBindings != nullptr) {
|
||||
const auto set = drawBindings->allocation.set;
|
||||
context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, record.pipeline->Layout(), 0, 1, &set, 0, nullptr);
|
||||
} else {
|
||||
resources.Bind(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, record.pipeline->Layout());
|
||||
}
|
||||
APS5_LOG_CHARS_OUT_DEBUG("Resources bound");
|
||||
if (record.pushBytes != nullptr) record.pipeline->PushConstants(commands, record.pushStages, *record.pushBytes);
|
||||
else record.pipeline->PushConstants(commands, shaders);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
#include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp"
|
||||
#include "prx/libc/include/HostThreadLocal.hpp"
|
||||
#include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp"
|
||||
#include "prx/libSceAgcDriver/Graphics/include/Resources.hpp"
|
||||
@@ -1894,6 +1895,7 @@ void Recorder::OnComplete(std::function<void()> action) {
|
||||
}
|
||||
|
||||
bool Recorder::noteWrite(std::uint64_t address, std::size_t bytes, bool ownLabel) {
|
||||
CaptureTrace::Log("buffer-write batch=%llu address=%llx bytes=%zu label=%d", static_cast<unsigned long long>(submissions + 1), static_cast<unsigned long long>(address), bytes, ownLabel);
|
||||
if (bytes == 0) return false;
|
||||
ensureOpen();
|
||||
const auto end = address + bytes;
|
||||
@@ -2015,6 +2017,7 @@ bool Recorder::ReadTracking() {
|
||||
}
|
||||
|
||||
void Recorder::NotePendingRead(std::uint64_t address, std::size_t bytes, ReadKind kind) {
|
||||
CaptureTrace::Log("buffer-read batch=%llu address=%llx bytes=%zu kind=%d", static_cast<unsigned long long>(submissions + 1), static_cast<unsigned long long>(address), bytes, static_cast<int>(kind));
|
||||
if (bytes == 0 || !ReadTrackingEnabled()) return;
|
||||
ensureOpen();
|
||||
open->reads.push_back({address, address + bytes, kind});
|
||||
@@ -2025,6 +2028,7 @@ void Recorder::NotePendingReads(std::span<const std::pair<std::uint64_t, std::ui
|
||||
if (ranges.empty() || !ReadTrackingEnabled()) return;
|
||||
ensureOpen();
|
||||
for (const auto& [begin, end] : ranges) {
|
||||
CaptureTrace::Log("buffer-read batch=%llu address=%llx bytes=%llu kind=%d", static_cast<unsigned long long>(submissions + 1), static_cast<unsigned long long>(begin), static_cast<unsigned long long>(end - begin), static_cast<int>(kind));
|
||||
if (end > begin) open->reads.push_back({begin, end, kind});
|
||||
}
|
||||
readsNoted.fetch_add(ranges.size(), std::memory_order_relaxed);
|
||||
@@ -2345,6 +2349,7 @@ void Recorder::Submit() {
|
||||
submission.pCommandBuffers = &batch->commands;
|
||||
// The timeline reaches this batch's serial when it completes (see WaitSerial).
|
||||
const std::uint64_t serial = submissions + 1;
|
||||
CaptureTrace::Log("submit batch=%llu reads=%zu writes=%zu", static_cast<unsigned long long>(serial), batch->reads.size(), batch->writes.size());
|
||||
VkTimelineSemaphoreSubmitInfoKHR timelineInfo{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO_KHR};
|
||||
timelineInfo.signalSemaphoreValueCount = 1;
|
||||
timelineInfo.pSignalSemaphoreValues = &serial;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
#include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp"
|
||||
#include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp"
|
||||
#include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp"
|
||||
#include <algorithm>
|
||||
@@ -260,6 +261,7 @@ std::shared_ptr<StorageTexture> sampledStorageSource(const Context& context, con
|
||||
|
||||
// `guestBytes` is the surface size when the caller described the surface already (0: described here).
|
||||
std::shared_ptr<Texture> cachedTexture(const Context& context, std::span<const std::uint32_t> words, const GuestTextureResource& resource, VkComponentMapping components, std::uint64_t guestBytes = 0) {
|
||||
CaptureTrace::Log("sampled-lookup address=%llx width=%u height=%u dcc=%llx", static_cast<unsigned long long>(resource.baseAddress), resource.width, resource.height, static_cast<unsigned long long>(resource.dccAddress));
|
||||
static const bool disabled = std::getenv("APS5_NO_TEXTURE_CACHE") != nullptr;
|
||||
const bool profile = LookupOutcomes::Profiled();
|
||||
const auto start = profile ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{};
|
||||
@@ -2460,6 +2462,70 @@ VkDescriptorSetLayout ShaderResources::Layout() const {
|
||||
return _layout;
|
||||
}
|
||||
|
||||
ShaderResources::DrawBindings::~DrawBindings() {
|
||||
if (cache != nullptr && allocation.set != VK_NULL_HANDLE) cache->Free(allocation);
|
||||
}
|
||||
|
||||
std::shared_ptr<ShaderResources::DrawBindings> ShaderResources::PrepareDrawBindings(Recorder& recorder) const {
|
||||
if (_set == VK_NULL_HANDLE || usesBda) return {};
|
||||
const auto reads = guestMemory.InPlaceReads();
|
||||
auto result = std::make_shared<DrawBindings>();
|
||||
std::vector<std::size_t> selected;
|
||||
for (std::size_t index = 0; index < allocations.size(); ++index) {
|
||||
const auto& item = allocations[index];
|
||||
if (!item.guest || item.written || guestMemory.WritesOverlap(item.address, item.size)) continue;
|
||||
const bool direct = std::any_of(reads.begin(), reads.end(), [&](const auto& range) { return item.address >= range.first && item.address < range.second && item.size <= range.second - item.address; });
|
||||
if (!direct || recorder.PendingWriteOverlaps(item.address, item.size)) continue;
|
||||
auto buffer = std::make_shared<Buffer>(context, item.size, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT);
|
||||
std::memcpy(buffer->Bytes().data(), reinterpret_cast<const void*>(item.address), item.size);
|
||||
selected.push_back(index);
|
||||
result->snapshots.push_back({item.address, std::move(buffer)});
|
||||
CaptureTrace::Log("draw-snapshot batch=%llu address=%llx bytes=%zu", static_cast<unsigned long long>(recorder.Submissions() + 1), static_cast<unsigned long long>(item.address), item.size);
|
||||
}
|
||||
if (selected.empty()) return {};
|
||||
Require(context.descriptorCache != nullptr, "draw snapshots require a descriptor cache");
|
||||
std::map<VkDescriptorType, std::uint32_t> counts;
|
||||
for (const auto& binding : bindings) counts[binding.layout.descriptorType] += binding.layout.descriptorCount;
|
||||
std::vector<VkDescriptorPoolSize> sizes;
|
||||
for (const auto& [type, count] : counts) sizes.push_back({type, count});
|
||||
result->cache = context.descriptorCache;
|
||||
result->allocation = result->cache->Allocate(_layout, sizes);
|
||||
Require(result->allocation.set != VK_NULL_HANDLE, "draw snapshot descriptor allocation failed");
|
||||
std::vector<VkCopyDescriptorSet> copies;
|
||||
for (const auto& binding : bindings) {
|
||||
VkCopyDescriptorSet copy{VK_STRUCTURE_TYPE_COPY_DESCRIPTOR_SET};
|
||||
copy.srcSet = _set;
|
||||
copy.srcBinding = binding.layout.binding;
|
||||
copy.dstSet = result->allocation.set;
|
||||
copy.dstBinding = binding.layout.binding;
|
||||
copy.descriptorCount = binding.layout.descriptorCount;
|
||||
copies.push_back(copy);
|
||||
}
|
||||
const auto update = context.Resolved(&DeviceFunctions::updateDescriptorSets, "vkUpdateDescriptorSets");
|
||||
update(context.device, 0, nullptr, static_cast<std::uint32_t>(copies.size()), copies.data());
|
||||
std::vector<VkDescriptorBufferInfo> infos;
|
||||
infos.reserve(selected.size());
|
||||
for (const auto& snapshot : result->snapshots) infos.push_back({snapshot.buffer->Handle(), 0, snapshot.buffer->Bytes().size()});
|
||||
std::vector<VkWriteDescriptorSet> writes;
|
||||
for (const auto& binding : bindings) {
|
||||
for (std::size_t element = 0; element < binding.allocations.size(); ++element) {
|
||||
const auto found = std::find(selected.begin(), selected.end(), binding.allocations[element]);
|
||||
if (found == selected.end()) continue;
|
||||
VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET};
|
||||
write.dstSet = result->allocation.set;
|
||||
write.dstBinding = binding.layout.binding;
|
||||
write.dstArrayElement = static_cast<std::uint32_t>(element);
|
||||
write.descriptorCount = 1;
|
||||
write.descriptorType = binding.layout.descriptorType;
|
||||
write.pBufferInfo = &infos[static_cast<std::size_t>(found - selected.begin())];
|
||||
writes.push_back(write);
|
||||
}
|
||||
}
|
||||
update(context.device, static_cast<std::uint32_t>(writes.size()), writes.data(), 0, nullptr);
|
||||
recorder.Keep(result);
|
||||
return result;
|
||||
}
|
||||
|
||||
void ShaderResources::Bind(VkCommandBuffer commands, VkPipelineBindPoint bindPoint, VkPipelineLayout layout) const {
|
||||
if (_set == VK_NULL_HANDLE) return;
|
||||
context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, bindPoint, layout, 0, 1, &_set, 0, nullptr);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
#include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp"
|
||||
#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp"
|
||||
#include "prx/libc/include/General.hpp"
|
||||
#include "prx/libSceAgcDriver/Graphics/include/Resources.hpp"
|
||||
@@ -1062,6 +1063,7 @@ bool StorageTexture::Refresh() {
|
||||
if (profile) LookupOutcomes::Add(stamped ? LookupOutcomes::RefreshUnchanged : LookupOutcomes::RefreshCompared, start);
|
||||
return true;
|
||||
}
|
||||
CaptureTrace::Log("refresh image=%llx bytes=%llu generation=%llu dirty=%d keysChanged=%d cpuWrote=%d", static_cast<unsigned long long>(descriptor.baseAddress), static_cast<unsigned long long>(guestBytes), static_cast<unsigned long long>(generation), dirty, keysChanged, cpuWrote);
|
||||
// Debug aid: APS5_TRACE_UPLOAD names why a storage image is uploaded again.
|
||||
static const bool traceUpload = std::getenv("APS5_TRACE_UPLOAD") != nullptr;
|
||||
if (traceUpload) {
|
||||
@@ -1115,6 +1117,7 @@ bool StorageTexture::Refresh() {
|
||||
if (changed[layer]) {
|
||||
pendingResults = true;
|
||||
if (blockUnits && droppable(layer)) {
|
||||
CaptureTrace::Log("drop-unit image=%llx unit=%u generation=%llu stamped=%d keys=%d", static_cast<unsigned long long>(descriptor.baseAddress), layer, static_cast<unsigned long long>(layerGeneration[layer]), layer < stampedBlocks.size() && stampedBlocks[layer] != 0, static_cast<int>(keys));
|
||||
layerPending[layer] = false;
|
||||
dropped = true;
|
||||
continue;
|
||||
@@ -1167,6 +1170,7 @@ void traceKeyStore(const char* path, const GuestTextureResource& descriptor, std
|
||||
}
|
||||
|
||||
void StorageTexture::upload(const std::vector<bool>* layers) {
|
||||
CaptureTrace::Log("upload image=%llx bytes=%llu generation=%llu reason=%s partial=%d", static_cast<unsigned long long>(descriptor.baseAddress), static_cast<unsigned long long>(guestBytes), static_cast<unsigned long long>(generation), uploadReason, layers != nullptr);
|
||||
const bool profile = LookupOutcomes::Profiled();
|
||||
const auto start = profile ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{};
|
||||
const auto elementBytes = BytesPerElement(descriptor.format);
|
||||
@@ -1812,6 +1816,7 @@ void StorageTexture::refreshGeneration() {
|
||||
}
|
||||
|
||||
void StorageTexture::markLayersPending(std::uint32_t first, std::uint32_t count) {
|
||||
CaptureTrace::Log("image-write image=%llx first=%u count=%u generation=%llu", static_cast<unsigned long long>(descriptor.baseAddress), first, count, static_cast<unsigned long long>(generation));
|
||||
static const bool eager = std::getenv("APS5_EAGER_WRITEBACK") != nullptr || std::getenv("APS5_NO_TEXTURE_CACHE") != nullptr;
|
||||
for (std::uint32_t layer = first; layer < first + count; ++layer) layerPending[layer] = true;
|
||||
// Results of this image now cover the alias's results borrowed into these units: this image
|
||||
@@ -2818,6 +2823,7 @@ void StorageTexture::writeBack(std::uint64_t address, std::size_t bytes) {
|
||||
}
|
||||
|
||||
void StorageTexture::writeBackLayers(const std::vector<bool>& layers) {
|
||||
CaptureTrace::Log("writeback image=%llx generation=%llu reason=%s units=%zu", static_cast<unsigned long long>(descriptor.baseAddress), static_cast<unsigned long long>(generation), flushReason, static_cast<std::size_t>(std::count(layers.begin(), layers.end(), true)));
|
||||
static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr;
|
||||
PhaseTimer timer;
|
||||
struct Account {
|
||||
|
||||
@@ -653,6 +653,44 @@ void resourceReadTests(const Device& device, Recorder& recorder) {
|
||||
Require(!recorder.PendingReadOverlaps(element, 16), "the build's read refuses after its batch ran");
|
||||
recorder.Sync();
|
||||
}
|
||||
std::weak_ptr<ShaderResources::DrawBindings> snapshotLifetime;
|
||||
{
|
||||
auto snapshotContext = context;
|
||||
DescriptorCache cache(snapshotContext);
|
||||
snapshotContext.descriptorCache = &cache;
|
||||
Recorder snapshotRecorder(snapshotContext);
|
||||
snapshotRecorder.Activate();
|
||||
ShaderResources resources(snapshotContext, compute);
|
||||
auto first = resources.PrepareDrawBindings(snapshotRecorder);
|
||||
Require(first != nullptr && first->snapshots.size() == 1, "read-only draw input was not snapshotted");
|
||||
std::memset(reinterpret_cast<void*>(element), 0x22, elementBytes);
|
||||
auto second = resources.PrepareDrawBindings(snapshotRecorder);
|
||||
Require(second != nullptr && second->snapshots.size() == 1, "cached draw input was not snapshotted again");
|
||||
Require(first->allocation.set != second->allocation.set, "in-flight draws share mutable descriptor bindings");
|
||||
std::memset(reinterpret_cast<void*>(element), 0x33, elementBytes);
|
||||
auto downloaded = std::make_shared<Buffer>(snapshotContext, elementBytes * 2, VK_BUFFER_USAGE_TRANSFER_DST_BIT);
|
||||
const auto commands = snapshotRecorder.Commands();
|
||||
RecordMemoryBarrier(snapshotContext, commands, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT);
|
||||
const auto copy = snapshotContext.Function<PFN_vkCmdCopyBuffer>("vkCmdCopyBuffer");
|
||||
VkBufferCopy region{0, 0, elementBytes};
|
||||
copy(commands, first->snapshots[0].buffer->Handle(), downloaded->Handle(), 1, ®ion);
|
||||
region.dstOffset = elementBytes;
|
||||
copy(commands, second->snapshots[0].buffer->Handle(), downloaded->Handle(), 1, ®ion);
|
||||
RecordMemoryBarrier(snapshotContext, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT);
|
||||
snapshotLifetime = first;
|
||||
first.reset();
|
||||
second.reset();
|
||||
Require(!snapshotLifetime.expired(), "draw snapshot was released before its GPU batch");
|
||||
snapshotRecorder.Sync();
|
||||
const auto contents = downloaded->Bytes();
|
||||
Require(std::all_of(contents.begin(), contents.begin() + elementBytes, [](std::byte value) { return value == std::byte{0x11}; }), "first draw observed overwritten input");
|
||||
Require(std::all_of(contents.begin() + elementBytes, contents.end(), [](std::byte value) { return value == std::byte{0x22}; }), "second draw observed overwritten input");
|
||||
snapshotRecorder.NotePendingWrite(element, elementBytes);
|
||||
Require(resources.PrepareDrawBindings(snapshotRecorder) == nullptr, "GPU-produced input was replaced with stale CPU memory");
|
||||
snapshotRecorder.Sync();
|
||||
}
|
||||
Require(snapshotLifetime.expired(), "draw snapshots outlived their recorder");
|
||||
recorder.Activate();
|
||||
{
|
||||
GuestAllocations::Mutation mutation;
|
||||
mutation.Remove(block);
|
||||
|
||||
Reference in New Issue
Block a user