diff --git a/CHANGELOG.md b/CHANGELOG.md index 31359bf8..9ba441b3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,9 @@ Release notes on GitHub are taken from the matching section here. where the driver is slow to destroy the old swapchain. Nightcap now waits at most 100 ms for a destroy and finishes slow ones in the background, so the first resize no longer freezes either. Quick resizes and window rebuilds no longer wait for those background destroys. +- With Vulkan, joining a game no longer freezes for about 44 seconds on laptops where NVIDIA's driver is + slow to replace a swapchain (seen with PRIME on X11). Nightcap now gives Roblox its existing swapchain + back when it rebuilds one that has not changed, so the driver never replaces it. - With Vulkan, Nightcap no longer lands on the slow software renderer (lavapipe) when it cannot pin a GPU driver. If no hardware Vulkan device exists at all, it starts with the OpenGL backend instead of showing a blank window; `VK_DRIVER_FILES` forces Vulkan. diff --git a/include/mocktail/graphics/swapchain_retirement.h b/include/mocktail/graphics/swapchain_retirement.h index 059a4484..ee18408a 100644 --- a/include/mocktail/graphics/swapchain_retirement.h +++ b/include/mocktail/graphics/swapchain_retirement.h @@ -4,15 +4,36 @@ #include #include +#include #include +#include #include #include namespace mocktail::graphics { +struct SwapchainShape { + VkSwapchainCreateFlagsKHR flags = 0; + std::uint32_t min_image_count = 0; + VkFormat format = VK_FORMAT_UNDEFINED; + VkColorSpaceKHR color_space = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR; + VkExtent2D extent{}; + std::uint32_t array_layers = 0; + VkImageUsageFlags usage = 0; + VkSurfaceTransformFlagBitsKHR transform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; + VkCompositeAlphaFlagBitsKHR alpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; + VkPresentModeKHR present_mode = VK_PRESENT_MODE_FIFO_KHR; + VkBool32 clipped = VK_FALSE; + + // None for chained or concurrent-sharing creates, which are never reused. + static std::optional From(const VkSwapchainCreateInfoKHR& info); + bool operator==(const SwapchainShape& other) const; +}; + struct HeldSwapchain { VkDevice device = VK_NULL_HANDLE; VkSwapchainKHR swapchain = VK_NULL_HANDLE; + // The host surface the swapchain was created on. VkSurfaceKHR surface = VK_NULL_HANDLE; // A copy: the game's callbacks struct need not outlive its destroy call. bool has_allocator = false; @@ -20,51 +41,77 @@ struct HeldSwapchain { const VkAllocationCallbacks* Allocator() const { return has_allocator ? &allocator : nullptr; } - // The game destroyed `surface` while this swapchain still owned the window; - // the host surface is destroyed after the swapchain. - bool surface_destroy_deferred = false; + std::optional reusable; + explicit operator bool() const { return swapchain != VK_NULL_HANDLE; } +}; + +struct KeptSurface { VkInstance instance = VK_NULL_HANDLE; - bool has_surface_allocator = false; - VkAllocationCallbacks surface_allocator{}; - const VkAllocationCallbacks* SurfaceAllocator() const { - return has_surface_allocator ? &surface_allocator : nullptr; + VkSurfaceKHR surface = VK_NULL_HANDLE; + bool has_allocator = false; + VkAllocationCallbacks allocator{}; + const VkAllocationCallbacks* Allocator() const { + return has_allocator ? &allocator : nullptr; } - explicit operator bool() const { return swapchain != VK_NULL_HANDLE; } + explicit operator bool() const { return surface != VK_NULL_HANDLE; } }; -// Decides when a destroyed swapchain may go to the background worker. NVIDIA's -// X11 driver can block ~22 s in vkDestroySwapchainKHR. A swapchain the game -// destroys while it still owns the window is held and passed as oldSwapchain -// to the next create, so the window is free while the worker destroys it. -// If the game also destroys its surface, it may retire into any new surface on -// that device, since every surface maps to the one window. -// Off until Enable(), so drivers that destroy promptly keep the old path. +// Keeps the driver from destroying and creating swapchains Roblox rebuilds +// unchanged. NVIDIA on X11 with PRIME blocks ~22 s in each swapchain destroy or +// retiring create. Roblox rebuilds an identical swapchain on every view change +// and destroys its swapchain and surface on every game join, so an identical +// create gets the current or the last destroyed swapchain back. Every surface +// is the one SDL window, so a swapchain may serve or retire into any surface; +// a surface the game destroys stays alive until no swapchain uses it. class SwapchainRetirement final { public: void Enable() { enabled_.store(true, std::memory_order_relaxed); } bool Enabled() const { return enabled_.load(std::memory_order_relaxed); } - // Drops the bookkeeping for a swapchain destroyed in place. - void Forget(VkSwapchainKHR swapchain); void Created(VkSwapchainKHR swapchain, VkSurfaceKHR surface, - VkSwapchainKHR old_swapchain); + VkSwapchainKHR old_swapchain, VkDevice device = VK_NULL_HANDLE, + const std::optional& shape = std::nullopt); + VkSwapchainKHR Reuse(VkDevice device, VkSwapchainKHR old_swapchain, + const SwapchainShape& shape); + // True when the game still holds another copy of a reused swapchain, so its + // destroy must not reach the driver. + bool DropReference(VkSwapchainKHR swapchain); + void NoteAcquired(VkSwapchainKHR swapchain, std::uint32_t image_index); + void NotePresented(VkSwapchainKHR swapchain, std::uint32_t image_index); + void NoteResult(VkSwapchainKHR swapchain, VkResult result); // A failed create still retires its oldSwapchain. void Retired(VkSwapchainKHR old_swapchain); - // Returns what to destroy now; a swapchain still owning the window is held. + // Returns what to destroy now; the last live swapchain is held instead. HeldSwapchain Destroyed(VkDevice device, VkSwapchainKHR swapchain, const VkAllocationCallbacks* allocator); - HeldSwapchain TakeForCreate(VkDevice device, VkSurfaceKHR surface, - VkSwapchainKHR* old_swapchain); - // True when `surface` belongs to the held swapchain and must outlive it. - bool DeferSurfaceDestroy(VkSurfaceKHR surface, VkInstance instance, - const VkAllocationCallbacks* allocator); - HeldSwapchain ReleaseIfSurface(VkSurfaceKHR surface); + HeldSwapchain TakeForCreate(VkDevice device, VkSwapchainKHR* old_swapchain); HeldSwapchain ReleaseIfDevice(VkDevice device); HeldSwapchain Release(); + // True when a swapchain still uses `surface`, so its host destroy waits. + bool SurfaceDestroyed(VkSurfaceKHR surface, VkInstance instance, + const VkAllocationCallbacks* allocator); + // Call once a swapchain on `surface` goes to the driver for destroy; returns + // the surface when the game destroyed it and nothing else uses it. + KeptSurface SwapchainGone(VkSurfaceKHR surface); private: + struct Live { + VkSurfaceKHR surface = VK_NULL_HANDLE; + VkDevice device = VK_NULL_HANDLE; + std::optional shape; + int references = 1; + std::uint64_t acquired = 0; + bool stale = false; + bool Reusable() const { return shape.has_value() && acquired == 0 && !stale; } + }; + struct SurfaceUse { + int swapchains = 0; + bool destroyed = false; + KeptSurface kept; + }; std::mutex mutex_; - std::unordered_map surfaces_; + std::unordered_map live_; std::unordered_set retired_; + std::unordered_map surfaces_; HeldSwapchain held_; std::atomic enabled_{false}; }; diff --git a/src/graphics/bionic_vulkan_loader_adapter.cc b/src/graphics/bionic_vulkan_loader_adapter.cc index 3796540e..78388ee3 100644 --- a/src/graphics/bionic_vulkan_loader_adapter.cc +++ b/src/graphics/bionic_vulkan_loader_adapter.cc @@ -1722,6 +1722,7 @@ void PostSwapchainDestroy(const mocktail::graphics::HeldSwapchain& held) { host_destroy(held.device, held.swapchain, held.Allocator()); const std::uint64_t elapsed_ms = (MonotonicNanos() - start_ns) / 1000000; if (elapsed_ms >= 100) { + Retirement().Enable(); std::fprintf(stderr, " [vulkan] old swapchain destroyed in the background " "after %llu ms\n", @@ -1729,23 +1730,54 @@ void PostSwapchainDestroy(const mocktail::graphics::HeldSwapchain& held) { } ReleaseLibrary(library); }); - if (!held.surface_destroy_deferred) { + const mocktail::graphics::KeptSurface kept = + Retirement().SwapchainGone(held.surface); + if (!kept) { return; } const auto host_destroy_surface = reinterpret_cast( - HostInstanceProc(held.instance, "vkDestroySurfaceKHR")); + HostInstanceProc(kept.instance, "vkDestroySurfaceKHR")); if (host_destroy_surface == nullptr) { return; } void* const surface_library = HoldLibraryOf(reinterpret_cast(host_destroy_surface)); // Queued, so it runs after the swapchain destroy above. - Teardown().Post([held, host_destroy_surface, surface_library] { - host_destroy_surface(held.instance, held.surface, held.SurfaceAllocator()); + Teardown().Post([kept, host_destroy_surface, surface_library] { + host_destroy_surface(kept.instance, kept.surface, kept.Allocator()); ReleaseLibrary(surface_library); }); } +void RegisterOverlaySwapchain(VkDevice device, VkSwapchainKHR swapchain, + const VkSwapchainCreateInfoKHR& create_info) { + const auto host_get_images = reinterpret_cast( + HostDeviceProc(device, "vkGetSwapchainImagesKHR")); + std::uint32_t image_count = 0; + if (host_get_images == nullptr || + host_get_images(device, swapchain, &image_count, nullptr) != VK_SUCCESS || + image_count == 0) { + return; + } + std::vector images(image_count); + const VkResult images_result = + host_get_images(device, swapchain, &image_count, images.data()); + if (images_result == VK_SUCCESS || images_result == VK_INCOMPLETE) { + images.resize(image_count); + (void)State().text_overlay.RegisterSwapchain( + device, swapchain, create_info, images.data(), image_count); + } +} + +void NoteAcquireResult(VkSwapchainKHR swapchain, VkResult result, + const std::uint32_t* image_index) { + if ((result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR) && + image_index != nullptr) { + Retirement().NoteAcquired(swapchain, *image_index); + } + Retirement().NoteResult(swapchain, result); +} + } // namespace extern "C" { @@ -1924,18 +1956,15 @@ vkDestroySurfaceKHR(VkInstance instance, VkSurfaceKHR surface, if (!EnsureInitialized()) { return; } - if (Retirement().Enabled() && - Retirement().DeferSurfaceDestroy(surface, instance, allocator)) { + if (Retirement().SurfaceDestroyed(surface, instance, allocator)) { std::fprintf(stderr, - " [vulkan] keeping the old surface until its swapchain " - "retires into the next one\n"); + " [vulkan] keeping the old surface until its swapchain is " + "destroyed\n"); return; } - PostSwapchainDestroy(Retirement().ReleaseIfSurface(surface)); const auto host_destroy = reinterpret_cast( HostInstanceProc(instance, "vkDestroySurfaceKHR")); - if (host_destroy == nullptr || !Retirement().Enabled() || - !Teardown().Busy()) { + if (host_destroy == nullptr || !Teardown().Busy()) { State().android_wsi.DestroySurface(instance, surface, allocator); return; } @@ -2405,7 +2434,7 @@ vkDestroyDevice(VkDevice device, const VkAllocationCallbacks* allocator) { PostSwapchainDestroy(Retirement().ReleaseIfDevice(device)); State().etc2.DropParkedGpuDecoder(device); if (host_destroy != nullptr) { - if (Retirement().Enabled() && Teardown().Busy()) { + if (Teardown().Busy()) { std::fprintf(stderr, " [vulkan] waiting for background destroys before " "destroying the device\n"); @@ -2549,9 +2578,24 @@ VKAPI_ATTR VkResult VKAPI_CALL vkCreateSwapchainKHR( } } } + const std::optional shape = + mocktail::graphics::SwapchainShape::From(host_info); + if (shape) { + const VkSwapchainKHR reused = + Retirement().Reuse(device, create_info->oldSwapchain, *shape); + if (reused != VK_NULL_HANDLE) { + *swapchain = reused; + std::fprintf(stderr, + " [vulkan] reusing the %s swapchain for an identical " + "create\n", + reused == create_info->oldSwapchain ? "current" : "kept"); + RegisterOverlaySwapchain(device, reused, *create_info); + observation.SetResult(VK_SUCCESS); + return VK_SUCCESS; + } + } const mocktail::graphics::HeldSwapchain held = - Retirement().TakeForCreate(device, create_info->surface, - &host_info.oldSwapchain); + Retirement().TakeForCreate(device, &host_info.oldSwapchain); const bool retires_held = held && host_info.oldSwapchain == held.swapchain; if (!retires_held) { PostSwapchainDestroy(held); @@ -2568,7 +2612,7 @@ VKAPI_ATTR VkResult VKAPI_CALL vkCreateSwapchainKHR( first_attempt = false; VkResult created = host_create(device, &info, allocator, swapchain); if (created == VK_ERROR_NATIVE_WINDOW_IN_USE_KHR && - Retirement().Enabled() && Teardown().Busy()) { + Teardown().Busy()) { std::fprintf(stderr, " [vulkan] waiting for the old swapchain's " "background destroy to free the window\n"); @@ -2587,24 +2631,8 @@ VKAPI_ATTR VkResult VKAPI_CALL vkCreateSwapchainKHR( return result; } Retirement().Created(*swapchain, create_info->surface, - create_info->oldSwapchain); - const auto host_get_images = reinterpret_cast( - HostDeviceProc(device, "vkGetSwapchainImagesKHR")); - std::uint32_t image_count = 0; - if (host_get_images == nullptr || - host_get_images(device, *swapchain, &image_count, nullptr) != - VK_SUCCESS || - image_count == 0) { - return result; - } - std::vector images(image_count); - const VkResult images_result = - host_get_images(device, *swapchain, &image_count, images.data()); - if (images_result == VK_SUCCESS || images_result == VK_INCOMPLETE) { - images.resize(image_count); - (void)State().text_overlay.RegisterSwapchain( - device, *swapchain, *create_info, images.data(), image_count); - } + create_info->oldSwapchain, device, shape); + RegisterOverlaySwapchain(device, *swapchain, *create_info); return result; } @@ -2614,20 +2642,19 @@ vkDestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain, if (swapchain == VK_NULL_HANDLE) { return; } + if (Retirement().DropReference(swapchain)) { + return; // A reused swapchain the game still holds as its new one. + } State().text_overlay.DestroySwapchain(device, swapchain); - if (Retirement().Enabled()) { - PostSwapchainDestroy(Retirement().Destroyed(device, swapchain, allocator)); + const mocktail::graphics::HeldSwapchain now = + Retirement().Destroyed(device, swapchain, allocator); + if (!now) { return; } - Retirement().Forget(swapchain); - mocktail::graphics::HeldSwapchain held; - held.device = device; - held.swapchain = swapchain; - held.has_allocator = allocator != nullptr; - if (held.has_allocator) { - held.allocator = *allocator; + PostSwapchainDestroy(now); + if (Retirement().Enabled()) { + return; } - PostSwapchainDestroy(held); // A healthy driver finishes in a few ms; the slow NVIDIA case takes ~22 s. constexpr std::chrono::milliseconds kInlineBudget{100}; if (!Teardown().WaitIdleFor(kInlineBudget)) { @@ -2659,6 +2686,7 @@ VKAPI_ATTR VkResult VKAPI_CALL vkAcquireNextImageKHR( if (fps_trace) { AcquireWaitTrace().Record(acquire_start_ns); } + NoteAcquireResult(swapchain, host_result, image_index); const VkResult result = NormalizeSwapchainResult(host_result); NoteSwapchainResult(result, "vkAcquireNextImageKHR"); observation.SetResult(result); @@ -2679,6 +2707,7 @@ VKAPI_ATTR VkResult VKAPI_CALL vkAcquireNextImage2KHR( "vkAcquireNextImage2KHR", "wait"); const VkResult host_result = host_acquire(device, acquire_info, image_index); + NoteAcquireResult(acquire_info->swapchain, host_result, image_index); const VkResult result = NormalizeSwapchainResult(host_result); NoteSwapchainResult(result, "vkAcquireNextImage2KHR"); observation.SetResult(result); @@ -3130,6 +3159,17 @@ vkQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* present_info) { const VkResult result = state.text_overlay.QueuePresent( queue, present_info, ObservedHostQueuePresent); scope.Arg("result", result); + if (present_info != nullptr) { + for (std::uint32_t index = 0; index < present_info->swapchainCount; + ++index) { + const VkSwapchainKHR presented = present_info->pSwapchains[index]; + Retirement().NotePresented(presented, + present_info->pImageIndices[index]); + Retirement().NoteResult(presented, present_info->pResults != nullptr + ? present_info->pResults[index] + : result); + } + } const VkResult normalized_result = NormalizeSwapchainResult(result); NoteSwapchainResult(normalized_result, "vkQueuePresentKHR"); if (normalized_result == VK_SUCCESS && note_present != nullptr) { diff --git a/src/graphics/swapchain_retirement.cc b/src/graphics/swapchain_retirement.cc index 11ea093e..c5a53241 100644 --- a/src/graphics/swapchain_retirement.cc +++ b/src/graphics/swapchain_retirement.cc @@ -4,28 +4,138 @@ namespace mocktail::graphics { +std::optional SwapchainShape::From( + const VkSwapchainCreateInfoKHR& info) { + if (info.pNext != nullptr || + info.imageSharingMode != VK_SHARING_MODE_EXCLUSIVE) { + return std::nullopt; + } + SwapchainShape shape; + shape.flags = info.flags; + shape.min_image_count = info.minImageCount; + shape.format = info.imageFormat; + shape.color_space = info.imageColorSpace; + shape.extent = info.imageExtent; + shape.array_layers = info.imageArrayLayers; + shape.usage = info.imageUsage; + shape.transform = info.preTransform; + shape.alpha = info.compositeAlpha; + shape.present_mode = info.presentMode; + shape.clipped = info.clipped; + return shape; +} + +bool SwapchainShape::operator==(const SwapchainShape& other) const { + return flags == other.flags && min_image_count == other.min_image_count && + format == other.format && color_space == other.color_space && + extent.width == other.extent.width && + extent.height == other.extent.height && + array_layers == other.array_layers && usage == other.usage && + transform == other.transform && alpha == other.alpha && + present_mode == other.present_mode && clipped == other.clipped; +} + void SwapchainRetirement::Created(VkSwapchainKHR swapchain, VkSurfaceKHR surface, - VkSwapchainKHR old_swapchain) { + VkSwapchainKHR old_swapchain, + VkDevice device, + const std::optional& shape) { std::lock_guard lock(mutex_); - surfaces_[swapchain] = surface; + Live live; + live.surface = surface; + live.device = device; + live.shape = shape; + live_[swapchain] = live; + ++surfaces_[surface].swapchains; if (old_swapchain != VK_NULL_HANDLE) { retired_.insert(old_swapchain); } } -void SwapchainRetirement::Retired(VkSwapchainKHR old_swapchain) { - if (old_swapchain == VK_NULL_HANDLE) { +VkSwapchainKHR SwapchainRetirement::Reuse(VkDevice device, + VkSwapchainKHR old_swapchain, + const SwapchainShape& shape) { + std::lock_guard lock(mutex_); + if (old_swapchain != VK_NULL_HANDLE) { + const auto found = live_.find(old_swapchain); + if (found == live_.end() || retired_.count(old_swapchain) != 0) { + return VK_NULL_HANDLE; + } + Live& live = found->second; + if (live.device != device || !live.Reusable() || !(*live.shape == shape)) { + return VK_NULL_HANDLE; + } + ++live.references; + return old_swapchain; + } + if (!held_ || !held_.reusable || held_.device != device || + !(*held_.reusable == shape)) { + return VK_NULL_HANDLE; + } + const HeldSwapchain held = std::exchange(held_, HeldSwapchain{}); + Live live; + live.surface = held.surface; + live.device = device; + live.shape = shape; + live_[held.swapchain] = live; + return held.swapchain; +} + +bool SwapchainRetirement::DropReference(VkSwapchainKHR swapchain) { + std::lock_guard lock(mutex_); + const auto found = live_.find(swapchain); + if (found == live_.end() || found->second.references <= 1) { + return false; + } + --found->second.references; + return true; +} + +void SwapchainRetirement::NoteAcquired(VkSwapchainKHR swapchain, + std::uint32_t image_index) { + std::lock_guard lock(mutex_); + const auto found = live_.find(swapchain); + if (found == live_.end()) { + return; + } + if (image_index >= 64) { + found->second.stale = true; + return; + } + found->second.acquired |= std::uint64_t{1} << image_index; +} + +void SwapchainRetirement::NotePresented(VkSwapchainKHR swapchain, + std::uint32_t image_index) { + if (image_index >= 64) { return; } std::lock_guard lock(mutex_); - retired_.insert(old_swapchain); + const auto found = live_.find(swapchain); + if (found != live_.end()) { + found->second.acquired &= ~(std::uint64_t{1} << image_index); + } +} + +void SwapchainRetirement::NoteResult(VkSwapchainKHR swapchain, + VkResult result) { + if (result != VK_SUBOPTIMAL_KHR && result != VK_ERROR_OUT_OF_DATE_KHR && + result != VK_ERROR_SURFACE_LOST_KHR) { + return; + } + std::lock_guard lock(mutex_); + const auto found = live_.find(swapchain); + if (found != live_.end()) { + found->second.stale = true; + } } -void SwapchainRetirement::Forget(VkSwapchainKHR swapchain) { +void SwapchainRetirement::Retired(VkSwapchainKHR old_swapchain) { + if (old_swapchain == VK_NULL_HANDLE) { + return; + } std::lock_guard lock(mutex_); - surfaces_.erase(swapchain); - retired_.erase(swapchain); + retired_.insert(old_swapchain); } HeldSwapchain SwapchainRetirement::Destroyed( @@ -39,61 +149,79 @@ HeldSwapchain SwapchainRetirement::Destroyed( destroyed.has_allocator = true; destroyed.allocator = *allocator; } - if (const auto found = surfaces_.find(swapchain); found != surfaces_.end()) { - destroyed.surface = found->second; - surfaces_.erase(found); + if (const auto found = live_.find(swapchain); found != live_.end()) { + destroyed.surface = found->second.surface; + if (found->second.Reusable()) { + destroyed.reusable = found->second.shape; + } + live_.erase(found); } if (retired_.erase(swapchain) != 0) { + destroyed.reusable.reset(); return destroyed; } return std::exchange(held_, destroyed); } HeldSwapchain SwapchainRetirement::TakeForCreate(VkDevice device, - VkSurfaceKHR surface, VkSwapchainKHR* old_swapchain) { std::lock_guard lock(mutex_); - if (held_ && held_.device == device && - (held_.surface == surface || held_.surface_destroy_deferred) && - old_swapchain != nullptr && + if (held_ && held_.device == device && old_swapchain != nullptr && *old_swapchain == VK_NULL_HANDLE) { *old_swapchain = held_.swapchain; } return std::exchange(held_, HeldSwapchain{}); } -bool SwapchainRetirement::DeferSurfaceDestroy( +HeldSwapchain SwapchainRetirement::ReleaseIfDevice(VkDevice device) { + std::lock_guard lock(mutex_); + return held_.device == device ? std::exchange(held_, HeldSwapchain{}) + : HeldSwapchain{}; +} + +HeldSwapchain SwapchainRetirement::Release() { + std::lock_guard lock(mutex_); + return std::exchange(held_, HeldSwapchain{}); +} + +bool SwapchainRetirement::SurfaceDestroyed( VkSurfaceKHR surface, VkInstance instance, const VkAllocationCallbacks* allocator) { std::lock_guard lock(mutex_); - if (!held_ || held_.surface != surface || held_.surface_destroy_deferred) { + const auto found = surfaces_.find(surface); + if (found == surfaces_.end() || found->second.swapchains <= 0) { + if (found != surfaces_.end()) { + surfaces_.erase(found); + } return false; } - held_.surface_destroy_deferred = true; - held_.instance = instance; - held_.has_surface_allocator = allocator != nullptr; + SurfaceUse& use = found->second; + use.destroyed = true; + use.kept.instance = instance; + use.kept.surface = surface; + use.kept.has_allocator = allocator != nullptr; if (allocator != nullptr) { - held_.surface_allocator = *allocator; + use.kept.allocator = *allocator; } return true; } -HeldSwapchain SwapchainRetirement::ReleaseIfSurface(VkSurfaceKHR surface) { - std::lock_guard lock(mutex_); - return held_.surface == surface && !held_.surface_destroy_deferred - ? std::exchange(held_, HeldSwapchain{}) - : HeldSwapchain{}; -} - -HeldSwapchain SwapchainRetirement::ReleaseIfDevice(VkDevice device) { - std::lock_guard lock(mutex_); - return held_.device == device ? std::exchange(held_, HeldSwapchain{}) - : HeldSwapchain{}; -} - -HeldSwapchain SwapchainRetirement::Release() { +KeptSurface SwapchainRetirement::SwapchainGone(VkSurfaceKHR surface) { std::lock_guard lock(mutex_); - return std::exchange(held_, HeldSwapchain{}); + const auto found = surfaces_.find(surface); + if (found == surfaces_.end()) { + return KeptSurface{}; + } + SurfaceUse& use = found->second; + if (use.swapchains > 0) { + --use.swapchains; + } + if (use.swapchains > 0 || !use.destroyed) { + return KeptSurface{}; + } + const KeptSurface kept = use.kept; + surfaces_.erase(found); + return kept; } } // namespace mocktail::graphics diff --git a/tests/swapchain_retirement_test.cc b/tests/swapchain_retirement_test.cc index f6d79f9b..d45a92c6 100644 --- a/tests/swapchain_retirement_test.cc +++ b/tests/swapchain_retirement_test.cc @@ -8,7 +8,9 @@ namespace { using mocktail::graphics::HeldSwapchain; +using mocktail::graphics::KeptSurface; using mocktail::graphics::SwapchainRetirement; +using mocktail::graphics::SwapchainShape; template Handle Fake(std::uintptr_t value) { @@ -21,6 +23,19 @@ const VkSurfaceKHR kSurface = Fake(0x20); const VkSurfaceKHR kOtherSurface = Fake(0x21); const VkSwapchainKHR kFirst = Fake(0x30); const VkSwapchainKHR kSecond = Fake(0x31); +const VkInstance kInstance = Fake(0x40); + +SwapchainShape Shape(std::uint32_t width = 1001, std::uint32_t height = 850) { + VkSwapchainCreateInfoKHR info{}; + info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; + info.minImageCount = 5; + info.imageFormat = VK_FORMAT_B8G8R8A8_UNORM; + info.imageExtent = {width, height}; + info.imageArrayLayers = 1; + info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; + info.presentMode = VK_PRESENT_MODE_IMMEDIATE_KHR; + return *SwapchainShape::From(info); +} TEST(SwapchainRetirementTest, StaysOffUntilEnabled) { SwapchainRetirement retirement; @@ -29,16 +44,6 @@ TEST(SwapchainRetirementTest, StaysOffUntilEnabled) { EXPECT_TRUE(retirement.Enabled()); } -TEST(SwapchainRetirementTest, ForgetsASwapchainDestroyedInPlace) { - SwapchainRetirement retirement; - retirement.Created(kFirst, kSurface, VK_NULL_HANDLE); - retirement.Created(kSecond, kSurface, kFirst); - retirement.Forget(kFirst); - - EXPECT_FALSE(retirement.Destroyed(kDevice, kFirst, nullptr)); - EXPECT_EQ(retirement.Release().surface, VK_NULL_HANDLE); -} - TEST(SwapchainRetirementTest, HoldsALiveSwapchainUntilTheNextCreateRetiresIt) { SwapchainRetirement retirement; retirement.Created(kFirst, kSurface, VK_NULL_HANDLE); @@ -46,8 +51,7 @@ TEST(SwapchainRetirementTest, HoldsALiveSwapchainUntilTheNextCreateRetiresIt) { EXPECT_FALSE(retirement.Destroyed(kDevice, kFirst, nullptr)); VkSwapchainKHR old_swapchain = VK_NULL_HANDLE; - const HeldSwapchain held = - retirement.TakeForCreate(kDevice, kSurface, &old_swapchain); + const HeldSwapchain held = retirement.TakeForCreate(kDevice, &old_swapchain); EXPECT_EQ(old_swapchain, kFirst); EXPECT_EQ(held.swapchain, kFirst); EXPECT_EQ(held.surface, kSurface); @@ -61,6 +65,7 @@ TEST(SwapchainRetirementTest, DestroysASwapchainTheGameAlreadyRetired) { const HeldSwapchain now = retirement.Destroyed(kDevice, kFirst, nullptr); EXPECT_EQ(now.swapchain, kFirst); + EXPECT_FALSE(now.reusable); EXPECT_FALSE(retirement.Release()); } @@ -70,8 +75,7 @@ TEST(SwapchainRetirementTest, KeepsTheGamesOwnOldSwapchain) { EXPECT_FALSE(retirement.Destroyed(kDevice, kFirst, nullptr)); VkSwapchainKHR old_swapchain = kSecond; - const HeldSwapchain held = - retirement.TakeForCreate(kDevice, kSurface, &old_swapchain); + const HeldSwapchain held = retirement.TakeForCreate(kDevice, &old_swapchain); EXPECT_EQ(old_swapchain, kSecond); EXPECT_EQ(held.swapchain, kFirst); } @@ -83,19 +87,7 @@ TEST(SwapchainRetirementTest, DoesNotRetireIntoAnotherDevice) { VkSwapchainKHR old_swapchain = VK_NULL_HANDLE; const HeldSwapchain held = - retirement.TakeForCreate(kOtherDevice, kSurface, &old_swapchain); - EXPECT_EQ(old_swapchain, VK_NULL_HANDLE); - EXPECT_EQ(held.swapchain, kFirst); -} - -TEST(SwapchainRetirementTest, DoesNotRetireIntoAnotherSurface) { - SwapchainRetirement retirement; - retirement.Created(kFirst, kSurface, VK_NULL_HANDLE); - EXPECT_FALSE(retirement.Destroyed(kDevice, kFirst, nullptr)); - - VkSwapchainKHR old_swapchain = VK_NULL_HANDLE; - const HeldSwapchain held = - retirement.TakeForCreate(kDevice, kOtherSurface, &old_swapchain); + retirement.TakeForCreate(kOtherDevice, &old_swapchain); EXPECT_EQ(old_swapchain, VK_NULL_HANDLE); EXPECT_EQ(held.swapchain, kFirst); } @@ -135,75 +127,197 @@ TEST(SwapchainRetirementTest, HoldsOnlyTheLatestSwapchain) { EXPECT_EQ(retirement.Release().swapchain, kSecond); } -TEST(SwapchainRetirementTest, ReleasesWhenItsSurfaceOrDeviceGoes) { +TEST(SwapchainRetirementTest, ReleasesTheHeldSwapchainWithItsDevice) { SwapchainRetirement retirement; retirement.Created(kFirst, kSurface, VK_NULL_HANDLE); EXPECT_FALSE(retirement.Destroyed(kDevice, kFirst, nullptr)); - EXPECT_FALSE(retirement.ReleaseIfSurface(kOtherSurface)); EXPECT_FALSE(retirement.ReleaseIfDevice(kOtherDevice)); - EXPECT_EQ(retirement.ReleaseIfSurface(kSurface).swapchain, kFirst); - - retirement.Created(kSecond, kSurface, VK_NULL_HANDLE); - EXPECT_FALSE(retirement.Destroyed(kDevice, kSecond, nullptr)); - EXPECT_EQ(retirement.ReleaseIfDevice(kDevice).swapchain, kSecond); + EXPECT_EQ(retirement.ReleaseIfDevice(kDevice).swapchain, kFirst); EXPECT_FALSE(retirement.Release()); } -const VkInstance kInstance = Fake(0x40); +TEST(SurfaceLifetimeTest, ASurfaceWithoutSwapchainsIsDestroyedAtOnce) { + SwapchainRetirement retirement; + EXPECT_FALSE(retirement.SurfaceDestroyed(kSurface, kInstance, nullptr)); +} -// Roblox rebuilds its surface on the kept device. The held swapchain still -// owns the window, so it keeps its surface and retires into the new one. -TEST(SwapchainRetirementTest, KeepsAHeldSwapchainsSurfaceForTheNextSurface) { +TEST(SurfaceLifetimeTest, ASurfaceOutlivesItsLastSwapchain) { SwapchainRetirement retirement; retirement.Created(kFirst, kSurface, VK_NULL_HANDLE); EXPECT_FALSE(retirement.Destroyed(kDevice, kFirst, nullptr)); - - EXPECT_FALSE(retirement.DeferSurfaceDestroy(kOtherSurface, kInstance, nullptr)); int user_data = 0; { VkAllocationCallbacks callbacks{}; callbacks.pUserData = &user_data; - EXPECT_TRUE(retirement.DeferSurfaceDestroy(kSurface, kInstance, &callbacks)); + EXPECT_TRUE(retirement.SurfaceDestroyed(kSurface, kInstance, &callbacks)); } - VkSwapchainKHR old_swapchain = VK_NULL_HANDLE; - const HeldSwapchain held = - retirement.TakeForCreate(kDevice, kOtherSurface, &old_swapchain); - EXPECT_EQ(old_swapchain, kFirst); - EXPECT_EQ(held.swapchain, kFirst); - EXPECT_TRUE(held.surface_destroy_deferred); - EXPECT_EQ(held.surface, kSurface); - EXPECT_EQ(held.instance, kInstance); - ASSERT_NE(held.SurfaceAllocator(), nullptr); - EXPECT_EQ(held.SurfaceAllocator()->pUserData, &user_data); - EXPECT_FALSE(retirement.Release()); + const HeldSwapchain held = retirement.Release(); + ASSERT_EQ(held.swapchain, kFirst); + const KeptSurface kept = retirement.SwapchainGone(held.surface); + EXPECT_EQ(kept.surface, kSurface); + EXPECT_EQ(kept.instance, kInstance); + ASSERT_NE(kept.Allocator(), nullptr); + EXPECT_EQ(kept.Allocator()->pUserData, &user_data); + EXPECT_FALSE(retirement.SwapchainGone(kSurface)); +} + +TEST(SurfaceLifetimeTest, ASurfaceTheGameStillHasIsNotDestroyed) { + SwapchainRetirement retirement; + retirement.Created(kFirst, kSurface, VK_NULL_HANDLE); + EXPECT_FALSE(retirement.SwapchainGone(kSurface)); + EXPECT_FALSE(retirement.SurfaceDestroyed(kSurface, kInstance, nullptr)); } -TEST(SwapchainRetirementTest, AKeptSurfaceStillNeverRetiresIntoAnotherDevice) { +TEST(SurfaceLifetimeTest, ASurfaceWaitsForEverySwapchainOnIt) { SwapchainRetirement retirement; retirement.Created(kFirst, kSurface, VK_NULL_HANDLE); + retirement.Created(kSecond, kSurface, kFirst); + EXPECT_TRUE(retirement.SurfaceDestroyed(kSurface, kInstance, nullptr)); + EXPECT_FALSE(retirement.SwapchainGone(kSurface)); + EXPECT_EQ(retirement.SwapchainGone(kSurface).surface, kSurface); +} + +TEST(SwapchainShapeTest, ChainedOrSharedCreatesAreNeverReused) { + VkSwapchainCreateInfoKHR info{}; + info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; + EXPECT_TRUE(SwapchainShape::From(info).has_value()); + VkImageFormatListCreateInfo list{}; + list.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO; + info.pNext = &list; + EXPECT_FALSE(SwapchainShape::From(info).has_value()); + info.pNext = nullptr; + info.imageSharingMode = VK_SHARING_MODE_CONCURRENT; + EXPECT_FALSE(SwapchainShape::From(info).has_value()); +} + +// Roblox's same-size rebuild: create(old = S) with identical parameters, then +// destroy(S). +TEST(SwapchainReuseTest, AnIdenticalRebuildGetsTheSameSwapchainBack) { + SwapchainRetirement retirement; + retirement.Created(kFirst, kSurface, VK_NULL_HANDLE, kDevice, Shape()); + + EXPECT_EQ(retirement.Reuse(kDevice, kFirst, Shape()), kFirst); + EXPECT_TRUE(retirement.DropReference(kFirst)); + EXPECT_FALSE(retirement.DropReference(kFirst)); + EXPECT_FALSE(retirement.Destroyed(kDevice, kFirst, nullptr)); + EXPECT_EQ(retirement.Release().swapchain, kFirst); +} + +TEST(SwapchainReuseTest, AChangedRebuildIsNotReused) { + SwapchainRetirement retirement; + retirement.Created(kFirst, kSurface, VK_NULL_HANDLE, kDevice, Shape()); + + EXPECT_EQ(retirement.Reuse(kDevice, kFirst, Shape(1200, 700)), + VK_NULL_HANDLE); + EXPECT_EQ(retirement.Reuse(kOtherDevice, kFirst, Shape()), VK_NULL_HANDLE); + EXPECT_FALSE(retirement.DropReference(kFirst)); +} + +TEST(SwapchainReuseTest, ASwapchainWithoutAShapeIsNotReused) { + SwapchainRetirement retirement; + retirement.Created(kFirst, kSurface, VK_NULL_HANDLE, kDevice); + EXPECT_EQ(retirement.Reuse(kDevice, kFirst, Shape()), VK_NULL_HANDLE); +} + +TEST(SwapchainReuseTest, AnAcquiredImageBlocksReuseUntilPresented) { + SwapchainRetirement retirement; + retirement.Created(kFirst, kSurface, VK_NULL_HANDLE, kDevice, Shape()); + retirement.NoteAcquired(kFirst, 2); + EXPECT_EQ(retirement.Reuse(kDevice, kFirst, Shape()), VK_NULL_HANDLE); + retirement.NotePresented(kFirst, 2); + EXPECT_EQ(retirement.Reuse(kDevice, kFirst, Shape()), kFirst); +} + +TEST(SwapchainReuseTest, AnImageIndexPastTheTrackedRangeBlocksReuse) { + SwapchainRetirement retirement; + retirement.Created(kFirst, kSurface, VK_NULL_HANDLE, kDevice, Shape()); + retirement.NoteAcquired(kFirst, 64); + retirement.NotePresented(kFirst, 64); + EXPECT_EQ(retirement.Reuse(kDevice, kFirst, Shape()), VK_NULL_HANDLE); +} + +TEST(SwapchainReuseTest, AnOutOfDateOrSuboptimalSwapchainIsNotReused) { + for (const VkResult result : {VK_SUBOPTIMAL_KHR, VK_ERROR_OUT_OF_DATE_KHR, + VK_ERROR_SURFACE_LOST_KHR}) { + SwapchainRetirement retirement; + retirement.Created(kFirst, kSurface, VK_NULL_HANDLE, kDevice, Shape()); + retirement.NoteResult(kFirst, VK_SUCCESS); + EXPECT_EQ(retirement.Reuse(kDevice, kFirst, Shape()), kFirst); + EXPECT_TRUE(retirement.DropReference(kFirst)); + + retirement.NoteResult(kFirst, result); + EXPECT_EQ(retirement.Reuse(kDevice, kFirst, Shape()), VK_NULL_HANDLE); + } +} + +TEST(SwapchainReuseTest, ASwapchainRetiredByAHostCreateIsNotReused) { + SwapchainRetirement retirement; + retirement.Created(kFirst, kSurface, VK_NULL_HANDLE, kDevice, Shape()); + retirement.Created(kSecond, kSurface, kFirst, kDevice, Shape()); + EXPECT_EQ(retirement.Reuse(kDevice, kFirst, Shape()), VK_NULL_HANDLE); +} + +// Roblox's game join as logged: destroy(S), destroy its surface, create a new +// surface, then create a swapchain with identical parameters and no +// oldSwapchain. +TEST(SwapchainReuseTest, AJoinGetsTheHeldSwapchainBack) { + SwapchainRetirement retirement; + retirement.Created(kFirst, kSurface, VK_NULL_HANDLE, kDevice, Shape()); + EXPECT_FALSE(retirement.Destroyed(kDevice, kFirst, nullptr)); + EXPECT_TRUE(retirement.SurfaceDestroyed(kSurface, kInstance, nullptr)); + + EXPECT_EQ(retirement.Reuse(kDevice, VK_NULL_HANDLE, Shape()), kFirst); + EXPECT_FALSE(retirement.Release()); + // It is live again: the next identical rebuild reuses it too. + EXPECT_EQ(retirement.Reuse(kDevice, kFirst, Shape()), kFirst); + EXPECT_TRUE(retirement.DropReference(kFirst)); + // The new surface has no host swapchain, so it goes at once; the old one + // waits for the reused swapchain. + EXPECT_FALSE(retirement.SurfaceDestroyed(kOtherSurface, kInstance, nullptr)); + EXPECT_FALSE(retirement.Destroyed(kDevice, kFirst, nullptr)); + EXPECT_EQ(retirement.SwapchainGone(retirement.Release().surface).surface, + kSurface); +} + +// The other order: the new surface exists before the old one is destroyed. +TEST(SwapchainReuseTest, AJoinThatMakesTheNewSurfaceFirstStillReuses) { + SwapchainRetirement retirement; + retirement.Created(kFirst, kSurface, VK_NULL_HANDLE, kDevice, Shape()); + EXPECT_FALSE(retirement.Destroyed(kDevice, kFirst, nullptr)); + EXPECT_TRUE(retirement.SurfaceDestroyed(kSurface, kInstance, nullptr)); + EXPECT_EQ(retirement.Reuse(kDevice, VK_NULL_HANDLE, Shape()), kFirst); +} + +TEST(SwapchainReuseTest, AHeldSwapchainThatDoesNotFitRetiresIntoTheCreate) { + SwapchainRetirement retirement; + retirement.Created(kFirst, kSurface, VK_NULL_HANDLE, kDevice, Shape()); EXPECT_FALSE(retirement.Destroyed(kDevice, kFirst, nullptr)); - EXPECT_TRUE(retirement.DeferSurfaceDestroy(kSurface, kInstance, nullptr)); + EXPECT_TRUE(retirement.SurfaceDestroyed(kSurface, kInstance, nullptr)); + EXPECT_EQ(retirement.Reuse(kDevice, VK_NULL_HANDLE, Shape(800, 600)), + VK_NULL_HANDLE); VkSwapchainKHR old_swapchain = VK_NULL_HANDLE; - const HeldSwapchain held = - retirement.TakeForCreate(kOtherDevice, kOtherSurface, &old_swapchain); - EXPECT_EQ(old_swapchain, VK_NULL_HANDLE); - EXPECT_EQ(held.swapchain, kFirst); - EXPECT_TRUE(held.surface_destroy_deferred); + const HeldSwapchain held = retirement.TakeForCreate(kDevice, &old_swapchain); + EXPECT_EQ(old_swapchain, kFirst); + EXPECT_EQ(retirement.SwapchainGone(held.surface).surface, kSurface); } -TEST(SwapchainRetirementTest, ReleasingTheDeviceReturnsTheKeptSurface) { +TEST(SwapchainReuseTest, AHeldSwapchainWithAnAcquiredImageIsNotReused) { SwapchainRetirement retirement; - retirement.Created(kFirst, kSurface, VK_NULL_HANDLE); + retirement.Created(kFirst, kSurface, VK_NULL_HANDLE, kDevice, Shape()); + retirement.NoteAcquired(kFirst, 0); EXPECT_FALSE(retirement.Destroyed(kDevice, kFirst, nullptr)); - EXPECT_TRUE(retirement.DeferSurfaceDestroy(kSurface, kInstance, nullptr)); + EXPECT_EQ(retirement.Reuse(kDevice, VK_NULL_HANDLE, Shape()), VK_NULL_HANDLE); +} - const HeldSwapchain held = retirement.ReleaseIfDevice(kDevice); - EXPECT_EQ(held.swapchain, kFirst); - EXPECT_TRUE(held.surface_destroy_deferred); - EXPECT_EQ(held.SurfaceAllocator(), nullptr); +TEST(SwapchainReuseTest, AHeldSwapchainIsNotReusedOnAnotherDevice) { + SwapchainRetirement retirement; + retirement.Created(kFirst, kSurface, VK_NULL_HANDLE, kDevice, Shape()); + EXPECT_FALSE(retirement.Destroyed(kDevice, kFirst, nullptr)); + EXPECT_EQ(retirement.Reuse(kOtherDevice, VK_NULL_HANDLE, Shape()), + VK_NULL_HANDLE); } } // namespace