SleakEngine 0.1.0
C++23 multi-backend game engine
Loading...
Searching...
No Matches
VulkanRenderer.cpp
Go to the documentation of this file.
8
9#include <SDL3/SDL_vulkan.h>
10#include <Core/Window.hpp>
11#include <algorithm>
12#include <cstddef>
13#include <cstdint>
14#include <cstdlib>
15#include <cstring>
16#include <format>
17#include <fstream>
18#include <limits>
19#include <optional>
20#include <set>
21#include <stdexcept>
22#include <string>
23#include <vector>
26#include "Core/Logger.hpp"
27#include "Core/CommandLine.hpp"
28#include "Camera/Camera.hpp"
29#include "Math/Matrix.hpp"
30#include <random>
31#include "SDL3/SDL_error.h"
32#include "SDL3/SDL_video.h"
33#ifdef PLATFORM_LINUX
34 #include "vulkan/vulkan_wayland.h"
35#elif defined(PLATFORM_WIN)
36 #include <vulkan/vulkan_win32.h>
37#endif
38
39namespace Sleak {
40 namespace RenderEngine {
41
42/// Constructs the renderer, sets the clear color, and registers
43/// ResourceManager factory callbacks.
45 : sdlWindow(window) {
47 clearColor = {{0.3f, 0.4f, 1.0f, 1.0f}};
48
59
61 [this](const void* data, uint32_t w, uint32_t h, TextureFormat fmt, uint32_t maxMip) -> ::Sleak::Texture* {
62 auto* tex = new VulkanTexture(device, physicalDevice, commands, graphicsQueue);
63 tex->SetMaxMipLevels(maxMip);
64 if (tex->LoadFromMemory(data, w, h, fmt)) {
65 WriteTextureDescriptors(tex);
66 return tex;
67 }
68 delete tex;
69 return nullptr;
70 });
71}
72
73/// Calls Cleanup() to tear down all Vulkan resources.
77
78/// Runs the full Vulkan bring-up sequence: instance, device, swapchain,
79/// pipelines, and sync objects.
81 m_captureMode = !CommandLine::GetValue("-capture").empty();
82
83 if (!InitVulkan())
84 SLEAK_RETURN_ERR("Failed to initialize Vulkan Instance!");
85
86 if (!SetupDebugMessenger()) {
87 SLEAK_WARN("Failed to setup validation layer of vulkan instance")
88 }
89
90 if (!CreateSurface())
91 SLEAK_RETURN_ERR("Failed to create render surface!")
92
93 if (!CreateDevice())
94 SLEAK_RETURN_ERR("Failed to initialize devices!");
95
96 CreatePipelineCache();
97
98 if (!CreateSwapChain())
99 SLEAK_RETURN_ERR("Failed to create swap chain!");
100
101 if (!CreateImageViews())
102 SLEAK_RETURN_ERR("Failed to create image views for renderer!");
103
104 if (!CreateDepthResources())
105 SLEAK_RETURN_ERR("Failed to create depth resources!");
106
107 if (!CreateMSAAColorResources())
108 SLEAK_RETURN_ERR("Failed to create MSAA color resources!");
109
110 if (!CreateRenderPass())
111 SLEAK_RETURN_ERR("Failed to create a render pass for the renderer!");
112
113 if (!CreateDescriptorSetLayout())
114 SLEAK_RETURN_ERR("Failed to create descriptor set layout!");
115
116 if (!CreateDescriptorPool())
117 SLEAK_RETURN_ERR("Failed to create descriptor pool!");
118
119 if (!AllocateDescriptorSets())
120 SLEAK_RETURN_ERR("Failed to allocate descriptor sets!");
121
122 if (!CreateCommandPool())
123 SLEAK_RETURN_ERR("Failed to create command pool for renderer!");
124
125 if (!CreateCommandBuffer())
126 SLEAK_RETURN_ERR("Failed to create command buffers for renderer!");
127
128 if (!CreateDefaultTexture())
129 SLEAK_WARN("Failed to create default white texture for Vulkan");
130
131 if (!CreateMainPipelineLayout())
132 SLEAK_RETURN_ERR("Failed to create graphics pipeline layout!");
133
134 if (!CreateShadowLightUBOResources())
135 SLEAK_WARN("Failed to create light UBO resources — dynamic lighting disabled");
136
137 if (!CreateSceneReadResources())
139 "Failed to create scene-read resources for transparent formats");
140
141 if (!CreateShadowResources())
142 SLEAK_WARN("Failed to create shadow mapping resources — shadows disabled");
143
144 if (!CreateFrameBuffer())
145 SLEAK_RETURN_ERR("Failed to create framebuffer of renderer!");
146
147 // Deferred GBuffer — initialized after swapchain framebuffers are ready
148 if (m_deferredEnabled) {
149 if (!CreateGBufferResources())
150 SLEAK_WARN("Failed to create GBuffer resources — deferred rendering disabled");
151 }
152
153 // Forward path
154 if (pipeline == VK_NULL_HANDLE && !CreateGraphicsPipeline())
155 SLEAK_RETURN_ERR("Failed to create graphics pipeline!");
156
157 // Eagerly create bone UBO resources so set 1 is always bound at pass start.
158 // Must happen after CreateDescriptorSetLayout() (boneDescriptorSetLayout is ready)
159 // and after GBuffer init (m_deferredEnabled is known).
160 if (!CreateBoneUBOResources())
161 SLEAK_WARN("Failed to pre-create bone UBO resources — skinned meshes may malfunction on first frame");
162
163 if (!CreateSyncObjects())
164 SLEAK_RETURN_ERR("Failed to synchronization objects of renderer!");
165
166 if (CommandLine::HasFlag("--gpuprofile")) CreateGpuProfiler();
167
169
170 SLEAK_INFO("Vulkan renderer has been initialized successfully!");
171
172 return true;
173}
174
175/// Acquires a swapchain image and begins the shadow/GBuffer/forward passes
176/// for the RenderCommandQueue to record into. A failed acquire returns early
177/// with only a UI frame open, leaving deletions unaged and uploads batched.
179 bFrameStarted = false;
180 m_inGeometryPass = false;
181 m_inForwardTransparentPass = false;
182 m_forwardPassOpen = false;
183 m_activeCustomFormat = 0;
184 m_sceneReadPrepared = false;
185 if (!bRender)
186 return;
187
188 // Commit staged lightVP. Do this BEFORE the shadow pass so the shadow
189 // map and the main pass both read the same m_lightVP this frame.
190 if (m_hasPendingLightVP) {
191 memcpy(m_lightVP, m_pendingLightVP, sizeof(m_lightVP));
192 }
193
194 // Apply pending changes between frames
201 PrebuildCustomFormatPipelines();
202
203 VkResult result;
204
205 if (device && !inFlightFences.empty()) {
206 vkWaitForFences(device, 1, &inFlightFences[currentFrame],
207 VK_TRUE, UINT64_MAX);
208 VulkanTexture::DestroyReleased(m_slotSerial[currentFrame]);
209 }
210 CollectGpuProfile();
211 UpdateSceneReadDescriptors(currentFrame);
212
213 // Clean up staging buffers from the previous use of this frame slot.
214 // The fence wait above guarantees the GPU finished both the transfer
215 // (waited on by the render submit) and the render itself.
216 auto& flush = m_asyncFlush[currentFrame];
217 if (flush.submitted) {
218 // Free command buffer FIRST to release references to staging buffers
219 if (flush.commandBuffer != VK_NULL_HANDLE) {
220 vkFreeCommandBuffers(flush.device, flush.commandPool, 1,
221 &flush.commandBuffer);
222 }
223 for (auto& pending : flush.stagingBuffers) {
224 vmaDestroyBuffer(VulkanBuffer::GetAllocator(), pending.buffer,
225 pending.memory);
226 VulkanBuffer::UntrackAllocation(pending.allocSize,
227 pending.memoryTypeIndex);
228 }
229 flush = {};
230 }
231
232 // Enable batched buffer uploads for this frame (async, zero CPU blocking).
233 // This is disabled during init/scene transitions where buffers may be
234 // created and destroyed before a flush.
236
237 // UI frame for skipped frames
238 auto beginSkippedUIFrame = [this]() {
239 bImFrameActive = false;
240 if (!bImInitialized) return;
241 ImGui_ImplVulkan_NewFrame();
242 ImGui_ImplSDL3_NewFrame();
243 ImGui::NewFrame();
244 bImFrameActive = true;
245 };
246
247 // Acquire the next image from the swapchain
248 result = vkAcquireNextImageKHR(device, swapChain, UINT64_MAX,
249 imageAvailableSemaphores[m_semaphoreIndex],
250 VK_NULL_HANDLE, &CurrentFrameIndex);
251 if (result == VK_ERROR_OUT_OF_DATE_KHR) {
252 RecreateSwapChain();
253 beginSkippedUIFrame();
254 return;
255 } else if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR) {
256 SLEAK_ERROR("Failed to acquire swapchain image!");
257 beginSkippedUIFrame();
258 return;
259 }
260
261 // Submitting frames age deletions
262 VulkanBuffer::ProcessDeferredDeletions(MAX_FRAMES_IN_FLIGHT);
264
265 // Wait if this swapchain image is still in use by a DIFFERENT frame slot
266 if (CurrentFrameIndex < imagesInFlight.size() &&
267 imagesInFlight[CurrentFrameIndex] != VK_NULL_HANDLE &&
268 imagesInFlight[CurrentFrameIndex] != inFlightFences[currentFrame]) {
269 vkWaitForFences(device, 1, &imagesInFlight[CurrentFrameIndex],
270 VK_TRUE, UINT64_MAX);
271 }
272 imagesInFlight[CurrentFrameIndex] = inFlightFences[currentFrame];
273
274 // Reset the fence only after all waits are done
275 vkResetFences(device, 1, &inFlightFences[currentFrame]);
276
277 // Select the command buffer for this frame-in-flight
278 command = commandBuffers[currentFrame];
279
280 // Reset and begin the command buffer
281 vkResetCommandBuffer(command, 0);
282
283 VkCommandBufferBeginInfo beginInfo{};
284 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
285 beginInfo.flags = 0;
286
287 if (vkBeginCommandBuffer(command, &beginInfo) != VK_SUCCESS) {
288 SLEAK_ERROR("Failed to begin command buffer!");
289 return;
290 }
291
292 bFrameStarted = true;
293 m_pbrMaterialSlot[currentFrame] = 0; // reset PBR material ring for this frame
294 m_pbrMaterialBindings[currentFrame].clear();
295 m_boneSlot[currentFrame] = 1; // slot 0 is the identity palette
296 BeginGpuFrame();
297
298 // Skip shadow pass if no cached draws — preserve previous frame's shadow map
299 auto* shadowQueue = RenderCommandQueue::GetInstance();
300 bool hasShadowDraws = shadowQueue && shadowQueue->HasCachedShadowDraws();
301
302 if (m_shadowResourcesCreated && m_shadowPassEnabled && hasShadowDraws) {
303 VkClearValue shadowClear{};
304 shadowClear.depthStencil = {1.0f, 0};
305
306 VkRenderPassBeginInfo shadowPassInfo{};
307 shadowPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
308 shadowPassInfo.renderPass = m_shadowRenderPass;
309 shadowPassInfo.framebuffer = m_shadowFramebuffer;
310 shadowPassInfo.renderArea.offset = {0, 0};
311 shadowPassInfo.renderArea.extent = {m_shadowMapResolution, m_shadowMapResolution};
312 shadowPassInfo.clearValueCount = 1;
313 shadowPassInfo.pClearValues = &shadowClear;
314
315 BeginGpuPass(GpuPass::Shadow);
316 vkCmdBeginRenderPass(command, &shadowPassInfo, VK_SUBPASS_CONTENTS_INLINE);
317 vkCmdBindPipeline(command, VK_PIPELINE_BIND_POINT_GRAPHICS, m_shadowPipeline);
318
319 // shadow_depth.vert statically declares `layout(set = 1, binding = 0) uniform BoneUBO`
320 // (skinning conditioned on boneWeights). The shader must have set 1 bound even for
321 // non-skinned casters, otherwise vkCmdDrawIndexed fires VUID-vkCmdDrawIndexed-None-08600.
322 // Bind the bone UBO once at pass start so all shadow draws (skinned or static) are legal.
323 BindIdentityBonePalette(pipelineLay);
324
325 VkViewport shadowViewport{};
326 shadowViewport.x = 0.0f;
327 shadowViewport.y = 0.0f;
328 shadowViewport.width = static_cast<float>(m_shadowMapResolution);
329 shadowViewport.height = static_cast<float>(m_shadowMapResolution);
330 shadowViewport.minDepth = 0.0f;
331 shadowViewport.maxDepth = 1.0f;
332 vkCmdSetViewport(command, 0, 1, &shadowViewport);
333
334 VkRect2D shadowScissor{};
335 shadowScissor.offset = {0, 0};
336 shadowScissor.extent = {m_shadowMapResolution, m_shadowMapResolution};
337 vkCmdSetScissor(command, 0, 1, &shadowScissor);
338
339 m_shadowPassActive = true;
340 m_shadowPCCacheValid = false;
341 m_shadowPCPushedLayout = VK_NULL_HANDLE;
342 memcpy(m_shadowMapLightVP, m_lightVP, sizeof(m_shadowMapLightVP));
343 m_shadowMapRendered = true;
344 auto* queue = RenderCommandQueue::GetInstance();
345 if (queue) {
346 queue->ExecuteShadowPass(this);
347 }
348 m_shadowPassActive = false;
349
350 vkCmdEndRenderPass(command);
351 EndGpuPass(GpuPass::Shadow);
352 }
353
354 // ---- Deferred path: begin GBuffer render pass ----
355 if (m_gbufferResourcesCreated && m_deferredEnabled) {
356 // 4 clear values: RT0, RT1, RT2, depth
357 VkClearValue gbufferClears[GBUFFER_COUNT + 1];
358 for (uint32_t i = 0; i < GBUFFER_COUNT; ++i) {
359 gbufferClears[i].color = {0.0f, 0.0f, 0.0f, 0.0f};
360 }
361 gbufferClears[GBUFFER_COUNT].depthStencil = {1.0f, 0};
362
363 VkRenderPassBeginInfo gbufferPassInfo{};
364 gbufferPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
365 gbufferPassInfo.renderPass = m_gbufferRenderPass;
366 gbufferPassInfo.framebuffer = m_gbufferFramebuffer;
367 gbufferPassInfo.renderArea.offset = {0, 0};
368 gbufferPassInfo.renderArea.extent = scExtent;
369 gbufferPassInfo.clearValueCount = GBUFFER_COUNT + 1;
370 gbufferPassInfo.pClearValues = gbufferClears;
371
372 BeginGpuPass(GpuPass::GBuffer);
373 vkCmdBeginRenderPass(command, &gbufferPassInfo, VK_SUBPASS_CONTENTS_INLINE);
374 vkCmdBindPipeline(command, VK_PIPELINE_BIND_POINT_GRAPHICS, m_gbufferPipeline);
375
376 // Set viewport and scissor
377 VkViewport viewport{};
378 viewport.x = 0.0f;
379 viewport.y = 0.0f;
380 viewport.width = static_cast<float>(scExtent.width);
381 viewport.height = static_cast<float>(scExtent.height);
382 viewport.minDepth = 0.0f;
383 viewport.maxDepth = 1.0f;
384 vkCmdSetViewport(command, 0, 1, &viewport);
385
386 VkRect2D scissor{};
387 scissor.offset = {0, 0};
388 scissor.extent = scExtent;
389 vkCmdSetScissor(command, 0, 1, &scissor);
390
391 // Bind descriptor sets for GBuffer geometry pass.
392 // Set 0 (PBR material) is bound per-material by BindPBRMaterial().
393 // Set 1 (bone matrices) starts at the identity palette so
394 // m_skinnedGbufferPipeline always finds a valid set 1.
395 // Sets 2-3 are frame-constant: light/shadow UBO and shadow samplers.
396 if (m_gbufferGeomLayout != VK_NULL_HANDLE && m_lightUBOCreated) {
397 BindIdentityBonePalette(m_gbufferGeomLayout);
398 vkCmdBindDescriptorSets(command, VK_PIPELINE_BIND_POINT_GRAPHICS,
399 m_gbufferGeomLayout, 2, 1,
400 &m_lightUBODescriptorSets[currentFrame], 0, nullptr);
401 vkCmdBindDescriptorSets(command, VK_PIPELINE_BIND_POINT_GRAPHICS,
402 m_gbufferGeomLayout, 3, 1,
403 &m_shadowSamplerDescriptorSets[currentFrame], 0, nullptr);
404 }
405
406 m_inGeometryPass = true;
407
408 // ImGui new frame (same as forward path below)
409 bImFrameActive = false;
410 if (bImInitialized) {
411 ImGui_ImplVulkan_NewFrame();
412 ImGui_ImplSDL3_NewFrame();
413 auto& io = ImGui::GetIO();
414 if (io.DisplaySize.x > 0.0f && io.DisplaySize.y > 0.0f) {
415 ImGui::NewFrame();
416 bImFrameActive = true;
417 }
418 }
419 return;
420 }
421
422 // ---- Forward path (non-deferred): begin main render pass ----
423 // When MSAA: 3 attachments (color, depth, resolve); otherwise 2
424 // Use stack array to avoid per-frame heap allocation
425 VkClearValue clearValues[3];
426 uint32_t clearValueCount = 2;
427 clearValues[0] = clearColor;
428 clearValues[1].depthStencil = {1.0f, 0};
429 if (m_msaaSamples != VK_SAMPLE_COUNT_1_BIT) {
430 clearValues[2].color = clearColor.color;
431 clearValueCount = 3;
432 }
433
434 VkRenderPassBeginInfo passInfo{};
435 passInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
436 passInfo.renderPass = renderPass;
437 passInfo.framebuffer = swapChainFramebuffers[CurrentFrameIndex];
438 passInfo.renderArea.offset = {0, 0};
439 passInfo.renderArea.extent = scExtent;
440 passInfo.clearValueCount = clearValueCount;
441 passInfo.pClearValues = clearValues;
442
443 BeginGpuPass(GpuPass::Forward);
444 vkCmdBeginRenderPass(command, &passInfo, VK_SUBPASS_CONTENTS_INLINE);
445
446 vkCmdBindPipeline(command, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
447
448 // Bind texture descriptor set if available
449 if (m_textureDescriptorsWritten &&
450 CurrentFrameIndex < descriptorSets.size()) {
451 vkCmdBindDescriptorSets(
452 command, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLay, 0, 1,
453 &descriptorSets[CurrentFrameIndex], 0, nullptr);
454 }
455
456 // Set dynamic viewport and scissor
457 VkViewport viewport{};
458 viewport.x = 0.0f;
459 viewport.y = 0.0f;
460 viewport.width = static_cast<float>(scExtent.width);
461 viewport.height = static_cast<float>(scExtent.height);
462 viewport.minDepth = 0.0f;
463 viewport.maxDepth = 1.0f;
464 vkCmdSetViewport(command, 0, 1, &viewport);
465
466 VkRect2D scissor{};
467 scissor.offset = {0, 0};
468 scissor.extent = scExtent;
469 vkCmdSetScissor(command, 0, 1, &scissor);
470
471 // Bind light UBO at set 2 and shadow sampler at set 3
472 if (m_lightUBOCreated) {
473 vkCmdBindDescriptorSets(
474 command, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLay, 2, 1,
475 &m_lightUBODescriptorSets[currentFrame], 0, nullptr);
476 vkCmdBindDescriptorSets(
477 command, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLay, 3, 1,
478 &m_shadowSamplerDescriptorSets[currentFrame], 0, nullptr);
479 }
480
481 // RenderCommandQueue will now call Draw/DrawIndexed/Bind* methods
482 // via the RenderContext interface on this object
483
484 bImFrameActive = false;
485 if (bImInitialized) {
486 ImGui_ImplVulkan_NewFrame();
487 ImGui_ImplSDL3_NewFrame();
488 auto& io = ImGui::GetIO();
489 if (io.DisplaySize.x > 0.0f && io.DisplaySize.y > 0.0f) {
490 ImGui::NewFrame();
491 bImFrameActive = true;
492 }
493 }
494}
495
496/// Ends the active render pass, submits the command buffer, and presents.
497/// A skipped frame only closes its UI frame.
499 if (!bRender || !bFrameStarted) {
500 // Skipped frame, no UI draw
501 if (bImFrameActive && bImInitialized) ImGui::EndFrame();
502 bImFrameActive = false;
503 return;
504 }
505
506 const bool deferredPath =
507 m_gbufferResourcesCreated && m_deferredEnabled && m_bloomResourcesCreated;
508
509 // Safety: if geometry pass is still open (ExecuteDeferredLightingPass not called),
510 // end it now so we don't have a dangling render pass.
511 if (m_gbufferResourcesCreated && m_deferredEnabled && m_inGeometryPass) {
512 vkCmdEndRenderPass(command);
513 EndGpuPass(GpuPass::GBuffer);
514 m_inGeometryPass = false;
515 }
516
517 // In deferred mode, open a forward render pass so the HDR scene image ends
518 // in SHADER_READ_ONLY_OPTIMAL regardless of whether any transparent pass
519 // ran. BeginForwardTransparentPass already opens this RP; if the game
520 // didn't call it (no transparent objects), open/close a trivial one here.
521 if (deferredPath && !m_forwardPassOpen && !m_inGeometryPass) {
522 VkRenderPassBeginInfo rpBegin{};
523 rpBegin.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
524 rpBegin.renderPass = m_forwardRenderPass;
525 rpBegin.framebuffer = m_forwardFramebuffers[CurrentFrameIndex];
526 rpBegin.renderArea.offset = {0, 0};
527 rpBegin.renderArea.extent = scExtent;
528 rpBegin.clearValueCount = 0;
529 BeginGpuPass(GpuPass::Forward);
530 vkCmdBeginRenderPass(command, &rpBegin, VK_SUBPASS_CONTENTS_INLINE);
531 m_forwardPassOpen = true;
532 }
533
534 // Close the forward pass (HDR scene → SHADER_READ_ONLY_OPTIMAL via finalLayout).
535 if (m_forwardPassOpen) {
536 vkCmdEndRenderPass(command);
537 EndGpuPass(GpuPass::Forward);
538 m_forwardPassOpen = false;
539 }
540
541 if (deferredPath) {
542 // TAA: accumulate current HDR frame with history into a ping-pong
543 // target that SSR, bloom and the composite read. Also handles the depth
544 // barrier (ATTACHMENT → READ_ONLY) so SSR can skip its own barrier.
545 RenderTAAPass();
546 // Screen-space reflections — reads the TAA-resolved scene + GBuffer.
547 RenderSSRPass();
548 // Bloom pyramid generates the bloom result from the HDR scene.
549 RenderBloomPass();
550 // Composite pass reads HDR scene + bloom + SSR, applies ACES + gamma,
551 // writes to the swapchain. ImGui is drawn inside this pass.
552 RenderBloomCompositePass();
553 } else {
554 // Forward (non-deferred) path — ImGui inside main render pass.
555 const bool drawUI = bImFrameActive && m_capturePath.empty();
556 if (drawUI) {
557 EndGpuPass(GpuPass::Forward);
558 BeginGpuPass(GpuPass::UI);
559 }
560 if (bImFrameActive) {
561 ImGui::Render();
562 if (drawUI)
563 ImGui_ImplVulkan_RenderDrawData(ImGui::GetDrawData(), command);
564 }
565 vkCmdEndRenderPass(command);
566 EndGpuPass(drawUI ? GpuPass::UI : GpuPass::Forward);
567 }
568
569 if (!m_capturePath.empty()) RecordFrameCaptureCopy();
570 EndGpuFrame();
571
572 if (vkEndCommandBuffer(command) != VK_SUCCESS) {
573 SLEAK_ERROR("Failed to end command buffer!");
574 return;
575 }
576
577 // Submit
578 VkSubmitInfo submitInfo{};
579 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
580
581 // Wait on image-available; also wait on transfer semaphore if uploads happened
582 VkSemaphore waitSemaphores[2];
583 VkPipelineStageFlags waitStages[2];
584 uint32_t waitCount = 0;
585
586 waitSemaphores[waitCount] = imageAvailableSemaphores[m_semaphoreIndex];
587 waitStages[waitCount] = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
588 waitCount++;
589
590 if (m_asyncFlush[currentFrame].submitted) {
591 waitSemaphores[waitCount] = m_transferSemaphores[currentFrame];
592 waitStages[waitCount] = VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
593 waitCount++;
594 }
595
596 submitInfo.waitSemaphoreCount = waitCount;
597 submitInfo.pWaitSemaphores = waitSemaphores;
598 submitInfo.pWaitDstStageMask = waitStages;
599
600 submitInfo.commandBufferCount = 1;
601 submitInfo.pCommandBuffers = &command;
602
603 // Index renderFinished semaphore by acquired image index: when image N
604 // is re-acquired, the previous present of image N is guaranteed complete,
605 // so renderFinishedSemaphores[N] is safe to reuse.
606 VkSemaphore signalSemaphores[] = {renderFinishedSemaphores[CurrentFrameIndex]};
607 submitInfo.signalSemaphoreCount = 1;
608 submitInfo.pSignalSemaphores = signalSemaphores;
609
610 if (vkQueueSubmit(graphicsQueue, 1, &submitInfo,
611 inFlightFences[currentFrame]) != VK_SUCCESS) {
612 SLEAK_ERROR("Failed to submit draw command buffer!");
613 } else {
614 MarkGpuFrameSubmitted();
615 m_slotSerial[currentFrame] = ++m_submitSerial;
616 VulkanTexture::SetReleaseSerial(m_submitSerial + 1);
617 }
618
619 // Present
620 VkPresentInfoKHR presentInfo{};
621 presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
622 presentInfo.waitSemaphoreCount = 1;
623 presentInfo.pWaitSemaphores = signalSemaphores;
624
625 VkSwapchainKHR swapChains[] = {swapChain};
626 presentInfo.swapchainCount = 1;
627 presentInfo.pSwapchains = swapChains;
628 presentInfo.pImageIndices = &CurrentFrameIndex;
629
630 VkResult presentResult = vkQueuePresentKHR(presentQueue, &presentInfo);
631
632 // Capture pins the extent
633 if (presentResult == VK_ERROR_OUT_OF_DATE_KHR ||
634 (presentResult == VK_SUBOPTIMAL_KHR && !m_captureMode &&
635 SurfaceExtentChanged())) {
636 RecreateSwapChain();
637 } else if (presentResult != VK_SUCCESS &&
638 presentResult != VK_SUBOPTIMAL_KHR) {
639 SLEAK_ERROR("Failed to present render!");
640 }
641
642 if (m_captureRecorded) FinishFrameCapture();
643
644 // Reset per-frame deferred state flags
645 m_forwardPassOpen = false;
646 m_inForwardTransparentPass = false;
647 m_inGeometryPass = false;
648 bFrameStarted = false; // command buffer submitted; recording is complete
649
650 currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT;
651 m_semaphoreIndex = (m_semaphoreIndex + 1) %
652 static_cast<uint32_t>(imageAvailableSemaphores.size());
653
655}
656
657/// True while the bound vertex buffer's format has no pipeline for this pass.
658bool VulkanRenderer::CustomFormatDrawsSuppressed() const {
659 return m_activeCustomFormat != 0 && m_customFormatUnbound;
660}
661
662/// Issues a non-indexed draw call and updates the vertex/triangle counters.
663void VulkanRenderer::Draw(uint32_t vertexCount) { Draw(vertexCount, 0); }
664
665void VulkanRenderer::Draw(uint32_t vertexCount, uint32_t firstVertex) {
666 if (!bFrameStarted) return;
667 if (CustomFormatDrawsSuppressed()) return;
668 vkCmdDraw(command, vertexCount, 1, firstVertex, 0);
669 if (!m_shadowPassActive) {
670 DrawnVertices += vertexCount;
671 DrawnTriangles += vertexCount / 3;
672 }
673}
674
675/// Issues an indexed draw call and updates the vertex/triangle counters.
676void VulkanRenderer::DrawIndexed(uint32_t indexCount) {
677 DrawIndexed(indexCount, 0, 0);
678}
679
680void VulkanRenderer::DrawIndexed(uint32_t indexCount, uint32_t firstIndex,
681 int32_t baseVertex) {
682 if (!bFrameStarted) return;
683 if (CustomFormatDrawsSuppressed()) return;
684 vkCmdDrawIndexed(command, indexCount, 1, firstIndex, baseVertex, 0);
685 if (!m_shadowPassActive) {
686 DrawnVertices += indexCount;
687 DrawnTriangles += indexCount / 3;
688 }
689}
690
691/// Issues an instanced, non-indexed draw call.
692void VulkanRenderer::DrawInstance(uint32_t instanceCount,
693 uint32_t vertexPerInstance) {
694 if (!bFrameStarted) return;
695 if (CustomFormatDrawsSuppressed()) return;
696 vkCmdDraw(command, vertexPerInstance, instanceCount, 0, 0);
697}
698
699/// Issues an instanced, indexed draw call.
700void VulkanRenderer::DrawIndexedInstance(uint32_t instanceCount,
701 uint32_t indexPerInstance) {
702 DrawIndexedInstance(instanceCount, indexPerInstance, 0, 0);
703}
704
705void VulkanRenderer::DrawIndexedInstance(uint32_t instanceCount,
706 uint32_t indexPerInstance,
707 uint32_t firstIndex,
708 int32_t baseVertex) {
709 if (!bFrameStarted) return;
710 if (CustomFormatDrawsSuppressed()) return;
711 vkCmdDrawIndexed(command, indexPerInstance, instanceCount, firstIndex,
712 baseVertex, 0);
713}
714
715/// Stores the cull face for the next pipeline rebuild (Vulkan state is baked).
717 // Vulkan pipeline state is baked, needs pipeline recreation.
718 // Store for next pipeline rebuild.
719 Face = face;
720}
721
722/// Stores the polygon mode for the next pipeline rebuild (Vulkan state is baked).
724 // Vulkan pipeline state is baked, needs pipeline recreation.
725 Mode = mode;
726}
727
728/// Sets the dynamic viewport on the active command buffer.
729void VulkanRenderer::SetViewport(float x, float y, float width,
730 float height, float minDepth,
731 float maxDepth) {
732 if (!bFrameStarted) return;
733 VkViewport viewport{};
734 viewport.x = x;
735 viewport.y = y;
736 viewport.width = width;
737 viewport.height = height;
738 viewport.minDepth = minDepth;
739 viewport.maxDepth = maxDepth;
740 vkCmdSetViewport(command, 0, 1, &viewport);
741}
742
743/// Stores the clear color used by the next BeginRender.
744void VulkanRenderer::ClearRenderTarget(float r, float g, float b,
745 float a) {
746 clearColor = {{r, g, b, a}};
747}
748
749/// No-op; depth/stencil clears are driven by the render pass clear values.
750void VulkanRenderer::ClearDepthStencil(bool clearDepth, bool clearStencil,
751 float depth, uint8_t stencil) {
752 // Handled by render pass clear values
753}
754
755/// Binds a vertex buffer slot, switching to the pipeline that matches the
756/// buffer's registered vertex format.
758 uint32_t slot) {
759 if (!bFrameStarted) return;
760 auto* vkBuf = static_cast<VulkanBuffer*>(buffer.get());
761 if (!vkBuf) return;
762
763 VertexFormatHandle wantFormat = buffer->GetVertexFormat();
764 if (wantFormat != 0) {
765 BeginCustomFormatPass(wantFormat);
766 } else if (m_activeCustomFormat != 0) {
768 }
769
770 VkBuffer buffers[] = {vkBuf->GetVkBuffer()};
771 VkDeviceSize offsets[] = {0};
772 vkCmdBindVertexBuffers(command, slot, 1, buffers, offsets);
773}
774
775/// Binds a 32-bit index buffer.
777 uint32_t slot) {
778 if (!bFrameStarted) return;
779 auto* vkBuf = static_cast<VulkanBuffer*>(buffer.get());
780 if (!vkBuf) return;
781 vkCmdBindIndexBuffer(command, vkBuf->GetVkBuffer(), 0,
782 VK_INDEX_TYPE_UINT32);
783}
784
785/// Pushes constant-buffer data via push constants, applying TAA jitter or the
786/// shadow push-constant cache. A shadow push that would repeat the bytes
787/// already pushed in this pass is skipped.
789 uint32_t slot) {
790 if (!bFrameStarted) return;
791 auto* vkBuf = static_cast<VulkanBuffer*>(buffer.get());
792 if (!vkBuf) return;
793
794 // Use push constants — recorded into the command buffer per draw call
795 void* data = vkBuf->GetData();
796 if (!data) return;
797
798 uint32_t size = static_cast<uint32_t>(vkBuf->GetSize());
799 if (size > PUSH_CONSTANT_BYTES) size = PUSH_CONSTANT_BYTES;
800
801 // Choose the pipeline layout that owns the currently bound pipeline.
802 // GBuffer geometry pass uses m_gbufferGeomLayout; all other passes use pipelineLay.
803 VkPipelineLayout activeLayout = (m_inGeometryPass && m_gbufferGeomLayout != VK_NULL_HANDLE)
804 ? m_gbufferGeomLayout : pipelineLay;
805
806 // In the geometry pass (not shadow), apply TAA sub-pixel jitter to WVP.
807 // Sub-pixel jitter: add jx*col3 to col0 and jy*col3 to col1.
808 // Y is negated because the geometry shader flips gl_Position.y.
809 if (m_inGeometryPass && !m_shadowPassActive && m_taaEnabled &&
810 (m_taaJitter[0] != 0.0f || m_taaJitter[1] != 0.0f) && size >= 64) {
811 float jdata[32];
812 memcpy(jdata, data, size);
813 const float jx = m_taaJitter[0] * 2.0f; // UV → NDC
814 const float jy = -m_taaJitter[1] * 2.0f; // negate for Y-flip
815 // GLSL computes WVP_cpu^T * v, so clip.x is dot(col0, v).
816 // Adding jx*col3 to col0 adds jx*clip.w to clip.x → uniform NDC shift.
817 for (int r = 0; r < 4; ++r) {
818 jdata[r * 4 + 0] += jx * jdata[r * 4 + 3]; // col0 += jx * col3
819 jdata[r * 4 + 1] += jy * jdata[r * 4 + 3]; // col1 += jy * col3
820 }
821 vkCmdPushConstants(command, activeLayout,
822 VK_SHADER_STAGE_VERTEX_BIT, 0, size, jdata);
823 m_shadowPCPushedLayout = VK_NULL_HANDLE;
824 return;
825 }
826
827 if (m_shadowPassActive && slot == 0 && size >= PUSH_CONSTANT_BYTES) {
828 // Shadow mode: push [LightVP*World (64)][World (64)].
829 // Buffer layout: [WVP (64 bytes)][World (64 bytes)].
830 // LightVP is frame-constant, so memoize on World and reuse the result
831 // across the many draws that share the identity transform.
832 const float* srcWorld = reinterpret_cast<const float*>(
833 static_cast<const char*>(data) + 64);
834
835 if (!m_shadowPCCacheValid ||
836 memcmp(srcWorld, m_shadowWorldCache, 64) != 0) {
837 // shadowWVP = World * LightVP (row-major)
838 for (int r = 0; r < 4; ++r) {
839 for (int c = 0; c < 4; ++c) {
840 float sum = 0.0f;
841 for (int k = 0; k < 4; ++k) {
842 sum += srcWorld[r * 4 + k] * m_lightVP[k * 4 + c];
843 }
844 m_shadowPCCache[r * 4 + c] = sum;
845 }
846 }
847 memcpy(&m_shadowPCCache[16], srcWorld, 64);
848 memcpy(m_shadowWorldCache, srcWorld, 64);
849 m_shadowPCCacheValid = true;
850 m_shadowPCPushedLayout = VK_NULL_HANDLE;
851 }
852
853 // Pushes survive pipeline binds
854 if (m_shadowPCPushedLayout != activeLayout) {
855 vkCmdPushConstants(command, activeLayout,
856 VK_SHADER_STAGE_VERTEX_BIT, 0,
857 PUSH_CONSTANT_BYTES, m_shadowPCCache);
858 m_shadowPCPushedLayout = activeLayout;
859 }
860 } else {
861 vkCmdPushConstants(command, activeLayout,
862 VK_SHADER_STAGE_VERTEX_BIT, 0, size, data);
863 m_shadowPCPushedLayout = VK_NULL_HANDLE;
864 }
865}
866
867/// Allocates and initializes a VulkanBuffer.
869 void* data) {
870 auto* buffer = new VulkanBuffer(device, physicalDevice, size, type,
871 commands, graphicsQueue);
872 if (!buffer->Initialize(data)) {
873 delete buffer;
874 return nullptr;
875 }
876 return buffer;
877}
878
879/// Compiles a VulkanShader from source.
880Shader* VulkanRenderer::CreateShader(const std::string& shaderSource) {
881 auto* shader = new VulkanShader(device);
882 if (shader->compile(shaderSource)) {
883 return shader;
884 }
885 delete shader;
886 return nullptr;
887}
888
889/// Loads a texture from disk and writes its descriptor sets.
890::Sleak::Texture* VulkanRenderer::CreateTexture(const std::string& TexturePath) {
891 auto* texture = new VulkanTexture(device, physicalDevice, commands,
892 graphicsQueue);
893 if (texture->LoadFromFile(TexturePath)) {
894 WriteTextureDescriptors(texture);
895 return texture;
896 }
897 delete texture;
898 return nullptr;
899}
900
901/// Loads a texture from an in-memory RGBA8 buffer.
903 uint32_t height,
904 void* data) {
905 auto* texture = new VulkanTexture(device, physicalDevice, commands,
906 graphicsQueue);
907 if (texture->LoadFromMemory(data, width, height, TextureFormat::RGBA8)) {
908 return texture;
909 }
910 delete texture;
911 return nullptr;
912}
913
914/// Loads a cubemap from six face images and writes it into the skybox
915/// descriptor sets.
917 const std::array<std::string, 6>& facePaths) {
918 auto* texture = new VulkanCubemapTexture(device, physicalDevice,
919 commands, graphicsQueue);
920 if (texture->LoadCubemap(facePaths)) {
921 // Create skybox pipeline if not already created
922 if (skyboxPipeline == VK_NULL_HANDLE) {
923 if (!CreateSkyboxPipeline()) {
924 SLEAK_ERROR("VulkanRenderer: Failed to create skybox pipeline");
925 delete texture;
926 return nullptr;
927 }
928 }
929
930 // Write cubemap to skybox descriptor sets
931 m_skyboxCubemapView = texture->GetImageView();
932 m_skyboxCubemapSampler = texture->GetSampler();
933 ++m_skyboxViewSerial;
934 for (size_t i = 0; i < skyboxDescriptorSets.size(); i++) {
935 VkDescriptorImageInfo imageInfo{};
936 imageInfo.imageLayout =
937 VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
938 imageInfo.imageView = m_skyboxCubemapView;
939 imageInfo.sampler = m_skyboxCubemapSampler;
940
941 VkWriteDescriptorSet descriptorWrite{};
942 descriptorWrite.sType =
943 VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
944 descriptorWrite.dstSet = skyboxDescriptorSets[i];
945 descriptorWrite.dstBinding = 0;
946 descriptorWrite.dstArrayElement = 0;
947 descriptorWrite.descriptorType =
948 VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
949 descriptorWrite.descriptorCount = 1;
950 descriptorWrite.pImageInfo = &imageInfo;
951
952 vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0,
953 nullptr);
954 }
955 m_skyboxDescriptorsWritten = true;
956
957 return texture;
958 }
959 delete texture;
960 return nullptr;
961}
962
963/// Loads an equirectangular panorama as a cubemap and writes it into the
964/// skybox descriptor sets.
966 const std::string& panoramaPath) {
967 auto* texture = new VulkanCubemapTexture(device, physicalDevice,
968 commands, graphicsQueue);
969 if (texture->LoadEquirectangular(panoramaPath)) {
970 // Create skybox pipeline if not already created
971 if (skyboxPipeline == VK_NULL_HANDLE) {
972 if (!CreateSkyboxPipeline()) {
973 SLEAK_ERROR("VulkanRenderer: Failed to create skybox pipeline");
974 delete texture;
975 return nullptr;
976 }
977 }
978
979 // Write cubemap to skybox descriptor sets
980 m_skyboxCubemapView = texture->GetImageView();
981 m_skyboxCubemapSampler = texture->GetSampler();
982 ++m_skyboxViewSerial;
983 for (size_t i = 0; i < skyboxDescriptorSets.size(); i++) {
984 VkDescriptorImageInfo imageInfo{};
985 imageInfo.imageLayout =
986 VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
987 imageInfo.imageView = m_skyboxCubemapView;
988 imageInfo.sampler = m_skyboxCubemapSampler;
989
990 VkWriteDescriptorSet descriptorWrite{};
991 descriptorWrite.sType =
992 VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
993 descriptorWrite.dstSet = skyboxDescriptorSets[i];
994 descriptorWrite.dstBinding = 0;
995 descriptorWrite.dstArrayElement = 0;
996 descriptorWrite.descriptorType =
997 VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
998 descriptorWrite.descriptorCount = 1;
999 descriptorWrite.pImageInfo = &imageInfo;
1000
1001 vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0,
1002 nullptr);
1003 }
1004 m_skyboxDescriptorsWritten = true;
1005
1006 // Trigger IBL precompute now that we have an environment cubemap
1007 return texture;
1008 }
1009 delete texture;
1010 return nullptr;
1011}
1012
1013/// Binds a texture's descriptor set at slot 0, skipping cubemaps and the
1014/// GBuffer geometry pass.
1016 uint32_t slot) {
1017 if (!bFrameStarted) return;
1018 if (!texture.IsValid() || slot != 0)
1019 return;
1020
1021 // Cubemap textures are bound via skybox pass, skip here
1022 if (texture->GetType() == TextureType::TextureCube)
1023 return;
1024
1025 auto* vkTex = static_cast<VulkanTexture*>(texture.get());
1026 if (!vkTex || !vkTex->HasDescriptorSets())
1027 return;
1028
1029 const auto& sets = vkTex->GetDescriptorSets();
1030 if (CurrentFrameIndex < sets.size()) {
1031 // In the GBuffer geometry pass set 0 is the PBR material descriptor set
1032 // (m_pbrMaterialDSL, bound by BindPBRMaterial via m_gbufferGeomLayout).
1033 // Binding a forward single-sampler descriptor set here with the wrong
1034 // layout would corrupt set 0 and trigger VK_ERROR_DEVICE_LOST.
1035 // BindPBRMaterial owns set 0 during the geometry pass — skip here.
1036 if (m_inGeometryPass)
1037 return;
1038 vkCmdBindDescriptorSets(
1039 command, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLay, 0, 1,
1040 &sets[CurrentFrameIndex], 0, nullptr);
1041 }
1042}
1043
1044/// Raw-pointer variant of BindTexture.
1045void VulkanRenderer::BindTextureRaw(Sleak::Texture* texture, uint32_t slot) {
1046 if (!bFrameStarted) return;
1047 if (!texture || slot != 0)
1048 return;
1049
1050 // Cubemap textures are bound via skybox pass, skip here
1051 if (texture->GetType() == TextureType::TextureCube)
1052 return;
1053
1054 auto* vkTex = static_cast<VulkanTexture*>(texture);
1055 if (!vkTex || !vkTex->HasDescriptorSets())
1056 return;
1057
1058 const auto& sets = vkTex->GetDescriptorSets();
1059 if (CurrentFrameIndex < sets.size()) {
1060 // In the GBuffer geometry pass set 0 is the PBR material descriptor set
1061 // (m_pbrMaterialDSL, bound by BindPBRMaterial via m_gbufferGeomLayout).
1062 // Binding a forward single-sampler descriptor set here with the wrong
1063 // layout would corrupt set 0 and trigger VK_ERROR_DEVICE_LOST.
1064 // BindPBRMaterial owns set 0 during the geometry pass — skip here.
1065 if (m_inGeometryPass)
1066 return;
1067 vkCmdBindDescriptorSets(
1068 command, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLay, 0, 1,
1069 &sets[CurrentFrameIndex], 0, nullptr);
1070 }
1071}
1072
1073/// Allocates one primary command buffer per frame in flight.
1074bool VulkanRenderer::CreateCommandBuffer() {
1075 commandBuffers.resize(MAX_FRAMES_IN_FLIGHT);
1076
1077 VkCommandBufferAllocateInfo allocInfo{};
1078 allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1079 allocInfo.commandPool = commands;
1080 allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1081 allocInfo.commandBufferCount = MAX_FRAMES_IN_FLIGHT;
1082
1083 if (vkAllocateCommandBuffers(device, &allocInfo,
1084 commandBuffers.data()) != VK_SUCCESS)
1085 SLEAK_RETURN_ERR("Failed to allocate command buffers!");
1086
1087 return true;
1088}
1089
1090/// Blocks until the device finishes all submitted GPU work.
1092 if (device) vkDeviceWaitIdle(device);
1093}
1094
1095/// Submits the open upload batch for this frame. A frame that failed to
1096/// start leaves it open, so it rides along with the next submitted frame.
1098 if (!bFrameStarted) return;
1099 m_asyncFlush[currentFrame] = VulkanBuffer::FlushPendingCopiesAsync(
1100 m_transferSemaphores[currentFrame]);
1101}
1102
1103/// Returns total bytes currently allocated by VulkanBuffer.
1105 return static_cast<size_t>(VulkanBuffer::GetTotalAllocatedBytes());
1106}
1107
1108/// Returns the device-local heap size reported by the allocator.
1110 return static_cast<size_t>(VulkanBuffer::GetDeviceLocalHeapSize());
1111}
1112
1113/// Tears down every Vulkan resource in reverse dependency order.
1115 SLEAK_INFO("Cleaning Vulkan...");
1116
1117 bRender = false;
1118
1119 // Wait for the device to finish all work
1120 if (device) {
1121 vkDeviceWaitIdle(device);
1123 }
1124
1126
1127 // Flush all deferred buffer deletions now that GPU is idle
1129
1130 // Shutdown ImGUI before destroying Vulkan resources
1131 if (bImInitialized) {
1132 ImGui_ImplVulkan_Shutdown();
1133 ImGui_ImplSDL3_Shutdown();
1134 ImGui::DestroyContext();
1135 bImInitialized = false;
1136 }
1137 if (imguiDescriptorPool) {
1138 vkDestroyDescriptorPool(device, imguiDescriptorPool, nullptr);
1139 imguiDescriptorPool = VK_NULL_HANDLE;
1140 }
1141
1142 DestroyPipelineCache();
1143
1144 // Drain released textures
1145 if (device) {
1146 delete m_defaultTexture;
1147 m_defaultTexture = nullptr;
1149 }
1150
1151 // Destroy descriptor pool (frees descriptor sets too)
1152 if (descriptorPool) {
1153 vkDestroyDescriptorPool(device, descriptorPool, nullptr);
1154 descriptorPool = VK_NULL_HANDLE;
1155 }
1156 descriptorSets.clear();
1157
1158 // Destroy skybox resources
1159 if (skyboxPipeline) {
1160 vkDestroyPipeline(device, skyboxPipeline, nullptr);
1161 skyboxPipeline = VK_NULL_HANDLE;
1162 }
1163 if (skyboxDescriptorPool) {
1164 vkDestroyDescriptorPool(device, skyboxDescriptorPool, nullptr);
1165 skyboxDescriptorPool = VK_NULL_HANDLE;
1166 }
1167 skyboxDescriptorSets.clear();
1168 delete skyboxShader;
1169 skyboxShader = nullptr;
1170
1171 // Destroy skinned pipeline resources
1172 if (skinnedPipeline) {
1173 vkDestroyPipeline(device, skinnedPipeline, nullptr);
1174 skinnedPipeline = VK_NULL_HANDLE;
1175 }
1176 delete skinnedShader;
1177 skinnedShader = nullptr;
1178
1179 // Destroy debug line pipeline resources
1180 if (debugLinePipeline) {
1181 vkDestroyPipeline(device, debugLinePipeline, nullptr);
1182 debugLinePipeline = VK_NULL_HANDLE;
1183 }
1184 delete debugLineShader;
1185 debugLineShader = nullptr;
1186
1187 // Destroy custom vertex format pipelines
1188 DestroyCustomFormatPipelines();
1189
1190 // Destroy MSAA color resources
1191 CleanupMSAAColorResources();
1192
1193 // Destroy deferred GBuffer resources
1194 CleanupGBufferResources();
1195
1196 // Destroy shadow mapping resources
1197 CleanupShadowResources();
1198 CleanupSceneReadResources();
1199
1200 // Backstop: free any shader modules whose resource-guarded cleanup was
1201 // skipped (guard false while shader non-null). Cleanups null after delete,
1202 // so these are no-ops when already freed — delete(nullptr) is safe.
1203 delete m_gbufferShader; m_gbufferShader = nullptr;
1204 delete m_lightingShader; m_lightingShader = nullptr;
1205 delete m_ssaoShader; m_ssaoShader = nullptr;
1206 delete m_ssaoBlurShader; m_ssaoBlurShader = nullptr;
1207 delete m_ssrShader; m_ssrShader = nullptr;
1208 delete m_taaShader; m_taaShader = nullptr;
1209 delete m_bloomThresholdShader; m_bloomThresholdShader = nullptr;
1210 delete m_bloomDownsampleShader; m_bloomDownsampleShader = nullptr;
1211 delete m_bloomUpsampleShader; m_bloomUpsampleShader = nullptr;
1212 delete m_bloomCompositeShader; m_bloomCompositeShader = nullptr;
1213
1214 // Destroy bone UBO resources
1215 CleanupBoneUBOResources();
1216
1217 // Destroy descriptor set layouts
1218 if (m_shadowSamplerDescriptorSetLayout) {
1219 vkDestroyDescriptorSetLayout(device, m_shadowSamplerDescriptorSetLayout, nullptr);
1220 m_shadowSamplerDescriptorSetLayout = VK_NULL_HANDLE;
1221 }
1222 if (m_lightUBODescriptorSetLayout) {
1223 vkDestroyDescriptorSetLayout(device, m_lightUBODescriptorSetLayout, nullptr);
1224 m_lightUBODescriptorSetLayout = VK_NULL_HANDLE;
1225 }
1226 if (boneDescriptorSetLayout) {
1227 vkDestroyDescriptorSetLayout(device, boneDescriptorSetLayout, nullptr);
1228 boneDescriptorSetLayout = VK_NULL_HANDLE;
1229 }
1230 if (descriptorSetLayout) {
1231 vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr);
1232 descriptorSetLayout = VK_NULL_HANDLE;
1233 }
1234
1235 // Clean up depth resources
1236 CleanupDepthResources();
1237
1238 // Destroy swapchain
1239 if (swapChain && device) {
1240 vkDestroySwapchainKHR(device, swapChain, nullptr);
1241 swapChain = VK_NULL_HANDLE;
1242 }
1243
1244 // Destroy framebuffers
1245 for (auto& buffer : swapChainFramebuffers) {
1246 if (buffer) {
1247 vkDestroyFramebuffer(device, buffer, nullptr);
1248 buffer = VK_NULL_HANDLE;
1249 }
1250 }
1251 swapChainFramebuffers.clear();
1252
1253 // Destroy image views
1254 for (auto& imgView : swapChainImageViews) {
1255 if (imgView) {
1256 vkDestroyImageView(device, imgView, nullptr);
1257 imgView = VK_NULL_HANDLE;
1258 }
1259 }
1260 swapChainImageViews.clear();
1261
1262 // Destroy sync objects
1263 for (auto& sem : imageAvailableSemaphores) {
1264 if (sem) vkDestroySemaphore(device, sem, nullptr);
1265 }
1266 imageAvailableSemaphores.clear();
1267
1268 for (auto& sem : renderFinishedSemaphores) {
1269 if (sem) vkDestroySemaphore(device, sem, nullptr);
1270 }
1271 renderFinishedSemaphores.clear();
1272
1273 for (auto& fence : inFlightFences) {
1274 if (fence) vkDestroyFence(device, fence, nullptr);
1275 }
1276 inFlightFences.clear();
1277
1278 // Destroy transfer semaphores and free any pending staging buffers
1279 for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
1280 if (m_transferSemaphores[i]) {
1281 vkDestroySemaphore(device, m_transferSemaphores[i], nullptr);
1282 m_transferSemaphores[i] = VK_NULL_HANDLE;
1283 }
1284 auto& af = m_asyncFlush[i];
1285 if (af.commandBuffer != VK_NULL_HANDLE) {
1286 vkFreeCommandBuffers(af.device, af.commandPool, 1,
1287 &af.commandBuffer);
1288 }
1289 for (auto& pending : af.stagingBuffers) {
1290 vmaDestroyBuffer(VulkanBuffer::GetAllocator(), pending.buffer,
1291 pending.memory);
1292 VulkanBuffer::UntrackAllocation(pending.allocSize);
1293 }
1294 af = {};
1295 }
1296
1297 // Destroy shader
1298 if (simpleShader) {
1299 delete simpleShader;
1300 simpleShader = nullptr;
1301 }
1302
1303 // Destroy pipeline
1304 if (pipeline) {
1305 vkDestroyPipeline(device, pipeline, nullptr);
1306 pipeline = VK_NULL_HANDLE;
1307 }
1308
1309 // Destroy pipeline layout
1310 if (pipelineLay) {
1311 vkDestroyPipelineLayout(device, pipelineLay, nullptr);
1312 pipelineLay = VK_NULL_HANDLE;
1313 }
1314
1315 // Destroy render pass
1316 if (renderPass) {
1317 vkDestroyRenderPass(device, renderPass, nullptr);
1318 renderPass = VK_NULL_HANDLE;
1319 }
1320
1321 // Destroy command pool (this will also free command buffers)
1322 if (commands) {
1323 vkDestroyCommandPool(device, commands, nullptr);
1324 commands = VK_NULL_HANDLE;
1325 }
1326
1327 // Destroy surface after swapchain is gone
1328 if (surface && instance) {
1329 vkDestroySurfaceKHR(instance, surface, nullptr);
1330 surface = VK_NULL_HANDLE;
1331 }
1332
1333 // Destroy debug messenger
1334 if (debugMessenger && vkDestroyDebugUtilsMessengerEXT) {
1335 vkDestroyDebugUtilsMessengerEXT(instance, debugMessenger, nullptr);
1336 debugMessenger = VK_NULL_HANDLE;
1337 }
1338
1339 CleanupGpuProfiler();
1340 CleanupFrameCapture();
1341
1342 // Drain any buffers freed during teardown, then destroy the VMA allocator
1343 // (it must outlive every vmaDestroyBuffer, and both precede vkDestroyDevice).
1346
1347 // Destroy logical device
1348 if (device) {
1349 vkDestroyDevice(device, nullptr);
1350 device = VK_NULL_HANDLE;
1351 }
1352
1353 // Destroy Vulkan instance
1354 if (instance) {
1355 vkDestroyInstance(instance, nullptr);
1356 instance = VK_NULL_HANDLE;
1357 }
1358}
1359
1360/// Recreates the swapchain when the surface extent no longer matches it.
1361void VulkanRenderer::Resize(uint32_t width, uint32_t height) {
1362 if (device && (swapChain == VK_NULL_HANDLE || SurfaceExtentChanged())) {
1363 RecreateSwapChain();
1364 }
1365}
1366
1367/// Rebuilds the swapchain and its dependents (image views, depth, MSAA,
1368/// framebuffers, GBuffer) after a resize or resolution change.
1369bool VulkanRenderer::RecreateSwapChain() {
1370 vkDeviceWaitIdle(device);
1371
1372 // Cleanup GBuffer BEFORE CleanupSwapChain (which destroys depth image)
1373 // to avoid dangling image view references in GBuffer framebuffer
1374 bool hadGBuffer = m_gbufferResourcesCreated;
1375 CleanupGBufferResources();
1376
1377 CleanupMSAAColorResources();
1378 CleanupSwapChain();
1379
1380 if (!CreateSwapChain()) {
1381 SLEAK_ERROR("Failed to recreate swap chain!");
1382 return false;
1383 }
1384 if (!CreateImageViews()) {
1385 SLEAK_ERROR("Failed to recreate image views!");
1386 return false;
1387 }
1388 if (!CreateDepthResources()) {
1389 SLEAK_ERROR("Failed to recreate depth resources!");
1390 return false;
1391 }
1392 if (!CreateMSAAColorResources()) {
1393 SLEAK_ERROR("Failed to recreate MSAA color resources!");
1394 return false;
1395 }
1396 if (!CreateFrameBuffer()) {
1397 SLEAK_ERROR("Failed to recreate framebuffers!");
1398 return false;
1399 }
1400
1401 if (!CreateImageSyncObjects()) {
1402 SLEAK_ERROR("Failed to recreate swapchain image semaphores!");
1403 return false;
1404 }
1405
1406 // Recreate GBuffer resources if they were previously created
1407 if (hadGBuffer && m_deferredEnabled) {
1408 if (!CreateGBufferResources())
1409 SLEAK_WARN("RecreateSwapChain: Failed to recreate GBuffer resources!");
1410 }
1411
1412 return true;
1413}
1414
1415/// Rebuilds the swapchain-dependent pipelines and render pass for a queued
1416/// MSAA sample count change.
1419 return;
1420 m_msaaChangeRequested = false;
1421
1422 uint32_t newCount = m_pendingMsaaSampleCount;
1423 m_msaaSampleCount = newCount;
1424
1425 // Convert to Vulkan enum
1426 switch (newCount) {
1427 case 1: m_msaaSamples = VK_SAMPLE_COUNT_1_BIT; break;
1428 case 2: m_msaaSamples = VK_SAMPLE_COUNT_2_BIT; break;
1429 case 4: m_msaaSamples = VK_SAMPLE_COUNT_4_BIT; break;
1430 case 8: m_msaaSamples = VK_SAMPLE_COUNT_8_BIT; break;
1431 default: m_msaaSamples = VK_SAMPLE_COUNT_1_BIT; break;
1432 }
1433
1434 SLEAK_INFO("Applying MSAA change: {}x", newCount);
1435
1436 vkDeviceWaitIdle(device);
1437
1438 // Destroy render pass
1439 if (renderPass) {
1440 vkDestroyRenderPass(device, renderPass, nullptr);
1441 renderPass = VK_NULL_HANDLE;
1442 }
1443
1444 // Destroy main-pass pipelines (NOT shadow pipeline)
1445 if (pipeline) {
1446 vkDestroyPipeline(device, pipeline, nullptr);
1447 pipeline = VK_NULL_HANDLE;
1448 }
1449 if (skyboxPipeline) {
1450 vkDestroyPipeline(device, skyboxPipeline, nullptr);
1451 skyboxPipeline = VK_NULL_HANDLE;
1452 }
1453 if (skinnedPipeline) {
1454 vkDestroyPipeline(device, skinnedPipeline, nullptr);
1455 skinnedPipeline = VK_NULL_HANDLE;
1456 }
1457 if (debugLinePipeline) {
1458 vkDestroyPipeline(device, debugLinePipeline, nullptr);
1459 debugLinePipeline = VK_NULL_HANDLE;
1460 }
1461 // Custom-format variants are built against the render passes torn down
1462 // here; drop them so the next draw rebuilds against the new ones.
1463 DestroyCustomFormatPipelines();
1464
1465 // Cleanup GBuffer BEFORE swapchain/depth (avoids dangling image view refs)
1466 CleanupGBufferResources();
1467
1468 // Shutdown ImGUI
1469 if (bImInitialized) {
1470 ImGui_ImplVulkan_Shutdown();
1471 ImGui_ImplSDL3_Shutdown();
1472 ImGui::DestroyContext();
1473 bImInitialized = false;
1474 }
1475 if (imguiDescriptorPool) {
1476 vkDestroyDescriptorPool(device, imguiDescriptorPool, nullptr);
1477 imguiDescriptorPool = VK_NULL_HANDLE;
1478 }
1479
1480 // Cleanup swapchain-related resources
1481 CleanupMSAAColorResources();
1482 CleanupSwapChain();
1483
1484 // Recreate everything
1485 CreateSwapChain();
1486 CreateImageSyncObjects();
1487 CreateImageViews();
1488 CreateDepthResources();
1489 CreateMSAAColorResources();
1490 CreateRenderPass();
1491 CreateFrameBuffer();
1492 CreateGraphicsPipeline();
1493 CreateSkyboxPipeline();
1494 CreateSkinnedPipeline();
1495 CreateDebugLinePipeline();
1496 if (m_deferredEnabled) CreateGBufferResources();
1497 CreateImGUI();
1498
1499 // Re-bind skybox cubemap texture to the new descriptor sets
1500 if (m_skyboxCubemapView != VK_NULL_HANDLE && m_skyboxCubemapSampler != VK_NULL_HANDLE) {
1501 for (size_t i = 0; i < skyboxDescriptorSets.size(); i++) {
1502 VkDescriptorImageInfo imageInfo{};
1503 imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
1504 imageInfo.imageView = m_skyboxCubemapView;
1505 imageInfo.sampler = m_skyboxCubemapSampler;
1506
1507 VkWriteDescriptorSet descriptorWrite{};
1508 descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
1509 descriptorWrite.dstSet = skyboxDescriptorSets[i];
1510 descriptorWrite.dstBinding = 0;
1511 descriptorWrite.dstArrayElement = 0;
1512 descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1513 descriptorWrite.descriptorCount = 1;
1514 descriptorWrite.pImageInfo = &imageInfo;
1515
1516 vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0, nullptr);
1517 }
1518 m_skyboxDescriptorsWritten = true;
1519 }
1520
1521 SLEAK_INFO("MSAA change applied successfully");
1522}
1523
1524/// Recreates the swapchain to apply a queued VSync toggle.
1527 return;
1528 m_vsyncChangeRequested = false;
1529 RecreateSwapChain();
1530 SLEAK_INFO("VSync {}", m_vsync ? "enabled" : "disabled");
1531}
1532
1533/// No-op; Vulkan polygon mode changes require pipeline recreation.
1535 // Pipeline recreation needed for Vulkan polygon mode changes
1536}
1537
1538/// No-op; Vulkan cull mode changes require pipeline recreation.
1540 // Pipeline recreation needed for Vulkan cull mode changes
1541}
1542
1543/// Creates the graphics command pool.
1544bool VulkanRenderer::CreateCommandPool() {
1545 VkCommandPoolCreateInfo poolInfo{};
1546 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
1547 poolInfo.queueFamilyIndex = QueueIDs.GraphicsIndex;
1548 poolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
1549
1550 if (vkCreateCommandPool(device, &poolInfo, nullptr, &commands) !=
1551 VK_SUCCESS)
1552 SLEAK_RETURN_ERR("Failed to create command pool!");
1553
1554 return true;
1555}
1556
1557/// Grows the per-image semaphores to the swapchain image count and clears
1558/// the image-to-fence table. Existing semaphores are kept: a present may
1559/// still reference them, and indices beyond the image count are harmless.
1560bool VulkanRenderer::CreateImageSyncObjects() {
1561 const size_t imageCount = swapChainImages.size();
1562 imagesInFlight.assign(imageCount, VK_NULL_HANDLE);
1563
1564 VkSemaphoreCreateInfo semaphoreInfo{};
1565 semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
1566
1567 while (imageAvailableSemaphores.size() < imageCount) {
1568 VkSemaphore available = VK_NULL_HANDLE;
1569 VkSemaphore finished = VK_NULL_HANDLE;
1570 if (vkCreateSemaphore(device, &semaphoreInfo, nullptr, &available) !=
1571 VK_SUCCESS ||
1572 vkCreateSemaphore(device, &semaphoreInfo, nullptr, &finished) !=
1573 VK_SUCCESS) {
1574 if (available) vkDestroySemaphore(device, available, nullptr);
1575 SLEAK_RETURN_ERR("Failed to create synchronization objects!");
1576 }
1577 imageAvailableSemaphores.push_back(available);
1578 renderFinishedSemaphores.push_back(finished);
1579 }
1580 return true;
1581}
1582
1583/// Creates the per-swapchain-image semaphores and per-frame fences and
1584/// transfer semaphores.
1585bool VulkanRenderer::CreateSyncObjects() {
1586 if (!CreateImageSyncObjects()) return false;
1587 inFlightFences.resize(MAX_FRAMES_IN_FLIGHT);
1588
1589 VkSemaphoreCreateInfo semaphoreInfo{};
1590 semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
1591
1592 VkFenceCreateInfo fenceInfo{};
1593 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1594 fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
1595
1596 // Create per-frame-in-flight fences and transfer semaphores
1597 for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
1598 if (vkCreateSemaphore(device, &semaphoreInfo, nullptr,
1599 &m_transferSemaphores[i]) != VK_SUCCESS ||
1600 vkCreateFence(device, &fenceInfo, nullptr,
1601 &inFlightFences[i]) != VK_SUCCESS) {
1602 SLEAK_RETURN_ERR("Failed to create synchronization objects!");
1603 }
1604 m_asyncFlush[i] = {};
1605 }
1606
1607 m_semaphoreIndex = 0;
1608 return true;
1609}
1610
1611/// Recreates the extent-dependent shadow map objects (image, view,
1612/// framebuffer) at the queued resolution. Keep in sync with
1613/// CreateShadowResources; samplers, render pass, and pipeline are extent-independent.
1615 if (!m_shadowResChangeRequested) return;
1617 if (!m_shadowResourcesCreated) return;
1619
1620 vkDeviceWaitIdle(device);
1621
1622 vkDestroyFramebuffer(device, m_shadowFramebuffer, nullptr);
1623 m_shadowFramebuffer = VK_NULL_HANDLE;
1624 vkDestroyImageView(device, m_shadowImageView, nullptr);
1625 m_shadowImageView = VK_NULL_HANDLE;
1626 vkDestroyImage(device, m_shadowImage, nullptr);
1627 m_shadowImage = VK_NULL_HANDLE;
1628 vkFreeMemory(device, m_shadowImageMemory, nullptr);
1629 m_shadowImageMemory = VK_NULL_HANDLE;
1630
1632 m_shadowMapRendered = false;
1633
1634 VkImageCreateInfo imageInfo{};
1635 imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
1636 imageInfo.imageType = VK_IMAGE_TYPE_2D;
1637 imageInfo.extent = {m_shadowMapResolution, m_shadowMapResolution, 1};
1638 imageInfo.mipLevels = 1;
1639 imageInfo.arrayLayers = 1;
1640 imageInfo.format = VK_FORMAT_D32_SFLOAT;
1641 imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
1642 imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
1643 imageInfo.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT |
1644 VK_IMAGE_USAGE_SAMPLED_BIT;
1645 imageInfo.samples = VK_SAMPLE_COUNT_1_BIT;
1646 imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
1647
1648 if (vkCreateImage(device, &imageInfo, nullptr, &m_shadowImage) !=
1649 VK_SUCCESS) {
1650 SLEAK_ERROR("Shadow resolution change: image creation failed");
1652 return;
1653 }
1654
1655 VkMemoryRequirements memReqs;
1656 vkGetImageMemoryRequirements(device, m_shadowImage, &memReqs);
1657
1658 VkMemoryAllocateInfo allocInfo{};
1659 allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
1660 allocInfo.allocationSize = memReqs.size;
1661 allocInfo.memoryTypeIndex = FindMemoryType(
1662 memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
1663
1664 if (vkAllocateMemory(device, &allocInfo, nullptr, &m_shadowImageMemory) !=
1665 VK_SUCCESS) {
1666 SLEAK_ERROR("Shadow resolution change: memory allocation failed");
1668 return;
1669 }
1670 vkBindImageMemory(device, m_shadowImage, m_shadowImageMemory, 0);
1671
1672 VkImageViewCreateInfo viewInfo{};
1673 viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
1674 viewInfo.image = m_shadowImage;
1675 viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
1676 viewInfo.format = VK_FORMAT_D32_SFLOAT;
1677 viewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
1678 viewInfo.subresourceRange.baseMipLevel = 0;
1679 viewInfo.subresourceRange.levelCount = 1;
1680 viewInfo.subresourceRange.baseArrayLayer = 0;
1681 viewInfo.subresourceRange.layerCount = 1;
1682
1683 if (vkCreateImageView(device, &viewInfo, nullptr, &m_shadowImageView) !=
1684 VK_SUCCESS) {
1685 SLEAK_ERROR("Shadow resolution change: image view creation failed");
1687 return;
1688 }
1689
1690 VkFramebufferCreateInfo fbInfo{};
1691 fbInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
1692 fbInfo.renderPass = m_shadowRenderPass;
1693 fbInfo.attachmentCount = 1;
1694 fbInfo.pAttachments = &m_shadowImageView;
1695 fbInfo.width = m_shadowMapResolution;
1696 fbInfo.height = m_shadowMapResolution;
1697 fbInfo.layers = 1;
1698
1699 if (vkCreateFramebuffer(device, &fbInfo, nullptr, &m_shadowFramebuffer) !=
1700 VK_SUCCESS) {
1701 SLEAK_ERROR("Shadow resolution change: framebuffer creation failed");
1703 return;
1704 }
1705
1706 // Initial layout transition — descriptor must be valid pre-first-pass
1707 {
1708 VkCommandBufferAllocateInfo cmdAllocInfo{};
1709 cmdAllocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1710 cmdAllocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1711 cmdAllocInfo.commandPool = commands;
1712 cmdAllocInfo.commandBufferCount = 1;
1713
1714 VkCommandBuffer cmdBuf;
1715 vkAllocateCommandBuffers(device, &cmdAllocInfo, &cmdBuf);
1716
1717 VkCommandBufferBeginInfo cmdBeginInfo{};
1718 cmdBeginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1719 cmdBeginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
1720 vkBeginCommandBuffer(cmdBuf, &cmdBeginInfo);
1721
1722 // Clear to far depth
1723 VkClearValue clear{};
1724 clear.depthStencil = {1.0f, 0};
1725 VkRenderPassBeginInfo clearPass{};
1726 clearPass.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
1727 clearPass.renderPass = m_shadowRenderPass;
1728 clearPass.framebuffer = m_shadowFramebuffer;
1729 clearPass.renderArea.extent = {m_shadowMapResolution,
1731 clearPass.clearValueCount = 1;
1732 clearPass.pClearValues = &clear;
1733 vkCmdBeginRenderPass(cmdBuf, &clearPass, VK_SUBPASS_CONTENTS_INLINE);
1734 vkCmdEndRenderPass(cmdBuf);
1735
1736 vkEndCommandBuffer(cmdBuf);
1737
1738 VkSubmitInfo layoutSubmit{};
1739 layoutSubmit.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1740 layoutSubmit.commandBufferCount = 1;
1741 layoutSubmit.pCommandBuffers = &cmdBuf;
1742
1743 VkFenceCreateInfo layoutFenceInfo{};
1744 layoutFenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1745 VkFence layoutFence;
1746 vkCreateFence(device, &layoutFenceInfo, nullptr, &layoutFence);
1747 vkQueueSubmit(graphicsQueue, 1, &layoutSubmit, layoutFence);
1748 vkWaitForFences(device, 1, &layoutFence, VK_TRUE, UINT64_MAX);
1749 vkDestroyFence(device, layoutFence, nullptr);
1750 vkFreeCommandBuffers(device, commands, 1, &cmdBuf);
1751 }
1752
1753 // Point set-3 descriptors at the new image view
1754 if (m_lightUBOCreated && m_shadowImageView && m_shadowSampler &&
1755 m_shadowRawSampler) {
1756 for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; ++i) {
1757 VkDescriptorImageInfo compareInfo{};
1758 compareInfo.imageLayout =
1759 VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL;
1760 compareInfo.imageView = m_shadowImageView;
1761 compareInfo.sampler = m_shadowSampler;
1762
1763 VkDescriptorImageInfo rawInfo{};
1764 rawInfo.imageLayout =
1765 VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL;
1766 rawInfo.imageView = m_shadowImageView;
1767 rawInfo.sampler = m_shadowRawSampler;
1768
1769 std::array<VkWriteDescriptorSet, 2> writes{};
1770 writes[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
1771 writes[0].dstSet = m_shadowSamplerDescriptorSets[i];
1772 writes[0].dstBinding = 0;
1773 writes[0].dstArrayElement = 0;
1774 writes[0].descriptorType =
1775 VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1776 writes[0].descriptorCount = 1;
1777 writes[0].pImageInfo = &compareInfo;
1778
1779 writes[1] = writes[0];
1780 writes[1].dstBinding = 1;
1781 writes[1].pImageInfo = &rawInfo;
1782
1783 vkUpdateDescriptorSets(device,
1784 static_cast<uint32_t>(writes.size()),
1785 writes.data(), 0, nullptr);
1786 }
1787 }
1788
1789 SLEAK_INFO("VulkanRenderer: Shadow map resized to {}x{}",
1791}
1792
1793/// Top-level orchestrator for deferred rendering: creates the GBuffer color
1794/// images, then the render passes, descriptors, and pipelines that read
1795/// them. Shares the depth image from CreateDepthResources() (already SAMPLED_BIT).
1796bool VulkanRenderer::CreateGBufferResources() {
1797 if (m_gbufferResourcesCreated) return true;
1798
1799 // Create GBuffer color attachment images
1800 for (uint32_t i = 0; i < GBUFFER_COUNT; ++i) {
1801 VkImageCreateInfo imageInfo{};
1802 imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
1803 imageInfo.imageType = VK_IMAGE_TYPE_2D;
1804 imageInfo.extent.width = scExtent.width;
1805 imageInfo.extent.height = scExtent.height;
1806 imageInfo.extent.depth = 1;
1807 imageInfo.mipLevels = 1;
1808 imageInfo.arrayLayers = 1;
1809 imageInfo.format = m_gbufferFormats[i];
1810 imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
1811 imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
1812 imageInfo.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT
1813 | VK_IMAGE_USAGE_SAMPLED_BIT;
1814 imageInfo.samples = VK_SAMPLE_COUNT_1_BIT;
1815 imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
1816
1817 if (vkCreateImage(device, &imageInfo, nullptr, &m_gbufferImages[i]) != VK_SUCCESS) {
1818 SLEAK_ERROR("GBuffer: Failed to create GBuffer image {}!", i);
1819 return false;
1820 }
1821
1822 VkMemoryRequirements memReqs;
1823 vkGetImageMemoryRequirements(device, m_gbufferImages[i], &memReqs);
1824
1825 VkMemoryAllocateInfo allocInfo{};
1826 allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
1827 allocInfo.allocationSize = memReqs.size;
1828 allocInfo.memoryTypeIndex = FindMemoryType(memReqs.memoryTypeBits,
1829 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
1830
1831 if (vkAllocateMemory(device, &allocInfo, nullptr, &m_gbufferMemory[i]) != VK_SUCCESS) {
1832 SLEAK_ERROR("GBuffer: Failed to allocate GBuffer memory {}!", i);
1833 return false;
1834 }
1835 vkBindImageMemory(device, m_gbufferImages[i], m_gbufferMemory[i], 0);
1836
1837 VkImageViewCreateInfo viewInfo{};
1838 viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
1839 viewInfo.image = m_gbufferImages[i];
1840 viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
1841 viewInfo.format = m_gbufferFormats[i];
1842 viewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1843 viewInfo.subresourceRange.baseMipLevel = 0;
1844 viewInfo.subresourceRange.levelCount = 1;
1845 viewInfo.subresourceRange.baseArrayLayer = 0;
1846 viewInfo.subresourceRange.layerCount = 1;
1847
1848 if (vkCreateImageView(device, &viewInfo, nullptr, &m_gbufferViews[i]) != VK_SUCCESS) {
1849 SLEAK_ERROR("GBuffer: Failed to create GBuffer image view {}!", i);
1850 return false;
1851 }
1852 }
1853
1854 if (!CreateGBufferRenderPass()) { SLEAK_ERROR("GBuffer: render pass failed!"); return false; }
1855 if (!CreateGBufferFramebuffer()) { SLEAK_ERROR("GBuffer: framebuffer failed!"); return false; }
1856 // SSAO + bloom must be created BEFORE the lighting/forward render passes
1857 // and BEFORE CreateGBufferDescriptorSets — the lighting pass framebuffers
1858 // reference m_hdrSceneView (created by CreateBloomResources) and the
1859 // GBuffer sampler set 0 binding 7 samples the SSAO blur result.
1860 if (!CreateSSAOResources()) { SLEAK_ERROR("GBuffer: SSAO resources failed!"); return false; }
1861 if (!CreateBloomResources()) { SLEAK_ERROR("GBuffer: bloom/HDR resources failed!"); return false; }
1862 if (!CreateSceneCopyImages())
1863 SLEAK_WARN(
1864 "GBuffer: scene snapshot images failed, transparent formats cannot "
1865 "read the scene");
1866 // SSR needs the HDR scene view (created by CreateBloomResources), so it
1867 // must come after that. The bloom composite pass later samples SSR.
1868 if (!CreateSSRResources()) { SLEAK_ERROR("GBuffer: SSR resources failed!"); return false; }
1869 // Prime the disabled-effect fallback images once so the per-frame disabled
1870 // paths can skip their redundant clears (ssao/ssr/bloom).
1871 m_ssaoFallbackPrimed = false;
1872 m_ssrFallbackPrimed = false;
1873 m_bloomFallbackPrimed = false;
1874 InitDisabledEffectFallbacks();
1875 if (!CreateGBufferDescriptorSets()) { SLEAK_ERROR("GBuffer: descriptor sets failed!"); return false; }
1876 if (!CreateDeferredCBResources()) { SLEAK_ERROR("GBuffer: deferred CB failed!"); return false; }
1877 if (!CreatePBRMaterialResources()) { SLEAK_ERROR("GBuffer: PBR material resources failed!"); return false; }
1878 if (!CreateIBLResources()) { SLEAK_ERROR("GBuffer: IBL resources failed!"); return false; }
1879 if (!CreateLightingRenderPass()) { SLEAK_ERROR("GBuffer: lighting RP failed!"); return false; }
1880 if (!CreateLightingFramebuffers()) { SLEAK_ERROR("GBuffer: lighting FBs failed!"); return false; }
1881 if (!CreateLightingPipeline()) { SLEAK_ERROR("GBuffer: lighting pipeline failed!"); return false; }
1882 if (!CreateForwardRenderPass()) { SLEAK_ERROR("GBuffer: forward RP failed!"); return false; }
1883 if (!CreateForwardFramebuffers()) { SLEAK_ERROR("GBuffer: forward FBs failed!"); return false; }
1884 if (!CreateGBufferPipeline()) { SLEAK_ERROR("GBuffer: gbuffer pipeline failed!"); return false; }
1885 if (!CreateSkinnedGbufferPipeline()) { SLEAK_ERROR("GBuffer: skinned gbuffer pipeline failed!"); return false; }
1886
1887 // Now that SSAO inputs (gNormalRough, gDepth) and SSAO blur
1888 // descriptor set 0 target are available, write SSAO descriptors.
1889 UpdateSSAODescriptors();
1890 // SSR input descriptors depend on m_gbufferViews + m_hdrSceneView, both
1891 // created above — safe to write now.
1892 UpdateSSRDescriptors();
1893
1894 // Recreate forward-pass pipelines so they use m_forwardRenderPass instead
1895 // of the main renderPass (which may have different attachments when MSAA
1896 // is active, or an incompatible finalLayout).
1897 if (m_forwardRenderPass != VK_NULL_HANDLE) {
1898 if (pipeline) { vkDestroyPipeline(device, pipeline, nullptr); pipeline = VK_NULL_HANDLE; }
1899 if (skyboxPipeline) { vkDestroyPipeline(device, skyboxPipeline, nullptr); skyboxPipeline = VK_NULL_HANDLE; }
1900 if (debugLinePipeline) { vkDestroyPipeline(device, debugLinePipeline, nullptr); debugLinePipeline = VK_NULL_HANDLE; }
1901 if (skinnedPipeline) {
1902 vkDestroyPipeline(device, skinnedPipeline, nullptr);
1903 skinnedPipeline = VK_NULL_HANDLE;
1904 }
1905 DestroyCustomFormatPipelines();
1906
1907 CreateGraphicsPipeline();
1908 CreateSkyboxPipeline();
1909 CreateDebugLinePipeline();
1910 CreateSkinnedPipeline();
1911
1912 m_gbufferResourcesCreated = true;
1913
1914 // Re-bind skybox cubemap to the newly allocated descriptor sets
1915 if (m_skyboxCubemapView != VK_NULL_HANDLE && m_skyboxCubemapSampler != VK_NULL_HANDLE) {
1916 for (size_t i = 0; i < skyboxDescriptorSets.size(); i++) {
1917 VkDescriptorImageInfo imageInfo{};
1918 imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
1919 imageInfo.imageView = m_skyboxCubemapView;
1920 imageInfo.sampler = m_skyboxCubemapSampler;
1921
1922 VkWriteDescriptorSet descriptorWrite{};
1923 descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
1924 descriptorWrite.dstSet = skyboxDescriptorSets[i];
1925 descriptorWrite.dstBinding = 0;
1926 descriptorWrite.dstArrayElement = 0;
1927 descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1928 descriptorWrite.descriptorCount = 1;
1929 descriptorWrite.pImageInfo = &imageInfo;
1930
1931 vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0, nullptr);
1932 }
1933 m_skyboxDescriptorsWritten = true;
1934 }
1935
1936 PrebuildCustomFormatPipelines();
1937 }
1938
1939 SLEAK_INFO("VulkanRenderer: Deferred GBuffer resources created ({}x{})",
1940 scExtent.width, scExtent.height);
1941 return true;
1942}
1943
1944}
1945}
int width
int height
#define SLEAK_ERROR(...)
Definition Logger.hpp:22
#define SLEAK_RETURN_ERR(...)
Definition Logger.hpp:25
#define SLEAK_INFO(...)
Definition Logger.hpp:20
#define SLEAK_WARN(...)
Definition Logger.hpp:21
#define PUSH_CONSTANT_BYTES
static std::string GetValue(const std::string &flag, const std::string &defaultVal="")
Returns the raw string value stored for -flag, or defaultVal if it was not passed.
static bool HasFlag(const std::string &flag)
True if --flag was present on the command line.
T * get() const
Definition RefPtr.hpp:170
Backend-agnostic GPU buffer: vertex, index, constant, or resource view target.
static RenderCommandQueue * GetInstance()
Lazily creates and returns the process-wide singleton instance.
virtual void ConfigureRenderMode()=0
Applies the current RenderMode (fill/wireframe/points) to backend state.
virtual void ConfigureRenderFace()=0
Applies the current RenderFace (cull mode) to backend state.
void UpdateFrameMetrics()
Rolls up frame count into rate/time/triangle stats once per MetricUpdateInterval.
Definition Renderer.hpp:267
void SetPerformanceCounter(bool value)
Definition Renderer.hpp:149
static void RegisterCreateCubemapTextureFromPanorama(T *instance, Texture *(T::*method)(const std::string &))
static void RegisterCreateCubemapTexture(T *instance, Texture *(T::*method)(const std::array< std::string, 6 > &))
static void RegisterCreateBuffer(T *instance, BufferBase *(T::*method)(BufferType, uint32_t, void *))
static void RegisterCreateShader(T *instance, Shader *(T::*method)(const std::string &))
static void RegisterCreateTextureFromMemory(std::function< Texture *(const void *, uint32_t, uint32_t, TextureFormat, uint32_t)> func)
static void RegisterCreateTexture(T *instance, Texture *(T::*method)(const std::string &))
Backend-agnostic compiled shader program.
Definition Shader.hpp:11
VMA-backed Vulkan buffer with staging uploads, batched copies, and a size-bucketed recycling pool.
static void ProcessDeferredDeletions(uint32_t maxFramesInFlight)
static VkDeviceSize GetTotalAllocatedBytes()
static void UntrackAllocation(VkDeviceSize size)
static void DestroyAllocator()
Destroys the staging pool and the allocator once every buffer is freed.
VulkanBuffer(VkDevice device, VkPhysicalDevice physicalDevice, uint32_t size, BufferType type, VkCommandPool commandPool, VkQueue graphicsQueue)
static AsyncFlushResult FlushPendingCopiesAsync(VkSemaphore signalSemaphore)
static VmaAllocator GetAllocator()
static VkDeviceSize GetDeviceLocalHeapSize()
static void SetBatchingEnabled(bool enabled)
VulkanCubemapTexture(VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
virtual size_t GetGPUMemoryBudget() const override
Returns the device-local heap size reported by the allocator.
virtual bool CreateImGUI() override
Initializes ImGui and its Vulkan backend against the active render pass.
virtual size_t GetGPUMemoryUsed() const override
Returns total bytes currently allocated by VulkanBuffer.
virtual void Draw(uint32_t vertexCount) override
Issues a non-indexed draw call and updates the vertex/triangle counters.
void ApplyShadowResolutionChange() override
Recreates the extent-dependent shadow map objects at the queued resolution.
virtual void SetViewport(float x, float y, float width, float height, float minDepth=0.0f, float maxDepth=1.0f) override
Sets the dynamic viewport on the active command buffer.
virtual void BindTexture(RefPtr< Sleak::Texture > texture, uint32_t slot=0) override
Binds a texture's descriptor set at slot 0, skipping cubemaps and the GBuffer geometry pass.
virtual void BindIndexBuffer(RefPtr< BufferBase > buffer, uint32_t slot=0) override
Binds a 32-bit index buffer.
virtual void ClearDepthStencil(bool clearDepth, bool clearStencil, float depth, uint8_t stencil) override
No-op; depth/stencil clears are driven by the render pass clear values.
virtual void DrawInstance(uint32_t instanceCount, uint32_t vertexPerInstance) override
Issues an instanced, non-indexed draw call.
virtual void FlushPendingTransfers() override
virtual void WaitIdle() override
Blocks until the device finishes all submitted GPU work.
virtual void SetRenderMode(RenderMode mode) override
Stores the polygon mode for the next pipeline rebuild (Vulkan state is baked).
virtual void BindTextureRaw(Sleak::Texture *texture, uint32_t slot=0) override
Raw-pointer variant of BindTexture.
virtual Shader * CreateShader(const std::string &shaderSource) override
Compiles a VulkanShader from source.
virtual void Cleanup() override
Tears down every Vulkan resource in reverse dependency order.
virtual void DrawIndexed(uint32_t indexCount) override
Issues an indexed draw call and updates the vertex/triangle counters.
virtual BufferBase * CreateBuffer(BufferType Type, uint32_t size, void *data) override
Allocates and initializes a VulkanBuffer.
~VulkanRenderer()
Calls Cleanup() to tear down all Vulkan resources.
void ApplyVSyncChange() override
Recreates the swapchain to apply a queued VSync toggle.
virtual void EndCustomFormatPass() override
Restores the previous pipeline and descriptor set after custom-format draws.
virtual Texture * CreateTextureFromData(uint32_t width, uint32_t height, void *data) override
Loads a texture from an in-memory RGBA8 buffer.
virtual void BindConstantBuffer(RefPtr< BufferBase > buffer, uint32_t slot=0) override
virtual void EndRender() override
Ends the active render pass, submits the command buffer, and presents.
virtual Texture * CreateTexture(const std::string &TexturePath) override
Loads a texture from disk and writes its descriptor sets.
virtual void SetRenderFace(RenderFace face) override
Stores the cull face for the next pipeline rebuild (Vulkan state is baked).
Texture * CreateCubemapTexture(const std::array< std::string, 6 > &facePaths)
Loads a cubemap from six face images and writes it into the skybox descriptor sets.
virtual void DrawIndexedInstance(uint32_t instanceCount, uint32_t indexPerInstance) override
Issues an instanced, indexed draw call.
Texture * CreateCubemapTextureFromPanorama(const std::string &panoramaPath)
Loads an equirectangular panorama as a cubemap and writes it into the skybox descriptor sets.
virtual void ClearRenderTarget(float r, float g, float b, float a) override
Stores the clear color used by the next BeginRender.
virtual void Resize(uint32_t width, uint32_t height) override
Recreates the swapchain for the new window dimensions.
virtual void BindVertexBuffer(RefPtr< BufferBase > buffer, uint32_t slot=0) override
virtual void BeginCustomFormatPass(VertexFormatHandle format) override
Binds the custom-format pipeline matching the currently active render pass.
Vulkan 2D texture: image + view + sampler, with per-swapchain-image descriptor sets.
static void DestroyReleased(uint64_t completedSerial)
Destroys released textures whose stamped submission has completed.
const std::vector< VkDescriptorSet > & GetDescriptorSets() const
VulkanTexture(VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
static void SetReleaseSerial(uint64_t serial)
static void DestroyAllReleased()
Destroys every released texture; the caller guarantees the GPU is idle.
virtual bool IsValid() const
True if the pointer is non-null.
virtual TextureType GetType() const =0
TextureFormat
Definition Texture.hpp:10
Backend-facing rendering layer shared by the four graphics backends.
RenderMode
Rasterizer fill style for a draw.
BufferType
GPU buffer usage kind, drives backend binding flags and layout.
RenderFace
Which triangle winding gets culled.
Root namespace for everything the engine exposes.
Definition Camera.hpp:10
uint32_t VertexFormatHandle