summaryrefslogtreecommitdiffstats
path: root/src/video_core/renderer_vulkan/vk_swapchain.cpp
blob: 08279e562e7e038c556f9f4919ba2fe5482d8f62 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
// Copyright 2019 yuzu Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.

#include <algorithm>
#include <array>
#include <limits>
#include <vector>

#include "common/assert.h"
#include "common/logging/log.h"
#include "core/core.h"
#include "core/frontend/framebuffer_layout.h"
#include "video_core/renderer_vulkan/declarations.h"
#include "video_core/renderer_vulkan/vk_device.h"
#include "video_core/renderer_vulkan/vk_resource_manager.h"
#include "video_core/renderer_vulkan/vk_swapchain.h"

namespace Vulkan {

namespace {
vk::SurfaceFormatKHR ChooseSwapSurfaceFormat(const std::vector<vk::SurfaceFormatKHR>& formats) {
    if (formats.size() == 1 && formats[0].format == vk::Format::eUndefined) {
        return {vk::Format::eB8G8R8A8Unorm, vk::ColorSpaceKHR::eSrgbNonlinear};
    }
    const auto& found = std::find_if(formats.begin(), formats.end(), [](const auto& format) {
        return format.format == vk::Format::eB8G8R8A8Unorm &&
               format.colorSpace == vk::ColorSpaceKHR::eSrgbNonlinear;
    });
    return found != formats.end() ? *found : formats[0];
}

vk::PresentModeKHR ChooseSwapPresentMode(const std::vector<vk::PresentModeKHR>& modes) {
    // Mailbox doesn't lock the application like fifo (vsync), prefer it
    const auto& found = std::find_if(modes.begin(), modes.end(), [](const auto& mode) {
        return mode == vk::PresentModeKHR::eMailbox;
    });
    return found != modes.end() ? *found : vk::PresentModeKHR::eFifo;
}

vk::Extent2D ChooseSwapExtent(const vk::SurfaceCapabilitiesKHR& capabilities, u32 width,
                              u32 height) {
    constexpr auto undefined_size{std::numeric_limits<u32>::max()};
    if (capabilities.currentExtent.width != undefined_size) {
        return capabilities.currentExtent;
    }
    vk::Extent2D extent = {width, height};
    extent.width = std::max(capabilities.minImageExtent.width,
                            std::min(capabilities.maxImageExtent.width, extent.width));
    extent.height = std::max(capabilities.minImageExtent.height,
                             std::min(capabilities.maxImageExtent.height, extent.height));
    return extent;
}
} // namespace

VKSwapchain::VKSwapchain(vk::SurfaceKHR surface, const VKDevice& device)
    : surface{surface}, device{device} {}

VKSwapchain::~VKSwapchain() = default;

void VKSwapchain::Create(u32 width, u32 height) {
    const auto dev = device.GetLogical();
    const auto& dld = device.GetDispatchLoader();
    const auto physical_device = device.GetPhysical();

    const vk::SurfaceCapabilitiesKHR capabilities{
        physical_device.getSurfaceCapabilitiesKHR(surface, dld)};
    if (capabilities.maxImageExtent.width == 0 || capabilities.maxImageExtent.height == 0) {
        return;
    }

    dev.waitIdle(dld);
    Destroy();

    CreateSwapchain(capabilities, width, height);
    CreateSemaphores();
    CreateImageViews();

    fences.resize(image_count, nullptr);
}

void VKSwapchain::AcquireNextImage() {
    const auto dev{device.GetLogical()};
    const auto& dld{device.GetDispatchLoader()};
    dev.acquireNextImageKHR(*swapchain, std::numeric_limits<u64>::max(),
                            *present_semaphores[frame_index], {}, &image_index, dld);

    if (auto& fence = fences[image_index]; fence) {
        fence->Wait();
        fence->Release();
        fence = nullptr;
    }
}

bool VKSwapchain::Present(vk::Semaphore render_semaphore, VKFence& fence) {
    const vk::Semaphore present_semaphore{*present_semaphores[frame_index]};
    const std::array<vk::Semaphore, 2> semaphores{present_semaphore, render_semaphore};
    const u32 wait_semaphore_count{render_semaphore ? 2U : 1U};
    const auto& dld{device.GetDispatchLoader()};
    const auto present_queue{device.GetPresentQueue()};
    bool recreated = false;

    const vk::PresentInfoKHR present_info(wait_semaphore_count, semaphores.data(), 1,
                                          &swapchain.get(), &image_index, {});
    switch (const auto result = present_queue.presentKHR(&present_info, dld); result) {
    case vk::Result::eSuccess:
        break;
    case vk::Result::eErrorOutOfDateKHR:
        if (current_width > 0 && current_height > 0) {
            Create(current_width, current_height);
            recreated = true;
        }
        break;
    default:
        LOG_CRITICAL(Render_Vulkan, "Vulkan failed to present swapchain due to {}!",
                     vk::to_string(result));
        UNREACHABLE();
    }

    ASSERT(fences[image_index] == nullptr);
    fences[image_index] = &fence;
    frame_index = (frame_index + 1) % image_count;
    return recreated;
}

bool VKSwapchain::HasFramebufferChanged(const Layout::FramebufferLayout& framebuffer) const {
    // TODO(Rodrigo): Handle framebuffer pixel format changes
    return framebuffer.width != current_width || framebuffer.height != current_height;
}

void VKSwapchain::CreateSwapchain(const vk::SurfaceCapabilitiesKHR& capabilities, u32 width,
                                  u32 height) {
    const auto dev{device.GetLogical()};
    const auto& dld{device.GetDispatchLoader()};
    const auto physical_device{device.GetPhysical()};

    const std::vector<vk::SurfaceFormatKHR> formats{
        physical_device.getSurfaceFormatsKHR(surface, dld)};

    const std::vector<vk::PresentModeKHR> present_modes{
        physical_device.getSurfacePresentModesKHR(surface, dld)};

    const vk::SurfaceFormatKHR surface_format{ChooseSwapSurfaceFormat(formats)};
    const vk::PresentModeKHR present_mode{ChooseSwapPresentMode(present_modes)};
    extent = ChooseSwapExtent(capabilities, width, height);

    current_width = extent.width;
    current_height = extent.height;

    u32 requested_image_count{capabilities.minImageCount + 1};
    if (capabilities.maxImageCount > 0 && requested_image_count > capabilities.maxImageCount) {
        requested_image_count = capabilities.maxImageCount;
    }

    vk::SwapchainCreateInfoKHR swapchain_ci(
        {}, surface, requested_image_count, surface_format.format, surface_format.colorSpace,
        extent, 1, vk::ImageUsageFlagBits::eColorAttachment, {}, {}, {},
        capabilities.currentTransform, vk::CompositeAlphaFlagBitsKHR::eOpaque, present_mode, false,
        {});

    const u32 graphics_family{device.GetGraphicsFamily()};
    const u32 present_family{device.GetPresentFamily()};
    const std::array<u32, 2> queue_indices{graphics_family, present_family};
    if (graphics_family != present_family) {
        swapchain_ci.imageSharingMode = vk::SharingMode::eConcurrent;
        swapchain_ci.queueFamilyIndexCount = static_cast<u32>(queue_indices.size());
        swapchain_ci.pQueueFamilyIndices = queue_indices.data();
    } else {
        swapchain_ci.imageSharingMode = vk::SharingMode::eExclusive;
    }

    swapchain = dev.createSwapchainKHRUnique(swapchain_ci, nullptr, dld);

    images = dev.getSwapchainImagesKHR(*swapchain, dld);
    image_count = static_cast<u32>(images.size());
    image_format = surface_format.format;
}

void VKSwapchain::CreateSemaphores() {
    const auto dev{device.GetLogical()};
    const auto& dld{device.GetDispatchLoader()};

    present_semaphores.resize(image_count);
    for (std::size_t i = 0; i < image_count; i++) {
        present_semaphores[i] = dev.createSemaphoreUnique({}, nullptr, dld);
    }
}

void VKSwapchain::CreateImageViews() {
    const auto dev{device.GetLogical()};
    const auto& dld{device.GetDispatchLoader()};

    image_views.resize(image_count);
    for (std::size_t i = 0; i < image_count; i++) {
        const vk::ImageViewCreateInfo image_view_ci({}, images[i], vk::ImageViewType::e2D,
                                                    image_format, {},
                                                    {vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1});
        image_views[i] = dev.createImageViewUnique(image_view_ci, nullptr, dld);
    }
}

void VKSwapchain::Destroy() {
    frame_index = 0;
    present_semaphores.clear();
    framebuffers.clear();
    image_views.clear();
    swapchain.reset();
}

} // namespace Vulkan