9#include <SDL3/SDL_vulkan.h>
31#include "SDL3/SDL_error.h"
32#include "SDL3/SDL_video.h"
34 #include "vulkan/vulkan_wayland.h"
35#elif defined(PLATFORM_WIN)
36 #include <vulkan/vulkan_win32.h>
47 clearColor = {{0.3f, 0.4f, 1.0f, 1.0f}};
62 auto* tex =
new VulkanTexture(device, physicalDevice, commands, graphicsQueue);
63 tex->SetMaxMipLevels(maxMip);
64 if (tex->LoadFromMemory(data, w, h, fmt)) {
65 WriteTextureDescriptors(tex);
86 if (!SetupDebugMessenger()) {
87 SLEAK_WARN(
"Failed to setup validation layer of vulkan instance")
96 CreatePipelineCache();
98 if (!CreateSwapChain())
101 if (!CreateImageViews())
104 if (!CreateDepthResources())
107 if (!CreateMSAAColorResources())
110 if (!CreateRenderPass())
113 if (!CreateDescriptorSetLayout())
116 if (!CreateDescriptorPool())
119 if (!AllocateDescriptorSets())
122 if (!CreateCommandPool())
125 if (!CreateCommandBuffer())
128 if (!CreateDefaultTexture())
129 SLEAK_WARN(
"Failed to create default white texture for Vulkan");
131 if (!CreateMainPipelineLayout())
134 if (!CreateShadowLightUBOResources())
135 SLEAK_WARN(
"Failed to create light UBO resources — dynamic lighting disabled");
137 if (!CreateSceneReadResources())
139 "Failed to create scene-read resources for transparent formats");
141 if (!CreateShadowResources())
142 SLEAK_WARN(
"Failed to create shadow mapping resources — shadows disabled");
144 if (!CreateFrameBuffer())
149 if (!CreateGBufferResources())
150 SLEAK_WARN(
"Failed to create GBuffer resources — deferred rendering disabled");
154 if (pipeline == VK_NULL_HANDLE && !CreateGraphicsPipeline())
160 if (!CreateBoneUBOResources())
161 SLEAK_WARN(
"Failed to pre-create bone UBO resources — skinned meshes may malfunction on first frame");
163 if (!CreateSyncObjects())
170 SLEAK_INFO(
"Vulkan renderer has been initialized successfully!");
179 bFrameStarted =
false;
180 m_inGeometryPass =
false;
181 m_inForwardTransparentPass =
false;
182 m_forwardPassOpen =
false;
183 m_activeCustomFormat = 0;
184 m_sceneReadPrepared =
false;
190 if (m_hasPendingLightVP) {
191 memcpy(m_lightVP, m_pendingLightVP,
sizeof(m_lightVP));
201 PrebuildCustomFormatPipelines();
205 if (device && !inFlightFences.empty()) {
206 vkWaitForFences(device, 1, &inFlightFences[currentFrame],
207 VK_TRUE, UINT64_MAX);
211 UpdateSceneReadDescriptors(currentFrame);
216 auto& flush = m_asyncFlush[currentFrame];
217 if (flush.submitted) {
219 if (flush.commandBuffer != VK_NULL_HANDLE) {
220 vkFreeCommandBuffers(flush.device, flush.commandPool, 1,
221 &flush.commandBuffer);
223 for (
auto& pending : flush.stagingBuffers) {
227 pending.memoryTypeIndex);
238 auto beginSkippedUIFrame = [
this]() {
241 ImGui_ImplVulkan_NewFrame();
242 ImGui_ImplSDL3_NewFrame();
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) {
253 beginSkippedUIFrame();
255 }
else if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR) {
257 beginSkippedUIFrame();
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);
272 imagesInFlight[CurrentFrameIndex] = inFlightFences[currentFrame];
275 vkResetFences(device, 1, &inFlightFences[currentFrame]);
278 command = commandBuffers[currentFrame];
281 vkResetCommandBuffer(command, 0);
283 VkCommandBufferBeginInfo beginInfo{};
284 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
287 if (vkBeginCommandBuffer(command, &beginInfo) != VK_SUCCESS) {
292 bFrameStarted =
true;
293 m_pbrMaterialSlot[currentFrame] = 0;
294 m_pbrMaterialBindings[currentFrame].clear();
295 m_boneSlot[currentFrame] = 1;
300 bool hasShadowDraws = shadowQueue && shadowQueue->HasCachedShadowDraws();
303 VkClearValue shadowClear{};
304 shadowClear.depthStencil = {1.0f, 0};
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};
312 shadowPassInfo.clearValueCount = 1;
313 shadowPassInfo.pClearValues = &shadowClear;
315 BeginGpuPass(GpuPass::Shadow);
316 vkCmdBeginRenderPass(command, &shadowPassInfo, VK_SUBPASS_CONTENTS_INLINE);
317 vkCmdBindPipeline(command, VK_PIPELINE_BIND_POINT_GRAPHICS, m_shadowPipeline);
323 BindIdentityBonePalette(pipelineLay);
325 VkViewport shadowViewport{};
326 shadowViewport.x = 0.0f;
327 shadowViewport.y = 0.0f;
330 shadowViewport.minDepth = 0.0f;
331 shadowViewport.maxDepth = 1.0f;
332 vkCmdSetViewport(command, 0, 1, &shadowViewport);
334 VkRect2D shadowScissor{};
335 shadowScissor.offset = {0, 0};
337 vkCmdSetScissor(command, 0, 1, &shadowScissor);
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;
346 queue->ExecuteShadowPass(
this);
348 m_shadowPassActive =
false;
350 vkCmdEndRenderPass(command);
351 EndGpuPass(GpuPass::Shadow);
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};
361 gbufferClears[GBUFFER_COUNT].depthStencil = {1.0f, 0};
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;
372 BeginGpuPass(GpuPass::GBuffer);
373 vkCmdBeginRenderPass(command, &gbufferPassInfo, VK_SUBPASS_CONTENTS_INLINE);
374 vkCmdBindPipeline(command, VK_PIPELINE_BIND_POINT_GRAPHICS, m_gbufferPipeline);
377 VkViewport viewport{};
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);
387 scissor.offset = {0, 0};
388 scissor.extent = scExtent;
389 vkCmdSetScissor(command, 0, 1, &scissor);
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);
406 m_inGeometryPass =
true;
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) {
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;
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;
443 BeginGpuPass(GpuPass::Forward);
444 vkCmdBeginRenderPass(command, &passInfo, VK_SUBPASS_CONTENTS_INLINE);
446 vkCmdBindPipeline(command, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
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);
457 VkViewport viewport{};
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);
467 scissor.offset = {0, 0};
468 scissor.extent = scExtent;
469 vkCmdSetScissor(command, 0, 1, &scissor);
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);
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) {
499 if (!bRender || !bFrameStarted) {
506 const bool deferredPath =
512 vkCmdEndRenderPass(command);
513 EndGpuPass(GpuPass::GBuffer);
514 m_inGeometryPass =
false;
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;
535 if (m_forwardPassOpen) {
536 vkCmdEndRenderPass(command);
537 EndGpuPass(GpuPass::Forward);
538 m_forwardPassOpen =
false;
552 RenderBloomCompositePass();
557 EndGpuPass(GpuPass::Forward);
558 BeginGpuPass(GpuPass::UI);
563 ImGui_ImplVulkan_RenderDrawData(ImGui::GetDrawData(), command);
565 vkCmdEndRenderPass(command);
566 EndGpuPass(drawUI ? GpuPass::UI : GpuPass::Forward);
569 if (!m_capturePath.empty()) RecordFrameCaptureCopy();
572 if (vkEndCommandBuffer(command) != VK_SUCCESS) {
578 VkSubmitInfo submitInfo{};
579 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
582 VkSemaphore waitSemaphores[2];
583 VkPipelineStageFlags waitStages[2];
584 uint32_t waitCount = 0;
586 waitSemaphores[waitCount] = imageAvailableSemaphores[m_semaphoreIndex];
587 waitStages[waitCount] = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
590 if (m_asyncFlush[currentFrame].submitted) {
591 waitSemaphores[waitCount] = m_transferSemaphores[currentFrame];
592 waitStages[waitCount] = VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
596 submitInfo.waitSemaphoreCount = waitCount;
597 submitInfo.pWaitSemaphores = waitSemaphores;
598 submitInfo.pWaitDstStageMask = waitStages;
600 submitInfo.commandBufferCount = 1;
601 submitInfo.pCommandBuffers = &command;
606 VkSemaphore signalSemaphores[] = {renderFinishedSemaphores[CurrentFrameIndex]};
607 submitInfo.signalSemaphoreCount = 1;
608 submitInfo.pSignalSemaphores = signalSemaphores;
610 if (vkQueueSubmit(graphicsQueue, 1, &submitInfo,
611 inFlightFences[currentFrame]) != VK_SUCCESS) {
612 SLEAK_ERROR(
"Failed to submit draw command buffer!");
614 MarkGpuFrameSubmitted();
615 m_slotSerial[currentFrame] = ++m_submitSerial;
620 VkPresentInfoKHR presentInfo{};
621 presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
622 presentInfo.waitSemaphoreCount = 1;
623 presentInfo.pWaitSemaphores = signalSemaphores;
625 VkSwapchainKHR swapChains[] = {swapChain};
626 presentInfo.swapchainCount = 1;
627 presentInfo.pSwapchains = swapChains;
628 presentInfo.pImageIndices = &CurrentFrameIndex;
630 VkResult presentResult = vkQueuePresentKHR(presentQueue, &presentInfo);
633 if (presentResult == VK_ERROR_OUT_OF_DATE_KHR ||
634 (presentResult == VK_SUBOPTIMAL_KHR && !m_captureMode &&
635 SurfaceExtentChanged())) {
637 }
else if (presentResult != VK_SUCCESS &&
638 presentResult != VK_SUBOPTIMAL_KHR) {
642 if (m_captureRecorded) FinishFrameCapture();
645 m_forwardPassOpen =
false;
646 m_inForwardTransparentPass =
false;
647 m_inGeometryPass =
false;
648 bFrameStarted =
false;
650 currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT;
651 m_semaphoreIndex = (m_semaphoreIndex + 1) %
652 static_cast<uint32_t
>(imageAvailableSemaphores.size());
658bool VulkanRenderer::CustomFormatDrawsSuppressed()
const {
659 return m_activeCustomFormat != 0 && m_customFormatUnbound;
666 if (!bFrameStarted)
return;
667 if (CustomFormatDrawsSuppressed())
return;
668 vkCmdDraw(command, vertexCount, 1, firstVertex, 0);
669 if (!m_shadowPassActive) {
681 int32_t baseVertex) {
682 if (!bFrameStarted)
return;
683 if (CustomFormatDrawsSuppressed())
return;
684 vkCmdDrawIndexed(command, indexCount, 1, firstIndex, baseVertex, 0);
685 if (!m_shadowPassActive) {
693 uint32_t vertexPerInstance) {
694 if (!bFrameStarted)
return;
695 if (CustomFormatDrawsSuppressed())
return;
696 vkCmdDraw(command, vertexPerInstance, instanceCount, 0, 0);
701 uint32_t indexPerInstance) {
706 uint32_t indexPerInstance,
708 int32_t baseVertex) {
709 if (!bFrameStarted)
return;
710 if (CustomFormatDrawsSuppressed())
return;
711 vkCmdDrawIndexed(command, indexPerInstance, instanceCount, firstIndex,
730 float height,
float minDepth,
732 if (!bFrameStarted)
return;
733 VkViewport viewport{};
736 viewport.width =
width;
738 viewport.minDepth = minDepth;
739 viewport.maxDepth = maxDepth;
740 vkCmdSetViewport(command, 0, 1, &viewport);
746 clearColor = {{r, g, b, a}};
751 float depth, uint8_t stencil) {
759 if (!bFrameStarted)
return;
764 if (wantFormat != 0) {
766 }
else if (m_activeCustomFormat != 0) {
770 VkBuffer buffers[] = {vkBuf->GetVkBuffer()};
771 VkDeviceSize offsets[] = {0};
772 vkCmdBindVertexBuffers(command, slot, 1, buffers, offsets);
778 if (!bFrameStarted)
return;
781 vkCmdBindIndexBuffer(command, vkBuf->GetVkBuffer(), 0,
782 VK_INDEX_TYPE_UINT32);
790 if (!bFrameStarted)
return;
798 uint32_t size =
static_cast<uint32_t
>(vkBuf->GetSize());
803 VkPipelineLayout activeLayout = (m_inGeometryPass && m_gbufferGeomLayout != VK_NULL_HANDLE)
804 ? m_gbufferGeomLayout : pipelineLay;
809 if (m_inGeometryPass && !m_shadowPassActive &&
m_taaEnabled &&
810 (m_taaJitter[0] != 0.0f || m_taaJitter[1] != 0.0f) && size >= 64) {
812 memcpy(jdata, data, size);
813 const float jx = m_taaJitter[0] * 2.0f;
814 const float jy = -m_taaJitter[1] * 2.0f;
817 for (
int r = 0; r < 4; ++r) {
818 jdata[r * 4 + 0] += jx * jdata[r * 4 + 3];
819 jdata[r * 4 + 1] += jy * jdata[r * 4 + 3];
821 vkCmdPushConstants(command, activeLayout,
822 VK_SHADER_STAGE_VERTEX_BIT, 0, size, jdata);
823 m_shadowPCPushedLayout = VK_NULL_HANDLE;
832 const float* srcWorld =
reinterpret_cast<const float*
>(
833 static_cast<const char*
>(data) + 64);
835 if (!m_shadowPCCacheValid ||
836 memcmp(srcWorld, m_shadowWorldCache, 64) != 0) {
838 for (
int r = 0; r < 4; ++r) {
839 for (
int c = 0; c < 4; ++c) {
841 for (
int k = 0; k < 4; ++k) {
842 sum += srcWorld[r * 4 + k] * m_lightVP[k * 4 + c];
844 m_shadowPCCache[r * 4 + c] = sum;
847 memcpy(&m_shadowPCCache[16], srcWorld, 64);
848 memcpy(m_shadowWorldCache, srcWorld, 64);
849 m_shadowPCCacheValid =
true;
850 m_shadowPCPushedLayout = VK_NULL_HANDLE;
854 if (m_shadowPCPushedLayout != activeLayout) {
855 vkCmdPushConstants(command, activeLayout,
856 VK_SHADER_STAGE_VERTEX_BIT, 0,
858 m_shadowPCPushedLayout = activeLayout;
861 vkCmdPushConstants(command, activeLayout,
862 VK_SHADER_STAGE_VERTEX_BIT, 0, size, data);
863 m_shadowPCPushedLayout = VK_NULL_HANDLE;
870 auto* buffer =
new VulkanBuffer(device, physicalDevice, size, type,
871 commands, graphicsQueue);
872 if (!buffer->Initialize(data)) {
882 if (shader->compile(shaderSource)) {
891 auto* texture =
new VulkanTexture(device, physicalDevice, commands,
893 if (texture->LoadFromFile(TexturePath)) {
894 WriteTextureDescriptors(texture);
905 auto* texture =
new VulkanTexture(device, physicalDevice, commands,
917 const std::array<std::string, 6>& facePaths) {
919 commands, graphicsQueue);
920 if (texture->LoadCubemap(facePaths)) {
922 if (skyboxPipeline == VK_NULL_HANDLE) {
923 if (!CreateSkyboxPipeline()) {
924 SLEAK_ERROR(
"VulkanRenderer: Failed to create skybox pipeline");
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;
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;
952 vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0,
955 m_skyboxDescriptorsWritten =
true;
966 const std::string& panoramaPath) {
968 commands, graphicsQueue);
969 if (texture->LoadEquirectangular(panoramaPath)) {
971 if (skyboxPipeline == VK_NULL_HANDLE) {
972 if (!CreateSkyboxPipeline()) {
973 SLEAK_ERROR(
"VulkanRenderer: Failed to create skybox pipeline");
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;
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;
1001 vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0,
1004 m_skyboxDescriptorsWritten =
true;
1017 if (!bFrameStarted)
return;
1018 if (!texture.
IsValid() || slot != 0)
1026 if (!vkTex || !vkTex->HasDescriptorSets())
1030 if (CurrentFrameIndex < sets.size()) {
1036 if (m_inGeometryPass)
1038 vkCmdBindDescriptorSets(
1039 command, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLay, 0, 1,
1040 &sets[CurrentFrameIndex], 0,
nullptr);
1046 if (!bFrameStarted)
return;
1047 if (!texture || slot != 0)
1055 if (!vkTex || !vkTex->HasDescriptorSets())
1059 if (CurrentFrameIndex < sets.size()) {
1065 if (m_inGeometryPass)
1067 vkCmdBindDescriptorSets(
1068 command, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLay, 0, 1,
1069 &sets[CurrentFrameIndex], 0,
nullptr);
1074bool VulkanRenderer::CreateCommandBuffer() {
1075 commandBuffers.resize(MAX_FRAMES_IN_FLIGHT);
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;
1083 if (vkAllocateCommandBuffers(device, &allocInfo,
1084 commandBuffers.data()) != VK_SUCCESS)
1092 if (device) vkDeviceWaitIdle(device);
1098 if (!bFrameStarted)
return;
1100 m_transferSemaphores[currentFrame]);
1121 vkDeviceWaitIdle(device);
1132 ImGui_ImplVulkan_Shutdown();
1133 ImGui_ImplSDL3_Shutdown();
1134 ImGui::DestroyContext();
1137 if (imguiDescriptorPool) {
1138 vkDestroyDescriptorPool(device, imguiDescriptorPool,
nullptr);
1139 imguiDescriptorPool = VK_NULL_HANDLE;
1142 DestroyPipelineCache();
1146 delete m_defaultTexture;
1147 m_defaultTexture =
nullptr;
1152 if (descriptorPool) {
1153 vkDestroyDescriptorPool(device, descriptorPool,
nullptr);
1154 descriptorPool = VK_NULL_HANDLE;
1156 descriptorSets.clear();
1159 if (skyboxPipeline) {
1160 vkDestroyPipeline(device, skyboxPipeline,
nullptr);
1161 skyboxPipeline = VK_NULL_HANDLE;
1163 if (skyboxDescriptorPool) {
1164 vkDestroyDescriptorPool(device, skyboxDescriptorPool,
nullptr);
1165 skyboxDescriptorPool = VK_NULL_HANDLE;
1167 skyboxDescriptorSets.clear();
1168 delete skyboxShader;
1169 skyboxShader =
nullptr;
1172 if (skinnedPipeline) {
1173 vkDestroyPipeline(device, skinnedPipeline,
nullptr);
1174 skinnedPipeline = VK_NULL_HANDLE;
1176 delete skinnedShader;
1177 skinnedShader =
nullptr;
1180 if (debugLinePipeline) {
1181 vkDestroyPipeline(device, debugLinePipeline,
nullptr);
1182 debugLinePipeline = VK_NULL_HANDLE;
1184 delete debugLineShader;
1185 debugLineShader =
nullptr;
1188 DestroyCustomFormatPipelines();
1191 CleanupMSAAColorResources();
1194 CleanupGBufferResources();
1197 CleanupShadowResources();
1198 CleanupSceneReadResources();
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;
1215 CleanupBoneUBOResources();
1218 if (m_shadowSamplerDescriptorSetLayout) {
1219 vkDestroyDescriptorSetLayout(device, m_shadowSamplerDescriptorSetLayout,
nullptr);
1220 m_shadowSamplerDescriptorSetLayout = VK_NULL_HANDLE;
1222 if (m_lightUBODescriptorSetLayout) {
1223 vkDestroyDescriptorSetLayout(device, m_lightUBODescriptorSetLayout,
nullptr);
1224 m_lightUBODescriptorSetLayout = VK_NULL_HANDLE;
1226 if (boneDescriptorSetLayout) {
1227 vkDestroyDescriptorSetLayout(device, boneDescriptorSetLayout,
nullptr);
1228 boneDescriptorSetLayout = VK_NULL_HANDLE;
1230 if (descriptorSetLayout) {
1231 vkDestroyDescriptorSetLayout(device, descriptorSetLayout,
nullptr);
1232 descriptorSetLayout = VK_NULL_HANDLE;
1236 CleanupDepthResources();
1239 if (swapChain && device) {
1240 vkDestroySwapchainKHR(device, swapChain,
nullptr);
1241 swapChain = VK_NULL_HANDLE;
1245 for (
auto& buffer : swapChainFramebuffers) {
1247 vkDestroyFramebuffer(device, buffer,
nullptr);
1248 buffer = VK_NULL_HANDLE;
1251 swapChainFramebuffers.clear();
1254 for (
auto& imgView : swapChainImageViews) {
1256 vkDestroyImageView(device, imgView,
nullptr);
1257 imgView = VK_NULL_HANDLE;
1260 swapChainImageViews.clear();
1263 for (
auto& sem : imageAvailableSemaphores) {
1264 if (sem) vkDestroySemaphore(device, sem,
nullptr);
1266 imageAvailableSemaphores.clear();
1268 for (
auto& sem : renderFinishedSemaphores) {
1269 if (sem) vkDestroySemaphore(device, sem,
nullptr);
1271 renderFinishedSemaphores.clear();
1273 for (
auto& fence : inFlightFences) {
1274 if (fence) vkDestroyFence(device, fence,
nullptr);
1276 inFlightFences.clear();
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;
1284 auto& af = m_asyncFlush[i];
1285 if (af.commandBuffer != VK_NULL_HANDLE) {
1286 vkFreeCommandBuffers(af.device, af.commandPool, 1,
1289 for (
auto& pending : af.stagingBuffers) {
1299 delete simpleShader;
1300 simpleShader =
nullptr;
1305 vkDestroyPipeline(device, pipeline,
nullptr);
1306 pipeline = VK_NULL_HANDLE;
1311 vkDestroyPipelineLayout(device, pipelineLay,
nullptr);
1312 pipelineLay = VK_NULL_HANDLE;
1317 vkDestroyRenderPass(device, renderPass,
nullptr);
1318 renderPass = VK_NULL_HANDLE;
1323 vkDestroyCommandPool(device, commands,
nullptr);
1324 commands = VK_NULL_HANDLE;
1328 if (surface && instance) {
1329 vkDestroySurfaceKHR(instance, surface,
nullptr);
1330 surface = VK_NULL_HANDLE;
1334 if (debugMessenger && vkDestroyDebugUtilsMessengerEXT) {
1335 vkDestroyDebugUtilsMessengerEXT(instance, debugMessenger,
nullptr);
1336 debugMessenger = VK_NULL_HANDLE;
1339 CleanupGpuProfiler();
1340 CleanupFrameCapture();
1349 vkDestroyDevice(device,
nullptr);
1350 device = VK_NULL_HANDLE;
1355 vkDestroyInstance(instance,
nullptr);
1356 instance = VK_NULL_HANDLE;
1362 if (device && (swapChain == VK_NULL_HANDLE || SurfaceExtentChanged())) {
1363 RecreateSwapChain();
1369bool VulkanRenderer::RecreateSwapChain() {
1370 vkDeviceWaitIdle(device);
1374 bool hadGBuffer = m_gbufferResourcesCreated;
1375 CleanupGBufferResources();
1377 CleanupMSAAColorResources();
1380 if (!CreateSwapChain()) {
1384 if (!CreateImageViews()) {
1388 if (!CreateDepthResources()) {
1389 SLEAK_ERROR(
"Failed to recreate depth resources!");
1392 if (!CreateMSAAColorResources()) {
1393 SLEAK_ERROR(
"Failed to recreate MSAA color resources!");
1396 if (!CreateFrameBuffer()) {
1401 if (!CreateImageSyncObjects()) {
1402 SLEAK_ERROR(
"Failed to recreate swapchain image semaphores!");
1408 if (!CreateGBufferResources())
1409 SLEAK_WARN(
"RecreateSwapChain: Failed to recreate GBuffer resources!");
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;
1434 SLEAK_INFO(
"Applying MSAA change: {}x", newCount);
1436 vkDeviceWaitIdle(device);
1440 vkDestroyRenderPass(device, renderPass,
nullptr);
1441 renderPass = VK_NULL_HANDLE;
1446 vkDestroyPipeline(device, pipeline,
nullptr);
1447 pipeline = VK_NULL_HANDLE;
1449 if (skyboxPipeline) {
1450 vkDestroyPipeline(device, skyboxPipeline,
nullptr);
1451 skyboxPipeline = VK_NULL_HANDLE;
1453 if (skinnedPipeline) {
1454 vkDestroyPipeline(device, skinnedPipeline,
nullptr);
1455 skinnedPipeline = VK_NULL_HANDLE;
1457 if (debugLinePipeline) {
1458 vkDestroyPipeline(device, debugLinePipeline,
nullptr);
1459 debugLinePipeline = VK_NULL_HANDLE;
1463 DestroyCustomFormatPipelines();
1466 CleanupGBufferResources();
1470 ImGui_ImplVulkan_Shutdown();
1471 ImGui_ImplSDL3_Shutdown();
1472 ImGui::DestroyContext();
1475 if (imguiDescriptorPool) {
1476 vkDestroyDescriptorPool(device, imguiDescriptorPool,
nullptr);
1477 imguiDescriptorPool = VK_NULL_HANDLE;
1481 CleanupMSAAColorResources();
1486 CreateImageSyncObjects();
1488 CreateDepthResources();
1489 CreateMSAAColorResources();
1491 CreateFrameBuffer();
1492 CreateGraphicsPipeline();
1493 CreateSkyboxPipeline();
1494 CreateSkinnedPipeline();
1495 CreateDebugLinePipeline();
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;
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;
1516 vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0,
nullptr);
1518 m_skyboxDescriptorsWritten =
true;
1521 SLEAK_INFO(
"MSAA change applied successfully");
1529 RecreateSwapChain();
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;
1550 if (vkCreateCommandPool(device, &poolInfo,
nullptr, &commands) !=
1560bool VulkanRenderer::CreateImageSyncObjects() {
1561 const size_t imageCount = swapChainImages.size();
1562 imagesInFlight.assign(imageCount, VK_NULL_HANDLE);
1564 VkSemaphoreCreateInfo semaphoreInfo{};
1565 semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
1567 while (imageAvailableSemaphores.size() < imageCount) {
1568 VkSemaphore available = VK_NULL_HANDLE;
1569 VkSemaphore finished = VK_NULL_HANDLE;
1570 if (vkCreateSemaphore(device, &semaphoreInfo,
nullptr, &available) !=
1572 vkCreateSemaphore(device, &semaphoreInfo,
nullptr, &finished) !=
1574 if (available) vkDestroySemaphore(device, available,
nullptr);
1577 imageAvailableSemaphores.push_back(available);
1578 renderFinishedSemaphores.push_back(finished);
1585bool VulkanRenderer::CreateSyncObjects() {
1586 if (!CreateImageSyncObjects())
return false;
1587 inFlightFences.resize(MAX_FRAMES_IN_FLIGHT);
1589 VkSemaphoreCreateInfo semaphoreInfo{};
1590 semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
1592 VkFenceCreateInfo fenceInfo{};
1593 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1594 fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
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) {
1604 m_asyncFlush[i] = {};
1607 m_semaphoreIndex = 0;
1620 vkDeviceWaitIdle(device);
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;
1632 m_shadowMapRendered =
false;
1634 VkImageCreateInfo imageInfo{};
1635 imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
1636 imageInfo.imageType = VK_IMAGE_TYPE_2D;
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;
1648 if (vkCreateImage(device, &imageInfo,
nullptr, &m_shadowImage) !=
1650 SLEAK_ERROR(
"Shadow resolution change: image creation failed");
1655 VkMemoryRequirements memReqs;
1656 vkGetImageMemoryRequirements(device, m_shadowImage, &memReqs);
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);
1664 if (vkAllocateMemory(device, &allocInfo,
nullptr, &m_shadowImageMemory) !=
1666 SLEAK_ERROR(
"Shadow resolution change: memory allocation failed");
1670 vkBindImageMemory(device, m_shadowImage, m_shadowImageMemory, 0);
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;
1683 if (vkCreateImageView(device, &viewInfo,
nullptr, &m_shadowImageView) !=
1685 SLEAK_ERROR(
"Shadow resolution change: image view creation failed");
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;
1699 if (vkCreateFramebuffer(device, &fbInfo,
nullptr, &m_shadowFramebuffer) !=
1701 SLEAK_ERROR(
"Shadow resolution change: framebuffer creation failed");
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;
1714 VkCommandBuffer cmdBuf;
1715 vkAllocateCommandBuffers(device, &cmdAllocInfo, &cmdBuf);
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);
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;
1731 clearPass.clearValueCount = 1;
1732 clearPass.pClearValues = &clear;
1733 vkCmdBeginRenderPass(cmdBuf, &clearPass, VK_SUBPASS_CONTENTS_INLINE);
1734 vkCmdEndRenderPass(cmdBuf);
1736 vkEndCommandBuffer(cmdBuf);
1738 VkSubmitInfo layoutSubmit{};
1739 layoutSubmit.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1740 layoutSubmit.commandBufferCount = 1;
1741 layoutSubmit.pCommandBuffers = &cmdBuf;
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);
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;
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;
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;
1779 writes[1] = writes[0];
1780 writes[1].dstBinding = 1;
1781 writes[1].pImageInfo = &rawInfo;
1783 vkUpdateDescriptorSets(device,
1784 static_cast<uint32_t
>(writes.size()),
1785 writes.data(), 0,
nullptr);
1789 SLEAK_INFO(
"VulkanRenderer: Shadow map resized to {}x{}",
1796bool VulkanRenderer::CreateGBufferResources() {
1797 if (m_gbufferResourcesCreated)
return true;
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;
1817 if (vkCreateImage(device, &imageInfo,
nullptr, &m_gbufferImages[i]) != VK_SUCCESS) {
1818 SLEAK_ERROR(
"GBuffer: Failed to create GBuffer image {}!", i);
1822 VkMemoryRequirements memReqs;
1823 vkGetImageMemoryRequirements(device, m_gbufferImages[i], &memReqs);
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);
1831 if (vkAllocateMemory(device, &allocInfo,
nullptr, &m_gbufferMemory[i]) != VK_SUCCESS) {
1832 SLEAK_ERROR(
"GBuffer: Failed to allocate GBuffer memory {}!", i);
1835 vkBindImageMemory(device, m_gbufferImages[i], m_gbufferMemory[i], 0);
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;
1848 if (vkCreateImageView(device, &viewInfo,
nullptr, &m_gbufferViews[i]) != VK_SUCCESS) {
1849 SLEAK_ERROR(
"GBuffer: Failed to create GBuffer image view {}!", i);
1854 if (!CreateGBufferRenderPass()) {
SLEAK_ERROR(
"GBuffer: render pass failed!");
return false; }
1855 if (!CreateGBufferFramebuffer()) {
SLEAK_ERROR(
"GBuffer: framebuffer failed!");
return false; }
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())
1864 "GBuffer: scene snapshot images failed, transparent formats cannot "
1868 if (!CreateSSRResources()) {
SLEAK_ERROR(
"GBuffer: SSR resources failed!");
return false; }
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; }
1889 UpdateSSAODescriptors();
1892 UpdateSSRDescriptors();
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;
1905 DestroyCustomFormatPipelines();
1907 CreateGraphicsPipeline();
1908 CreateSkyboxPipeline();
1909 CreateDebugLinePipeline();
1910 CreateSkinnedPipeline();
1912 m_gbufferResourcesCreated =
true;
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;
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;
1931 vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0,
nullptr);
1933 m_skyboxDescriptorsWritten =
true;
1936 PrebuildCustomFormatPipelines();
1939 SLEAK_INFO(
"VulkanRenderer: Deferred GBuffer resources created ({}x{})",
1940 scExtent.width, scExtent.height);
#define SLEAK_RETURN_ERR(...)
#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.
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.
bool m_vsyncChangeRequested
void UpdateFrameMetrics()
Rolls up frame count into rate/time/triangle stats once per MetricUpdateInterval.
uint32_t m_msaaSampleCount
uint32_t m_pendingMsaaSampleCount
void SetPerformanceCounter(bool value)
bool m_shadowResChangeRequested
bool m_msaaChangeRequested
uint32_t m_shadowMapResolution
bool m_shadowResourcesCreated
uint32_t m_pendingShadowMapResolution
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.
VMA-backed Vulkan buffer with staging uploads, batched copies, and a size-bucketed recycling pool.
static void AdvanceDeletionFrame()
static void DiscardPendingCopies()
void * GetData() override
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.
static void FlushAllDeferredDeletions()
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.
VulkanRenderer(Window *window)
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.
void ApplyMSAAChange() override
virtual void BeginRender() override
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 bool Initialize() override
virtual void BeginCustomFormatPass(VertexFormatHandle format) override
Binds the custom-format pipeline matching the currently active render pass.
VulkanShader(VkDevice dev)
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
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.
uint32_t VertexFormatHandle