SleakEngine 0.1.0
C++23 multi-backend game engine
Loading...
Searching...
No Matches
VulkanCapture.cpp
Go to the documentation of this file.
1#include <cstddef>
2#include <cstdint>
3#include <fstream>
4#include <initializer_list>
5#include <string>
6#include <vector>
7
9#include "Core/Logger.hpp"
10
11namespace Sleak {
12namespace RenderEngine {
13
14namespace {
15
16/// Byte offsets of red, green, and blue inside one 4-byte texel; false when
17/// the format is not an 8-bit RGBA or BGRA layout.
18bool ChannelOffsets(VkFormat format, uint32_t& r, uint32_t& g, uint32_t& b) {
19 switch (format) {
20 case VK_FORMAT_B8G8R8A8_UNORM:
21 case VK_FORMAT_B8G8R8A8_SRGB:
22 r = 2;
23 g = 1;
24 b = 0;
25 return true;
26 case VK_FORMAT_R8G8B8A8_UNORM:
27 case VK_FORMAT_R8G8B8A8_SRGB:
28 case VK_FORMAT_A8B8G8R8_UNORM_PACK32:
29 case VK_FORMAT_A8B8G8R8_SRGB_PACK32:
30 r = 0;
31 g = 1;
32 b = 2;
33 return true;
34 default:
35 return false;
36 }
37}
38
39/// Picks a host-visible, host-coherent memory type, preferring cached ones.
40uint32_t FindReadbackMemoryType(VkPhysicalDevice gpu, uint32_t typeBits) {
41 VkPhysicalDeviceMemoryProperties props;
42 vkGetPhysicalDeviceMemoryProperties(gpu, &props);
43 const VkMemoryPropertyFlags coherent = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
44 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
45 for (VkMemoryPropertyFlags wanted :
46 {coherent | VK_MEMORY_PROPERTY_HOST_CACHED_BIT, coherent}) {
47 for (uint32_t i = 0; i < props.memoryTypeCount; ++i) {
48 if ((typeBits & (1u << i)) &&
49 (props.memoryTypes[i].propertyFlags & wanted) == wanted)
50 return i;
51 }
52 }
53 return UINT32_MAX;
54}
55
56} // namespace
57
58/// Arms a UI-free readback of the next presented frame into a binary PPM.
59bool VulkanRenderer::RequestFrameCapture(const std::string& path) {
60 if (path.empty()) return false;
61 if (!m_swapchainTransferSrc) {
63 "Frame capture: swapchain was created without TRANSFER_SRC usage");
64 return false;
65 }
66 uint32_t r, g, b;
67 if (!ChannelOffsets(scImageFormat, r, g, b)) {
68 SLEAK_ERROR("Frame capture: unsupported swapchain format {}",
69 static_cast<int>(scImageFormat));
70 return false;
71 }
72 m_capturePath = path;
73 return true;
74}
75
76/// Records the swapchain-image-to-buffer copy for an armed capture. Runs after
77/// the final render pass, so the image is in PRESENT_SRC_KHR.
78void VulkanRenderer::RecordFrameCaptureCopy() {
79 CleanupFrameCapture();
80
81 VkBufferCreateInfo bufferInfo{};
82 bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
83 bufferInfo.size =
84 static_cast<VkDeviceSize>(scExtent.width) * scExtent.height * 4;
85 bufferInfo.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
86 bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
87
88 if (vkCreateBuffer(device, &bufferInfo, nullptr, &m_captureBuffer) !=
89 VK_SUCCESS)
90 m_captureBuffer = VK_NULL_HANDLE;
91 bool ok = m_captureBuffer != VK_NULL_HANDLE;
92 if (ok) {
93 VkMemoryRequirements req;
94 vkGetBufferMemoryRequirements(device, m_captureBuffer, &req);
95 VkMemoryAllocateInfo alloc{};
96 alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
97 alloc.allocationSize = req.size;
98 alloc.memoryTypeIndex =
99 FindReadbackMemoryType(physicalDevice, req.memoryTypeBits);
100 if (alloc.memoryTypeIndex == UINT32_MAX ||
101 vkAllocateMemory(device, &alloc, nullptr, &m_captureMemory) !=
102 VK_SUCCESS)
103 m_captureMemory = VK_NULL_HANDLE;
104 ok = m_captureMemory != VK_NULL_HANDLE &&
105 vkBindBufferMemory(device, m_captureBuffer, m_captureMemory, 0) ==
106 VK_SUCCESS;
107 }
108 if (!ok) {
109 SLEAK_ERROR("Frame capture: readback buffer allocation failed");
110 CleanupFrameCapture();
111 m_capturePath.clear();
112 return;
113 }
114
115 const VkImage image = swapChainImages[CurrentFrameIndex];
116
117 VkImageMemoryBarrier toCopy{};
118 toCopy.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
119 toCopy.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
120 toCopy.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
121 toCopy.oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
122 toCopy.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
123 toCopy.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
124 toCopy.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
125 toCopy.image = image;
126 toCopy.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
127 vkCmdPipelineBarrier(command, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
128 VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0,
129 nullptr, 1, &toCopy);
130
131 VkBufferImageCopy region{};
132 region.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
133 region.imageExtent = {scExtent.width, scExtent.height, 1};
134 vkCmdCopyImageToBuffer(command, image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
135 m_captureBuffer, 1, &region);
136
137 VkImageMemoryBarrier toPresent = toCopy;
138 toPresent.srcAccessMask = 0;
139 toPresent.dstAccessMask = 0;
140 toPresent.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
141 toPresent.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
142
143 VkMemoryBarrier toHost{};
144 toHost.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
145 toHost.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
146 toHost.dstAccessMask = VK_ACCESS_HOST_READ_BIT;
147 vkCmdPipelineBarrier(
148 command, VK_PIPELINE_STAGE_TRANSFER_BIT,
149 VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 1,
150 &toHost, 0, nullptr, 1, &toPresent);
151
152 m_captureExtent = scExtent;
153 m_captureFormat = scImageFormat;
154 m_captureRecorded = true;
155}
156
157/// Waits for the captured frame, writes the PPM, and disarms the capture.
158void VulkanRenderer::FinishFrameCapture() {
159 m_captureRecorded = false;
160 std::string path;
161 path.swap(m_capturePath);
162
163 const VkResult wait = vkWaitForFences(
164 device, 1, &inFlightFences[currentFrame], VK_TRUE, 10'000'000'000ull);
165 void* mapped = nullptr;
166 if (wait != VK_SUCCESS ||
167 vkMapMemory(device, m_captureMemory, 0, VK_WHOLE_SIZE, 0, &mapped) !=
168 VK_SUCCESS) {
169 SLEAK_ERROR("Frame capture: readback of {} failed ({})", path,
170 static_cast<int>(wait));
171 CleanupFrameCapture();
172 return;
173 }
174
175 uint32_t r = 0, g = 1, b = 2;
176 ChannelOffsets(m_captureFormat, r, g, b);
177 const size_t pixels =
178 static_cast<size_t>(m_captureExtent.width) * m_captureExtent.height;
179 const auto* src = static_cast<const uint8_t*>(mapped);
180 std::vector<uint8_t> rgb(pixels * 3);
181 for (size_t i = 0; i < pixels; ++i) {
182 rgb[i * 3 + 0] = src[i * 4 + r];
183 rgb[i * 3 + 1] = src[i * 4 + g];
184 rgb[i * 3 + 2] = src[i * 4 + b];
185 }
186 vkUnmapMemory(device, m_captureMemory);
187 CleanupFrameCapture();
188
189 std::ofstream out(path, std::ios::binary);
190 out << "P6\n"
191 << m_captureExtent.width << " " << m_captureExtent.height << "\n255\n";
192 out.write(reinterpret_cast<const char*>(rgb.data()),
193 static_cast<std::streamsize>(rgb.size()));
194 if (!out) {
195 SLEAK_ERROR("Frame capture: could not write {}", path);
196 return;
197 }
198 SLEAK_INFO("Frame capture: wrote {}x{} to {}", m_captureExtent.width,
199 m_captureExtent.height, path);
200}
201
202/// Frees the capture readback buffer.
203void VulkanRenderer::CleanupFrameCapture() {
204 if (m_captureBuffer != VK_NULL_HANDLE) {
205 vkDestroyBuffer(device, m_captureBuffer, nullptr);
206 m_captureBuffer = VK_NULL_HANDLE;
207 }
208 if (m_captureMemory != VK_NULL_HANDLE) {
209 vkFreeMemory(device, m_captureMemory, nullptr);
210 m_captureMemory = VK_NULL_HANDLE;
211 }
212}
213
214} // namespace RenderEngine
215} // namespace Sleak
#define SLEAK_ERROR(...)
Definition Logger.hpp:22
#define SLEAK_INFO(...)
Definition Logger.hpp:20
bool RequestFrameCapture(const std::string &path) override
Arms a UI-free readback of the next presented frame into a binary PPM.
Backend-facing rendering layer shared by the four graphics backends.
Root namespace for everything the engine exposes.
Definition Camera.hpp:10