LCOV - code coverage report
Current view: top level - source/renderer/backend/vulkan - SwapChain.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 0 273 0.0 %
Date: 2026-12-03 01:19:39 Functions: 0 19 0.0 %

          Line data    Source code
       1             : /* Copyright (C) 2026 Wildfire Games.
       2             :  * This file is part of 0 A.D.
       3             :  *
       4             :  * 0 A.D. is free software: you can redistribute it and/or modify
       5             :  * it under the terms of the GNU General Public License as published by
       6             :  * the Free Software Foundation, either version 2 of the License, or
       7             :  * (at your option) any later version.
       8             :  *
       9             :  * 0 A.D. is distributed in the hope that it will be useful,
      10             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      11             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      12             :  * GNU General Public License for more details.
      13             :  *
      14             :  * You should have received a copy of the GNU General Public License
      15             :  * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
      16             :  */
      17             : 
      18             : #include "precompiled.h"
      19             : 
      20             : #include "SwapChain.h"
      21             : 
      22             : #include "graphics/Color.h"
      23             : #include "lib/debug.h"
      24             : #include "lib/hash.h"
      25             : #include "maths/MathUtil.h"
      26             : #include "ps/CLogger.h"
      27             : #include "ps/ConfigDB.h"
      28             : #include "ps/Profile.h"
      29             : #include "renderer/backend/ITexture.h"
      30             : #include "renderer/backend/Sampler.h"
      31             : #include "renderer/backend/vulkan/Device.h"
      32             : #include "renderer/backend/vulkan/DeviceSelection.h"
      33             : #include "renderer/backend/vulkan/Framebuffer.h"
      34             : #include "renderer/backend/vulkan/RingCommandContext.h"
      35             : #include "renderer/backend/vulkan/Texture.h"
      36             : #include "renderer/backend/vulkan/Utilities.h"
      37             : 
      38             : #include <algorithm>
      39             : #include <cstdio>
      40             : #include <iterator>
      41             : #include <limits>
      42             : #include <SDL_video.h>
      43             : #include <utility>
      44             : 
      45             : namespace Renderer
      46             : {
      47             : 
      48             : namespace Backend
      49             : {
      50             : 
      51             : namespace Vulkan
      52             : {
      53             : 
      54             : // static
      55           0 : std::unique_ptr<CSwapChain> CSwapChain::Create(
      56             :     CDevice* device, CSubmitScheduler* submitScheduler,
      57             :     const uint32_t queueFamilyIndex, VkQueue queue,
      58             :     const char* name, VkSurfaceKHR surface,
      59             :     int surfaceDrawableWidth, int surfaceDrawableHeight,
      60             :     const bool vsync, std::unique_ptr<ISwapChain> oldSwapChain)
      61             : {
      62             :     // We don't need to wait to destroy the depth texture as it's independent
      63             :     // from VkSwapchainKHR.
      64           0 :     if (oldSwapChain)
      65             :     {
      66           0 :         oldSwapChain->As<CSwapChain>()->m_DepthTexture.reset();
      67             : 
      68             :         // Workaround to free the depth texture immediately.
      69           0 :         device->OnSwapChainRecreation();
      70             :     }
      71             : 
      72             :     // It seems some drivers might not reuse the same swapchain memory. So
      73             :     // to avoid higher memory peaks destroy the old swapchain before.
      74           0 :     const bool destroyOldSwapchainBefore{
      75           0 :         g_ConfigDB.Get("renderer.backend.vulkan.destroyoldswapchainbefore", false)};
      76           0 :     if (destroyOldSwapchainBefore)
      77           0 :         oldSwapChain.reset();
      78             : 
      79           0 :     VkPhysicalDevice physicalDevice = device->GetChoosenPhysicalDevice().device;
      80             : 
      81           0 :     VkSurfaceCapabilitiesKHR surfaceCapabilities{};
      82           0 :     ENSURE_VK_SUCCESS(vkGetPhysicalDeviceSurfaceCapabilitiesKHR(
      83             :         physicalDevice, surface, &surfaceCapabilities));
      84             : 
      85           0 :     const uint32_t swapChainWidth = Clamp<uint32_t>(surfaceDrawableWidth,
      86             :         surfaceCapabilities.minImageExtent.width,
      87             :         surfaceCapabilities.maxImageExtent.width);
      88           0 :     const uint32_t swapChainHeight = Clamp<uint32_t>(surfaceDrawableHeight,
      89             :         surfaceCapabilities.minImageExtent.height,
      90             :         surfaceCapabilities.maxImageExtent.height);
      91             : 
      92             :     // Some drivers (for example NVIDIA on Windows during minimize) might
      93             :     // return zeroes for both minImageExtent and maxImageExtent. It means we're
      94             :     // not able to create any swapchain. Because we can't choose zeros (they're
      95             :     // not allowed) and we can't choose values bigger than maxImageExtent
      96             :     // (which are also zeroes in that case).
      97           0 :     if (swapChainWidth == 0 || swapChainHeight == 0)
      98           0 :         return nullptr;
      99             : 
     100           0 :     std::vector<VkSurfaceFormatKHR> surfaceFormats;
     101           0 :     uint32_t surfaceFormatCount = 0;
     102           0 :     ENSURE_VK_SUCCESS(vkGetPhysicalDeviceSurfaceFormatsKHR(
     103             :         physicalDevice, surface, &surfaceFormatCount, nullptr));
     104           0 :     if (surfaceFormatCount > 0)
     105             :     {
     106           0 :         surfaceFormats.resize(surfaceFormatCount);
     107           0 :         ENSURE_VK_SUCCESS(vkGetPhysicalDeviceSurfaceFormatsKHR(
     108             :             physicalDevice, surface, &surfaceFormatCount, surfaceFormats.data()));
     109             :     }
     110             : 
     111           0 :     std::vector<VkPresentModeKHR> presentModes;
     112           0 :     uint32_t presentModeCount = 0;
     113           0 :     ENSURE_VK_SUCCESS(vkGetPhysicalDeviceSurfacePresentModesKHR(
     114             :         physicalDevice, surface, &presentModeCount, nullptr));
     115           0 :     if (presentModeCount > 0)
     116             :     {
     117           0 :         presentModes.resize(presentModeCount);
     118           0 :         ENSURE_VK_SUCCESS(vkGetPhysicalDeviceSurfacePresentModesKHR(
     119             :             physicalDevice, surface, &presentModeCount, presentModes.data()));
     120             :     }
     121             : 
     122             :     // VK_PRESENT_MODE_FIFO_KHR is guaranteed to be supported.
     123           0 :     VkPresentModeKHR presentMode = VK_PRESENT_MODE_FIFO_KHR;
     124           0 :     auto isPresentModeAvailable = [&presentModes](const VkPresentModeKHR presentMode)
     125             :     {
     126           0 :         return std::find(presentModes.begin(), presentModes.end(), presentMode) != presentModes.end();
     127           0 :     };
     128           0 :     if (vsync)
     129             :     {
     130             :         // TODO: use the adaptive one when possible.
     131             :         // https://gitlab.freedesktop.org/mesa/mesa/-/issues/5516
     132             :         //if (isPresentModeAvailable(VK_PRESENT_MODE_MAILBOX_KHR))
     133             :         //  presentMode = VK_PRESENT_MODE_MAILBOX_KHR;
     134             :     }
     135             :     else
     136             :     {
     137           0 :         if (isPresentModeAvailable(VK_PRESENT_MODE_IMMEDIATE_KHR))
     138           0 :             presentMode = VK_PRESENT_MODE_IMMEDIATE_KHR;
     139             :     }
     140             : 
     141             :     // Spec says:
     142             :     //   The number of format pairs supported must be greater than or equal to 1.
     143             :     //   pSurfaceFormats must not contain an entry whose value for format is
     144             :     //   VK_FORMAT_UNDEFINED.
     145           0 :     const auto surfaceFormatIt =
     146           0 :         std::find_if(surfaceFormats.begin(), surfaceFormats.end(), IsSurfaceFormatSupported);
     147           0 :     if (surfaceFormatIt == surfaceFormats.end())
     148             :     {
     149           0 :         LOGERROR("Can't find a suitable surface format to render to.");
     150           0 :         return nullptr;
     151             :     }
     152           0 :     const VkSurfaceFormatKHR& surfaceFormat = *surfaceFormatIt;
     153             : 
     154           0 :     VkSwapchainCreateInfoKHR swapChainCreateInfo{};
     155           0 :     swapChainCreateInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
     156           0 :     swapChainCreateInfo.surface = surface;
     157             :     // minImageCount + 1 is to have a less chance for a presenter to wait.
     158             :     // maxImageCount might be zero, it means it's unlimited.
     159           0 :     const uint32_t maxImageCount = surfaceCapabilities.maxImageCount > 0
     160           0 :         ? surfaceCapabilities.maxImageCount
     161             :         : std::numeric_limits<uint32_t>::max();
     162           0 :     const uint32_t minImageCount = surfaceCapabilities.minImageCount < maxImageCount
     163           0 :         ? surfaceCapabilities.minImageCount + 1
     164             :         : surfaceCapabilities.minImageCount;
     165           0 :     swapChainCreateInfo.minImageCount =
     166           0 :         Clamp<uint32_t>(NUMBER_OF_FRAMES_IN_FLIGHT,
     167             :             minImageCount, maxImageCount);
     168           0 :     swapChainCreateInfo.imageFormat = surfaceFormat.format;
     169           0 :     swapChainCreateInfo.imageColorSpace = surfaceFormat.colorSpace;
     170           0 :     swapChainCreateInfo.imageExtent.width = swapChainWidth;
     171           0 :     swapChainCreateInfo.imageExtent.height = swapChainHeight;
     172           0 :     swapChainCreateInfo.imageArrayLayers = 1;
     173             :     // VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT is guaranteed to present.
     174             :     // VK_IMAGE_USAGE_TRANSFER_SRC_BIT allows a simpler backbuffer readback.
     175             :     // VK_IMAGE_USAGE_TRANSFER_DST_BIT allows a blit to the backbuffer.
     176             :     // VK_IMAGE_USAGE_STORAGE_BIT allows to write to the backbuffer directly
     177             :     // from a compute shader.
     178           0 :     swapChainCreateInfo.imageUsage =
     179           0 :         (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_STORAGE_BIT) &
     180           0 :             surfaceCapabilities.supportedUsageFlags;
     181           0 :     swapChainCreateInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
     182             :     // We need to set these only if imageSharingMode is VK_SHARING_MODE_CONCURRENT.
     183           0 :     swapChainCreateInfo.queueFamilyIndexCount = 0;
     184           0 :     swapChainCreateInfo.pQueueFamilyIndices = nullptr;
     185             :     // By default VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR is preferable.
     186           0 :     if (surfaceCapabilities.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR)
     187           0 :         swapChainCreateInfo.preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
     188             :     else
     189           0 :         swapChainCreateInfo.preTransform = surfaceCapabilities.currentTransform;
     190             :     // By default VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR is preferable, other bits
     191             :     // might require some format or rendering adjustemnts to avoid
     192             :     // semi-transparent areas.
     193           0 :     const VkCompositeAlphaFlagBitsKHR compositeAlphaOrder[] =
     194             :     {
     195             :         VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
     196             :         VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR,
     197             :         VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR,
     198             :         VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR
     199             :     };
     200           0 :     for (const VkCompositeAlphaFlagBitsKHR compositeAlpha : compositeAlphaOrder)
     201           0 :         if (compositeAlpha & surfaceCapabilities.supportedCompositeAlpha)
     202             :         {
     203           0 :             swapChainCreateInfo.compositeAlpha = compositeAlpha;
     204           0 :             break;
     205             :         }
     206           0 :     swapChainCreateInfo.presentMode = presentMode;
     207           0 :     swapChainCreateInfo.clipped = VK_TRUE;
     208           0 :     if (oldSwapChain)
     209           0 :         swapChainCreateInfo.oldSwapchain = oldSwapChain->As<CSwapChain>()->GetVkSwapchain();
     210             : 
     211           0 :     std::unique_ptr<CSwapChain> swapChain(new CSwapChain());
     212           0 :     swapChain->m_Device = device;
     213           0 :     swapChain->m_SubmitScheduler = submitScheduler;
     214           0 :     swapChain->m_Queue = queue;
     215             : 
     216           0 :     RETURN_NULLPTR_IF_NOT_VK_SUCCESS(vkCreateSwapchainKHR(
     217             :         device->GetVkDevice(), &swapChainCreateInfo, nullptr, &swapChain->m_SwapChain));
     218             : 
     219           0 :     device->SetObjectName(VK_OBJECT_TYPE_SWAPCHAIN_KHR, swapChain->m_SwapChain, name);
     220             : 
     221           0 :     uint32_t imageCount = 0;
     222           0 :     VkResult getSwapchainImagesResult = VK_INCOMPLETE;
     223           0 :     do
     224             :     {
     225           0 :         getSwapchainImagesResult = vkGetSwapchainImagesKHR(
     226           0 :             device->GetVkDevice(), swapChain->m_SwapChain, &imageCount, nullptr);
     227           0 :         if (getSwapchainImagesResult == VK_SUCCESS && imageCount > 0)
     228             :         {
     229           0 :             swapChain->m_Images.resize(imageCount);
     230           0 :             getSwapchainImagesResult = vkGetSwapchainImagesKHR(
     231           0 :                 device->GetVkDevice(), swapChain->m_SwapChain, &imageCount, swapChain->m_Images.data());
     232             :         }
     233           0 :     } while (getSwapchainImagesResult == VK_INCOMPLETE);
     234           0 :     LOGMESSAGE("SwapChain image count: {} (min: {})", imageCount, swapChainCreateInfo.minImageCount);
     235           0 :     ENSURE_VK_SUCCESS(getSwapchainImagesResult);
     236           0 :     ENSURE(imageCount > 0);
     237             : 
     238             :     // We create a depth texture to mimic GL behavior where SDL creates it for
     239             :     // a backbuffer.
     240           0 :     swapChain->m_DepthTexture = CTexture::Create(
     241             :         device, "SwapChainDepthTexture", ITexture::Type::TEXTURE_2D,
     242             :         ITexture::Usage::DEPTH_STENCIL_ATTACHMENT,
     243             :         device->GetPreferredDepthStencilFormat(
     244             :             Renderer::Backend::ITexture::Usage::DEPTH_STENCIL_ATTACHMENT,
     245             :             true, true),
     246           0 :         swapChainWidth, swapChainHeight, Sampler::MakeDefaultSampler(
     247             :             Sampler::Filter::NEAREST, Sampler::AddressMode::CLAMP_TO_EDGE),
     248           0 :         1, 1);
     249             : 
     250           0 :     swapChain->m_ImageFormat = swapChainCreateInfo.imageFormat;
     251             : 
     252           0 :     swapChain->m_Textures.resize(imageCount);
     253           0 :     swapChain->m_Backbuffers.resize(imageCount);
     254             :     char nameBuffer[64];
     255           0 :     for (size_t index = 0; index < imageCount; ++index)
     256             :     {
     257           0 :         snprintf(nameBuffer, std::size(nameBuffer), "SwapChainImage #%zu", index);
     258           0 :         device->SetObjectName(VK_OBJECT_TYPE_IMAGE, swapChain->m_Images[index], nameBuffer);
     259           0 :         snprintf(nameBuffer, std::size(nameBuffer), "SwapChainImageView #%zu", index);
     260           0 :         swapChain->m_Textures[index] = CTexture::WrapBackbufferImage(
     261           0 :             device, nameBuffer, swapChain->m_Images[index], swapChainCreateInfo.imageFormat,
     262           0 :             swapChainCreateInfo.imageUsage, swapChainWidth, swapChainHeight);
     263             :     }
     264             : 
     265             :     // +1 to minimize waiting on our side instead of vkAcquireNextImageKHR.
     266           0 :     for (size_t index{0}; index < NUMBER_OF_FRAMES_IN_FLIGHT + 1; ++index)
     267             :     {
     268           0 :         VkSemaphore semaphore{VK_NULL_HANDLE};
     269             : 
     270           0 :         VkSemaphoreCreateInfo semaphoreCreateInfo{};
     271           0 :         semaphoreCreateInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
     272             : 
     273           0 :         RETURN_NULLPTR_IF_NOT_VK_SUCCESS(vkCreateSemaphore(
     274             :             device->GetVkDevice(), &semaphoreCreateInfo, nullptr, &semaphore));
     275           0 :         snprintf(nameBuffer, std::size(nameBuffer), "SwapChainAcquireSemaphore #%zu", index);
     276           0 :         device->SetObjectName(VK_OBJECT_TYPE_SEMAPHORE, semaphore, nameBuffer);
     277             : 
     278           0 :         swapChain->m_FrameObjects.emplace_back(FrameObject{semaphore, CSubmitScheduler::INVALID_SUBMIT_HANDLE});
     279             :     }
     280             : 
     281           0 :     for (size_t index{0}; index < imageCount; ++index)
     282             :     {
     283           0 :         VkSemaphore semaphore{VK_NULL_HANDLE};
     284             : 
     285           0 :         VkSemaphoreCreateInfo semaphoreCreateInfo{};
     286           0 :         semaphoreCreateInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
     287             : 
     288           0 :         RETURN_NULLPTR_IF_NOT_VK_SUCCESS(vkCreateSemaphore(
     289             :             device->GetVkDevice(), &semaphoreCreateInfo, nullptr, &semaphore));
     290           0 :         snprintf(nameBuffer, std::size(nameBuffer), "SwapChainSubmitSemaphore #%zu", index);
     291           0 :         device->SetObjectName(VK_OBJECT_TYPE_SEMAPHORE, semaphore, nameBuffer);
     292             : 
     293           0 :         swapChain->m_SubmitSemaphores.emplace_back(semaphore);
     294             :     }
     295             : 
     296           0 :     swapChain->m_AcquireCommandContext = CRingCommandContext::Create(
     297           0 :         device, NUMBER_OF_FRAMES_IN_FLIGHT, queueFamilyIndex, *submitScheduler);
     298           0 :     if (!swapChain->m_AcquireCommandContext)
     299           0 :         return nullptr;
     300           0 :     swapChain->m_PresentCommandContext = CRingCommandContext::Create(
     301           0 :         device, NUMBER_OF_FRAMES_IN_FLIGHT, queueFamilyIndex, *submitScheduler);
     302           0 :     if (!swapChain->m_PresentCommandContext)
     303           0 :         return nullptr;
     304             : 
     305           0 :     swapChain->m_DebugWaitIdleBeforeAcquire = g_ConfigDB.Get(
     306             :         "renderer.backend.vulkan.debugwaitidlebeforeacquire",
     307           0 :         swapChain->m_DebugWaitIdleBeforeAcquire);
     308           0 :     swapChain->m_DebugWaitIdleBeforePresent = g_ConfigDB.Get(
     309             :         "renderer.backend.vulkan.debugwaitidlebeforepresent",
     310           0 :         swapChain->m_DebugWaitIdleBeforePresent);
     311           0 :     swapChain->m_DebugWaitIdleAfterPresent = g_ConfigDB.Get(
     312             :         "renderer.backend.vulkan.debugwaitidleafterpresent",
     313           0 :         swapChain->m_DebugWaitIdleAfterPresent);
     314             : 
     315           0 :     swapChain->m_IsValid = true;
     316             : 
     317           0 :     return swapChain;
     318             : }
     319             : 
     320           0 : CSwapChain::CSwapChain() = default;
     321             : 
     322           0 : CSwapChain::~CSwapChain()
     323             : {
     324           0 :     VkDevice device{m_Device->GetVkDevice()};
     325             : 
     326           0 :     m_Backbuffers.clear();
     327             : 
     328           0 :     m_Textures.clear();
     329           0 :     m_DepthTexture.reset();
     330             : 
     331           0 :     if (m_SwapChain != VK_NULL_HANDLE)
     332           0 :         vkDestroySwapchainKHR(device, m_SwapChain, nullptr);
     333             : 
     334           0 :     for (FrameObject& frameObject : m_FrameObjects)
     335             :     {
     336           0 :         if (frameObject.submitHandle != CSubmitScheduler::INVALID_SUBMIT_HANDLE)
     337           0 :             m_SubmitScheduler->WaitUntilFree(frameObject.submitHandle);
     338             : 
     339           0 :         if (frameObject.acquireImageSemaphore != VK_NULL_HANDLE)
     340           0 :             vkDestroySemaphore(device, frameObject.acquireImageSemaphore, nullptr);
     341             :     }
     342             : 
     343           0 :     for (VkSemaphore& semaphore : m_SubmitSemaphores)
     344           0 :         if (semaphore != VK_NULL_HANDLE)
     345           0 :             vkDestroySemaphore(device, semaphore, nullptr);
     346           0 : }
     347             : 
     348           0 : IDevice* CSwapChain::GetDevice()
     349             : {
     350           0 :     return m_Device;
     351             : }
     352             : 
     353           0 : bool CSwapChain::AcquireNextBackbuffer()
     354             : {
     355           0 :     ENSURE(m_IsValid);
     356             : 
     357           0 :     PROFILE3("AcquireNextBackbuffer");
     358             : 
     359             :     // We need to make sure we can reuse the semaphore.
     360           0 :     FrameObject& frameObject{m_FrameObjects[m_FrameID % m_FrameObjects.size()]};
     361           0 :     if (frameObject.submitHandle != CSubmitScheduler::INVALID_SUBMIT_HANDLE)
     362             :     {
     363           0 :         PROFILE3("WaitAcquireSemaphore");
     364           0 :         m_SubmitScheduler->WaitUntilFree(frameObject.submitHandle);
     365           0 :     }
     366             : 
     367           0 :     if (m_DebugWaitIdleBeforeAcquire)
     368           0 :         vkDeviceWaitIdle(m_Device->GetVkDevice());
     369             : 
     370           0 :     if (!AcquireNextImage())
     371             :         return false;
     372           0 :     SubmitCommandsAfterAcquireNextImage(*m_AcquireCommandContext);
     373             : 
     374           0 :     m_SubmitScheduler->EnqueueWaitOnNextSubmit(
     375             :         frameObject.acquireImageSemaphore, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT);
     376           0 :     m_AcquireCommandContext->Flush();
     377             :     return true;
     378             : }
     379             : 
     380           0 : void CSwapChain::Present()
     381             : {
     382           0 :     ENSURE(m_IsValid);
     383           0 :     ENSURE(m_CurrentImageIndex != std::numeric_limits<uint32_t>::max());
     384           0 :     ENSURE(m_CurrentImageIndex < m_SubmitSemaphores.size());
     385             : 
     386           0 :     PROFILE3("Present");
     387           0 :     FrameObject& frameObject{m_FrameObjects[m_FrameID % m_FrameObjects.size()]};
     388             : 
     389           0 :     SubmitCommandsBeforePresent(*m_PresentCommandContext);
     390           0 :     m_SubmitScheduler->EnqueueSignalOnNextSubmit(m_SubmitSemaphores[m_CurrentImageIndex]);
     391           0 :     m_PresentCommandContext->Flush();
     392           0 :     frameObject.submitHandle = m_SubmitScheduler->Flush();
     393             : 
     394           0 :     if (m_DebugWaitIdleBeforePresent)
     395           0 :         vkDeviceWaitIdle(m_Device->GetVkDevice());
     396             : 
     397           0 :     Present(m_SubmitSemaphores[m_CurrentImageIndex], m_Queue);
     398             : 
     399           0 :     if (m_DebugWaitIdleAfterPresent)
     400           0 :         vkDeviceWaitIdle(m_Device->GetVkDevice());
     401             : 
     402           0 :     m_Device->OnPresent();
     403           0 :     ++m_FrameID;
     404           0 : }
     405             : 
     406           0 : size_t CSwapChain::SwapChainBackbuffer::BackbufferKeyHash::operator()(const BackbufferKey& key) const
     407             : {
     408           0 :     size_t seed = 0;
     409           0 :     hash_combine(seed, std::get<0>(key));
     410           0 :     hash_combine(seed, std::get<1>(key));
     411           0 :     hash_combine(seed, std::get<2>(key));
     412           0 :     hash_combine(seed, std::get<3>(key));
     413           0 :     return seed;
     414             : }
     415             : 
     416           0 : CSwapChain::SwapChainBackbuffer::SwapChainBackbuffer() = default;
     417             : 
     418           0 : CSwapChain::SwapChainBackbuffer::SwapChainBackbuffer(SwapChainBackbuffer&& other) = default;
     419             : 
     420           0 : CSwapChain::SwapChainBackbuffer& CSwapChain::SwapChainBackbuffer::operator=(SwapChainBackbuffer&& other) = default;
     421             : 
     422           0 : bool CSwapChain::AcquireNextImage()
     423             : {
     424           0 :     ENSURE(m_IsValid);
     425           0 :     ENSURE(m_CurrentImageIndex == std::numeric_limits<uint32_t>::max());
     426             : 
     427           0 :     VkSemaphore acquireImageSemaphore{m_FrameObjects[m_FrameID % m_FrameObjects.size()].acquireImageSemaphore};
     428           0 :     const VkResult acquireResult = vkAcquireNextImageKHR(
     429           0 :         m_Device->GetVkDevice(), m_SwapChain, std::numeric_limits<uint64_t>::max(),
     430             :         acquireImageSemaphore,
     431             :         VK_NULL_HANDLE, &m_CurrentImageIndex);
     432           0 :     if (acquireResult != VK_SUCCESS)
     433             :     {
     434           0 :         if (acquireResult == VK_ERROR_OUT_OF_DATE_KHR)
     435           0 :             m_IsValid = false;
     436           0 :         else if (acquireResult != VK_SUBOPTIMAL_KHR)
     437             :         {
     438           0 :             LOGERROR("Acquire result: {} ({})",
     439             :                 static_cast<int>(acquireResult), Utilities::GetVkResultName(acquireResult));
     440           0 :             debug_warn("Unknown acquire error.");
     441             :         }
     442             :     }
     443           0 :     return m_IsValid;
     444             : }
     445             : 
     446           0 : void CSwapChain::SubmitCommandsAfterAcquireNextImage(
     447             :     CRingCommandContext& commandContext)
     448             : {
     449           0 :     const bool firstAcquirement = !m_Textures[m_CurrentImageIndex]->IsInitialized();
     450           0 :     Utilities::SubmitImageMemoryBarrier(
     451             :         commandContext.GetCommandBuffer(),
     452           0 :         m_Images[m_CurrentImageIndex], 0, 0,
     453             :         0, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
     454             :         firstAcquirement ? VK_IMAGE_LAYOUT_UNDEFINED : VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
     455             :         VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
     456             :         VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT);
     457           0 :     if (!m_DepthTexture->IsInitialized())
     458             :     {
     459           0 :         Utilities::SubmitImageMemoryBarrier(
     460             :             commandContext.GetCommandBuffer(),
     461             :             m_DepthTexture->GetImage(), 0, 0,
     462             :             0, VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
     463             :             VK_IMAGE_LAYOUT_UNDEFINED,
     464             :             VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
     465             :             VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT,
     466             :             VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT);
     467             :     }
     468           0 : }
     469             : 
     470           0 : void CSwapChain::SubmitCommandsBeforePresent(
     471             :     CRingCommandContext& commandContext)
     472             : {
     473           0 :     ENSURE(m_CurrentImageIndex != std::numeric_limits<uint32_t>::max());
     474             : 
     475           0 :     Utilities::SubmitImageMemoryBarrier(
     476           0 :         commandContext.GetCommandBuffer(), m_Images[m_CurrentImageIndex], 0, 0,
     477             :         VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, 0,
     478             :         VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
     479             :         VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
     480           0 : }
     481             : 
     482           0 : void CSwapChain::Present(VkSemaphore submitDone, VkQueue queue)
     483             : {
     484           0 :     ENSURE(m_IsValid);
     485           0 :     ENSURE(m_CurrentImageIndex != std::numeric_limits<uint32_t>::max());
     486             : 
     487           0 :     VkSwapchainKHR swapChains[] = {m_SwapChain};
     488             : 
     489           0 :     VkPresentInfoKHR presentInfo{};
     490           0 :     presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
     491           0 :     presentInfo.swapchainCount = 1;
     492           0 :     presentInfo.pSwapchains = swapChains;
     493           0 :     presentInfo.pImageIndices = &m_CurrentImageIndex;
     494           0 :     presentInfo.waitSemaphoreCount = 1;
     495           0 :     presentInfo.pWaitSemaphores = &submitDone;
     496           0 :     const VkResult presentResult = vkQueuePresentKHR(queue, &presentInfo);
     497           0 :     if (presentResult != VK_SUCCESS)
     498             :     {
     499           0 :         if (presentResult == VK_ERROR_OUT_OF_DATE_KHR)
     500           0 :             m_IsValid = false;
     501           0 :         else if (presentResult != VK_SUBOPTIMAL_KHR)
     502             :         {
     503           0 :             LOGERROR("Present result: {} ({})",
     504             :                 static_cast<int>(presentResult), Utilities::GetVkResultName(presentResult));
     505           0 :             debug_warn("Unknown present error.");
     506             :         }
     507             :     }
     508             : 
     509           0 :     m_CurrentImageIndex = std::numeric_limits<uint32_t>::max();
     510           0 : }
     511             : 
     512           0 : IFramebuffer* CSwapChain::GetCurrentBackbuffer(
     513             :     const AttachmentLoadOp colorAttachmentLoadOp,
     514             :     const AttachmentStoreOp colorAttachmentStoreOp,
     515             :     const AttachmentLoadOp depthStencilAttachmentLoadOp,
     516             :     const AttachmentStoreOp depthStencilAttachmentStoreOp)
     517             : {
     518           0 :     ENSURE(m_IsValid);
     519           0 :     ENSURE(m_CurrentImageIndex != std::numeric_limits<uint32_t>::max());
     520           0 :     SwapChainBackbuffer& swapChainBackbuffer =
     521           0 :         m_Backbuffers[m_CurrentImageIndex];
     522           0 :     const SwapChainBackbuffer::BackbufferKey key{
     523             :         colorAttachmentLoadOp, colorAttachmentStoreOp,
     524           0 :         depthStencilAttachmentLoadOp, depthStencilAttachmentStoreOp};
     525           0 :     auto it = swapChainBackbuffer.backbuffers.find(key);
     526           0 :     if (it == swapChainBackbuffer.backbuffers.end())
     527             :     {
     528           0 :         char nameBuffer[64];
     529           0 :         snprintf(nameBuffer, std::size(nameBuffer), "Backbuffer #%u", m_CurrentImageIndex);
     530             : 
     531           0 :         SColorAttachment colorAttachment{};
     532           0 :         colorAttachment.texture = m_Textures[m_CurrentImageIndex].get();
     533           0 :         colorAttachment.loadOp = colorAttachmentLoadOp;
     534           0 :         colorAttachment.storeOp = colorAttachmentStoreOp;
     535             : 
     536           0 :         SDepthStencilAttachment depthStencilAttachment{};
     537           0 :         depthStencilAttachment.texture = m_DepthTexture.get();
     538           0 :         depthStencilAttachment.loadOp = depthStencilAttachmentLoadOp;
     539           0 :         depthStencilAttachment.storeOp = depthStencilAttachmentStoreOp;
     540             : 
     541           0 :         it = swapChainBackbuffer.backbuffers.emplace(key, CFramebuffer::Create(
     542             :             m_Device, nameBuffer, &colorAttachment, &depthStencilAttachment)).first;
     543             :     }
     544           0 :     return it->second.get();
     545             : }
     546             : 
     547           0 : CTexture* CSwapChain::GetCurrentBackbufferTexture()
     548             : {
     549           0 :     ENSURE(m_CurrentImageIndex != std::numeric_limits<uint32_t>::max());
     550           0 :     return m_Textures[m_CurrentImageIndex].get();
     551             : }
     552             : 
     553           0 : CTexture* CSwapChain::GetOrCreateBackbufferReadbackTexture()
     554             : {
     555           0 :     ENSURE(m_IsValid);
     556           0 :     if (!m_BackbufferReadbackTexture)
     557             :     {
     558           0 :         CTexture* currentBackbufferTexture{GetCurrentBackbufferTexture()};
     559           0 :         m_BackbufferReadbackTexture = CTexture::CreateReadback(
     560             :             m_Device, "BackbufferReadback",
     561             :             currentBackbufferTexture->GetFormat(),
     562             :             currentBackbufferTexture->GetWidth(),
     563           0 :             currentBackbufferTexture->GetHeight());
     564             :     }
     565           0 :     return m_BackbufferReadbackTexture.get();
     566             : }
     567             : 
     568             : } // namespace Vulkan
     569             : 
     570             : } // namespace Backend
     571             : 
     572             : } // namespace Renderer

Generated by: LCOV version 1.16