From 09e109d6ef5e58a5037a8e8b91795a009e2ebf5c Mon Sep 17 00:00:00 2001 From: Florian RICHER Date: Fri, 15 Nov 2024 12:38:14 +0100 Subject: [PATCH] Update vk_swapchain - Refactor drop swapchain - Fix crash when re-create swapchain --- src/vulkan/vk_swapchain.rs | 45 ++++++++++++++++++++++++-------------- 1 file changed, 29 insertions(+), 16 deletions(-) diff --git a/src/vulkan/vk_swapchain.rs b/src/vulkan/vk_swapchain.rs index fc6ee25..e531fc5 100644 --- a/src/vulkan/vk_swapchain.rs +++ b/src/vulkan/vk_swapchain.rs @@ -1,7 +1,7 @@ use crate::vulkan::{VkSurface, LOG_TARGET}; use ash::prelude::VkResult; use ash::vk; -use ash::vk::{Extent2D, PresentModeKHR, SurfaceFormatKHR, SurfaceTransformFlagsKHR, SwapchainKHR}; +use ash::vk::{Extent2D, PresentModeKHR, SurfaceFormatKHR, SurfaceTransformFlagsKHR, SwapchainCreateInfoKHR, SwapchainKHR}; pub struct VkSwapchain { swapchain_loader: ash::khr::swapchain::Device, @@ -35,7 +35,24 @@ impl VkSwapchain { } pub fn create_swapchain(&mut self, surface: &VkSurface) -> VkResult<()> { - let swapchain_create_info = vk::SwapchainCreateInfoKHR::default() + let mut swapchain_create_info = self.create_swapchain_info(surface); + + if let Some(old_swapchain) = self.swapchain { + swapchain_create_info.old_swapchain = old_swapchain; + } + + let swapchain = unsafe { + self.swapchain_loader.create_swapchain(&swapchain_create_info, None)? + }; + log::debug!(target: LOG_TARGET, "Swapchain created : {swapchain_create_info:#?}"); + + self.swapchain = Some(swapchain); + + Ok(()) + } + + fn create_swapchain_info(&self, surface: &VkSurface) -> SwapchainCreateInfoKHR { + SwapchainCreateInfoKHR::default() .surface(surface.surface) .min_image_count(self.desired_image_count) .image_color_space(self.surface_format.color_space) @@ -47,25 +64,21 @@ impl VkSwapchain { .composite_alpha(vk::CompositeAlphaFlagsKHR::OPAQUE) .present_mode(self.present_mode) .clipped(true) - .image_array_layers(1); + .image_array_layers(1) + } - let swapchain = unsafe { - self.swapchain_loader.create_swapchain(&swapchain_create_info, None)? - }; - log::debug!(target: LOG_TARGET, "Swapchain created : {swapchain_create_info:#?}"); - - self.swapchain = Some(swapchain); - - Ok(()) + fn drop_current_swapchain(&mut self) { + if let Some(swapchain) = self.swapchain { + unsafe { + self.swapchain_loader.destroy_swapchain(swapchain, None); + self.swapchain = None; + } + } } } impl Drop for VkSwapchain { fn drop(&mut self) { - if let Some(swapchain) = self.swapchain { - unsafe { - self.swapchain_loader.destroy_swapchain(swapchain, None); - } - } + self.drop_current_swapchain() } } \ No newline at end of file