SleakEngine 0.1.0
C++23 multi-backend game engine
Loading...
Searching...
No Matches
VulkanProfiler.cpp
Go to the documentation of this file.
1#include <Debug/Benchmark.hpp>
2#include <algorithm>
3#include <array>
4#include <cstdint>
5#include <format>
6#include <limits>
7#include <string>
8#include <vector>
9
11#include "Core/Logger.hpp"
12
13namespace Sleak {
14namespace RenderEngine {
15
16namespace {
17
18constexpr float kGpuLogIntervalSeconds = 2.0f;
19
20constexpr std::array kGpuRowNames = {"shadow", "gbuffer", "ssao", "lighting",
21 "forward", "taa", "ssr", "bloom",
22 "tonemap", "ui", "other", "total"};
23
24} // namespace
25
26/// Creates the timestamp query pool; leaves profiling off when the graphics
27/// queue has no timestamp support.
28bool VulkanRenderer::CreateGpuProfiler() {
29 static_assert(kGpuRowNames.size() == GPU_ROW_COUNT);
30
31 VkPhysicalDeviceProperties props;
32 vkGetPhysicalDeviceProperties(physicalDevice, &props);
33
34 uint32_t familyCount = 0;
35 vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &familyCount,
36 nullptr);
37 std::vector<VkQueueFamilyProperties> families(familyCount);
38 vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &familyCount,
39 families.data());
40
41 const uint32_t validBits =
42 QueueIDs.GraphicsIndex < familyCount
43 ? families[QueueIDs.GraphicsIndex].timestampValidBits
44 : 0;
45 if (validBits == 0 || props.limits.timestampPeriod <= 0.0f) {
47 "GPU profiler: graphics queue has no timestamp support, "
48 "--gpuprofile ignored");
49 return false;
50 }
51
52 VkQueryPoolCreateInfo info{};
53 info.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
54 info.queryType = VK_QUERY_TYPE_TIMESTAMP;
55 info.queryCount = MAX_FRAMES_IN_FLIGHT * GPU_QUERIES_PER_FRAME;
56 if (vkCreateQueryPool(device, &info, nullptr, &m_gpuQueryPool) !=
57 VK_SUCCESS) {
58 SLEAK_WARN("GPU profiler: query pool creation failed");
59 m_gpuQueryPool = VK_NULL_HANDLE;
60 return false;
61 }
62
63 m_gpuTickNs = static_cast<double>(props.limits.timestampPeriod);
64 m_gpuTickMask = validBits >= std::numeric_limits<uint64_t>::digits
65 ? ~0ull
66 : ((1ull << validBits) - 1);
67 m_gpuSlots = {};
68 m_gpuSumMs = {};
69 m_gpuMaxMs = {};
70 m_gpuRuns = {};
71 m_gpuLastMs = {};
72 m_gpuWindowFrames = 0;
73 m_gpuWindowTimer.Reset();
74 m_gpuProfilerEnabled = true;
75
76 SLEAK_INFO("GPU profiler: on ({} timestamp bits, {:.3f} ns/tick)",
77 validBits, m_gpuTickNs);
78 return true;
79}
80
81/// Destroys the timestamp query pool.
82void VulkanRenderer::CleanupGpuProfiler() {
83 m_gpuProfilerEnabled = false;
84 if (m_gpuQueryPool != VK_NULL_HANDLE) {
85 vkDestroyQueryPool(device, m_gpuQueryPool, nullptr);
86 m_gpuQueryPool = VK_NULL_HANDLE;
87 }
88}
89
90/// Folds this slot's finished timestamps into the running window and logs the
91/// table once the window elapses. Call after the slot's fence.
92void VulkanRenderer::CollectGpuProfile() {
93 if (!m_gpuProfilerEnabled) return;
94 GpuProfileSlot& slot = m_gpuSlots[currentFrame];
95 if (!slot.submitted) return;
96 slot.submitted = false;
97
98 // value + availability per query
99 const uint32_t queryCount = 2 + 2 * slot.pairCount;
100 std::array<uint64_t, GPU_QUERIES_PER_FRAME * 2> data{};
101 const VkResult res = vkGetQueryPoolResults(
102 device, m_gpuQueryPool, currentFrame * GPU_QUERIES_PER_FRAME,
103 queryCount, queryCount * 2 * sizeof(uint64_t), data.data(),
104 2 * sizeof(uint64_t),
105 VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WITH_AVAILABILITY_BIT);
106 if (res != VK_SUCCESS || data[1] == 0 || data[3] == 0) return;
107
108 auto ticksToMs = [this](uint64_t begin, uint64_t end) {
109 const uint64_t ticks = (end - begin) & m_gpuTickMask;
110 return static_cast<float>(static_cast<double>(ticks) * m_gpuTickNs *
111 1e-6);
112 };
113
114 std::array<float, GPU_ROW_COUNT> frameMs{};
115 std::array<bool, GPU_ROW_COUNT> ran{};
116 float passSum = 0.0f;
117 for (uint32_t i = 0; i < slot.pairCount; ++i) {
118 const uint64_t* begin = &data[(2 + 2 * i) * 2];
119 const uint64_t* end = &data[(3 + 2 * i) * 2];
120 if (begin[1] == 0 || end[1] == 0) continue;
121 const float ms = ticksToMs(begin[0], end[0]);
122 const auto row = static_cast<uint32_t>(slot.pairPass[i]);
123 frameMs[row] += ms;
124 ran[row] = true;
125 passSum += ms;
126 }
127 frameMs[GPU_ROW_TOTAL] = ticksToMs(data[0], data[2]);
128 frameMs[GPU_ROW_OTHER] = std::max(0.0f, frameMs[GPU_ROW_TOTAL] - passSum);
129 ran[GPU_ROW_TOTAL] = true;
130 ran[GPU_ROW_OTHER] = true;
131
132 for (uint32_t row = 0; row < GPU_ROW_COUNT; ++row) {
133 m_gpuLastMs[row] = ran[row] ? frameMs[row] : 0.0f;
134 if (!ran[row]) continue;
135 m_gpuSumMs[row] += frameMs[row];
136 m_gpuMaxMs[row] = std::max(m_gpuMaxMs[row], frameMs[row]);
137 ++m_gpuRuns[row];
138 }
139 ++m_gpuWindowFrames;
140
141 const float elapsed = m_gpuWindowTimer.Elapsed();
142 if (elapsed < kGpuLogIntervalSeconds) return;
143 LogGpuProfile(elapsed);
144 m_gpuSumMs = {};
145 m_gpuMaxMs = {};
146 m_gpuRuns = {};
147 m_gpuWindowFrames = 0;
148 m_gpuWindowTimer.Reset();
149}
150
151/// Resets this slot's queries and stamps the frame start.
152void VulkanRenderer::BeginGpuFrame() {
153 if (!m_gpuProfilerEnabled) return;
154 GpuProfileSlot& slot = m_gpuSlots[currentFrame];
155 slot = {};
156 slot.recording = true;
157 const uint32_t base = currentFrame * GPU_QUERIES_PER_FRAME;
158 vkCmdResetQueryPool(command, m_gpuQueryPool, base, GPU_QUERIES_PER_FRAME);
159 vkCmdWriteTimestamp(command, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
160 m_gpuQueryPool, base);
161}
162
163/// Closes any pass left open and stamps the frame end.
164void VulkanRenderer::EndGpuFrame() {
165 if (!m_gpuProfilerEnabled) return;
166 GpuProfileSlot& slot = m_gpuSlots[currentFrame];
167 if (!slot.recording) return;
168 if (slot.pairOpen) EndGpuPass(slot.pairPass[slot.pairCount]);
169 vkCmdWriteTimestamp(command, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
170 m_gpuQueryPool,
171 currentFrame * GPU_QUERIES_PER_FRAME + 1);
172 slot.recording = false;
173}
174
175/// Flags this slot's queries for readback on its next fence wait.
176void VulkanRenderer::MarkGpuFrameSubmitted() {
177 if (!m_gpuProfilerEnabled) return;
178 m_gpuSlots[currentFrame].submitted = true;
179}
180
181/// Stamps the start of a pass. Timestamps use BOTTOM_OF_PIPE so each pair
182/// measures the time the pass adds once earlier work has drained.
183void VulkanRenderer::BeginGpuPass(GpuPass pass) {
184 if (!m_gpuProfilerEnabled) return;
185 GpuProfileSlot& slot = m_gpuSlots[currentFrame];
186 if (!slot.recording || slot.pairOpen || slot.pairCount >= GPU_MAX_PAIRS)
187 return;
188 vkCmdWriteTimestamp(
189 command, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, m_gpuQueryPool,
190 currentFrame * GPU_QUERIES_PER_FRAME + 2 + 2 * slot.pairCount);
191 slot.pairPass[slot.pairCount] = pass;
192 slot.pairOpen = true;
193}
194
195/// Stamps the end of the pass opened by the matching BeginGpuPass.
196void VulkanRenderer::EndGpuPass(GpuPass pass) {
197 if (!m_gpuProfilerEnabled) return;
198 GpuProfileSlot& slot = m_gpuSlots[currentFrame];
199 if (!slot.recording || !slot.pairOpen ||
200 slot.pairPass[slot.pairCount] != pass)
201 return;
202 vkCmdWriteTimestamp(
203 command, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, m_gpuQueryPool,
204 currentFrame * GPU_QUERIES_PER_FRAME + 3 + 2 * slot.pairCount);
205 slot.pairOpen = false;
206 ++slot.pairCount;
207}
208
209/// Logs the averaged per-pass table for the current window.
210void VulkanRenderer::LogGpuProfile(float seconds) const {
211 SLEAK_INFO("GPU profile: {} frames in {:.1f} s, avg / max ms",
212 m_gpuWindowFrames, seconds);
213 for (uint32_t row = 0; row < GPU_ROW_COUNT; ++row) {
214 if (m_gpuRuns[row] == 0) continue;
215 const double avg = m_gpuSumMs[row] / m_gpuRuns[row];
216 const std::string runs =
217 m_gpuRuns[row] < m_gpuWindowFrames
218 ? std::format(" ({}/{} frames)", m_gpuRuns[row],
219 m_gpuWindowFrames)
220 : std::string();
221 SLEAK_INFO(" {:<9}{:8.3f}{:8.3f}{}", kGpuRowNames[row], avg,
222 m_gpuMaxMs[row], runs);
223 }
224}
225
226/// Adds per-pass GPU millisecond columns when --gpuprofile is on. Values lag
227/// the CSV row by MAX_FRAMES_IN_FLIGHT frames.
229 if (!m_gpuProfilerEnabled) return;
230 for (uint32_t row = 0; row < GPU_ROW_COUNT; ++row) {
231 if (row == GPU_ROW_OTHER) continue;
232 bench.RegisterMetric(std::format("GPU_{}_ms", kGpuRowNames[row]),
233 [this, row] { return m_gpuLastMs[row]; });
234 }
235}
236
237} // namespace RenderEngine
238} // namespace Sleak
#define SLEAK_INFO(...)
Definition Logger.hpp:20
#define SLEAK_WARN(...)
Definition Logger.hpp:21
void RegisterMetric(const std::string &name, std::function< float()> getter)
Register a custom metric (e.g. render distance from Game).
Definition Benchmark.cpp:33
void RegisterBenchmarkMetrics(Benchmark &bench) override
Adds per-pass GPU millisecond columns when –gpuprofile is on.
Backend-facing rendering layer shared by the four graphics backends.
Root namespace for everything the engine exposes.
Definition Camera.hpp:10