Files
Seele/src/Engine/Graphics/Vulkan/Window.cpp
T

423 lines
18 KiB
C++

#include "Window.h"
#include "Command.h"
#include "Enums.h"
#include "Graphics.h"
#include "Resources.h"
#include <vulkan/vulkan_core.h>
#define GLFW_EXPOSE_NATIVE_WAYLAND
#define GLFW_EXPOSE_NATIVE_X11
#include <GLFW/glfw3.h>
#include <GLFW/glfw3native.h>
#include <X11/Xlib.h>
#include <sstream>
#include <vulkan/vulkan_wayland.h>
#include <vulkan/vulkan_xlib.h>
using namespace Seele;
using namespace Seele::Vulkan;
namespace {
VkResult createSurfaceFromNativeHandles(VkInstance instance, GLFWwindow* handle, VkSurfaceKHR* surface, std::string& reason) {
#if defined(GLFW_PLATFORM_WAYLAND)
if (glfwGetPlatform() == GLFW_PLATFORM_WAYLAND) {
auto createWaylandSurface = reinterpret_cast<PFN_vkCreateWaylandSurfaceKHR>(
vkGetInstanceProcAddr(instance, "vkCreateWaylandSurfaceKHR"));
if (createWaylandSurface == nullptr) {
reason = "vkCreateWaylandSurfaceKHR is unavailable on the Vulkan instance";
return VK_ERROR_EXTENSION_NOT_PRESENT;
}
wl_display* display = glfwGetWaylandDisplay();
wl_surface* waylandSurface = glfwGetWaylandWindow(handle);
if (display == nullptr || waylandSurface == nullptr) {
reason = "GLFW did not provide valid Wayland native handles";
return VK_ERROR_INITIALIZATION_FAILED;
}
VkWaylandSurfaceCreateInfoKHR createInfo = {
.sType = VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR,
.pNext = nullptr,
.flags = 0,
.display = display,
.surface = waylandSurface,
};
return createWaylandSurface(instance, &createInfo, nullptr, surface);
}
#endif
#if defined(GLFW_PLATFORM_X11)
if (glfwGetPlatform() == GLFW_PLATFORM_X11) {
auto createXlibSurface = reinterpret_cast<PFN_vkCreateXlibSurfaceKHR>(
vkGetInstanceProcAddr(instance, "vkCreateXlibSurfaceKHR"));
if (createXlibSurface == nullptr) {
reason = "vkCreateXlibSurfaceKHR is unavailable on the Vulkan instance";
return VK_ERROR_EXTENSION_NOT_PRESENT;
}
Display* display = glfwGetX11Display();
::Window x11Window = glfwGetX11Window(handle);
if (display == nullptr || x11Window == 0) {
reason = "GLFW did not provide valid X11 native handles";
return VK_ERROR_INITIALIZATION_FAILED;
}
VkXlibSurfaceCreateInfoKHR createInfo = {
.sType = VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR,
.pNext = nullptr,
.flags = 0,
.dpy = display,
.window = x11Window,
};
return createXlibSurface(instance, &createInfo, nullptr, surface);
}
#endif
reason = "Unsupported GLFW platform for manual Vulkan surface creation";
return VK_ERROR_EXTENSION_NOT_PRESENT;
}
}
double currentFrameDelta = 0;
double Gfx::getCurrentFrameDelta() { return currentFrameDelta; }
double currentFrameTime = 0;
double Gfx::getCurrentFrameTime() { return currentFrameTime; }
uint32 currentFrameIndex = std::numeric_limits<uint32>::max();
uint32 Gfx::getCurrentFrameIndex() { return currentFrameIndex; }
void glfwKeyCallback(GLFWwindow* handle, int key, int, int action, int modifier) {
if (key == -1) {
return;
}
auto* window = static_cast<Seele::Vulkan::Window*>(glfwGetWindowUserPointer(handle));
window->keyPress(static_cast<Seele::KeyCode>(key), static_cast<InputAction>(action), modifier);
}
void glfwMouseMoveCallback(GLFWwindow* handle, double xpos, double ypos) {
auto* window = static_cast<Seele::Vulkan::Window*>(glfwGetWindowUserPointer(handle));
window->mouseMove(xpos, ypos);
}
void glfwMouseButtonCallback(GLFWwindow* handle, int button, int action, int modifier) {
auto* window = static_cast<Seele::Vulkan::Window*>(glfwGetWindowUserPointer(handle));
window->mouseButton(static_cast<MouseButton>(button), static_cast<InputAction>(action), static_cast<KeyModifierFlags>(modifier));
}
void glfwScrollCallback(GLFWwindow* handle, double xoffset, double yoffset) {
auto* window = static_cast<Seele::Vulkan::Window*>(glfwGetWindowUserPointer(handle));
window->scroll(xoffset, yoffset);
}
void glfwFileCallback(GLFWwindow* handle, int count, const char** paths) {
auto* window = static_cast<Seele::Vulkan::Window*>(glfwGetWindowUserPointer(handle));
window->fileDrop(count, paths);
}
void glfwCloseCallback(GLFWwindow* handle) {
auto* window = static_cast<Seele::Vulkan::Window*>(glfwGetWindowUserPointer(handle));
window->close();
}
void glfwFramebufferResizeCallback(GLFWwindow* handle, int width, int height) {
auto* window = static_cast<Seele::Vulkan::Window*>(glfwGetWindowUserPointer(handle));
window->resize(width, height);
}
Seele::Vulkan::Window::Window(PGraphics graphics, const WindowCreateInfo& createInfo)
: graphics(graphics), preferences(createInfo), instance(graphics->getInstance()), swapchain(VK_NULL_HANDLE) {
glfwGetMonitorContentScale(glfwGetPrimaryMonitor(), &contentScaleX, &contentScaleY);
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);
GLFWwindow* handle = glfwCreateWindow(createInfo.width / contentScaleX, createInfo.height / contentScaleY, createInfo.title, nullptr, nullptr);
if (handle == nullptr) {
const char* glfwError = nullptr;
glfwGetError(&glfwError);
std::string message = "Failed to create GLFW window";
if (glfwError != nullptr) {
message += ": ";
message += glfwError;
}
throw std::runtime_error(message);
}
windowHandle = handle;
glfwSetWindowUserPointer(handle, this);
glfwSetKeyCallback(handle, &glfwKeyCallback);
glfwSetCursorPosCallback(handle, &glfwMouseMoveCallback);
glfwSetMouseButtonCallback(handle, &glfwMouseButtonCallback);
glfwSetScrollCallback(handle, &glfwScrollCallback);
glfwSetDropCallback(handle, &glfwFileCallback);
glfwSetWindowCloseCallback(handle, &glfwCloseCallback);
glfwSetFramebufferSizeCallback(handle, &glfwFramebufferResizeCallback);
// glfwSetWindowSizeCallback(handle, &glfwResizeCallback);
VkResult surfaceResult = glfwCreateWindowSurface(instance, handle, nullptr, &surface);
if (surfaceResult != VK_SUCCESS || surface == VK_NULL_HANDLE) {
const char* glfwError = nullptr;
glfwGetError(&glfwError);
std::string nativeReason;
surfaceResult = createSurfaceFromNativeHandles(instance, handle, &surface, nativeReason);
if (surfaceResult != VK_SUCCESS || surface == VK_NULL_HANDLE) {
std::ostringstream oss;
oss << "Failed to create Vulkan surface via GLFW (VkResult=" << surfaceResult << ")";
if (glfwError != nullptr) {
oss << ": " << glfwError;
}
if (!nativeReason.empty()) {
oss << ". Native fallback failed: " << nativeReason;
}
throw std::runtime_error(oss.str());
}
}
querySurface();
chooseSwapSurfaceFormat();
framebufferFormat = cast(format.format);
chooseSwapPresentMode();
chooseSwapExtent();
framebufferWidth = extent.width;
framebufferHeight = extent.height;
createSwapChain();
}
Seele::Vulkan::Window::~Window() {
vkDestroySwapchainKHR(graphics->getDevice(), swapchain, nullptr);
vkDestroySurfaceKHR(instance, surface, nullptr);
glfwDestroyWindow(static_cast<GLFWwindow*>(windowHandle));
}
void Seele::Vulkan::Window::pollInput() { glfwPollEvents(); }
void Seele::Vulkan::Window::show() { glfwShowWindow(static_cast<GLFWwindow*>(windowHandle)); }
void Seele::Vulkan::Window::beginFrame() {
imageAvailableFences[currentSemaphoreIndex]->reset();
imageAvailableSemaphores[currentSemaphoreIndex]->resolveSignal();
imageAvailableSemaphores[currentSemaphoreIndex]->rotateSemaphore();
VK_CHECK(vkAcquireNextImageKHR(graphics->getDevice(), swapchain, std::numeric_limits<uint64>::max(),
imageAvailableSemaphores[currentSemaphoreIndex]->getHandle(),
imageAvailableFences[currentSemaphoreIndex]->getHandle(), &currentImageIndex));
imageAvailableSemaphores[currentSemaphoreIndex]->encodeSignal();
imageAvailableFences[currentSemaphoreIndex]->submit();
// The image was reacquired, so the previous presentation using this image's
// renderDone semaphore has completed and it can be safely reused
renderingDoneSemaphores[currentImageIndex]->resolveSignal();
graphics->getGraphicsCommands()->getCommands()->waitForSemaphore(VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
imageAvailableSemaphores[currentSemaphoreIndex]);
static double start = glfwGetTime();
double end = glfwGetTime();
currentFrameDelta = end - start;
currentFrameTime += currentFrameDelta;
start = end;
}
void Seele::Vulkan::Window::endFrame() {
swapChainTextures[currentImageIndex]->changeLayout(Gfx::SE_IMAGE_LAYOUT_PRESENT_SRC_KHR, Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
Gfx::SE_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, Gfx::SE_ACCESS_MEMORY_READ_BIT,
Gfx::SE_PIPELINE_STAGE_TOP_OF_PIPE_BIT);
renderingDoneSemaphores[currentImageIndex]->rotateSemaphore();
graphics->getGraphicsCommands()->submitCommands(renderingDoneSemaphores[currentImageIndex]);
VkSemaphore renderDoneHandle = renderingDoneSemaphores[currentImageIndex]->getHandle();
VkResult swapChainResult;
VkPresentInfoKHR presentInfo = {
.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
.pNext = nullptr,
.waitSemaphoreCount = 1,
.pWaitSemaphores = &renderDoneHandle,
.swapchainCount = 1,
.pSwapchains = &swapchain,
.pImageIndices = &currentImageIndex,
.pResults = &swapChainResult,
};
VkResult r = vkQueuePresentKHR(graphics->getGraphicsCommands()->getQueue()->getHandle(), &presentInfo);
// std::cout << "Semaphore " << renderDoneHandle << " signals present for image index " << currentImageIndex << std::endl;
if (swapChainResult == VK_ERROR_OUT_OF_DATE_KHR || swapChainResult == VK_SUBOPTIMAL_KHR || r == VK_ERROR_OUT_OF_DATE_KHR || r == VK_SUBOPTIMAL_KHR) {
createSwapChain();
} else {
VK_CHECK(r);
}
currentSemaphoreIndex = (currentSemaphoreIndex + 1) % Gfx::numFramesBuffered;
currentFrameIndex = currentSemaphoreIndex;
// graphics->waitDeviceIdle();
}
bool Seele::Vulkan::Window::shouldClose() const {
return glfwWindowShouldClose((GLFWwindow*)windowHandle);
}
Gfx::PTexture2D Seele::Vulkan::Window::getBackBuffer() const { return PTexture2D(swapChainTextures[currentImageIndex]); }
void Seele::Vulkan::Window::setKeyCallback(std::function<void(Seele::KeyCode, InputAction, KeyModifierFlags)> callback) { keyCallback = callback; }
void Seele::Vulkan::Window::setMouseMoveCallback(std::function<void(double, double)> callback) { mouseMoveCallback = callback; }
void Seele::Vulkan::Window::setMouseButtonCallback(std::function<void(MouseButton, InputAction, KeyModifierFlags)> callback) { mouseButtonCallback = callback; }
void Seele::Vulkan::Window::setScrollCallback(std::function<void(double, double)> callback) { scrollCallback = callback; }
void Seele::Vulkan::Window::setFileCallback(std::function<void(int, const char**)> callback) { fileCallback = callback; }
void Seele::Vulkan::Window::setCloseCallback(std::function<void()> callback) { closeCallback = callback; }
void Seele::Vulkan::Window::setResizeCallback(std::function<void(uint32, uint32)> callback) { resizeCallback = callback; }
void Seele::Vulkan::Window::keyPress(Seele::KeyCode code, InputAction action, KeyModifierFlags modifier) { keyCallback(code, action, modifier); }
void Seele::Vulkan::Window::mouseMove(double x, double y) { mouseMoveCallback(x, y); }
void Seele::Vulkan::Window::mouseButton(MouseButton button, InputAction action, KeyModifierFlags modifier) { mouseButtonCallback(button, action, modifier); }
void Seele::Vulkan::Window::scroll(double x, double y) { scrollCallback(x, y); }
void Seele::Vulkan::Window::fileDrop(int num, const char** files) { fileCallback(num, files); }
void Seele::Vulkan::Window::close() { closeCallback(); }
void Seele::Vulkan::Window::resize(int width, int height) {
if (width == 0 || height == 0) {
paused = true;
return;
}
paused = false;
querySurface();
chooseSwapSurfaceFormat();
framebufferFormat = cast(format.format);
chooseSwapPresentMode();
chooseSwapExtent();
framebufferWidth = extent.width;
framebufferHeight = extent.height;
createSwapChain();
resizeCallback(width, height);
}
void Seele::Vulkan::Window::querySurface() {
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(graphics->getPhysicalDevice(), surface, &capabilities);
uint32 numFormats;
vkGetPhysicalDeviceSurfaceFormatsKHR(graphics->getPhysicalDevice(), surface, &numFormats, nullptr);
supportedFormats.resize(numFormats);
vkGetPhysicalDeviceSurfaceFormatsKHR(graphics->getPhysicalDevice(), surface, &numFormats, supportedFormats.data());
uint32 numPresentModes;
vkGetPhysicalDeviceSurfacePresentModesKHR(graphics->getPhysicalDevice(), surface, &numPresentModes, nullptr);
supportedPresentModes.resize(numFormats);
vkGetPhysicalDeviceSurfacePresentModesKHR(graphics->getPhysicalDevice(), surface, &numPresentModes, supportedPresentModes.data());
}
void Seele::Vulkan::Window::chooseSwapSurfaceFormat() {
for (const auto& supportedFormat : supportedFormats) {
if (supportedFormat.format == cast(preferences.preferredFormat)) {
format = supportedFormat;
return;
}
}
for (const auto& supportedFormat : supportedFormats) {
if (supportedFormat.format == VK_FORMAT_R8G8B8A8_SRGB && supportedFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) {
format = supportedFormat;
return;
}
}
format = supportedFormats[0];
}
void Seele::Vulkan::Window::chooseSwapPresentMode() {
for (const auto& supportedPresentMode : supportedPresentModes) {
if (supportedPresentMode == VK_PRESENT_MODE_MAILBOX_KHR) {
presentMode = supportedPresentMode;
return;
}
}
presentMode = VK_PRESENT_MODE_FIFO_KHR;
}
void Seele::Vulkan::Window::chooseSwapExtent() {
if (capabilities.currentExtent.width != std::numeric_limits<uint32>::max()) {
extent = capabilities.currentExtent;
return;
}
int width, height;
glfwGetFramebufferSize(static_cast<GLFWwindow*>(windowHandle), &width, &height);
extent = {
static_cast<uint32>(width),
static_cast<uint32>(height),
};
extent.width = std::clamp(extent.width, capabilities.minImageExtent.width, capabilities.maxImageExtent.width);
extent.height = std::clamp(extent.height, capabilities.minImageExtent.height, capabilities.maxImageExtent.height);
}
void Seele::Vulkan::Window::createSwapChain() {
graphics->waitDeviceIdle();
uint32 imageCount = Gfx::numFramesBuffered;
VkSwapchainCreateInfoKHR createInfo = {
.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
.pNext = nullptr,
.surface = surface,
.minImageCount = Gfx::numFramesBuffered,
.imageFormat = format.format,
.imageColorSpace = format.colorSpace,
.imageExtent = extent,
.imageArrayLayers = 1,
.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT,
.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE,
.preTransform = capabilities.currentTransform,
.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
.presentMode = presentMode,
.clipped = VK_TRUE,
.oldSwapchain = swapchain,
};
VK_CHECK(vkCreateSwapchainKHR(graphics->getDevice(), &createInfo, nullptr, &swapchain));
VK_CHECK(vkGetSwapchainImagesKHR(graphics->getDevice(), swapchain, &imageCount, swapChainImages.data()));
for (uint32 i = 0; i < imageCount; ++i) {
swapChainTextures[i] = new Texture2D(graphics,
TextureCreateInfo{
.format = cast(format.format),
.width = extent.width,
.height = extent.height,
.depth = 1,
.elements = 1,
.samples = 1,
.usage = Gfx::SE_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | Gfx::SE_IMAGE_USAGE_TRANSFER_DST_BIT,
},
swapChainImages[i]);
if (imageAvailableFences[i] != nullptr) {
imageAvailableFences[i]->wait(100000);
imageAvailableFences[i]->reset();
}
imageAvailableFences[i] = new Fence(graphics);
imageAvailableSemaphores[i] = new Semaphore(graphics);
renderingDoneSemaphores[i] = new Semaphore(graphics);
}
}
Viewport::Viewport(PWindow owner, const ViewportCreateInfo& viewportInfo) : Gfx::Viewport(owner, viewportInfo) {
handle.x = static_cast<float>(offsetX);
handle.y = static_cast<float>(offsetY + sizeY);
handle.width = static_cast<float>(sizeX);
handle.height = -static_cast<float>(sizeY);
handle.minDepth = 1.f;
handle.maxDepth = 0.f;
}
Viewport::~Viewport() {}
void Viewport::resize(uint32 newX, uint32 newY) {
sizeX = newX;
sizeY = newY;
handle.width = static_cast<float>(sizeX);
handle.height = -static_cast<float>(sizeY);
}
void Viewport::move(uint32 newOffsetX, uint32 newOffsetY) {
offsetX = newOffsetX;
offsetY = newOffsetY;
handle.x = static_cast<float>(offsetX);
handle.y = static_cast<float>(offsetY + sizeY);
}