From 8d72aba9e3358fdf51578533ab7f46602f7fd103 Mon Sep 17 00:00:00 2001 From: Laszlo Agocs Date: Sun, 12 Feb 2017 15:08:52 +0100 Subject: Introduce QVulkanWindow A convenience subclass of QWindow that provides a Vulkan-capable window with a double-buffered FIFO swapchain. While advanced use cases are better served by a custom QWindow subclass, many applications can benefit from having a convenient helper that makes getting started easier. Add also three examples of increasing complexity, and a variant that shows embeddeding into widgets via QWindowContainer. [ChangeLog][QtGui] Added QVulkanWindow, a convenience subclass of QWindow. Task-number: QTBUG-55981 Change-Id: I6cdc9ff1390ac6258e278377233fd369a0bfeddc Reviewed-by: Andy Nichols --- examples/examples.pro | 5 +- examples/vulkan/doc/images/hellovulkantexture.png | Bin 0 -> 10259 bytes examples/vulkan/doc/images/hellovulkantriangle.png | Bin 0 -> 30952 bytes examples/vulkan/doc/images/hellovulkanwidget.png | Bin 0 -> 25256 bytes examples/vulkan/doc/images/hellovulkanwindow.png | Bin 0 -> 2736 bytes examples/vulkan/doc/src/hellovulkantexture.qdoc | 41 + examples/vulkan/doc/src/hellovulkantriangle.qdoc | 49 + examples/vulkan/doc/src/hellovulkanwidget.qdoc | 49 + examples/vulkan/doc/src/hellovulkanwindow.qdoc | 101 + .../hellovulkantexture/hellovulkantexture.cpp | 828 ++++++ .../vulkan/hellovulkantexture/hellovulkantexture.h | 108 + .../hellovulkantexture/hellovulkantexture.pro | 7 + .../hellovulkantexture/hellovulkantexture.qrc | 7 + examples/vulkan/hellovulkantexture/main.cpp | 91 + examples/vulkan/hellovulkantexture/qt256.png | Bin 0 -> 6208 bytes examples/vulkan/hellovulkantexture/texture.frag | 12 + examples/vulkan/hellovulkantexture/texture.vert | 18 + .../vulkan/hellovulkantexture/texture_frag.spv | Bin 0 -> 556 bytes .../vulkan/hellovulkantexture/texture_vert.spv | Bin 0 -> 968 bytes .../hellovulkantriangle/hellovulkantriangle.pro | 12 + .../hellovulkantriangle/hellovulkantriangle.qrc | 6 + examples/vulkan/hellovulkantriangle/main.cpp | 100 + .../vulkan/hellovulkanwidget/hellovulkanwidget.cpp | 182 ++ .../vulkan/hellovulkanwidget/hellovulkanwidget.h | 98 + .../vulkan/hellovulkanwidget/hellovulkanwidget.pro | 16 + .../vulkan/hellovulkanwidget/hellovulkanwidget.qrc | 6 + examples/vulkan/hellovulkanwidget/main.cpp | 93 + .../vulkan/hellovulkanwindow/hellovulkanwindow.cpp | 128 + .../vulkan/hellovulkanwindow/hellovulkanwindow.h | 77 + .../vulkan/hellovulkanwindow/hellovulkanwindow.pro | 6 + examples/vulkan/hellovulkanwindow/main.cpp | 93 + examples/vulkan/shared/color.frag | 10 + examples/vulkan/shared/color.vert | 18 + examples/vulkan/shared/color_frag.spv | Bin 0 -> 496 bytes examples/vulkan/shared/color_vert.spv | Bin 0 -> 960 bytes examples/vulkan/shared/trianglerenderer.cpp | 513 ++++ examples/vulkan/shared/trianglerenderer.h | 85 + examples/vulkan/vulkan.pro | 7 + src/gui/vulkan/qvulkanwindow.cpp | 2678 ++++++++++++++++++++ src/gui/vulkan/qvulkanwindow.h | 161 ++ src/gui/vulkan/qvulkanwindow_p.h | 188 ++ src/gui/vulkan/vulkan.pri | 7 +- tests/auto/gui/qvulkan/tst_qvulkan.cpp | 282 ++- 43 files changed, 6076 insertions(+), 6 deletions(-) create mode 100644 examples/vulkan/doc/images/hellovulkantexture.png create mode 100644 examples/vulkan/doc/images/hellovulkantriangle.png create mode 100644 examples/vulkan/doc/images/hellovulkanwidget.png create mode 100644 examples/vulkan/doc/images/hellovulkanwindow.png create mode 100644 examples/vulkan/doc/src/hellovulkantexture.qdoc create mode 100644 examples/vulkan/doc/src/hellovulkantriangle.qdoc create mode 100644 examples/vulkan/doc/src/hellovulkanwidget.qdoc create mode 100644 examples/vulkan/doc/src/hellovulkanwindow.qdoc create mode 100644 examples/vulkan/hellovulkantexture/hellovulkantexture.cpp create mode 100644 examples/vulkan/hellovulkantexture/hellovulkantexture.h create mode 100644 examples/vulkan/hellovulkantexture/hellovulkantexture.pro create mode 100644 examples/vulkan/hellovulkantexture/hellovulkantexture.qrc create mode 100644 examples/vulkan/hellovulkantexture/main.cpp create mode 100644 examples/vulkan/hellovulkantexture/qt256.png create mode 100644 examples/vulkan/hellovulkantexture/texture.frag create mode 100644 examples/vulkan/hellovulkantexture/texture.vert create mode 100644 examples/vulkan/hellovulkantexture/texture_frag.spv create mode 100644 examples/vulkan/hellovulkantexture/texture_vert.spv create mode 100644 examples/vulkan/hellovulkantriangle/hellovulkantriangle.pro create mode 100644 examples/vulkan/hellovulkantriangle/hellovulkantriangle.qrc create mode 100644 examples/vulkan/hellovulkantriangle/main.cpp create mode 100644 examples/vulkan/hellovulkanwidget/hellovulkanwidget.cpp create mode 100644 examples/vulkan/hellovulkanwidget/hellovulkanwidget.h create mode 100644 examples/vulkan/hellovulkanwidget/hellovulkanwidget.pro create mode 100644 examples/vulkan/hellovulkanwidget/hellovulkanwidget.qrc create mode 100644 examples/vulkan/hellovulkanwidget/main.cpp create mode 100644 examples/vulkan/hellovulkanwindow/hellovulkanwindow.cpp create mode 100644 examples/vulkan/hellovulkanwindow/hellovulkanwindow.h create mode 100644 examples/vulkan/hellovulkanwindow/hellovulkanwindow.pro create mode 100644 examples/vulkan/hellovulkanwindow/main.cpp create mode 100644 examples/vulkan/shared/color.frag create mode 100644 examples/vulkan/shared/color.vert create mode 100644 examples/vulkan/shared/color_frag.spv create mode 100644 examples/vulkan/shared/color_vert.spv create mode 100644 examples/vulkan/shared/trianglerenderer.cpp create mode 100644 examples/vulkan/shared/trianglerenderer.h create mode 100644 examples/vulkan/vulkan.pro create mode 100644 src/gui/vulkan/qvulkanwindow.cpp create mode 100644 src/gui/vulkan/qvulkanwindow.h create mode 100644 src/gui/vulkan/qvulkanwindow_p.h diff --git a/examples/examples.pro b/examples/examples.pro index f66c5cbf22..d2ce1fd294 100644 --- a/examples/examples.pro +++ b/examples/examples.pro @@ -15,7 +15,10 @@ SUBDIRS = \ widgets \ xml -qtHaveModule(gui):qtConfig(opengl): SUBDIRS += opengl +qtHaveModule(gui) { + qtConfig(opengl): SUBDIRS += opengl + qtConfig(vulkan): SUBDIRS += vulkan +} aggregate.files = aggregate/examples.pro aggregate.path = $$[QT_INSTALL_EXAMPLES] diff --git a/examples/vulkan/doc/images/hellovulkantexture.png b/examples/vulkan/doc/images/hellovulkantexture.png new file mode 100644 index 0000000000..0cb47a70be Binary files /dev/null and b/examples/vulkan/doc/images/hellovulkantexture.png differ diff --git a/examples/vulkan/doc/images/hellovulkantriangle.png b/examples/vulkan/doc/images/hellovulkantriangle.png new file mode 100644 index 0000000000..f88b27a873 Binary files /dev/null and b/examples/vulkan/doc/images/hellovulkantriangle.png differ diff --git a/examples/vulkan/doc/images/hellovulkanwidget.png b/examples/vulkan/doc/images/hellovulkanwidget.png new file mode 100644 index 0000000000..b85d4dc596 Binary files /dev/null and b/examples/vulkan/doc/images/hellovulkanwidget.png differ diff --git a/examples/vulkan/doc/images/hellovulkanwindow.png b/examples/vulkan/doc/images/hellovulkanwindow.png new file mode 100644 index 0000000000..c55029312c Binary files /dev/null and b/examples/vulkan/doc/images/hellovulkanwindow.png differ diff --git a/examples/vulkan/doc/src/hellovulkantexture.qdoc b/examples/vulkan/doc/src/hellovulkantexture.qdoc new file mode 100644 index 0000000000..d0e0ca90a8 --- /dev/null +++ b/examples/vulkan/doc/src/hellovulkantexture.qdoc @@ -0,0 +1,41 @@ +/**************************************************************************** +** +** Copyright (C) 2017 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Free Documentation License Usage +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. Please review the following information to ensure +** the GNU Free Documentation License version 1.3 requirements +** will be met: https://www.gnu.org/licenses/fdl-1.3.html. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \example hellovulkantexture + \ingroup examples-vulkan + \title Hello Vulkan Texture Vulkan Example + \brief Shows the basics of rendering with textures in a QVulkanWindow + + The \e{Hello Vulkan Texture Example} builds on \l hellovulkantriangle. Here + instead of drawing a single triangle, a triangle strip is drawn in order to + get a quad on the screen. This is then textured using a QImage loaded from + a .png image file. + + \image hellovulkantexture.png + \include examples-run.qdocinc +*/ diff --git a/examples/vulkan/doc/src/hellovulkantriangle.qdoc b/examples/vulkan/doc/src/hellovulkantriangle.qdoc new file mode 100644 index 0000000000..81af776ea1 --- /dev/null +++ b/examples/vulkan/doc/src/hellovulkantriangle.qdoc @@ -0,0 +1,49 @@ +/**************************************************************************** +** +** Copyright (C) 2017 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Free Documentation License Usage +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. Please review the following information to ensure +** the GNU Free Documentation License version 1.3 requirements +** will be met: https://www.gnu.org/licenses/fdl-1.3.html. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \example hellovulkantriangle + \ingroup examples-vulkan + \title Hello Vulkan Triangle Example + \brief Shows the basics of rendering with QVulkanWindow and the Vulkan API + + The \e{Hello Vulkan Triangle Example} builds on \l hellovulkanwindow. This + time a full graphics pipeline is created, including a vertex and fragment + shader. This pipeline is then used to render a triangle. + + \image hellovulkantriangle.png + + The example also demonstrates multisample antialiasing. Based on the + supported sample counts reported by QVulkanWindow::supportedSampleCounts() + the example chooses between 8x, 4x, or no multisampling. Once configured + via QVulkanWindow::setSamples(), QVulkanWindow takes care of the rest: the + additional multisample color buffers are created automatically, and + resolving into the swapchain buffers is performed at the end of the default + render pass for each frame. + + \include examples-run.qdocinc +*/ diff --git a/examples/vulkan/doc/src/hellovulkanwidget.qdoc b/examples/vulkan/doc/src/hellovulkanwidget.qdoc new file mode 100644 index 0000000000..7987bdeff9 --- /dev/null +++ b/examples/vulkan/doc/src/hellovulkanwidget.qdoc @@ -0,0 +1,49 @@ +/**************************************************************************** +** +** Copyright (C) 2017 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Free Documentation License Usage +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. Please review the following information to ensure +** the GNU Free Documentation License version 1.3 requirements +** will be met: https://www.gnu.org/licenses/fdl-1.3.html. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \example hellovulkanwidget + \ingroup examples-vulkan + \title Hello Vulkan Widget Example + \brief Shows the usage of QVulkanWindow in QWidget applications + + The \e{Hello Vulkan Widget Example} is a variant of \l hellovulkantriangle + that embeds the QVulkanWindow into a QWidget-based user interface using + QWidget::createWindowContainer(). + + \image hellovulkanwidget.png + + The code to set up the Vulkan pipeline and render the triangle is the same + as in \l hellovulkantriangle. In addition, this example demonstrates + another feature of QVulkanWindow: reading the image content back from the + color buffer into a QImage. By clicking the Grab button, the example + renders the next frame and follows it up with a transfer operation in order + to get the swapchain color buffer content copied into host accessible + memory. The image is then saved to disk via QImage::save(). + + \include examples-run.qdocinc +*/ diff --git a/examples/vulkan/doc/src/hellovulkanwindow.qdoc b/examples/vulkan/doc/src/hellovulkanwindow.qdoc new file mode 100644 index 0000000000..06cc9c1c28 --- /dev/null +++ b/examples/vulkan/doc/src/hellovulkanwindow.qdoc @@ -0,0 +1,101 @@ +/**************************************************************************** +** +** Copyright (C) 2017 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Free Documentation License Usage +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. Please review the following information to ensure +** the GNU Free Documentation License version 1.3 requirements +** will be met: https://www.gnu.org/licenses/fdl-1.3.html. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \example hellovulkanwindow + \title Hello Vulkan Window Example + \ingroup examples-vulkan + \brief Shows the basics of using QVulkanWindow + + The \e{Hello Vulkan Window Example} shows the basics of using QVulkanWindow + in order to display rendering with the Vulkan graphics API on systems that + support this. + + \image hellovulkanwindow.png + + In this example there will be no actual rendering: it simply begins and + ends a render pass, which results in clearing the buffers to a fixed value. + The color buffer clear value changes on every frame. + + \section1 Startup + + Each Qt application using Vulkan will have to have a \c{Vulkan instance} + which encapsulates application-level state and initializes a Vulkan library. + + A QVulkanWindow must always be associated with a QVulkanInstance and hence + the example performs instance creation before the window. The + QVulkanInstance object must also outlive the window. + + \snippet hellovulkanwindow/main.cpp 0 + + The example enables validation layers, when supported. When the requested + layers are not present, the request will be ignored. Additional layers and + extensions can be enabled in a similar manner. + + \snippet hellovulkanwindow/main.cpp 1 + + Once the instance is ready, it is time to create a window. Note that \c w + lives on the stack and is declared after \c inst. + + \section1 The QVulkanWindow Subclass + + To add custom functionality to a QVulkanWindow, subclassing is used. This + follows the existing patterns from QOpenGLWindow and QOpenGLWidget. + However, QVulkanWindow utilizes a separate QVulkanWindowRenderer object. + This resembles QQuickFramebufferObject, and allows better separation of the + functions that are supposed to be reimplemented. + + \snippet hellovulkanwindow/hellovulkanwindow.h 0 + + The QVulkanWindow subclass reimplements the factory function + QVulkanWindow::createRenderer(). This simply returns a new instance of the + QVulkanWindowRenderer subclass. In order to be able to access various + Vulkan resources via the window object, a pointer to the window is passed + and stored via the constructor. + + \snippet hellovulkanwindow/hellovulkanwindow.cpp 0 + + Graphics resource creation and destruction is typically done in one of the + init - resource functions. + + \snippet hellovulkanwindow/hellovulkanwindow.cpp 1 + + \section1 The Actual Rendering + + QVulkanWindow subclasses queue their draw calls in their reimplementation + of QVulkanWindowRenderer::startNextFrame(). Once done, they are required to + call back QVulkanWindow::frameReady(). The example has no asynchronous + command generation, so the frameReady() call is made directly from + startNextFrame(). + + \snippet hellovulkanwindow/hellovulkanwindow.cpp 2 + + To get continuous updates, the example simply invokes + QWindow::requestUpdate() in order to schedule a repaint. + + \include examples-run.qdocinc +*/ diff --git a/examples/vulkan/hellovulkantexture/hellovulkantexture.cpp b/examples/vulkan/hellovulkantexture/hellovulkantexture.cpp new file mode 100644 index 0000000000..9953352e28 --- /dev/null +++ b/examples/vulkan/hellovulkantexture/hellovulkantexture.cpp @@ -0,0 +1,828 @@ +/**************************************************************************** +** +** Copyright (C) 2017 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "hellovulkantexture.h" +#include +#include +#include + +// Use a triangle strip to get a quad. +// +// Note that the vertex data and the projection matrix assume OpenGL. With +// Vulkan Y is negated in clip space and the near/far plane is at 0/1 instead +// of -1/1. These will be corrected for by an extra transformation when +// calculating the modelview-projection matrix. +static float vertexData[] = { + // x, y, z, u, v + -1, -1, 0, 0, 1, + -1, 1, 0, 0, 0, + 1, -1, 0, 1, 1, + 1, 1, 0, 1, 0 +}; + +static const int UNIFORM_DATA_SIZE = 16 * sizeof(float); + +static inline VkDeviceSize aligned(VkDeviceSize v, VkDeviceSize byteAlign) +{ + return (v + byteAlign - 1) & ~(byteAlign - 1); +} + +QVulkanWindowRenderer *VulkanWindow::createRenderer() +{ + return new VulkanRenderer(this); +} + +VulkanRenderer::VulkanRenderer(QVulkanWindow *w) + : m_window(w) +{ +} + +VkShaderModule VulkanRenderer::createShader(const QString &name) +{ + QFile file(name); + if (!file.open(QIODevice::ReadOnly)) { + qWarning("Failed to read shader %s", qPrintable(name)); + return VK_NULL_HANDLE; + } + QByteArray blob = file.readAll(); + file.close(); + + VkShaderModuleCreateInfo shaderInfo; + memset(&shaderInfo, 0, sizeof(shaderInfo)); + shaderInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; + shaderInfo.codeSize = blob.size(); + shaderInfo.pCode = reinterpret_cast(blob.constData()); + VkShaderModule shaderModule; + VkResult err = m_devFuncs->vkCreateShaderModule(m_window->device(), &shaderInfo, nullptr, &shaderModule); + if (err != VK_SUCCESS) { + qWarning("Failed to create shader module: %d", err); + return VK_NULL_HANDLE; + } + + return shaderModule; +} + +bool VulkanRenderer::createTexture(const QString &name) +{ + QImage img(name); + if (img.isNull()) { + qWarning("Failed to load image %s", qPrintable(name)); + return false; + } + + // Convert to byte ordered RGBA8. Use premultiplied alpha, see pColorBlendState in the pipeline. + img = img.convertToFormat(QImage::Format_RGBA8888_Premultiplied); + + QVulkanFunctions *f = m_window->vulkanInstance()->functions(); + VkDevice dev = m_window->device(); + + const bool srgb = QCoreApplication::arguments().contains(QStringLiteral("--srgb")); + if (srgb) + qDebug("sRGB swapchain was requested, making texture sRGB too"); + + m_texFormat = srgb ? VK_FORMAT_R8G8B8A8_SRGB : VK_FORMAT_R8G8B8A8_UNORM; + + // Now we can either map and copy the image data directly, or have to go + // through a staging buffer to copy and convert into the internal optimal + // tiling format. + VkFormatProperties props; + f->vkGetPhysicalDeviceFormatProperties(m_window->physicalDevice(), m_texFormat, &props); + const bool canSampleLinear = (props.linearTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT); + const bool canSampleOptimal = (props.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT); + if (!canSampleLinear && !canSampleOptimal) { + qWarning("Neither linear nor optimal image sampling is supported for RGBA8"); + return false; + } + + static bool alwaysStage = qEnvironmentVariableIntValue("QT_VK_FORCE_STAGE_TEX"); + + if (canSampleLinear && !alwaysStage) { + if (!createTextureImage(img.size(), &m_texImage, &m_texMem, + VK_IMAGE_TILING_LINEAR, VK_IMAGE_USAGE_SAMPLED_BIT, + m_window->hostVisibleMemoryIndex())) + return false; + + if (!writeLinearImage(img, m_texImage, m_texMem)) + return false; + + m_texLayoutPending = true; + } else { + if (!createTextureImage(img.size(), &m_texStaging, &m_texStagingMem, + VK_IMAGE_TILING_LINEAR, VK_IMAGE_USAGE_TRANSFER_SRC_BIT, + m_window->hostVisibleMemoryIndex())) + return false; + + if (!createTextureImage(img.size(), &m_texImage, &m_texMem, + VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, + m_window->deviceLocalMemoryIndex())) + return false; + + if (!writeLinearImage(img, m_texStaging, m_texStagingMem)) + return false; + + m_texStagingPending = true; + } + + VkImageViewCreateInfo viewInfo; + memset(&viewInfo, 0, sizeof(viewInfo)); + viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + viewInfo.image = m_texImage; + viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; + viewInfo.format = m_texFormat; + viewInfo.components.r = VK_COMPONENT_SWIZZLE_R; + viewInfo.components.g = VK_COMPONENT_SWIZZLE_G; + viewInfo.components.b = VK_COMPONENT_SWIZZLE_B; + viewInfo.components.a = VK_COMPONENT_SWIZZLE_A; + viewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + viewInfo.subresourceRange.levelCount = viewInfo.subresourceRange.layerCount = 1; + + VkResult err = m_devFuncs->vkCreateImageView(dev, &viewInfo, nullptr, &m_texView); + if (err != VK_SUCCESS) { + qWarning("Failed to create image view for texture: %d", err); + return false; + } + + m_texSize = img.size(); + + return true; +} + +bool VulkanRenderer::createTextureImage(const QSize &size, VkImage *image, VkDeviceMemory *mem, + VkImageTiling tiling, VkImageUsageFlags usage, uint32_t memIndex) +{ + VkDevice dev = m_window->device(); + + VkImageCreateInfo imageInfo; + memset(&imageInfo, 0, sizeof(imageInfo)); + imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + imageInfo.imageType = VK_IMAGE_TYPE_2D; + imageInfo.format = m_texFormat; + imageInfo.extent.width = size.width(); + imageInfo.extent.height = size.height(); + imageInfo.extent.depth = 1; + imageInfo.mipLevels = 1; + imageInfo.arrayLayers = 1; + imageInfo.samples = VK_SAMPLE_COUNT_1_BIT; + imageInfo.tiling = tiling; + imageInfo.usage = usage; + imageInfo.initialLayout = VK_IMAGE_LAYOUT_PREINITIALIZED; + + VkResult err = m_devFuncs->vkCreateImage(dev, &imageInfo, nullptr, image); + if (err != VK_SUCCESS) { + qWarning("Failed to create linear image for texture: %d", err); + return false; + } + + VkMemoryRequirements memReq; + m_devFuncs->vkGetImageMemoryRequirements(dev, *image, &memReq); + + VkMemoryAllocateInfo allocInfo = { + VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, + nullptr, + memReq.size, + memIndex + }; + qDebug("allocating %u bytes for texture image", uint32_t(memReq.size)); + + err = m_devFuncs->vkAllocateMemory(dev, &allocInfo, nullptr, mem); + if (err != VK_SUCCESS) { + qWarning("Failed to allocate memory for linear image: %d", err); + return false; + } + + err = m_devFuncs->vkBindImageMemory(dev, *image, *mem, 0); + if (err != VK_SUCCESS) { + qWarning("Failed to bind linear image memory: %d", err); + return false; + } + + return true; +} + +bool VulkanRenderer::writeLinearImage(const QImage &img, VkImage image, VkDeviceMemory memory) +{ + VkDevice dev = m_window->device(); + + VkImageSubresource subres = { + VK_IMAGE_ASPECT_COLOR_BIT, + 0, // mip level + 0 + }; + VkSubresourceLayout layout; + m_devFuncs->vkGetImageSubresourceLayout(dev, image, &subres, &layout); + + uchar *p; + VkResult err = m_devFuncs->vkMapMemory(dev, memory, layout.offset, layout.size, 0, reinterpret_cast(&p)); + if (err != VK_SUCCESS) { + qWarning("Failed to map memory for linear image: %d", err); + return false; + } + + for (int y = 0; y < img.height(); ++y) { + const uchar *line = img.constScanLine(y); + memcpy(p, line, img.width() * 4); + p += layout.rowPitch; + } + + m_devFuncs->vkUnmapMemory(dev, memory); + return true; +} + +void VulkanRenderer::ensureTexture() +{ + if (!m_texLayoutPending && !m_texStagingPending) + return; + + Q_ASSERT(m_texLayoutPending != m_texStagingPending); + VkCommandBuffer cb = m_window->currentCommandBuffer(); + + VkImageMemoryBarrier barrier; + memset(&barrier, 0, sizeof(barrier)); + barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + barrier.subresourceRange.levelCount = barrier.subresourceRange.layerCount = 1; + + if (m_texLayoutPending) { + m_texLayoutPending = false; + + barrier.oldLayout = VK_IMAGE_LAYOUT_PREINITIALIZED; + barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + barrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; + barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; + barrier.image = m_texImage; + + m_devFuncs->vkCmdPipelineBarrier(cb, + VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, + 0, 0, nullptr, 0, nullptr, + 1, &barrier); + } else { + m_texStagingPending = false; + + barrier.oldLayout = VK_IMAGE_LAYOUT_PREINITIALIZED; + barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; + barrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; + barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; + barrier.image = m_texStaging; + m_devFuncs->vkCmdPipelineBarrier(cb, + VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, + 0, 0, nullptr, 0, nullptr, + 1, &barrier); + + barrier.oldLayout = VK_IMAGE_LAYOUT_PREINITIALIZED; + barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + barrier.srcAccessMask = 0; + barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + barrier.image = m_texImage; + m_devFuncs->vkCmdPipelineBarrier(cb, + VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, + 0, 0, nullptr, 0, nullptr, + 1, &barrier); + + VkImageCopy copyInfo; + memset(©Info, 0, sizeof(copyInfo)); + copyInfo.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + copyInfo.srcSubresource.layerCount = 1; + copyInfo.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + copyInfo.dstSubresource.layerCount = 1; + copyInfo.extent.width = m_texSize.width(); + copyInfo.extent.height = m_texSize.height(); + copyInfo.extent.depth = 1; + m_devFuncs->vkCmdCopyImage(cb, m_texStaging, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + m_texImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©Info); + + barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; + barrier.image = m_texImage; + m_devFuncs->vkCmdPipelineBarrier(cb, + VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, + 0, 0, nullptr, 0, nullptr, + 1, &barrier); + } +} + +void VulkanRenderer::initResources() +{ + qDebug("initResources"); + + VkDevice dev = m_window->device(); + m_devFuncs = m_window->vulkanInstance()->deviceFunctions(dev); + + // The setup is similar to hellovulkantriangle. The difference is the + // presence of a second vertex attribute (texcoord), a sampler, and that we + // need blending. + + const int concurrentFrameCount = m_window->concurrentFrameCount(); + const VkPhysicalDeviceLimits *pdevLimits = &m_window->physicalDeviceProperties()->limits; + const VkDeviceSize uniAlign = pdevLimits->minUniformBufferOffsetAlignment; + qDebug("uniform buffer offset alignment is %u", (uint) uniAlign); + VkBufferCreateInfo bufInfo; + memset(&bufInfo, 0, sizeof(bufInfo)); + bufInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + // Our internal layout is vertex, uniform, uniform, ... with each uniform buffer start offset aligned to uniAlign. + const VkDeviceSize vertexAllocSize = aligned(sizeof(vertexData), uniAlign); + const VkDeviceSize uniformAllocSize = aligned(UNIFORM_DATA_SIZE, uniAlign); + bufInfo.size = vertexAllocSize + concurrentFrameCount * uniformAllocSize; + bufInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; + + VkResult err = m_devFuncs->vkCreateBuffer(dev, &bufInfo, nullptr, &m_buf); + if (err != VK_SUCCESS) + qFatal("Failed to create buffer: %d", err); + + VkMemoryRequirements memReq; + m_devFuncs->vkGetBufferMemoryRequirements(dev, m_buf, &memReq); + + VkMemoryAllocateInfo memAllocInfo = { + VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, + nullptr, + memReq.size, + m_window->hostVisibleMemoryIndex() + }; + + err = m_devFuncs->vkAllocateMemory(dev, &memAllocInfo, nullptr, &m_bufMem); + if (err != VK_SUCCESS) + qFatal("Failed to allocate memory: %d", err); + + err = m_devFuncs->vkBindBufferMemory(dev, m_buf, m_bufMem, 0); + if (err != VK_SUCCESS) + qFatal("Failed to bind buffer memory: %d", err); + + quint8 *p; + err = m_devFuncs->vkMapMemory(dev, m_bufMem, 0, memReq.size, 0, reinterpret_cast(&p)); + if (err != VK_SUCCESS) + qFatal("Failed to map memory: %d", err); + memcpy(p, vertexData, sizeof(vertexData)); + QMatrix4x4 ident; + memset(m_uniformBufInfo, 0, sizeof(m_uniformBufInfo)); + for (int i = 0; i < concurrentFrameCount; ++i) { + const VkDeviceSize offset = vertexAllocSize + i * uniformAllocSize; + memcpy(p + offset, ident.constData(), 16 * sizeof(float)); + m_uniformBufInfo[i].buffer = m_buf; + m_uniformBufInfo[i].offset = offset; + m_uniformBufInfo[i].range = uniformAllocSize; + } + m_devFuncs->vkUnmapMemory(dev, m_bufMem); + + VkVertexInputBindingDescription vertexBindingDesc = { + 0, // binding + 5 * sizeof(float), + VK_VERTEX_INPUT_RATE_VERTEX + }; + VkVertexInputAttributeDescription vertexAttrDesc[] = { + { // position + 0, // location + 0, // binding + VK_FORMAT_R32G32B32_SFLOAT, + 0 + }, + { // texcoord + 1, + 0, + VK_FORMAT_R32G32_SFLOAT, + 3 * sizeof(float) + } + }; + + VkPipelineVertexInputStateCreateInfo vertexInputInfo; + vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; + vertexInputInfo.pNext = nullptr; + vertexInputInfo.flags = 0; + vertexInputInfo.vertexBindingDescriptionCount = 1; + vertexInputInfo.pVertexBindingDescriptions = &vertexBindingDesc; + vertexInputInfo.vertexAttributeDescriptionCount = 2; + vertexInputInfo.pVertexAttributeDescriptions = vertexAttrDesc; + + // Sampler. + VkSamplerCreateInfo samplerInfo; + memset(&samplerInfo, 0, sizeof(samplerInfo)); + samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; + samplerInfo.magFilter = VK_FILTER_NEAREST; + samplerInfo.minFilter = VK_FILTER_NEAREST; + samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; + samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; + samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; + err = m_devFuncs->vkCreateSampler(dev, &samplerInfo, nullptr, &m_sampler); + if (err != VK_SUCCESS) + qFatal("Failed to create sampler: %d", err); + + // Texture. + if (!createTexture(QStringLiteral(":/qt256.png"))) + qFatal("Failed to create texture"); + + // Set up descriptor set and its layout. + VkDescriptorPoolSize descPoolSizes[2] = { + { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, uint32_t(concurrentFrameCount) }, + { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, uint32_t(concurrentFrameCount) } + }; + VkDescriptorPoolCreateInfo descPoolInfo; + memset(&descPoolInfo, 0, sizeof(descPoolInfo)); + descPoolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; + descPoolInfo.maxSets = concurrentFrameCount; + descPoolInfo.poolSizeCount = 2; + descPoolInfo.pPoolSizes = descPoolSizes; + err = m_devFuncs->vkCreateDescriptorPool(dev, &descPoolInfo, nullptr, &m_descPool); + if (err != VK_SUCCESS) + qFatal("Failed to create descriptor pool: %d", err); + + VkDescriptorSetLayoutBinding layoutBinding[2] = + { + { + 0, // binding + VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, + 1, // descriptorCount + VK_SHADER_STAGE_VERTEX_BIT, + nullptr + }, + { + 1, // binding + VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, + 1, // descriptorCount + VK_SHADER_STAGE_FRAGMENT_BIT, + nullptr + } + }; + VkDescriptorSetLayoutCreateInfo descLayoutInfo = { + VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, + nullptr, + 0, + 2, // bindingCount + layoutBinding + }; + err = m_devFuncs->vkCreateDescriptorSetLayout(dev, &descLayoutInfo, nullptr, &m_descSetLayout); + if (err != VK_SUCCESS) + qFatal("Failed to create descriptor set layout: %d", err); + + for (int i = 0; i < concurrentFrameCount; ++i) { + VkDescriptorSetAllocateInfo descSetAllocInfo = { + VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, + nullptr, + m_descPool, + 1, + &m_descSetLayout + }; + err = m_devFuncs->vkAllocateDescriptorSets(dev, &descSetAllocInfo, &m_descSet[i]); + if (err != VK_SUCCESS) + qFatal("Failed to allocate descriptor set: %d", err); + + VkWriteDescriptorSet descWrite[2]; + memset(descWrite, 0, sizeof(descWrite)); + descWrite[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + descWrite[0].dstSet = m_descSet[i]; + descWrite[0].dstBinding = 0; + descWrite[0].descriptorCount = 1; + descWrite[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; + descWrite[0].pBufferInfo = &m_uniformBufInfo[i]; + + VkDescriptorImageInfo descImageInfo = { + m_sampler, + m_texView, + VK_IMAGE_LAYOUT_GENERAL + }; + + descWrite[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + descWrite[1].dstSet = m_descSet[i]; + descWrite[1].dstBinding = 1; + descWrite[1].descriptorCount = 1; + descWrite[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + descWrite[1].pImageInfo = &descImageInfo; + + m_devFuncs->vkUpdateDescriptorSets(dev, 2, descWrite, 0, nullptr); + } + + // Pipeline cache + VkPipelineCacheCreateInfo pipelineCacheInfo; + memset(&pipelineCacheInfo, 0, sizeof(pipelineCacheInfo)); + pipelineCacheInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO; + err = m_devFuncs->vkCreatePipelineCache(dev, &pipelineCacheInfo, nullptr, &m_pipelineCache); + if (err != VK_SUCCESS) + qFatal("Failed to create pipeline cache: %d", err); + + // Pipeline layout + VkPipelineLayoutCreateInfo pipelineLayoutInfo; + memset(&pipelineLayoutInfo, 0, sizeof(pipelineLayoutInfo)); + pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; + pipelineLayoutInfo.setLayoutCount = 1; + pipelineLayoutInfo.pSetLayouts = &m_descSetLayout; + err = m_devFuncs->vkCreatePipelineLayout(dev, &pipelineLayoutInfo, nullptr, &m_pipelineLayout); + if (err != VK_SUCCESS) + qFatal("Failed to create pipeline layout: %d", err); + + // Shaders + VkShaderModule vertShaderModule = createShader(QStringLiteral(":/texture_vert.spv")); + VkShaderModule fragShaderModule = createShader(QStringLiteral(":/texture_frag.spv")); + + // Graphics pipeline + VkGraphicsPipelineCreateInfo pipelineInfo; + memset(&pipelineInfo, 0, sizeof(pipelineInfo)); + pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; + + VkPipelineShaderStageCreateInfo shaderStages[2] = { + { + VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, + nullptr, + 0, + VK_SHADER_STAGE_VERTEX_BIT, + vertShaderModule, + "main", + nullptr + }, + { + VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, + nullptr, + 0, + VK_SHADER_STAGE_FRAGMENT_BIT, + fragShaderModule, + "main", + nullptr + } + }; + pipelineInfo.stageCount = 2; + pipelineInfo.pStages = shaderStages; + + pipelineInfo.pVertexInputState = &vertexInputInfo; + + VkPipelineInputAssemblyStateCreateInfo ia; + memset(&ia, 0, sizeof(ia)); + ia.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; + ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP; + pipelineInfo.pInputAssemblyState = &ia; + + // The viewport and scissor will be set dynamically via vkCmdSetViewport/Scissor. + // This way the pipeline does not need to be touched when resizing the window. + VkPipelineViewportStateCreateInfo vp; + memset(&vp, 0, sizeof(vp)); + vp.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; + vp.viewportCount = 1; + vp.scissorCount = 1; + pipelineInfo.pViewportState = &vp; + + VkPipelineRasterizationStateCreateInfo rs; + memset(&rs, 0, sizeof(rs)); + rs.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; + rs.polygonMode = VK_POLYGON_MODE_FILL; + rs.cullMode = VK_CULL_MODE_NONE; // we want the back face as well + rs.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; + rs.lineWidth = 1.0f; + pipelineInfo.pRasterizationState = &rs; + + VkPipelineMultisampleStateCreateInfo ms; + memset(&ms, 0, sizeof(ms)); + ms.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; + ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; + pipelineInfo.pMultisampleState = &ms; + + VkPipelineDepthStencilStateCreateInfo ds; + memset(&ds, 0, sizeof(ds)); + ds.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; + ds.depthTestEnable = VK_TRUE; + ds.depthWriteEnable = VK_TRUE; + ds.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL; + pipelineInfo.pDepthStencilState = &ds; + + VkPipelineColorBlendStateCreateInfo cb; + memset(&cb, 0, sizeof(cb)); + cb.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; + // assume pre-multiplied alpha, blend, write out all of rgba + VkPipelineColorBlendAttachmentState att; + memset(&att, 0, sizeof(att)); + att.colorWriteMask = 0xF; + att.blendEnable = VK_TRUE; + att.srcColorBlendFactor = VK_BLEND_FACTOR_ONE; + att.dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; + att.colorBlendOp = VK_BLEND_OP_ADD; + att.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; + att.dstAlphaBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; + att.alphaBlendOp = VK_BLEND_OP_ADD; + cb.attachmentCount = 1; + cb.pAttachments = &att; + pipelineInfo.pColorBlendState = &cb; + + VkDynamicState dynEnable[] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; + VkPipelineDynamicStateCreateInfo dyn; + memset(&dyn, 0, sizeof(dyn)); + dyn.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; + dyn.dynamicStateCount = sizeof(dynEnable) / sizeof(VkDynamicState); + dyn.pDynamicStates = dynEnable; + pipelineInfo.pDynamicState = &dyn; + + pipelineInfo.layout = m_pipelineLayout; + pipelineInfo.renderPass = m_window->defaultRenderPass(); + + err = m_devFuncs->vkCreateGraphicsPipelines(dev, m_pipelineCache, 1, &pipelineInfo, nullptr, &m_pipeline); + if (err != VK_SUCCESS) + qFatal("Failed to create graphics pipeline: %d", err); + + if (vertShaderModule) + m_devFuncs->vkDestroyShaderModule(dev, vertShaderModule, nullptr); + if (fragShaderModule) + m_devFuncs->vkDestroyShaderModule(dev, fragShaderModule, nullptr); +} + +void VulkanRenderer::initSwapChainResources() +{ + qDebug("initSwapChainResources"); + + // Projection matrix + m_proj = *m_window->clipCorrectionMatrix(); // adjust for Vulkan-OpenGL clip space differences + const QSize sz = m_window->swapChainImageSize(); + m_proj.perspective(45.0f, sz.width() / (float) sz.height(), 0.01f, 100.0f); + m_proj.translate(0, 0, -4); +} + +void VulkanRenderer::releaseSwapChainResources() +{ + qDebug("releaseSwapChainResources"); +} + +void VulkanRenderer::releaseResources() +{ + qDebug("releaseResources"); + + VkDevice dev = m_window->device(); + + if (m_sampler) { + m_devFuncs->vkDestroySampler(dev, m_sampler, nullptr); + m_sampler = VK_NULL_HANDLE; + } + + if (m_texStaging) { + m_devFuncs->vkDestroyImage(dev, m_texStaging, nullptr); + m_texStaging = VK_NULL_HANDLE; + } + + if (m_texStagingMem) { + m_devFuncs->vkFreeMemory(dev, m_texStagingMem, nullptr); + m_texStagingMem = VK_NULL_HANDLE; + } + + if (m_texView) { + m_devFuncs->vkDestroyImageView(dev, m_texView, nullptr); + m_texView = VK_NULL_HANDLE; + } + + if (m_texImage) { + m_devFuncs->vkDestroyImage(dev, m_texImage, nullptr); + m_texImage = VK_NULL_HANDLE; + } + + if (m_texMem) { + m_devFuncs->vkFreeMemory(dev, m_texMem, nullptr); + m_texMem = VK_NULL_HANDLE; + } + + if (m_pipeline) { + m_devFuncs->vkDestroyPipeline(dev, m_pipeline, nullptr); + m_pipeline = VK_NULL_HANDLE; + } + + if (m_pipelineLayout) { + m_devFuncs->vkDestroyPipelineLayout(dev, m_pipelineLayout, nullptr); + m_pipelineLayout = VK_NULL_HANDLE; + } + + if (m_pipelineCache) { + m_devFuncs->vkDestroyPipelineCache(dev, m_pipelineCache, nullptr); + m_pipelineCache = VK_NULL_HANDLE; + } + + if (m_descSetLayout) { + m_devFuncs->vkDestroyDescriptorSetLayout(dev, m_descSetLayout, nullptr); + m_descSetLayout = VK_NULL_HANDLE; + } + + if (m_descPool) { + m_devFuncs->vkDestroyDescriptorPool(dev, m_descPool, nullptr); + m_descPool = VK_NULL_HANDLE; + } + + if (m_buf) { + m_devFuncs->vkDestroyBuffer(dev, m_buf, nullptr); + m_buf = VK_NULL_HANDLE; + } + + if (m_bufMem) { + m_devFuncs->vkFreeMemory(dev, m_bufMem, nullptr); + m_bufMem = VK_NULL_HANDLE; + } +} + +void VulkanRenderer::startNextFrame() +{ + VkDevice dev = m_window->device(); + VkCommandBuffer cb = m_window->currentCommandBuffer(); + const QSize sz = m_window->swapChainImageSize(); + + // Add the necessary barriers and do the host-linear -> device-optimal copy, if not yet done. + ensureTexture(); + + VkClearColorValue clearColor = { 0, 0, 0, 1 }; + VkClearDepthStencilValue clearDS = { 1, 0 }; + VkClearValue clearValues[2]; + memset(clearValues, 0, sizeof(clearValues)); + clearValues[0].color = clearColor; + clearValues[1].depthStencil = clearDS; + + VkRenderPassBeginInfo rpBeginInfo; + memset(&rpBeginInfo, 0, sizeof(rpBeginInfo)); + rpBeginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; + rpBeginInfo.renderPass = m_window->defaultRenderPass(); + rpBeginInfo.framebuffer = m_window->currentFramebuffer(); + rpBeginInfo.renderArea.extent.width = sz.width(); + rpBeginInfo.renderArea.extent.height = sz.height(); + rpBeginInfo.clearValueCount = 2; + rpBeginInfo.pClearValues = clearValues; + VkCommandBuffer cmdBuf = m_window->currentCommandBuffer(); + m_devFuncs->vkCmdBeginRenderPass(cmdBuf, &rpBeginInfo, VK_SUBPASS_CONTENTS_INLINE); + + quint8 *p; + VkResult err = m_devFuncs->vkMapMemory(dev, m_bufMem, m_uniformBufInfo[m_window->currentFrame()].offset, + UNIFORM_DATA_SIZE, 0, reinterpret_cast(&p)); + if (err != VK_SUCCESS) + qFatal("Failed to map memory: %d", err); + QMatrix4x4 m = m_proj; + m.rotate(m_rotation, 0, 0, 1); + memcpy(p, m.constData(), 16 * sizeof(float)); + m_devFuncs->vkUnmapMemory(dev, m_bufMem); + + // Not exactly a real animation system, just advance on every frame for now. + m_rotation += 1.0f; + + m_devFuncs->vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipeline); + m_devFuncs->vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipelineLayout, 0, 1, + &m_descSet[m_window->currentFrame()], 0, nullptr); + VkDeviceSize vbOffset = 0; + m_devFuncs->vkCmdBindVertexBuffers(cb, 0, 1, &m_buf, &vbOffset); + + VkViewport viewport; + viewport.x = viewport.y = 0; + viewport.width = sz.width(); + viewport.height = sz.height(); + viewport.minDepth = 0; + viewport.maxDepth = 1; + m_devFuncs->vkCmdSetViewport(cb, 0, 1, &viewport); + + VkRect2D scissor; + scissor.offset.x = scissor.offset.y = 0; + scissor.extent.width = viewport.width; + scissor.extent.height = viewport.height; + m_devFuncs->vkCmdSetScissor(cb, 0, 1, &scissor); + + m_devFuncs->vkCmdDraw(cb, 4, 1, 0, 0); + + m_devFuncs->vkCmdEndRenderPass(cmdBuf); + + m_window->frameReady(); + m_window->requestUpdate(); // render continuously, throttled by the presentation rate +} diff --git a/examples/vulkan/hellovulkantexture/hellovulkantexture.h b/examples/vulkan/hellovulkantexture/hellovulkantexture.h new file mode 100644 index 0000000000..a8c96d1987 --- /dev/null +++ b/examples/vulkan/hellovulkantexture/hellovulkantexture.h @@ -0,0 +1,108 @@ +/**************************************************************************** +** +** Copyright (C) 2017 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include + +class VulkanRenderer : public QVulkanWindowRenderer +{ +public: + VulkanRenderer(QVulkanWindow *w); + + void initResources() override; + void initSwapChainResources() override; + void releaseSwapChainResources() override; + void releaseResources() override; + + void startNextFrame() override; + +private: + VkShaderModule createShader(const QString &name); + bool createTexture(const QString &name); + bool createTextureImage(const QSize &size, VkImage *image, VkDeviceMemory *mem, + VkImageTiling tiling, VkImageUsageFlags usage, uint32_t memIndex); + bool writeLinearImage(const QImage &img, VkImage image, VkDeviceMemory memory); + void ensureTexture(); + + QVulkanWindow *m_window; + QVulkanDeviceFunctions *m_devFuncs; + + VkDeviceMemory m_bufMem = VK_NULL_HANDLE; + VkBuffer m_buf = VK_NULL_HANDLE; + VkDescriptorBufferInfo m_uniformBufInfo[QVulkanWindow::MAX_CONCURRENT_FRAME_COUNT]; + + VkDescriptorPool m_descPool = VK_NULL_HANDLE; + VkDescriptorSetLayout m_descSetLayout = VK_NULL_HANDLE; + VkDescriptorSet m_descSet[QVulkanWindow::MAX_CONCURRENT_FRAME_COUNT]; + + VkPipelineCache m_pipelineCache = VK_NULL_HANDLE; + VkPipelineLayout m_pipelineLayout = VK_NULL_HANDLE; + VkPipeline m_pipeline = VK_NULL_HANDLE; + + VkSampler m_sampler = VK_NULL_HANDLE; + VkImage m_texImage = VK_NULL_HANDLE; + VkDeviceMemory m_texMem = VK_NULL_HANDLE; + bool m_texLayoutPending = false; + VkImageView m_texView = VK_NULL_HANDLE; + VkImage m_texStaging = VK_NULL_HANDLE; + VkDeviceMemory m_texStagingMem = VK_NULL_HANDLE; + bool m_texStagingPending = false; + QSize m_texSize; + VkFormat m_texFormat; + + QMatrix4x4 m_proj; + float m_rotation = 0.0f; +}; + +class VulkanWindow : public QVulkanWindow +{ +public: + QVulkanWindowRenderer *createRenderer() override; +}; diff --git a/examples/vulkan/hellovulkantexture/hellovulkantexture.pro b/examples/vulkan/hellovulkantexture/hellovulkantexture.pro new file mode 100644 index 0000000000..59bfcda715 --- /dev/null +++ b/examples/vulkan/hellovulkantexture/hellovulkantexture.pro @@ -0,0 +1,7 @@ +HEADERS += hellovulkantexture.h +SOURCES += hellovulkantexture.cpp main.cpp +RESOURCES += hellovulkantexture.qrc + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/vulkan/hellovulkantexture +INSTALLS += target diff --git a/examples/vulkan/hellovulkantexture/hellovulkantexture.qrc b/examples/vulkan/hellovulkantexture/hellovulkantexture.qrc new file mode 100644 index 0000000000..04e7cda859 --- /dev/null +++ b/examples/vulkan/hellovulkantexture/hellovulkantexture.qrc @@ -0,0 +1,7 @@ + + + texture_vert.spv + texture_frag.spv + qt256.png + + diff --git a/examples/vulkan/hellovulkantexture/main.cpp b/examples/vulkan/hellovulkantexture/main.cpp new file mode 100644 index 0000000000..1144463b70 --- /dev/null +++ b/examples/vulkan/hellovulkantexture/main.cpp @@ -0,0 +1,91 @@ +/**************************************************************************** +** +** Copyright (C) 2017 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include +#include "hellovulkantexture.h" + +Q_LOGGING_CATEGORY(lcVk, "qt.vulkan") + +int main(int argc, char *argv[]) +{ + QGuiApplication app(argc, argv); + + QLoggingCategory::setFilterRules(QStringLiteral("qt.vulkan=true")); + + QVulkanInstance inst; + +#ifndef Q_OS_ANDROID + inst.setLayers(QByteArrayList() << "VK_LAYER_LUNARG_standard_validation"); +#else + inst.setLayers(QByteArrayList() + << "VK_LAYER_GOOGLE_threading" + << "VK_LAYER_LUNARG_parameter_validation" + << "VK_LAYER_LUNARG_object_tracker" + << "VK_LAYER_LUNARG_core_validation" + << "VK_LAYER_LUNARG_image" + << "VK_LAYER_LUNARG_swapchain" + << "VK_LAYER_GOOGLE_unique_objects"); +#endif + + if (!inst.create()) + qFatal("Failed to create Vulkan instance: %d", inst.errorCode()); + + VulkanWindow w; + w.setVulkanInstance(&inst); + if (QCoreApplication::arguments().contains(QStringLiteral("--srgb"))) + w.setPreferredColorFormats(QVector() << VK_FORMAT_B8G8R8A8_SRGB); + + w.resize(1024, 768); + w.show(); + + return app.exec(); +} diff --git a/examples/vulkan/hellovulkantexture/qt256.png b/examples/vulkan/hellovulkantexture/qt256.png new file mode 100644 index 0000000000..30c621c9c6 Binary files /dev/null and b/examples/vulkan/hellovulkantexture/qt256.png differ diff --git a/examples/vulkan/hellovulkantexture/texture.frag b/examples/vulkan/hellovulkantexture/texture.frag new file mode 100644 index 0000000000..e6021fe905 --- /dev/null +++ b/examples/vulkan/hellovulkantexture/texture.frag @@ -0,0 +1,12 @@ +#version 440 + +layout(location = 0) in vec2 v_texcoord; + +layout(location = 0) out vec4 fragColor; + +layout(binding = 1) uniform sampler2D tex; + +void main() +{ + fragColor = texture(tex, v_texcoord); +} diff --git a/examples/vulkan/hellovulkantexture/texture.vert b/examples/vulkan/hellovulkantexture/texture.vert new file mode 100644 index 0000000000..de486cb772 --- /dev/null +++ b/examples/vulkan/hellovulkantexture/texture.vert @@ -0,0 +1,18 @@ +#version 440 + +layout(location = 0) in vec4 position; +layout(location = 1) in vec2 texcoord; + +layout(location = 0) out vec2 v_texcoord; + +layout(std140, binding = 0) uniform buf { + mat4 mvp; +} ubuf; + +out gl_PerVertex { vec4 gl_Position; }; + +void main() +{ + v_texcoord = texcoord; + gl_Position = ubuf.mvp * position; +} diff --git a/examples/vulkan/hellovulkantexture/texture_frag.spv b/examples/vulkan/hellovulkantexture/texture_frag.spv new file mode 100644 index 0000000000..7521ef6eef Binary files /dev/null and b/examples/vulkan/hellovulkantexture/texture_frag.spv differ diff --git a/examples/vulkan/hellovulkantexture/texture_vert.spv b/examples/vulkan/hellovulkantexture/texture_vert.spv new file mode 100644 index 0000000000..6292c0de31 Binary files /dev/null and b/examples/vulkan/hellovulkantexture/texture_vert.spv differ diff --git a/examples/vulkan/hellovulkantriangle/hellovulkantriangle.pro b/examples/vulkan/hellovulkantriangle/hellovulkantriangle.pro new file mode 100644 index 0000000000..db016da3ac --- /dev/null +++ b/examples/vulkan/hellovulkantriangle/hellovulkantriangle.pro @@ -0,0 +1,12 @@ +HEADERS += \ + ../shared/trianglerenderer.h + +SOURCES += \ + main.cpp \ + ../shared/trianglerenderer.cpp + +RESOURCES += hellovulkantriangle.qrc + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/vulkan/hellovulkantriangle +INSTALLS += target diff --git a/examples/vulkan/hellovulkantriangle/hellovulkantriangle.qrc b/examples/vulkan/hellovulkantriangle/hellovulkantriangle.qrc new file mode 100644 index 0000000000..489fc7295a --- /dev/null +++ b/examples/vulkan/hellovulkantriangle/hellovulkantriangle.qrc @@ -0,0 +1,6 @@ + + + ../shared/color_vert.spv + ../shared/color_frag.spv + + diff --git a/examples/vulkan/hellovulkantriangle/main.cpp b/examples/vulkan/hellovulkantriangle/main.cpp new file mode 100644 index 0000000000..d3eef2e14a --- /dev/null +++ b/examples/vulkan/hellovulkantriangle/main.cpp @@ -0,0 +1,100 @@ +/**************************************************************************** +** +** Copyright (C) 2017 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include +#include "../shared/trianglerenderer.h" + +Q_LOGGING_CATEGORY(lcVk, "qt.vulkan") + +class VulkanWindow : public QVulkanWindow +{ +public: + QVulkanWindowRenderer *createRenderer() override; +}; + +QVulkanWindowRenderer *VulkanWindow::createRenderer() +{ + return new TriangleRenderer(this, true); // try MSAA, when available +} + +int main(int argc, char *argv[]) +{ + QGuiApplication app(argc, argv); + + QLoggingCategory::setFilterRules(QStringLiteral("qt.vulkan=true")); + + QVulkanInstance inst; + +#ifndef Q_OS_ANDROID + inst.setLayers(QByteArrayList() << "VK_LAYER_LUNARG_standard_validation"); +#else + inst.setLayers(QByteArrayList() + << "VK_LAYER_GOOGLE_threading" + << "VK_LAYER_LUNARG_parameter_validation" + << "VK_LAYER_LUNARG_object_tracker" + << "VK_LAYER_LUNARG_core_validation" + << "VK_LAYER_LUNARG_image" + << "VK_LAYER_LUNARG_swapchain" + << "VK_LAYER_GOOGLE_unique_objects"); +#endif + + if (!inst.create()) + qFatal("Failed to create Vulkan instance: %d", inst.errorCode()); + + VulkanWindow w; + w.setVulkanInstance(&inst); + + w.resize(1024, 768); + w.show(); + + return app.exec(); +} diff --git a/examples/vulkan/hellovulkanwidget/hellovulkanwidget.cpp b/examples/vulkan/hellovulkanwidget/hellovulkanwidget.cpp new file mode 100644 index 0000000000..ecab104399 --- /dev/null +++ b/examples/vulkan/hellovulkanwidget/hellovulkanwidget.cpp @@ -0,0 +1,182 @@ +/**************************************************************************** +** +** Copyright (C) 2017 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "hellovulkanwidget.h" +#include +#include +#include +#include +#include +#include +#include +#include + +MainWindow::MainWindow(VulkanWindow *w) + : m_window(w) +{ + QWidget *wrapper = QWidget::createWindowContainer(w); + + m_info = new QTextEdit; + m_info->setReadOnly(true); + + m_number = new QLCDNumber(3); + m_number->setSegmentStyle(QLCDNumber::Filled); + + QPushButton *grabButton = new QPushButton(tr("&Grab")); + grabButton->setFocusPolicy(Qt::NoFocus); + + connect(grabButton, &QPushButton::clicked, this, &MainWindow::onGrabRequested); + + QPushButton *quitButton = new QPushButton(tr("&Quit")); + quitButton->setFocusPolicy(Qt::NoFocus); + + connect(quitButton, &QPushButton::clicked, qApp, &QCoreApplication::quit); + + QVBoxLayout *layout = new QVBoxLayout; + layout->addWidget(m_info, 2); + layout->addWidget(m_number, 1); + layout->addWidget(wrapper, 5); + layout->addWidget(grabButton, 1); + layout->addWidget(quitButton, 1); + setLayout(layout); +} + +void MainWindow::onVulkanInfoReceived(const QString &text) +{ + m_info->setText(text); +} + +void MainWindow::onFrameQueued(int colorValue) +{ + m_number->display(colorValue); +} + +void MainWindow::onGrabRequested() +{ + if (!m_window->supportsGrab()) { + QMessageBox::warning(this, tr("Cannot grab"), tr("This swapchain does not support readbacks.")); + return; + } + + QImage img = m_window->grab(); + + // Our startNextFrame() implementation is synchronous so img is ready to be + // used right here. + + QFileDialog fd(this); + fd.setAcceptMode(QFileDialog::AcceptSave); + fd.setDefaultSuffix("png"); + fd.selectFile("test.png"); + if (fd.exec() == QDialog::Accepted) + img.save(fd.selectedFiles().first()); +} + +QVulkanWindowRenderer *VulkanWindow::createRenderer() +{ + return new VulkanRenderer(this); +} + +VulkanRenderer::VulkanRenderer(VulkanWindow *w) + : TriangleRenderer(w) +{ +} + +void VulkanRenderer::initResources() +{ + TriangleRenderer::initResources(); + + QVulkanInstance *inst = m_window->vulkanInstance(); + m_devFuncs = inst->deviceFunctions(m_window->device()); + + QString info; + info += QString().sprintf("Number of physical devices: %d\n", m_window->availablePhysicalDevices().count()); + + QVulkanFunctions *f = inst->functions(); + VkPhysicalDeviceProperties props; + f->vkGetPhysicalDeviceProperties(m_window->physicalDevice(), &props); + info += QString().sprintf("Active physical device name: '%s' version %d.%d.%d\nAPI version %d.%d.%d\n", + props.deviceName, + VK_VERSION_MAJOR(props.driverVersion), VK_VERSION_MINOR(props.driverVersion), + VK_VERSION_PATCH(props.driverVersion), + VK_VERSION_MAJOR(props.apiVersion), VK_VERSION_MINOR(props.apiVersion), + VK_VERSION_PATCH(props.apiVersion)); + + info += QStringLiteral("Supported instance layers:\n"); + for (const QVulkanLayer &layer : inst->supportedLayers()) + info += QString().sprintf(" %s v%u\n", layer.name.constData(), layer.version); + info += QStringLiteral("Enabled instance layers:\n"); + for (const QByteArray &layer : inst->layers()) + info += QString().sprintf(" %s\n", layer.constData()); + + info += QStringLiteral("Supported instance extensions:\n"); + for (const QVulkanExtension &ext : inst->supportedExtensions()) + info += QString().sprintf(" %s v%u\n", ext.name.constData(), ext.version); + info += QStringLiteral("Enabled instance extensions:\n"); + for (const QByteArray &ext : inst->extensions()) + info += QString().sprintf(" %s\n", ext.constData()); + + info += QString().sprintf("Color format: %u\nDepth-stencil format: %u\n", + m_window->colorFormat(), m_window->depthStencilFormat()); + + info += QStringLiteral("Supported sample counts:"); + QList sampleCounts = m_window->supportedSampleCounts().toList(); + std::sort(sampleCounts.begin(), sampleCounts.end()); + for (int count : sampleCounts) + info += QLatin1Char(' ') + QString::number(count); + info += QLatin1Char('\n'); + + emit static_cast(m_window)->vulkanInfoReceived(info); +} + +void VulkanRenderer::startNextFrame() +{ + TriangleRenderer::startNextFrame(); + emit static_cast(m_window)->frameQueued(int(m_rotation) % 360); +} diff --git a/examples/vulkan/hellovulkanwidget/hellovulkanwidget.h b/examples/vulkan/hellovulkanwidget/hellovulkanwidget.h new file mode 100644 index 0000000000..b1f4824006 --- /dev/null +++ b/examples/vulkan/hellovulkanwidget/hellovulkanwidget.h @@ -0,0 +1,98 @@ +/**************************************************************************** +** +** Copyright (C) 2017 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "../shared/trianglerenderer.h" +#include + +class VulkanWindow; + +QT_BEGIN_NAMESPACE +class QTextEdit; +class QLCDNumber; +QT_END_NAMESPACE + +class MainWindow : public QWidget +{ + Q_OBJECT + +public: + MainWindow(VulkanWindow *w); + +public slots: + void onVulkanInfoReceived(const QString &text); + void onFrameQueued(int colorValue); + void onGrabRequested(); + +private: + VulkanWindow *m_window; + QTextEdit *m_info; + QLCDNumber *m_number; +}; + +class VulkanRenderer : public TriangleRenderer +{ +public: + VulkanRenderer(VulkanWindow *w); + + void initResources() override; + void startNextFrame() override; +}; + +class VulkanWindow : public QVulkanWindow +{ + Q_OBJECT + +public: + QVulkanWindowRenderer *createRenderer() override; + +signals: + void vulkanInfoReceived(const QString &text); + void frameQueued(int colorValue); +}; diff --git a/examples/vulkan/hellovulkanwidget/hellovulkanwidget.pro b/examples/vulkan/hellovulkanwidget/hellovulkanwidget.pro new file mode 100644 index 0000000000..7b87d7f210 --- /dev/null +++ b/examples/vulkan/hellovulkanwidget/hellovulkanwidget.pro @@ -0,0 +1,16 @@ +QT += widgets + +HEADERS += \ + hellovulkanwidget.h \ + ../shared/trianglerenderer.h + +SOURCES += \ + hellovulkanwidget.cpp \ + main.cpp \ + ../shared/trianglerenderer.cpp + +RESOURCES += hellovulkanwidget.qrc + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/vulkan/hellovulkanwidget +INSTALLS += target diff --git a/examples/vulkan/hellovulkanwidget/hellovulkanwidget.qrc b/examples/vulkan/hellovulkanwidget/hellovulkanwidget.qrc new file mode 100644 index 0000000000..489fc7295a --- /dev/null +++ b/examples/vulkan/hellovulkanwidget/hellovulkanwidget.qrc @@ -0,0 +1,6 @@ + + + ../shared/color_vert.spv + ../shared/color_frag.spv + + diff --git a/examples/vulkan/hellovulkanwidget/main.cpp b/examples/vulkan/hellovulkanwidget/main.cpp new file mode 100644 index 0000000000..320e015e67 --- /dev/null +++ b/examples/vulkan/hellovulkanwidget/main.cpp @@ -0,0 +1,93 @@ +/**************************************************************************** +** +** Copyright (C) 2017 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include +#include "hellovulkanwidget.h" + +Q_LOGGING_CATEGORY(lcVk, "qt.vulkan") + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + + QLoggingCategory::setFilterRules(QStringLiteral("qt.vulkan=true")); + + QVulkanInstance inst; + +#ifndef Q_OS_ANDROID + inst.setLayers(QByteArrayList() << "VK_LAYER_LUNARG_standard_validation"); +#else + inst.setLayers(QByteArrayList() + << "VK_LAYER_GOOGLE_threading" + << "VK_LAYER_LUNARG_parameter_validation" + << "VK_LAYER_LUNARG_object_tracker" + << "VK_LAYER_LUNARG_core_validation" + << "VK_LAYER_LUNARG_image" + << "VK_LAYER_LUNARG_swapchain" + << "VK_LAYER_GOOGLE_unique_objects"); +#endif + + if (!inst.create()) + qFatal("Failed to create Vulkan instance: %d", inst.errorCode()); + + VulkanWindow *vulkanWindow = new VulkanWindow; + vulkanWindow->setVulkanInstance(&inst); + + MainWindow mainWindow(vulkanWindow); + QObject::connect(vulkanWindow, &VulkanWindow::vulkanInfoReceived, &mainWindow, &MainWindow::onVulkanInfoReceived); + QObject::connect(vulkanWindow, &VulkanWindow::frameQueued, &mainWindow, &MainWindow::onFrameQueued); + + mainWindow.resize(1024, 768); + mainWindow.show(); + + return app.exec(); +} diff --git a/examples/vulkan/hellovulkanwindow/hellovulkanwindow.cpp b/examples/vulkan/hellovulkanwindow/hellovulkanwindow.cpp new file mode 100644 index 0000000000..0a7d1d4174 --- /dev/null +++ b/examples/vulkan/hellovulkanwindow/hellovulkanwindow.cpp @@ -0,0 +1,128 @@ +/**************************************************************************** +** +** Copyright (C) 2017 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "hellovulkanwindow.h" +#include + +//! [0] +QVulkanWindowRenderer *VulkanWindow::createRenderer() +{ + return new VulkanRenderer(this); +} + +VulkanRenderer::VulkanRenderer(QVulkanWindow *w) + : m_window(w) +{ +} +//! [0] + +//! [1] +void VulkanRenderer::initResources() +{ + qDebug("initResources"); + + m_devFuncs = m_window->vulkanInstance()->deviceFunctions(m_window->device()); +} +//! [1] + +void VulkanRenderer::initSwapChainResources() +{ + qDebug("initSwapChainResources"); +} + +void VulkanRenderer::releaseSwapChainResources() +{ + qDebug("releaseSwapChainResources"); +} + +void VulkanRenderer::releaseResources() +{ + qDebug("releaseResources"); +} + +//! [2] +void VulkanRenderer::startNextFrame() +{ + m_green += 0.005f; + if (m_green > 1.0f) + m_green = 0.0f; + + VkClearColorValue clearColor = { 0.0f, m_green, 0.0f, 1.0f }; + VkClearDepthStencilValue clearDS = { 1.0f, 0 }; + VkClearValue clearValues[2]; + memset(clearValues, 0, sizeof(clearValues)); + clearValues[0].color = clearColor; + clearValues[1].depthStencil = clearDS; + + VkRenderPassBeginInfo rpBeginInfo; + memset(&rpBeginInfo, 0, sizeof(rpBeginInfo)); + rpBeginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; + rpBeginInfo.renderPass = m_window->defaultRenderPass(); + rpBeginInfo.framebuffer = m_window->currentFramebuffer(); + const QSize sz = m_window->swapChainImageSize(); + rpBeginInfo.renderArea.extent.width = sz.width(); + rpBeginInfo.renderArea.extent.height = sz.height(); + rpBeginInfo.clearValueCount = 2; + rpBeginInfo.pClearValues = clearValues; + VkCommandBuffer cmdBuf = m_window->currentCommandBuffer(); + m_devFuncs->vkCmdBeginRenderPass(cmdBuf, &rpBeginInfo, VK_SUBPASS_CONTENTS_INLINE); + + // Do nothing else. We will just clear to green, changing the component on + // every invocation. This also helps verifying the rate to which the thread + // is throttled to. (The elapsed time between startNextFrame calls should + // typically be around 16 ms. Note that rendering is 2 frames ahead of what + // is displayed.) + + m_devFuncs->vkCmdEndRenderPass(cmdBuf); + + m_window->frameReady(); + m_window->requestUpdate(); // render continuously, throttled by the presentation rate +} +//! [2] diff --git a/examples/vulkan/hellovulkanwindow/hellovulkanwindow.h b/examples/vulkan/hellovulkanwindow/hellovulkanwindow.h new file mode 100644 index 0000000000..5f52e402ca --- /dev/null +++ b/examples/vulkan/hellovulkanwindow/hellovulkanwindow.h @@ -0,0 +1,77 @@ +/**************************************************************************** +** +** Copyright (C) 2017 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +//! [0] +class VulkanRenderer : public QVulkanWindowRenderer +{ +public: + VulkanRenderer(QVulkanWindow *w); + + void initResources() override; + void initSwapChainResources() override; + void releaseSwapChainResources() override; + void releaseResources() override; + + void startNextFrame() override; + +private: + QVulkanWindow *m_window; + QVulkanDeviceFunctions *m_devFuncs; + float m_green = 0; +}; + +class VulkanWindow : public QVulkanWindow +{ +public: + QVulkanWindowRenderer *createRenderer() override; +}; +//! [0] diff --git a/examples/vulkan/hellovulkanwindow/hellovulkanwindow.pro b/examples/vulkan/hellovulkanwindow/hellovulkanwindow.pro new file mode 100644 index 0000000000..8f7d9494e2 --- /dev/null +++ b/examples/vulkan/hellovulkanwindow/hellovulkanwindow.pro @@ -0,0 +1,6 @@ +HEADERS += hellovulkanwindow.h +SOURCES += hellovulkanwindow.cpp main.cpp + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/vulkan/hellovulkanwindow +INSTALLS += target diff --git a/examples/vulkan/hellovulkanwindow/main.cpp b/examples/vulkan/hellovulkanwindow/main.cpp new file mode 100644 index 0000000000..313c28f9e0 --- /dev/null +++ b/examples/vulkan/hellovulkanwindow/main.cpp @@ -0,0 +1,93 @@ +/**************************************************************************** +** +** Copyright (C) 2017 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include +#include "hellovulkanwindow.h" + +Q_LOGGING_CATEGORY(lcVk, "qt.vulkan") + +int main(int argc, char *argv[]) +{ + QGuiApplication app(argc, argv); + + QLoggingCategory::setFilterRules(QStringLiteral("qt.vulkan=true")); + +//! [0] + QVulkanInstance inst; + +#ifndef Q_OS_ANDROID + inst.setLayers(QByteArrayList() << "VK_LAYER_LUNARG_standard_validation"); +#else + inst.setLayers(QByteArrayList() + << "VK_LAYER_GOOGLE_threading" + << "VK_LAYER_LUNARG_parameter_validation" + << "VK_LAYER_LUNARG_object_tracker" + << "VK_LAYER_LUNARG_core_validation" + << "VK_LAYER_LUNARG_image" + << "VK_LAYER_LUNARG_swapchain" + << "VK_LAYER_GOOGLE_unique_objects"); +#endif + + if (!inst.create()) + qFatal("Failed to create Vulkan instance: %d", inst.errorCode()); +//! [0] + +//! [1] + VulkanWindow w; + w.setVulkanInstance(&inst); + + w.resize(1024, 768); + w.show(); +//! [1] + + return app.exec(); +} diff --git a/examples/vulkan/shared/color.frag b/examples/vulkan/shared/color.frag new file mode 100644 index 0000000000..375587662f --- /dev/null +++ b/examples/vulkan/shared/color.frag @@ -0,0 +1,10 @@ +#version 440 + +layout(location = 0) in vec3 v_color; + +layout(location = 0) out vec4 fragColor; + +void main() +{ + fragColor = vec4(v_color, 1.0); +} diff --git a/examples/vulkan/shared/color.vert b/examples/vulkan/shared/color.vert new file mode 100644 index 0000000000..02492c0e65 --- /dev/null +++ b/examples/vulkan/shared/color.vert @@ -0,0 +1,18 @@ +#version 440 + +layout(location = 0) in vec4 position; +layout(location = 1) in vec3 color; + +layout(location = 0) out vec3 v_color; + +layout(std140, binding = 0) uniform buf { + mat4 mvp; +} ubuf; + +out gl_PerVertex { vec4 gl_Position; }; + +void main() +{ + v_color = color; + gl_Position = ubuf.mvp * position; +} diff --git a/examples/vulkan/shared/color_frag.spv b/examples/vulkan/shared/color_frag.spv new file mode 100644 index 0000000000..30e33b76ca Binary files /dev/null and b/examples/vulkan/shared/color_frag.spv differ diff --git a/examples/vulkan/shared/color_vert.spv b/examples/vulkan/shared/color_vert.spv new file mode 100644 index 0000000000..a1f42e3119 Binary files /dev/null and b/examples/vulkan/shared/color_vert.spv differ diff --git a/examples/vulkan/shared/trianglerenderer.cpp b/examples/vulkan/shared/trianglerenderer.cpp new file mode 100644 index 0000000000..f2e636bbe6 --- /dev/null +++ b/examples/vulkan/shared/trianglerenderer.cpp @@ -0,0 +1,513 @@ +/**************************************************************************** +** +** Copyright (C) 2017 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "trianglerenderer.h" +#include +#include + +// Note that the vertex data and the projection matrix assume OpenGL. With +// Vulkan Y is negated in clip space and the near/far plane is at 0/1 instead +// of -1/1. These will be corrected for by an extra transformation when +// calculating the modelview-projection matrix. +static float vertexData[] = { + 0.0f, 0.5f, 1.0f, 0.0f, 0.0f, + -0.5f, -0.5f, 0.0f, 1.0f, 0.0f, + 0.5f, -0.5f, 0.0f, 0.0f, 1.0f +}; + +static const int UNIFORM_DATA_SIZE = 16 * sizeof(float); + +static inline VkDeviceSize aligned(VkDeviceSize v, VkDeviceSize byteAlign) +{ + return (v + byteAlign - 1) & ~(byteAlign - 1); +} + +TriangleRenderer::TriangleRenderer(QVulkanWindow *w, bool msaa) + : m_window(w) +{ + if (msaa) { + QSet counts = w->supportedSampleCounts(); + qDebug() << "Supported sample counts:" << counts; + for (int s = 16; s >= 4; s /= 2) { + if (counts.contains(s)) { + qDebug("Requesting sample count %d", s); + m_window->setSampleCount(s); + break; + } + } + } +} + +VkShaderModule TriangleRenderer::createShader(const QString &name) +{ + QFile file(name); + if (!file.open(QIODevice::ReadOnly)) { + qWarning("Failed to read shader %s", qPrintable(name)); + return VK_NULL_HANDLE; + } + QByteArray blob = file.readAll(); + file.close(); + + VkShaderModuleCreateInfo shaderInfo; + memset(&shaderInfo, 0, sizeof(shaderInfo)); + shaderInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; + shaderInfo.codeSize = blob.size(); + shaderInfo.pCode = reinterpret_cast(blob.constData()); + VkShaderModule shaderModule; + VkResult err = m_devFuncs->vkCreateShaderModule(m_window->device(), &shaderInfo, nullptr, &shaderModule); + if (err != VK_SUCCESS) { + qWarning("Failed to create shader module: %d", err); + return VK_NULL_HANDLE; + } + + return shaderModule; +} + +void TriangleRenderer::initResources() +{ + qDebug("initResources"); + + VkDevice dev = m_window->device(); + m_devFuncs = m_window->vulkanInstance()->deviceFunctions(dev); + + // Prepare the vertex and uniform data. The vertex data will never + // change so one buffer is sufficient regardless of the value of + // QVulkanWindow::CONCURRENT_FRAME_COUNT. Uniform data is changing per + // frame however so active frames have to have a dedicated copy. + + // Use just one memory allocation and one buffer. We will then specify the + // appropriate offsets for uniform buffers in the VkDescriptorBufferInfo. + // Have to watch out for + // VkPhysicalDeviceLimits::minUniformBufferOffsetAlignment, though. + + // The uniform buffer is not strictly required in this example, we could + // have used push constants as well since our single matrix (64 bytes) fits + // into the spec mandated minimum limit of 128 bytes. However, once that + // limit is not sufficient, the per-frame buffers, as shown below, will + // become necessary. + + const int concurrentFrameCount = m_window->concurrentFrameCount(); + const VkPhysicalDeviceLimits *pdevLimits = &m_window->physicalDeviceProperties()->limits; + const VkDeviceSize uniAlign = pdevLimits->minUniformBufferOffsetAlignment; + qDebug("uniform buffer offset alignment is %u", (uint) uniAlign); + VkBufferCreateInfo bufInfo; + memset(&bufInfo, 0, sizeof(bufInfo)); + bufInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + // Our internal layout is vertex, uniform, uniform, ... with each uniform buffer start offset aligned to uniAlign. + const VkDeviceSize vertexAllocSize = aligned(sizeof(vertexData), uniAlign); + const VkDeviceSize uniformAllocSize = aligned(UNIFORM_DATA_SIZE, uniAlign); + bufInfo.size = vertexAllocSize + concurrentFrameCount * uniformAllocSize; + bufInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; + + VkResult err = m_devFuncs->vkCreateBuffer(dev, &bufInfo, nullptr, &m_buf); + if (err != VK_SUCCESS) + qFatal("Failed to create buffer: %d", err); + + VkMemoryRequirements memReq; + m_devFuncs->vkGetBufferMemoryRequirements(dev, m_buf, &memReq); + + VkMemoryAllocateInfo memAllocInfo = { + VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, + nullptr, + memReq.size, + m_window->hostVisibleMemoryIndex() + }; + + err = m_devFuncs->vkAllocateMemory(dev, &memAllocInfo, nullptr, &m_bufMem); + if (err != VK_SUCCESS) + qFatal("Failed to allocate memory: %d", err); + + err = m_devFuncs->vkBindBufferMemory(dev, m_buf, m_bufMem, 0); + if (err != VK_SUCCESS) + qFatal("Failed to bind buffer memory: %d", err); + + quint8 *p; + err = m_devFuncs->vkMapMemory(dev, m_bufMem, 0, memReq.size, 0, reinterpret_cast(&p)); + if (err != VK_SUCCESS) + qFatal("Failed to map memory: %d", err); + memcpy(p, vertexData, sizeof(vertexData)); + QMatrix4x4 ident; + memset(m_uniformBufInfo, 0, sizeof(m_uniformBufInfo)); + for (int i = 0; i < concurrentFrameCount; ++i) { + const VkDeviceSize offset = vertexAllocSize + i * uniformAllocSize; + memcpy(p + offset, ident.constData(), 16 * sizeof(float)); + m_uniformBufInfo[i].buffer = m_buf; + m_uniformBufInfo[i].offset = offset; + m_uniformBufInfo[i].range = uniformAllocSize; + } + m_devFuncs->vkUnmapMemory(dev, m_bufMem); + + VkVertexInputBindingDescription vertexBindingDesc = { + 0, // binding + 5 * sizeof(float), + VK_VERTEX_INPUT_RATE_VERTEX + }; + VkVertexInputAttributeDescription vertexAttrDesc[] = { + { // position + 0, // location + 0, // binding + VK_FORMAT_R32G32_SFLOAT, + 0 + }, + { // color + 1, + 0, + VK_FORMAT_R32G32B32_SFLOAT, + 2 * sizeof(float) + } + }; + + VkPipelineVertexInputStateCreateInfo vertexInputInfo; + vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; + vertexInputInfo.pNext = nullptr; + vertexInputInfo.flags = 0; + vertexInputInfo.vertexBindingDescriptionCount = 1; + vertexInputInfo.pVertexBindingDescriptions = &vertexBindingDesc; + vertexInputInfo.vertexAttributeDescriptionCount = 2; + vertexInputInfo.pVertexAttributeDescriptions = vertexAttrDesc; + + // Set up descriptor set and its layout. + VkDescriptorPoolSize descPoolSizes = { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, uint32_t(concurrentFrameCount) }; + VkDescriptorPoolCreateInfo descPoolInfo; + memset(&descPoolInfo, 0, sizeof(descPoolInfo)); + descPoolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; + descPoolInfo.maxSets = concurrentFrameCount; + descPoolInfo.poolSizeCount = 1; + descPoolInfo.pPoolSizes = &descPoolSizes; + err = m_devFuncs->vkCreateDescriptorPool(dev, &descPoolInfo, nullptr, &m_descPool); + if (err != VK_SUCCESS) + qFatal("Failed to create descriptor pool: %d", err); + + VkDescriptorSetLayoutBinding layoutBinding = { + 0, // binding + VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, + 1, + VK_SHADER_STAGE_VERTEX_BIT, + nullptr + }; + VkDescriptorSetLayoutCreateInfo descLayoutInfo = { + VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, + nullptr, + 0, + 1, + &layoutBinding + }; + err = m_devFuncs->vkCreateDescriptorSetLayout(dev, &descLayoutInfo, nullptr, &m_descSetLayout); + if (err != VK_SUCCESS) + qFatal("Failed to create descriptor set layout: %d", err); + + for (int i = 0; i < concurrentFrameCount; ++i) { + VkDescriptorSetAllocateInfo descSetAllocInfo = { + VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, + nullptr, + m_descPool, + 1, + &m_descSetLayout + }; + err = m_devFuncs->vkAllocateDescriptorSets(dev, &descSetAllocInfo, &m_descSet[i]); + if (err != VK_SUCCESS) + qFatal("Failed to allocate descriptor set: %d", err); + + VkWriteDescriptorSet descWrite; + memset(&descWrite, 0, sizeof(descWrite)); + descWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + descWrite.dstSet = m_descSet[i]; + descWrite.descriptorCount = 1; + descWrite.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; + descWrite.pBufferInfo = &m_uniformBufInfo[i]; + m_devFuncs->vkUpdateDescriptorSets(dev, 1, &descWrite, 0, nullptr); + } + + // Pipeline cache + VkPipelineCacheCreateInfo pipelineCacheInfo; + memset(&pipelineCacheInfo, 0, sizeof(pipelineCacheInfo)); + pipelineCacheInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO; + err = m_devFuncs->vkCreatePipelineCache(dev, &pipelineCacheInfo, nullptr, &m_pipelineCache); + if (err != VK_SUCCESS) + qFatal("Failed to create pipeline cache: %d", err); + + // Pipeline layout + VkPipelineLayoutCreateInfo pipelineLayoutInfo; + memset(&pipelineLayoutInfo, 0, sizeof(pipelineLayoutInfo)); + pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; + pipelineLayoutInfo.setLayoutCount = 1; + pipelineLayoutInfo.pSetLayouts = &m_descSetLayout; + err = m_devFuncs->vkCreatePipelineLayout(dev, &pipelineLayoutInfo, nullptr, &m_pipelineLayout); + if (err != VK_SUCCESS) + qFatal("Failed to create pipeline layout: %d", err); + + // Shaders + VkShaderModule vertShaderModule = createShader(QStringLiteral(":/color_vert.spv")); + VkShaderModule fragShaderModule = createShader(QStringLiteral(":/color_frag.spv")); + + // Graphics pipeline + VkGraphicsPipelineCreateInfo pipelineInfo; + memset(&pipelineInfo, 0, sizeof(pipelineInfo)); + pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; + + VkPipelineShaderStageCreateInfo shaderStages[2] = { + { + VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, + nullptr, + 0, + VK_SHADER_STAGE_VERTEX_BIT, + vertShaderModule, + "main", + nullptr + }, + { + VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, + nullptr, + 0, + VK_SHADER_STAGE_FRAGMENT_BIT, + fragShaderModule, + "main", + nullptr + } + }; + pipelineInfo.stageCount = 2; + pipelineInfo.pStages = shaderStages; + + pipelineInfo.pVertexInputState = &vertexInputInfo; + + VkPipelineInputAssemblyStateCreateInfo ia; + memset(&ia, 0, sizeof(ia)); + ia.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; + ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + pipelineInfo.pInputAssemblyState = &ia; + + // The viewport and scissor will be set dynamically via vkCmdSetViewport/Scissor. + // This way the pipeline does not need to be touched when resizing the window. + VkPipelineViewportStateCreateInfo vp; + memset(&vp, 0, sizeof(vp)); + vp.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; + vp.viewportCount = 1; + vp.scissorCount = 1; + pipelineInfo.pViewportState = &vp; + + VkPipelineRasterizationStateCreateInfo rs; + memset(&rs, 0, sizeof(rs)); + rs.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; + rs.polygonMode = VK_POLYGON_MODE_FILL; + rs.cullMode = VK_CULL_MODE_NONE; // we want the back face as well + rs.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; + rs.lineWidth = 1.0f; + pipelineInfo.pRasterizationState = &rs; + + VkPipelineMultisampleStateCreateInfo ms; + memset(&ms, 0, sizeof(ms)); + ms.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; + // Enable multisampling. + ms.rasterizationSamples = m_window->sampleCountFlagBits(); + pipelineInfo.pMultisampleState = &ms; + + VkPipelineDepthStencilStateCreateInfo ds; + memset(&ds, 0, sizeof(ds)); + ds.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; + ds.depthTestEnable = VK_TRUE; + ds.depthWriteEnable = VK_TRUE; + ds.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL; + pipelineInfo.pDepthStencilState = &ds; + + VkPipelineColorBlendStateCreateInfo cb; + memset(&cb, 0, sizeof(cb)); + cb.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; + // no blend, write out all of rgba + VkPipelineColorBlendAttachmentState att; + memset(&att, 0, sizeof(att)); + att.colorWriteMask = 0xF; + cb.attachmentCount = 1; + cb.pAttachments = &att; + pipelineInfo.pColorBlendState = &cb; + + VkDynamicState dynEnable[] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; + VkPipelineDynamicStateCreateInfo dyn; + memset(&dyn, 0, sizeof(dyn)); + dyn.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; + dyn.dynamicStateCount = sizeof(dynEnable) / sizeof(VkDynamicState); + dyn.pDynamicStates = dynEnable; + pipelineInfo.pDynamicState = &dyn; + + pipelineInfo.layout = m_pipelineLayout; + pipelineInfo.renderPass = m_window->defaultRenderPass(); + + err = m_devFuncs->vkCreateGraphicsPipelines(dev, m_pipelineCache, 1, &pipelineInfo, nullptr, &m_pipeline); + if (err != VK_SUCCESS) + qFatal("Failed to create graphics pipeline: %d", err); + + if (vertShaderModule) + m_devFuncs->vkDestroyShaderModule(dev, vertShaderModule, nullptr); + if (fragShaderModule) + m_devFuncs->vkDestroyShaderModule(dev, fragShaderModule, nullptr); +} + +void TriangleRenderer::initSwapChainResources() +{ + qDebug("initSwapChainResources"); + + // Projection matrix + m_proj = *m_window->clipCorrectionMatrix(); // adjust for Vulkan-OpenGL clip space differences + const QSize sz = m_window->swapChainImageSize(); + m_proj.perspective(45.0f, sz.width() / (float) sz.height(), 0.01f, 100.0f); + m_proj.translate(0, 0, -4); +} + +void TriangleRenderer::releaseSwapChainResources() +{ + qDebug("releaseSwapChainResources"); +} + +void TriangleRenderer::releaseResources() +{ + qDebug("releaseResources"); + + VkDevice dev = m_window->device(); + + if (m_pipeline) { + m_devFuncs->vkDestroyPipeline(dev, m_pipeline, nullptr); + m_pipeline = VK_NULL_HANDLE; + } + + if (m_pipelineLayout) { + m_devFuncs->vkDestroyPipelineLayout(dev, m_pipelineLayout, nullptr); + m_pipelineLayout = VK_NULL_HANDLE; + } + + if (m_pipelineCache) { + m_devFuncs->vkDestroyPipelineCache(dev, m_pipelineCache, nullptr); + m_pipelineCache = VK_NULL_HANDLE; + } + + if (m_descSetLayout) { + m_devFuncs->vkDestroyDescriptorSetLayout(dev, m_descSetLayout, nullptr); + m_descSetLayout = VK_NULL_HANDLE; + } + + if (m_descPool) { + m_devFuncs->vkDestroyDescriptorPool(dev, m_descPool, nullptr); + m_descPool = VK_NULL_HANDLE; + } + + if (m_buf) { + m_devFuncs->vkDestroyBuffer(dev, m_buf, nullptr); + m_buf = VK_NULL_HANDLE; + } + + if (m_bufMem) { + m_devFuncs->vkFreeMemory(dev, m_bufMem, nullptr); + m_bufMem = VK_NULL_HANDLE; + } +} + +void TriangleRenderer::startNextFrame() +{ + VkDevice dev = m_window->device(); + VkCommandBuffer cb = m_window->currentCommandBuffer(); + const QSize sz = m_window->swapChainImageSize(); + + VkClearColorValue clearColor = { 0, 0, 0, 1 }; + VkClearDepthStencilValue clearDS = { 1, 0 }; + VkClearValue clearValues[3]; + memset(clearValues, 0, sizeof(clearValues)); + clearValues[0].color = clearValues[2].color = clearColor; + clearValues[1].depthStencil = clearDS; + + VkRenderPassBeginInfo rpBeginInfo; + memset(&rpBeginInfo, 0, sizeof(rpBeginInfo)); + rpBeginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; + rpBeginInfo.renderPass = m_window->defaultRenderPass(); + rpBeginInfo.framebuffer = m_window->currentFramebuffer(); + rpBeginInfo.renderArea.extent.width = sz.width(); + rpBeginInfo.renderArea.extent.height = sz.height(); + rpBeginInfo.clearValueCount = m_window->sampleCountFlagBits() > VK_SAMPLE_COUNT_1_BIT ? 3 : 2; + rpBeginInfo.pClearValues = clearValues; + VkCommandBuffer cmdBuf = m_window->currentCommandBuffer(); + m_devFuncs->vkCmdBeginRenderPass(cmdBuf, &rpBeginInfo, VK_SUBPASS_CONTENTS_INLINE); + + quint8 *p; + VkResult err = m_devFuncs->vkMapMemory(dev, m_bufMem, m_uniformBufInfo[m_window->currentFrame()].offset, + UNIFORM_DATA_SIZE, 0, reinterpret_cast(&p)); + if (err != VK_SUCCESS) + qFatal("Failed to map memory: %d", err); + QMatrix4x4 m = m_proj; + m.rotate(m_rotation, 0, 1, 0); + memcpy(p, m.constData(), 16 * sizeof(float)); + m_devFuncs->vkUnmapMemory(dev, m_bufMem); + + // Not exactly a real animation system, just advance on every frame for now. + m_rotation += 1.0f; + + m_devFuncs->vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipeline); + m_devFuncs->vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipelineLayout, 0, 1, + &m_descSet[m_window->currentFrame()], 0, nullptr); + VkDeviceSize vbOffset = 0; + m_devFuncs->vkCmdBindVertexBuffers(cb, 0, 1, &m_buf, &vbOffset); + + VkViewport viewport; + viewport.x = viewport.y = 0; + viewport.width = sz.width(); + viewport.height = sz.height(); + viewport.minDepth = 0; + viewport.maxDepth = 1; + m_devFuncs->vkCmdSetViewport(cb, 0, 1, &viewport); + + VkRect2D scissor; + scissor.offset.x = scissor.offset.y = 0; + scissor.extent.width = viewport.width; + scissor.extent.height = viewport.height; + m_devFuncs->vkCmdSetScissor(cb, 0, 1, &scissor); + + m_devFuncs->vkCmdDraw(cb, 3, 1, 0, 0); + + m_devFuncs->vkCmdEndRenderPass(cmdBuf); + + m_window->frameReady(); + m_window->requestUpdate(); // render continuously, throttled by the presentation rate +} diff --git a/examples/vulkan/shared/trianglerenderer.h b/examples/vulkan/shared/trianglerenderer.h new file mode 100644 index 0000000000..9a33291a95 --- /dev/null +++ b/examples/vulkan/shared/trianglerenderer.h @@ -0,0 +1,85 @@ +/**************************************************************************** +** +** Copyright (C) 2017 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +class TriangleRenderer : public QVulkanWindowRenderer +{ +public: + TriangleRenderer(QVulkanWindow *w, bool msaa = false); + + void initResources() override; + void initSwapChainResources() override; + void releaseSwapChainResources() override; + void releaseResources() override; + + void startNextFrame() override; + +protected: + VkShaderModule createShader(const QString &name); + + QVulkanWindow *m_window; + QVulkanDeviceFunctions *m_devFuncs; + + VkDeviceMemory m_bufMem = VK_NULL_HANDLE; + VkBuffer m_buf = VK_NULL_HANDLE; + VkDescriptorBufferInfo m_uniformBufInfo[QVulkanWindow::MAX_CONCURRENT_FRAME_COUNT]; + + VkDescriptorPool m_descPool = VK_NULL_HANDLE; + VkDescriptorSetLayout m_descSetLayout = VK_NULL_HANDLE; + VkDescriptorSet m_descSet[QVulkanWindow::MAX_CONCURRENT_FRAME_COUNT]; + + VkPipelineCache m_pipelineCache = VK_NULL_HANDLE; + VkPipelineLayout m_pipelineLayout = VK_NULL_HANDLE; + VkPipeline m_pipeline = VK_NULL_HANDLE; + + QMatrix4x4 m_proj; + float m_rotation = 0.0f; +}; diff --git a/examples/vulkan/vulkan.pro b/examples/vulkan/vulkan.pro new file mode 100644 index 0000000000..ef5496bcd4 --- /dev/null +++ b/examples/vulkan/vulkan.pro @@ -0,0 +1,7 @@ +TEMPLATE = subdirs + +SUBDIRS = hellovulkanwindow \ + hellovulkantriangle \ + hellovulkantexture + +qtHaveModule(widgets): SUBDIRS += hellovulkanwidget diff --git a/src/gui/vulkan/qvulkanwindow.cpp b/src/gui/vulkan/qvulkanwindow.cpp new file mode 100644 index 0000000000..2540a69426 --- /dev/null +++ b/src/gui/vulkan/qvulkanwindow.cpp @@ -0,0 +1,2678 @@ +/**************************************************************************** +** +** Copyright (C) 2017 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qvulkanwindow_p.h" +#include "qvulkanfunctions.h" +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +Q_LOGGING_CATEGORY(lcVk, "qt.vulkan") + +/*! + \class QVulkanWindow + \inmodule QtGui + \since 5.10 + \brief The QVulkanWindow class is a convenience subclass of QWindow to perform Vulkan rendering. + + QVulkanWindow is a Vulkan-capable QWindow that manages a Vulkan device, a + graphics queue, a command pool and buffer, a depth-stencil image and a + double-buffered FIFO swapchain, while taking care of correct behavior when it + comes to events like resize, special situations like not having a device + queue supporting both graphics and presentation, device lost scenarios, and + additional functionality like reading the rendered content back. Conceptually + it is the counterpart of QOpenGLWindow in the Vulkan world. + + \note QVulkanWindow does not always eliminate the need to implement a fully + custom QWindow subclass as it will not necessarily be sufficient in advanced + use cases. + + QVulkanWindow can be embedded into QWidget-based user interfaces via + QWidget::createWindowContainer(). This approach has a number of limitations, + however. Make sure to study the + \l{QWidget::createWindowContainer()}{documentation} first. + + A typical application using QVulkanWindow may look like the following: + + \code + class VulkanRenderer : public QVulkanWindowRenderer + { + public: + VulkanRenderer(QVulkanWindow *w) : m_window(w) { } + + void initResources() override + { + m_devFuncs = m_window->vulkanInstance()->deviceFunctions(m_window->device()); + ... + } + void initSwapChainResources() override { ... } + void releaseSwapChainResources() override { ... } + void releaseResources() override { ... } + + void startNextFrame() override + { + VkCommandBuffer cmdBuf = m_window->currentCommandBuffer(); + ... + m_devFuncs->vkCmdBeginRenderPass(...); + ... + m_window->frameReady(); + } + + private: + QVulkanWindow *m_window; + QVulkanDeviceFunctions *m_devFuncs; + }; + + class VulkanWindow : public QVulkanWindow + { + public: + QVulkanWindowRenderer *createRenderer() override { + return new VulkanRenderer(this); + } + }; + + int main(int argc, char *argv[]) + { + QGuiApplication app(argc, argv); + + QVulkanInstance inst; + // enable the standard validation layers, when available + inst.setLayers(QByteArrayList() << "VK_LAYER_LUNARG_standard_validation"); + if (!inst.create()) + qFatal("Failed to create Vulkan instance: %d", inst.errorCode()); + + VulkanWindow w; + w.setVulkanInstance(&inst); + w.showMaximized(); + + return app.exec(); + } + \endcode + + As it can be seen in the example, the main patterns in QVulkanWindow usage are: + + \list + + \li The QVulkanInstance is associated via QWindow::setVulkanInstance(). It is + then retrievable via QWindow::vulkanInstance() from everywhere, on any + thread. + + \li Similarly to QVulkanInstance, device extensions can be queried via + supportedDeviceExtensions() before the actual initialization. Requesting an + extension to be enabled is done via setDeviceExtensions(). Such calls must be + made before the window becomes visible, that is, before calling show() or + similar functions. Unsupported extension requests are gracefully ignored. + + \li The renderer is implemented in a QVulkanWindowRenderer subclass, an + instance of which is created in the createRenderer() factory function. + + \li The core Vulkan commands are exposed via the QVulkanFunctions object, + retrievable by calling QVulkanInstance::functions(). Device level functions + are available after creating a VkDevice by calling + QVulkanInstance::deviceFunctions(). + + \li The building of the draw calls for the next frame happens in + QVulkanWindowRenderer::startNextFrame(). The implementation is expected to + add commands to the command buffer returned from currentCommandBuffer(). + Returning from the function does not indicate that the commands are ready for + submission. Rather, an explicit call to frameReady() is required. This allows + asynchronous generation of commands, possibly on multiple threads. Simple + implementations will simply call frameReady() at the end of their + QVulkanWindowRenderer::startNextFrame(). + + \li The basic Vulkan resources (physical device, graphics queue, a command + pool, the window's main command buffer, image formats, etc.) are exposed on + the QVulkanWindow via lightweight getter functions. Some of these are for + convenience only, and applications are always free to query, create and + manage additional resources directly via the Vulkan API. + + \li The renderer lives in the gui/main thread, like the window itself. This + thread is then throttled to the presentation rate, similarly to how OpenGl + with a swap interval of 1 would behave. However, the renderer implementation + is free to utilize multiple threads in any way it sees fit. The accessors + like vulkanInstance(), currentCommandBuffer(), etc. can be called from any + thread. The submission of the main command buffer, the queueing of present, + and the building of the next frame do not start until frameReady() is + invoked on the gui/main thread. + + \li When the window is made visible, the content is updated automatically. + Further updates can be requested by calling QWindow::requestUpdate(). To + render continuously, call requestUpdate() after frameReady(). + + \endlist + + For troubleshooting, enable the logging category \c{qt.vulkan}. Critical + errors are printed via qWarning() automatically. + + \section1 Coordinate system differences between OpenGL and Vulkan + + There are two notable differences to be aware of: First, with Vulkan Y points + down the screen in clip space, while OpenGL uses an upwards pointing Y axis. + Second, the standard OpenGL projection matrix assume a near and far plane + values of -1 and 1, while Vulkan prefers 0 and 1. + + In order to help applications migrate from OpenGL-based code without having + to flip Y coordinates in the vertex data, and to allow using QMatrix4x4 + functions like QMatrix4x4::perspective() while keeping the Vulkan viewport's + minDepth and maxDepth set to 0 and 1, QVulkanWindow provides a correction + matrix retrievable by calling clipCorrectionMatrix(). + + \section1 Multisampling + + While disabled by default, multisample antialiasing is fully supported by + QVulkanWindow. Additional color buffers and resolving into the swapchain's + non-multisample buffers are all managed automatically. + + To query the supported sample counts, call supportedSampleCounts(). When the + returned set contains 4, 8, ..., passing one of those values to setSampleCount() + requests multisample rendering. + + \note unlike QSurfaceFormat::setSamples(), the list of supported sample + counts are exposed to the applications in advance and there is no automatic + falling back to lower sample counts in setSampleCount(). If the requested value + is not supported, a warning is shown and a no multisampling will be used. + + \section1 Reading images back + + When supportsGrab() returns true, QVulkanWindow can perform readbacks from + the color buffer into a QImage. grab() is a slow and inefficient operation, + so frequent usage should be avoided. It is nonetheless valuable since it + allows applications to take screenshots, or tools and tests to process and + verify the output of the GPU rendering. + + \section1 sRGB support + + While many applications will be fine with the default behavior of + QVulkanWindow when it comes to swapchain image formats, + setPreferredColorFormats() allows requesting a pre-defined format. This is + useful most notably when working in the sRGB color space. Passing a format + like \c{VK_FORMAT_B8G8R8A8_SRGB} results in choosing an sRGB format, when + available. + + \section1 Validation layers + + During application development it can be extremely valuable to have the + Vulkan validation layers enabled. As shown in the example code above, calling + QVulkanInstance::setLayers() on the QVulkanInstance before + QVulkanInstance::create() enables validation, assuming the Vulkan driver + stack in the system contains the necessary layers. + + \note Be aware of platform-specific differences. On desktop platforms + installing the \l{https://www.lunarg.com/vulkan-sdk/}{Vulkan SDK} is + typically sufficient. However, Android for example requires deploying + additional shared libraries together with the application, and also mandates + a different list of validation layer names. See + \l{https://developer.android.com/ndk/guides/graphics/validation-layer.html}{the + Android Vulkan development pages} for more information. + + \note QVulkanWindow does not expose device layers since this functionality + has been deprecated since version 1.0.13 of the Vulkan API. + + \sa QVulkanInstance, QVulkanFunctions, QWindow + */ + +/*! + Constructs a new QVulkanWindow with the given \a parent. + + The surface type is set to QSurface::VulkanSurface. + */ +QVulkanWindow::QVulkanWindow(QWindow *parent) + : QWindow(*(new QVulkanWindowPrivate), parent) +{ + setSurfaceType(QSurface::VulkanSurface); +} + +/*! + Destructor. +*/ +QVulkanWindow::~QVulkanWindow() +{ +} + +QVulkanWindowPrivate::~QVulkanWindowPrivate() +{ + // graphics resource cleanup is already done at this point due to + // QPlatformSurfaceEvent::SurfaceAboutToBeDestroyed + + delete renderer; +} + +/*! + \enum QVulkanWindow::Flag + + This enum describes the flags that can be passed to setFlags(). + + \value PersistentResources Ensures no graphics resources are released when + the window becomes unexposed. The default behavior is to release + everything, and reinitialize later when becoming visible again. + */ + +/*! + Configures the behavior based on the provided \a flags. + + \note This function must be called before the window is made visible or at + latest in QVulkanWindowRenderer::preInitResources(), and has no effect if + called afterwards. + */ +void QVulkanWindow::setFlags(Flags flags) +{ + Q_D(QVulkanWindow); + if (d->status != QVulkanWindowPrivate::StatusUninitialized) { + qWarning("QVulkanWindow: Attempted to set flags when already initialized"); + return; + } + d->flags = flags; +} + +/*! + \return the requested flags. + */ +QVulkanWindow::Flags QVulkanWindow::flags() const +{ + Q_D(const QVulkanWindow); + return d->flags; +} + +/*! + \return the list of properties for the supported physical devices in the system. + + \note This function can be called before making the window visible. + */ +QVector QVulkanWindow::availablePhysicalDevices() +{ + Q_D(QVulkanWindow); + if (!d->physDevs.isEmpty() && !d->physDevProps.isEmpty()) + return d->physDevProps; + + QVulkanInstance *inst = vulkanInstance(); + if (!inst) { + qWarning("QVulkanWindow: Attempted to call availablePhysicalDevices() without a QVulkanInstance"); + return d->physDevProps; + } + + QVulkanFunctions *f = inst->functions(); + uint32_t count = 1; + VkResult err = f->vkEnumeratePhysicalDevices(inst->vkInstance(), &count, nullptr); + if (err != VK_SUCCESS) { + qWarning("QVulkanWindow: Failed to get physical device count: %d", err); + return d->physDevProps; + } + + qCDebug(lcVk, "%d physical devices", count); + if (!count) + return d->physDevProps; + + QVector devs(count); + err = f->vkEnumeratePhysicalDevices(inst->vkInstance(), &count, devs.data()); + if (err != VK_SUCCESS) { + qWarning("QVulkanWindow: Failed to enumerate physical devices: %d", err); + return d->physDevProps; + } + + d->physDevs = devs; + d->physDevProps.resize(count); + for (uint32_t i = 0; i < count; ++i) { + VkPhysicalDeviceProperties *p = &d->physDevProps[i]; + f->vkGetPhysicalDeviceProperties(d->physDevs.at(i), p); + qCDebug(lcVk, "Physical device [%d]: name '%s' version %d.%d.%d", i, p->deviceName, + VK_VERSION_MAJOR(p->driverVersion), VK_VERSION_MINOR(p->driverVersion), + VK_VERSION_PATCH(p->driverVersion)); + } + + return d->physDevProps; +} + +/*! + Requests the usage of the physical device with index \a idx. The index + corresponds to the list returned from availablePhysicalDevices(). + + By default the first physical device is used. + + \note This function must be called before the window is made visible or at + latest in QVulkanWindowRenderer::preInitResources(), and has no effect if + called afterwards. + */ +void QVulkanWindow::setPhysicalDeviceIndex(int idx) +{ + Q_D(QVulkanWindow); + if (d->status != QVulkanWindowPrivate::StatusUninitialized) { + qWarning("QVulkanWindow: Attempted to set physical device when already initialized"); + return; + } + const int count = availablePhysicalDevices().count(); + if (idx < 0 || idx >= count) { + qWarning("QVulkanWindow: Invalid physical device index %d (total physical devices: %d)", idx, count); + return; + } + d->physDevIndex = idx; +} + +/*! + \return the list of the extensions that are supported by logical devices + created from the physical device selected by setPhysicalDeviceIndex(). + + \note This function can be called before making the window visible. + */ +QVulkanInfoVector QVulkanWindow::supportedDeviceExtensions() +{ + Q_D(QVulkanWindow); + + availablePhysicalDevices(); + + if (d->physDevs.isEmpty()) { + qWarning("QVulkanWindow: No physical devices found"); + return QVulkanInfoVector(); + } + + VkPhysicalDevice physDev = d->physDevs.at(d->physDevIndex); + if (d->supportedDevExtensions.contains(physDev)) + return d->supportedDevExtensions.value(physDev); + + QVulkanFunctions *f = vulkanInstance()->functions(); + uint32_t count = 0; + VkResult err = f->vkEnumerateDeviceExtensionProperties(physDev, nullptr, &count, nullptr); + if (err == VK_SUCCESS) { + QVector extProps(count); + err = f->vkEnumerateDeviceExtensionProperties(physDev, nullptr, &count, extProps.data()); + if (err == VK_SUCCESS) { + QVulkanInfoVector exts; + for (const VkExtensionProperties &prop : extProps) { + QVulkanExtension ext; + ext.name = prop.extensionName; + ext.version = prop.specVersion; + exts.append(ext); + } + d->supportedDevExtensions.insert(physDev, exts); + qDebug(lcVk) << "Supported device extensions:" << exts; + return exts; + } + } + + qWarning("QVulkanWindow: Failed to query device extension count: %d", err); + return QVulkanInfoVector(); +} + +/*! + Sets the list of device \a extensions to be enabled. + + Unsupported extensions are ignored. + + The swapchain extension will always be added automatically, no need to + include it in this list. + + \note This function must be called before the window is made visible or at + latest in QVulkanWindowRenderer::preInitResources(), and has no effect if + called afterwards. + */ +void QVulkanWindow::setDeviceExtensions(const QByteArrayList &extensions) +{ + Q_D(QVulkanWindow); + if (d->status != QVulkanWindowPrivate::StatusUninitialized) { + qWarning("QVulkanWindow: Attempted to set device extensions when already initialized"); + return; + } + d->requestedDevExtensions = extensions; +} + +/*! + Sets the preferred \a formats of the swapchain. + + By default no application-preferred format is set. In this case the + surface's preferred format will be used or, in absence of that, + \c{VK_FORMAT_B8G8R8A8_UNORM}. + + The list in \a formats is ordered. If the first format is not supported, + the second will be considered, and so on. When no formats in the list are + supported, the behavior is the same as in the default case. + + To query the actual format after initialization, call colorFormat(). + + \note This function must be called before the window is made visible or at + latest in QVulkanWindowRenderer::preInitResources(), and has no effect if + called afterwards. + + \note Reimplementing QVulkanWindowRenderer::preInitResources() allows + dynamically examining the list of supported formats, should that be + desired. There the surface is retrievable via + QVulkanInstace::surfaceForWindow(), while this function can still safely be + called to affect the later stages of initialization. + + \sa colorFormat() + */ +void QVulkanWindow::setPreferredColorFormats(const QVector &formats) +{ + Q_D(QVulkanWindow); + if (d->status != QVulkanWindowPrivate::StatusUninitialized) { + qWarning("QVulkanWindow: Attempted to set preferred color format when already initialized"); + return; + } + d->requestedColorFormats = formats; +} + +static struct { + VkSampleCountFlagBits mask; + int count; +} qvk_sampleCounts[] = { + { VK_SAMPLE_COUNT_1_BIT, 1 }, + { VK_SAMPLE_COUNT_2_BIT, 2 }, + { VK_SAMPLE_COUNT_4_BIT, 4 }, + { VK_SAMPLE_COUNT_8_BIT, 8 }, + { VK_SAMPLE_COUNT_16_BIT, 16 }, + { VK_SAMPLE_COUNT_32_BIT, 32 }, + { VK_SAMPLE_COUNT_64_BIT, 64 } +}; + +/* + \return the set of supported sample counts when using the physical device + selected by setPhysicalDeviceIndex(). + + By default QVulkanWindow uses a sample count of 1. By calling setSampleCount() + with a different value (2, 4, 8, ...) from the set returned by this + function, multisample anti-aliasing can be requested. + + \note This function can be called before making the window visible. + + \sa setSampleCount() + */ +QSet QVulkanWindow::supportedSampleCounts() +{ + Q_D(const QVulkanWindow); + QSet result; + + availablePhysicalDevices(); + + if (d->physDevs.isEmpty()) { + qWarning("QVulkanWindow: No physical devices found"); + return result; + } + + const VkPhysicalDeviceLimits *limits = &d->physDevProps[d->physDevIndex].limits; + VkSampleCountFlags color = limits->framebufferColorSampleCounts; + VkSampleCountFlags depth = limits->framebufferDepthSampleCounts; + VkSampleCountFlags stencil = limits->framebufferStencilSampleCounts; + + for (size_t i = 0; i < sizeof(qvk_sampleCounts) / sizeof(qvk_sampleCounts[0]); ++i) { + if ((color & qvk_sampleCounts[i].mask) + && (depth & qvk_sampleCounts[i].mask) + && (stencil & qvk_sampleCounts[i].mask)) + { + result.insert(qvk_sampleCounts[i].count); + } + } + + return result; +} + +/*! + Requests multisample antialiasing with the given \a sampleCount. The valid + values are 1, 2, 4, 8, ... up until the maximum value supported by the + physical device. + + When the sample count is greater than 1, QVulkanWindow will create a + multisample color buffer instead of simply targeting the swapchain's + images. The rendering in the multisample buffer will get resolved into the + non-multisample buffers at the end of each frame. + + To examine the list of supported sample counts, call supportedSampleCounts(). + + When setting up the rendering pipeline, call sampleCountFlagBits() to query the + active sample count as a \c VkSampleCountFlagBits value. + + \note This function must be called before the window is made visible or at + latest in QVulkanWindowRenderer::preInitResources(), and has no effect if + called afterwards. + + \sa supportedSampleCounts(), sampleCountFlagBits() + */ +void QVulkanWindow::setSampleCount(int sampleCount) +{ + Q_D(QVulkanWindow); + if (d->status != QVulkanWindowPrivate::StatusUninitialized) { + qWarning("QVulkanWindow: Attempted to set sample count when already initialized"); + return; + } + + // Stay compatible with QSurfaceFormat and friends where samples == 0 means the same as 1. + sampleCount = qBound(1, sampleCount, 64); + + if (!supportedSampleCounts().contains(sampleCount)) { + qWarning("QVulkanWindow: Attempted to set unsupported sample count %d", sampleCount); + return; + } + + for (size_t i = 0; i < sizeof(qvk_sampleCounts) / sizeof(qvk_sampleCounts[0]); ++i) { + if (qvk_sampleCounts[i].count == sampleCount) { + d->sampleCount = qvk_sampleCounts[i].mask; + return; + } + } + + Q_UNREACHABLE(); +} + +void QVulkanWindowPrivate::init() +{ + Q_Q(QVulkanWindow); + Q_ASSERT(status == StatusUninitialized); + + qCDebug(lcVk, "QVulkanWindow init"); + + inst = q->vulkanInstance(); + if (!inst) { + qWarning("QVulkanWindow: Attempted to initialize without a QVulkanInstance"); + // This is a simple user error, recheck on the next expose instead of + // going into the permanent failure state. + status = StatusFailRetry; + return; + } + + if (!renderer) + renderer = q->createRenderer(); + + surface = QVulkanInstance::surfaceForWindow(q); + if (surface == VK_NULL_HANDLE) { + qWarning("QVulkanWindow: Failed to retrieve Vulkan surface for window"); + status = StatusFailRetry; + return; + } + + q->availablePhysicalDevices(); + + if (physDevs.isEmpty()) { + qWarning("QVulkanWindow: No physical devices found"); + status = StatusFail; + return; + } + + if (physDevIndex < 0 || physDevIndex >= physDevs.count()) { + qWarning("QVulkanWindow: Invalid physical device index; defaulting to 0"); + physDevIndex = 0; + } + qCDebug(lcVk, "Using physical device [%d]", physDevIndex); + + // Give a last chance to do decisions based on the physical device and the surface. + if (renderer) + renderer->preInitResources(); + + VkPhysicalDevice physDev = physDevs.at(physDevIndex); + QVulkanFunctions *f = inst->functions(); + + uint32_t queueCount = 0; + f->vkGetPhysicalDeviceQueueFamilyProperties(physDev, &queueCount, nullptr); + QVector queueFamilyProps(queueCount); + f->vkGetPhysicalDeviceQueueFamilyProperties(physDev, &queueCount, queueFamilyProps.data()); + gfxQueueFamilyIdx = uint32_t(-1); + presQueueFamilyIdx = uint32_t(-1); + for (int i = 0; i < queueFamilyProps.count(); ++i) { + const bool supportsPresent = inst->supportsPresent(physDev, i, q); + qCDebug(lcVk, "queue family %d: flags=0x%x count=%d supportsPresent=%d", i, + queueFamilyProps[i].queueFlags, queueFamilyProps[i].queueCount, supportsPresent); + if (gfxQueueFamilyIdx == uint32_t(-1) + && (queueFamilyProps[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) + && supportsPresent) + gfxQueueFamilyIdx = i; + } + if (gfxQueueFamilyIdx != uint32_t(-1)) { + presQueueFamilyIdx = gfxQueueFamilyIdx; + } else { + qCDebug(lcVk, "No queue with graphics+present; trying separate queues"); + for (int i = 0; i < queueFamilyProps.count(); ++i) { + if (gfxQueueFamilyIdx == uint32_t(-1) && (queueFamilyProps[i].queueFlags & VK_QUEUE_GRAPHICS_BIT)) + gfxQueueFamilyIdx = i; + if (presQueueFamilyIdx == uint32_t(-1) && inst->supportsPresent(physDev, i, q)) + presQueueFamilyIdx = i; + } + } + if (gfxQueueFamilyIdx == uint32_t(-1)) { + qWarning("QVulkanWindow: No graphics queue family found"); + status = StatusFail; + return; + } + if (presQueueFamilyIdx == uint32_t(-1)) { + qWarning("QVulkanWindow: No present queue family found"); + status = StatusFail; + return; + } +#ifdef QT_DEBUG + // allow testing the separate present queue case in debug builds on AMD cards + if (qEnvironmentVariableIsSet("QT_VK_PRESENT_QUEUE_INDEX")) + presQueueFamilyIdx = qEnvironmentVariableIntValue("QT_VK_PRESENT_QUEUE_INDEX"); +#endif + qCDebug(lcVk, "Using queue families: graphics = %u present = %u", gfxQueueFamilyIdx, presQueueFamilyIdx); + + VkDeviceQueueCreateInfo queueInfo[2]; + const float prio[] = { 0 }; + memset(queueInfo, 0, sizeof(queueInfo)); + queueInfo[0].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; + queueInfo[0].queueFamilyIndex = gfxQueueFamilyIdx; + queueInfo[0].queueCount = 1; + queueInfo[0].pQueuePriorities = prio; + if (gfxQueueFamilyIdx != presQueueFamilyIdx) { + queueInfo[1].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; + queueInfo[1].queueFamilyIndex = presQueueFamilyIdx; + queueInfo[1].queueCount = 1; + queueInfo[1].pQueuePriorities = prio; + } + + // Filter out unsupported extensions in order to keep symmetry + // with how QVulkanInstance behaves. Add the swapchain extension. + QVector devExts; + QVulkanInfoVector supportedExtensions = q->supportedDeviceExtensions(); + QByteArrayList reqExts = requestedDevExtensions; + reqExts.append("VK_KHR_swapchain"); + for (const QByteArray &ext : reqExts) { + if (supportedExtensions.contains(ext)) + devExts.append(ext.constData()); + } + qCDebug(lcVk) << "Enabling device extensions:" << devExts; + + VkDeviceCreateInfo devInfo; + memset(&devInfo, 0, sizeof(devInfo)); + devInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; + devInfo.queueCreateInfoCount = gfxQueueFamilyIdx == presQueueFamilyIdx ? 1 : 2; + devInfo.pQueueCreateInfos = queueInfo; + devInfo.enabledExtensionCount = devExts.count(); + devInfo.ppEnabledExtensionNames = devExts.constData(); + + // Device layers are not supported by QVulkanWindow since that's an already deprecated + // API. However, have a workaround for systems with older API and layers (f.ex. L4T + // 24.2 for the Jetson TX1 provides API 1.0.13 and crashes when the validation layer + // is enabled for the instance but not the device). + uint32_t apiVersion = physDevProps[physDevIndex].apiVersion; + if (VK_VERSION_MAJOR(apiVersion) == 1 + && VK_VERSION_MINOR(apiVersion) == 0 + && VK_VERSION_PATCH(apiVersion) <= 13) + { + // Make standard validation work at least. + const QByteArray stdValName = QByteArrayLiteral("VK_LAYER_LUNARG_standard_validation"); + const char *stdValNamePtr = stdValName.constData(); + if (inst->layers().contains(stdValName)) { + uint32_t count = 0; + VkResult err = f->vkEnumerateDeviceLayerProperties(physDev, &count, nullptr); + if (err == VK_SUCCESS) { + QVector layerProps(count); + err = f->vkEnumerateDeviceLayerProperties(physDev, &count, layerProps.data()); + if (err == VK_SUCCESS) { + for (const VkLayerProperties &prop : layerProps) { + if (!strncmp(prop.layerName, stdValNamePtr, stdValName.count())) { + devInfo.enabledLayerCount = 1; + devInfo.ppEnabledLayerNames = &stdValNamePtr; + break; + } + } + } + } + } + } + + VkResult err = f->vkCreateDevice(physDev, &devInfo, nullptr, &dev); + if (err == VK_ERROR_DEVICE_LOST) { + qWarning("QVulkanWindow: Physical device lost"); + if (renderer) + renderer->physicalDeviceLost(); + // clear the caches so the list of physical devices is re-queried + physDevs.clear(); + physDevProps.clear(); + status = StatusUninitialized; + qCDebug(lcVk, "Attempting to restart in 2 seconds"); + QTimer::singleShot(2000, q, [this]() { ensureStarted(); }); + return; + } + if (err != VK_SUCCESS) { + qWarning("QVulkanWindow: Failed to create device: %d", err); + status = StatusFail; + return; + } + + devFuncs = inst->deviceFunctions(dev); + Q_ASSERT(devFuncs); + + devFuncs->vkGetDeviceQueue(dev, gfxQueueFamilyIdx, 0, &gfxQueue); + if (gfxQueueFamilyIdx == presQueueFamilyIdx) + presQueue = gfxQueue; + else + devFuncs->vkGetDeviceQueue(dev, presQueueFamilyIdx, 0, &presQueue); + + VkCommandPoolCreateInfo poolInfo; + memset(&poolInfo, 0, sizeof(poolInfo)); + poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; + poolInfo.queueFamilyIndex = gfxQueueFamilyIdx; + err = devFuncs->vkCreateCommandPool(dev, &poolInfo, nullptr, &cmdPool); + if (err != VK_SUCCESS) { + qWarning("QVulkanWindow: Failed to create command pool: %d", err); + status = StatusFail; + return; + } + if (gfxQueueFamilyIdx != presQueueFamilyIdx) { + poolInfo.queueFamilyIndex = presQueueFamilyIdx; + err = devFuncs->vkCreateCommandPool(dev, &poolInfo, nullptr, &presCmdPool); + if (err != VK_SUCCESS) { + qWarning("QVulkanWindow: Failed to create command pool for present queue: %d", err); + status = StatusFail; + return; + } + } + + hostVisibleMemIndex = 0; + VkPhysicalDeviceMemoryProperties physDevMemProps; + bool hostVisibleMemIndexSet = false; + f->vkGetPhysicalDeviceMemoryProperties(physDev, &physDevMemProps); + for (uint32_t i = 0; i < physDevMemProps.memoryTypeCount; ++i) { + const VkMemoryType *memType = physDevMemProps.memoryTypes; + qCDebug(lcVk, "memtype %d: flags=0x%x", i, memType[i].propertyFlags); + // Find a host visible, host coherent memtype. If there is one that is + // cached as well (in addition to being coherent), prefer that. + const int hostVisibleAndCoherent = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; + if ((memType[i].propertyFlags & hostVisibleAndCoherent) == hostVisibleAndCoherent) { + if (!hostVisibleMemIndexSet + || (memType[i].propertyFlags & VK_MEMORY_PROPERTY_HOST_CACHED_BIT)) { + hostVisibleMemIndexSet = true; + hostVisibleMemIndex = i; + } + } + } + qCDebug(lcVk, "Picked memtype %d for host visible memory", hostVisibleMemIndex); + deviceLocalMemIndex = 0; + for (uint32_t i = 0; i < physDevMemProps.memoryTypeCount; ++i) { + const VkMemoryType *memType = physDevMemProps.memoryTypes; + // Just pick the first device local memtype. + if (memType[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) { + deviceLocalMemIndex = i; + break; + } + } + qCDebug(lcVk, "Picked memtype %d for device local memory", deviceLocalMemIndex); + + if (!vkGetPhysicalDeviceSurfaceCapabilitiesKHR || !vkGetPhysicalDeviceSurfaceFormatsKHR) { + vkGetPhysicalDeviceSurfaceCapabilitiesKHR = reinterpret_cast( + inst->getInstanceProcAddr("vkGetPhysicalDeviceSurfaceCapabilitiesKHR")); + vkGetPhysicalDeviceSurfaceFormatsKHR = reinterpret_cast( + inst->getInstanceProcAddr("vkGetPhysicalDeviceSurfaceFormatsKHR")); + if (!vkGetPhysicalDeviceSurfaceCapabilitiesKHR || !vkGetPhysicalDeviceSurfaceFormatsKHR) { + qWarning("QVulkanWindow: Physical device surface queries not available"); + status = StatusFail; + return; + } + } + + // Figure out the color format here. Must not wait until recreateSwapChain() + // because the renderpass should be available already from initResources (so + // that apps do not have to defer pipeline creation to + // initSwapChainResources), but the renderpass needs the final color format. + + uint32_t formatCount = 0; + vkGetPhysicalDeviceSurfaceFormatsKHR(physDev, surface, &formatCount, nullptr); + QVector formats(formatCount); + if (formatCount) + vkGetPhysicalDeviceSurfaceFormatsKHR(physDev, surface, &formatCount, formats.data()); + + colorFormat = VK_FORMAT_B8G8R8A8_UNORM; // our documented default if all else fails + colorSpace = VkColorSpaceKHR(0); // this is in fact VK_COLOR_SPACE_SRGB_NONLINEAR_KHR + + // Pick the preferred format, if there is one. + if (!formats.isEmpty() && formats[0].format != VK_FORMAT_UNDEFINED) { + colorFormat = formats[0].format; + colorSpace = formats[0].colorSpace; + } + + // Try to honor the user request. + if (!formats.isEmpty() && !requestedColorFormats.isEmpty()) { + for (VkFormat reqFmt : qAsConst(requestedColorFormats)) { + auto r = std::find_if(formats.cbegin(), formats.cend(), + [reqFmt](const VkSurfaceFormatKHR &sfmt) { return sfmt.format == reqFmt; }); + if (r != formats.cend()) { + colorFormat = r->format; + colorSpace = r->colorSpace; + break; + } + } + } + + const VkFormat dsFormatCandidates[] = { + VK_FORMAT_D24_UNORM_S8_UINT, + VK_FORMAT_D32_SFLOAT_S8_UINT, + VK_FORMAT_D16_UNORM_S8_UINT + }; + const int dsFormatCandidateCount = sizeof(dsFormatCandidates) / sizeof(VkFormat); + int dsFormatIdx = 0; + while (dsFormatIdx < dsFormatCandidateCount) { + dsFormat = dsFormatCandidates[dsFormatIdx]; + VkFormatProperties fmtProp; + f->vkGetPhysicalDeviceFormatProperties(physDev, dsFormat, &fmtProp); + if (fmtProp.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) + break; + ++dsFormatIdx; + } + if (dsFormatIdx == dsFormatCandidateCount) + qWarning("QVulkanWindow: Failed to find an optimal depth-stencil format"); + + qCDebug(lcVk, "Color format: %d Depth-stencil format: %d", colorFormat, dsFormat); + + if (!createDefaultRenderPass()) + return; + + if (renderer) + renderer->initResources(); + + status = StatusDeviceReady; +} + +void QVulkanWindowPrivate::reset() +{ + if (!dev) // do not rely on 'status', a half done init must be cleaned properly too + return; + + qCDebug(lcVk, "QVulkanWindow reset"); + + devFuncs->vkDeviceWaitIdle(dev); + + if (renderer) + renderer->releaseResources(); + + if (defaultRenderPass) { + devFuncs->vkDestroyRenderPass(dev, defaultRenderPass, nullptr); + defaultRenderPass = VK_NULL_HANDLE; + } + + if (cmdPool) { + devFuncs->vkDestroyCommandPool(dev, cmdPool, nullptr); + cmdPool = VK_NULL_HANDLE; + } + + if (presCmdPool) { + devFuncs->vkDestroyCommandPool(dev, presCmdPool, nullptr); + presCmdPool = VK_NULL_HANDLE; + } + + if (frameGrabImage) { + devFuncs->vkDestroyImage(dev, frameGrabImage, nullptr); + frameGrabImage = VK_NULL_HANDLE; + } + + if (frameGrabImageMem) { + devFuncs->vkFreeMemory(dev, frameGrabImageMem, nullptr); + frameGrabImageMem = VK_NULL_HANDLE; + } + + if (dev) { + devFuncs->vkDestroyDevice(dev, nullptr); + inst->resetDeviceFunctions(dev); + dev = VK_NULL_HANDLE; + vkCreateSwapchainKHR = nullptr; // re-resolve swapchain funcs later on since some come via the device + } + + surface = VK_NULL_HANDLE; + + status = StatusUninitialized; +} + +bool QVulkanWindowPrivate::createDefaultRenderPass() +{ + VkAttachmentDescription attDesc[3]; + memset(attDesc, 0, sizeof(attDesc)); + + const bool msaa = sampleCount > VK_SAMPLE_COUNT_1_BIT; + + // This is either the non-msaa render target or the resolve target. + attDesc[0].format = colorFormat; + attDesc[0].samples = VK_SAMPLE_COUNT_1_BIT; + attDesc[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; // ignored when msaa + attDesc[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE; + attDesc[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; + attDesc[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; + attDesc[0].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + attDesc[0].finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; + + attDesc[1].format = dsFormat; + attDesc[1].samples = sampleCount; + attDesc[1].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; + attDesc[1].storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; + attDesc[1].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; + attDesc[1].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; + attDesc[1].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + attDesc[1].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; + + if (msaa) { + // msaa render target + attDesc[2].format = colorFormat; + attDesc[2].samples = sampleCount; + attDesc[2].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; + attDesc[2].storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; + attDesc[2].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; + attDesc[2].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; + attDesc[2].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + attDesc[2].finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + } + + VkAttachmentReference colorRef = { 0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL }; + VkAttachmentReference resolveRef = { 0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL }; + VkAttachmentReference dsRef = { 1, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL }; + + VkSubpassDescription subPassDesc; + memset(&subPassDesc, 0, sizeof(subPassDesc)); + subPassDesc.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; + subPassDesc.colorAttachmentCount = 1; + subPassDesc.pColorAttachments = &colorRef; + subPassDesc.pDepthStencilAttachment = &dsRef; + + VkRenderPassCreateInfo rpInfo; + memset(&rpInfo, 0, sizeof(rpInfo)); + rpInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; + rpInfo.attachmentCount = 2; + rpInfo.pAttachments = attDesc; + rpInfo.subpassCount = 1; + rpInfo.pSubpasses = &subPassDesc; + + if (msaa) { + colorRef.attachment = 2; + subPassDesc.pResolveAttachments = &resolveRef; + rpInfo.attachmentCount = 3; + } + + VkResult err = devFuncs->vkCreateRenderPass(dev, &rpInfo, nullptr, &defaultRenderPass); + if (err != VK_SUCCESS) { + qWarning("QVulkanWindow: Failed to create renderpass: %d", err); + return false; + } + + return true; +} + +void QVulkanWindowPrivate::recreateSwapChain() +{ + Q_Q(QVulkanWindow); + Q_ASSERT(status >= StatusDeviceReady); + + swapChainImageSize = q->size() * q->devicePixelRatio(); // note: may change below due to surfaceCaps + + if (swapChainImageSize.isEmpty()) // handle null window size gracefully + return; + + QVulkanInstance *inst = q->vulkanInstance(); + QVulkanFunctions *f = inst->functions(); + devFuncs->vkDeviceWaitIdle(dev); + + if (!vkCreateSwapchainKHR) { + vkCreateSwapchainKHR = reinterpret_cast(f->vkGetDeviceProcAddr(dev, "vkCreateSwapchainKHR")); + vkDestroySwapchainKHR = reinterpret_cast(f->vkGetDeviceProcAddr(dev, "vkDestroySwapchainKHR")); + vkGetSwapchainImagesKHR = reinterpret_cast(f->vkGetDeviceProcAddr(dev, "vkGetSwapchainImagesKHR")); + vkAcquireNextImageKHR = reinterpret_cast(f->vkGetDeviceProcAddr(dev, "vkAcquireNextImageKHR")); + vkQueuePresentKHR = reinterpret_cast(f->vkGetDeviceProcAddr(dev, "vkQueuePresentKHR")); + } + + VkPhysicalDevice physDev = physDevs.at(physDevIndex); + VkSurfaceCapabilitiesKHR surfaceCaps; + vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physDev, surface, &surfaceCaps); + uint32_t reqBufferCount = swapChainBufferCount; + if (surfaceCaps.maxImageCount) + reqBufferCount = qBound(surfaceCaps.minImageCount, reqBufferCount, surfaceCaps.maxImageCount); + + VkExtent2D bufferSize = surfaceCaps.currentExtent; + if (bufferSize.width == uint32_t(-1)) { + Q_ASSERT(bufferSize.height == uint32_t(-1)); + bufferSize.width = swapChainImageSize.width(); + bufferSize.height = swapChainImageSize.height(); + } else { + swapChainImageSize = QSize(bufferSize.width, bufferSize.height); + } + + VkSurfaceTransformFlagBitsKHR preTransform = + (surfaceCaps.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) + ? VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR + : surfaceCaps.currentTransform; + + VkCompositeAlphaFlagBitsKHR compositeAlpha = + (surfaceCaps.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR) + ? VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR + : VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; + + if (q->requestedFormat().hasAlpha()) { + if (surfaceCaps.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR) + compositeAlpha = VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR; + else if (surfaceCaps.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR) + compositeAlpha = VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR; + } + + VkImageUsageFlags usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; + swapChainSupportsReadBack = (surfaceCaps.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_SRC_BIT); + if (swapChainSupportsReadBack) + usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; + + VkSwapchainKHR oldSwapChain = swapChain; + VkSwapchainCreateInfoKHR swapChainInfo; + memset(&swapChainInfo, 0, sizeof(swapChainInfo)); + swapChainInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; + swapChainInfo.surface = surface; + swapChainInfo.minImageCount = reqBufferCount; + swapChainInfo.imageFormat = colorFormat; + swapChainInfo.imageColorSpace = colorSpace; + swapChainInfo.imageExtent = bufferSize; + swapChainInfo.imageArrayLayers = 1; + swapChainInfo.imageUsage = usage; + swapChainInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; + swapChainInfo.preTransform = preTransform; + swapChainInfo.compositeAlpha = compositeAlpha; + swapChainInfo.presentMode = presentMode; + swapChainInfo.clipped = true; + swapChainInfo.oldSwapchain = oldSwapChain; + + qCDebug(lcVk, "Creating new swap chain of %d buffers, size %dx%d", reqBufferCount, bufferSize.width, bufferSize.height); + + VkSwapchainKHR newSwapChain; + VkResult err = vkCreateSwapchainKHR(dev, &swapChainInfo, nullptr, &newSwapChain); + if (err != VK_SUCCESS) { + qWarning("QVulkanWindow: Failed to create swap chain: %d", err); + return; + } + + if (oldSwapChain) + releaseSwapChain(); + + swapChain = newSwapChain; + + uint32_t actualSwapChainBufferCount = 0; + err = vkGetSwapchainImagesKHR(dev, swapChain, &actualSwapChainBufferCount, nullptr); + if (err != VK_SUCCESS || actualSwapChainBufferCount < 2) { + qWarning("QVulkanWindow: Failed to get swapchain images: %d (count=%d)", err, actualSwapChainBufferCount); + return; + } + + qCDebug(lcVk, "Actual swap chain buffer count: %d (supportsReadback=%d)", + actualSwapChainBufferCount, swapChainSupportsReadBack); + if (actualSwapChainBufferCount > MAX_SWAPCHAIN_BUFFER_COUNT) { + qWarning("QVulkanWindow: Too many swapchain buffers (%d)", actualSwapChainBufferCount); + return; + } + swapChainBufferCount = actualSwapChainBufferCount; + + VkImage swapChainImages[MAX_SWAPCHAIN_BUFFER_COUNT]; + err = vkGetSwapchainImagesKHR(dev, swapChain, &actualSwapChainBufferCount, swapChainImages); + if (err != VK_SUCCESS) { + qWarning("QVulkanWindow: Failed to get swapchain images: %d", err); + return; + } + + if (!createTransientImage(dsFormat, + VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, + VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT, + &dsImage, + &dsMem, + &dsView, + 1)) + { + return; + } + + const bool msaa = sampleCount > VK_SAMPLE_COUNT_1_BIT; + VkImage msaaImages[MAX_SWAPCHAIN_BUFFER_COUNT]; + VkImageView msaaViews[MAX_SWAPCHAIN_BUFFER_COUNT]; + + if (msaa) { + if (!createTransientImage(colorFormat, + VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, + VK_IMAGE_ASPECT_COLOR_BIT, + msaaImages, + &msaaImageMem, + msaaViews, + swapChainBufferCount)) + { + return; + } + } + + VkFenceCreateInfo fenceInfo = { VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, nullptr, VK_FENCE_CREATE_SIGNALED_BIT }; + + for (int i = 0; i < swapChainBufferCount; ++i) { + ImageResources &image(imageRes[i]); + image.image = swapChainImages[i]; + + if (msaa) { + image.msaaImage = msaaImages[i]; + image.msaaImageView = msaaViews[i]; + } + + VkImageViewCreateInfo imgViewInfo; + memset(&imgViewInfo, 0, sizeof(imgViewInfo)); + imgViewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + imgViewInfo.image = swapChainImages[i]; + imgViewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; + imgViewInfo.format = colorFormat; + imgViewInfo.components.r = VK_COMPONENT_SWIZZLE_R; + imgViewInfo.components.g = VK_COMPONENT_SWIZZLE_G; + imgViewInfo.components.b = VK_COMPONENT_SWIZZLE_B; + imgViewInfo.components.a = VK_COMPONENT_SWIZZLE_A; + imgViewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + imgViewInfo.subresourceRange.levelCount = imgViewInfo.subresourceRange.layerCount = 1; + err = devFuncs->vkCreateImageView(dev, &imgViewInfo, nullptr, &image.imageView); + if (err != VK_SUCCESS) { + qWarning("QVulkanWindow: Failed to create swapchain image view %d: %d", i, err); + return; + } + + err = devFuncs->vkCreateFence(dev, &fenceInfo, nullptr, &image.cmdFence); + if (err != VK_SUCCESS) { + qWarning("QVulkanWindow: Failed to create command buffer fence: %d", err); + return; + } + image.cmdFenceWaitable = true; // fence was created in signaled state + + VkImageView views[3] = { image.imageView, + dsView, + msaa ? image.msaaImageView : VK_NULL_HANDLE }; + VkFramebufferCreateInfo fbInfo; + memset(&fbInfo, 0, sizeof(fbInfo)); + fbInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; + fbInfo.renderPass = defaultRenderPass; + fbInfo.attachmentCount = msaa ? 3 : 2; + fbInfo.pAttachments = views; + fbInfo.width = swapChainImageSize.width(); + fbInfo.height = swapChainImageSize.height(); + fbInfo.layers = 1; + VkResult err = devFuncs->vkCreateFramebuffer(dev, &fbInfo, nullptr, &image.fb); + if (err != VK_SUCCESS) { + qWarning("QVulkanWindow: Failed to create framebuffer: %d", err); + return; + } + + if (gfxQueueFamilyIdx != presQueueFamilyIdx) { + // pre-build the static image-acquire-on-present-queue command buffer + VkCommandBufferAllocateInfo cmdBufInfo = { + VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, nullptr, presCmdPool, VK_COMMAND_BUFFER_LEVEL_PRIMARY, 1 }; + err = devFuncs->vkAllocateCommandBuffers(dev, &cmdBufInfo, &image.presTransCmdBuf); + if (err != VK_SUCCESS) { + qWarning("QVulkanWindow: Failed to allocate acquire-on-present-queue command buffer: %d", err); + return; + } + VkCommandBufferBeginInfo cmdBufBeginInfo = { + VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, nullptr, + VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT, nullptr }; + err = devFuncs->vkBeginCommandBuffer(image.presTransCmdBuf, &cmdBufBeginInfo); + if (err != VK_SUCCESS) { + qWarning("QVulkanWindow: Failed to begin acquire-on-present-queue command buffer: %d", err); + return; + } + VkImageMemoryBarrier presTrans; + memset(&presTrans, 0, sizeof(presTrans)); + presTrans.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + presTrans.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + presTrans.oldLayout = presTrans.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; + presTrans.srcQueueFamilyIndex = gfxQueueFamilyIdx; + presTrans.dstQueueFamilyIndex = presQueueFamilyIdx; + presTrans.image = image.image; + presTrans.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + presTrans.subresourceRange.levelCount = presTrans.subresourceRange.layerCount = 1; + devFuncs->vkCmdPipelineBarrier(image.presTransCmdBuf, + VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + 0, 0, nullptr, 0, nullptr, + 1, &presTrans); + err = devFuncs->vkEndCommandBuffer(image.presTransCmdBuf); + if (err != VK_SUCCESS) { + qWarning("QVulkanWindow: Failed to end acquire-on-present-queue command buffer: %d", err); + return; + } + } + } + + currentImage = 0; + + VkSemaphoreCreateInfo semInfo = { VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, nullptr, 0 }; + for (int i = 0; i < frameLag; ++i) { + FrameResources &frame(frameRes[i]); + + frame.imageAcquired = false; + frame.imageSemWaitable = false; + + devFuncs->vkCreateFence(dev, &fenceInfo, nullptr, &frame.fence); + frame.fenceWaitable = true; // fence was created in signaled state + + devFuncs->vkCreateSemaphore(dev, &semInfo, nullptr, &frame.imageSem); + devFuncs->vkCreateSemaphore(dev, &semInfo, nullptr, &frame.drawSem); + if (gfxQueueFamilyIdx != presQueueFamilyIdx) + devFuncs->vkCreateSemaphore(dev, &semInfo, nullptr, &frame.presTransSem); + } + + currentFrame = 0; + + if (renderer) + renderer->initSwapChainResources(); + + status = StatusReady; +} + +uint32_t QVulkanWindowPrivate::chooseTransientImageMemType(VkImage img, uint32_t startIndex) +{ + VkPhysicalDeviceMemoryProperties physDevMemProps; + inst->functions()->vkGetPhysicalDeviceMemoryProperties(physDevs[physDevIndex], &physDevMemProps); + + VkMemoryRequirements memReq; + devFuncs->vkGetImageMemoryRequirements(dev, img, &memReq); + uint32_t memTypeIndex = uint32_t(-1); + + if (memReq.memoryTypeBits) { + // Find a device local + lazily allocated, or at least device local memtype. + const VkMemoryType *memType = physDevMemProps.memoryTypes; + bool foundDevLocal = false; + for (uint32_t i = startIndex; i < physDevMemProps.memoryTypeCount; ++i) { + if (memReq.memoryTypeBits & (1 << i)) { + if (memType[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) { + if (!foundDevLocal) { + foundDevLocal = true; + memTypeIndex = i; + } + if (memType[i].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) { + memTypeIndex = i; + break; + } + } + } + } + } + + return memTypeIndex; +} + +static inline VkDeviceSize aligned(VkDeviceSize v, VkDeviceSize byteAlign) +{ + return (v + byteAlign - 1) & ~(byteAlign - 1); +} + +bool QVulkanWindowPrivate::createTransientImage(VkFormat format, + VkImageUsageFlags usage, + VkImageAspectFlags aspectMask, + VkImage *images, + VkDeviceMemory *mem, + VkImageView *views, + int count) +{ + VkMemoryRequirements memReq; + VkResult err; + + for (int i = 0; i < count; ++i) { + VkImageCreateInfo imgInfo; + memset(&imgInfo, 0, sizeof(imgInfo)); + imgInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + imgInfo.imageType = VK_IMAGE_TYPE_2D; + imgInfo.format = format; + imgInfo.extent.width = swapChainImageSize.width(); + imgInfo.extent.height = swapChainImageSize.height(); + imgInfo.extent.depth = 1; + imgInfo.mipLevels = imgInfo.arrayLayers = 1; + imgInfo.samples = sampleCount; + imgInfo.tiling = VK_IMAGE_TILING_OPTIMAL; + imgInfo.usage = usage | VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT; + + err = devFuncs->vkCreateImage(dev, &imgInfo, nullptr, images + i); + if (err != VK_SUCCESS) { + qWarning("QVulkanWindow: Failed to create image: %d", err); + return false; + } + + // Assume the reqs are the same since the images are same in every way. + // Still, call GetImageMemReq for every image, in order to prevent the + // validation layer from complaining. + devFuncs->vkGetImageMemoryRequirements(dev, images[i], &memReq); + } + + VkMemoryAllocateInfo memInfo; + memset(&memInfo, 0, sizeof(memInfo)); + memInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + memInfo.allocationSize = aligned(memReq.size, memReq.alignment) * count; + + uint32_t startIndex = 0; + do { + memInfo.memoryTypeIndex = chooseTransientImageMemType(images[0], startIndex); + if (memInfo.memoryTypeIndex == uint32_t(-1)) { + qWarning("QVulkanWindow: No suitable memory type found"); + return false; + } + startIndex = memInfo.memoryTypeIndex + 1; + qCDebug(lcVk, "Allocating %u bytes for transient image (memtype %u)", + uint32_t(memInfo.allocationSize), memInfo.memoryTypeIndex); + err = devFuncs->vkAllocateMemory(dev, &memInfo, nullptr, mem); + if (err != VK_SUCCESS && err != VK_ERROR_OUT_OF_DEVICE_MEMORY) { + qWarning("QVulkanWindow: Failed to allocate image memory: %d", err); + return false; + } + } while (err != VK_SUCCESS); + + VkDeviceSize ofs = 0; + for (int i = 0; i < count; ++i) { + err = devFuncs->vkBindImageMemory(dev, images[i], *mem, ofs); + if (err != VK_SUCCESS) { + qWarning("QVulkanWindow: Failed to bind image memory: %d", err); + return false; + } + ofs += aligned(memReq.size, memReq.alignment); + + VkImageViewCreateInfo imgViewInfo; + memset(&imgViewInfo, 0, sizeof(imgViewInfo)); + imgViewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + imgViewInfo.image = images[i]; + imgViewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; + imgViewInfo.format = format; + imgViewInfo.components.r = VK_COMPONENT_SWIZZLE_R; + imgViewInfo.components.g = VK_COMPONENT_SWIZZLE_G; + imgViewInfo.components.b = VK_COMPONENT_SWIZZLE_B; + imgViewInfo.components.a = VK_COMPONENT_SWIZZLE_A; + imgViewInfo.subresourceRange.aspectMask = aspectMask; + imgViewInfo.subresourceRange.levelCount = imgViewInfo.subresourceRange.layerCount = 1; + + err = devFuncs->vkCreateImageView(dev, &imgViewInfo, nullptr, views + i); + if (err != VK_SUCCESS) { + qWarning("QVulkanWindow: Failed to create image view: %d", err); + return false; + } + } + + return true; +} + +void QVulkanWindowPrivate::releaseSwapChain() +{ + if (!dev || !swapChain) // do not rely on 'status', a half done init must be cleaned properly too + return; + + qCDebug(lcVk, "Releasing swapchain"); + + devFuncs->vkDeviceWaitIdle(dev); + + if (renderer) + renderer->releaseSwapChainResources(); + + for (int i = 0; i < frameLag; ++i) { + FrameResources &frame(frameRes[i]); + if (frame.fence) { + if (frame.fenceWaitable) + devFuncs->vkWaitForFences(dev, 1, &frame.fence, VK_TRUE, UINT64_MAX); + devFuncs->vkDestroyFence(dev, frame.fence, nullptr); + frame.fence = VK_NULL_HANDLE; + frame.fenceWaitable = false; + } + if (frame.imageSem) { + devFuncs->vkDestroySemaphore(dev, frame.imageSem, nullptr); + frame.imageSem = VK_NULL_HANDLE; + } + if (frame.drawSem) { + devFuncs->vkDestroySemaphore(dev, frame.drawSem, nullptr); + frame.drawSem = VK_NULL_HANDLE; + } + if (frame.presTransSem) { + devFuncs->vkDestroySemaphore(dev, frame.presTransSem, nullptr); + frame.presTransSem = VK_NULL_HANDLE; + } + } + + for (int i = 0; i < swapChainBufferCount; ++i) { + ImageResources &image(imageRes[i]); + if (image.cmdFence) { + if (image.cmdFenceWaitable) + devFuncs->vkWaitForFences(dev, 1, &image.cmdFence, VK_TRUE, UINT64_MAX); + devFuncs->vkDestroyFence(dev, image.cmdFence, nullptr); + image.cmdFence = VK_NULL_HANDLE; + image.cmdFenceWaitable = false; + } + if (image.fb) { + devFuncs->vkDestroyFramebuffer(dev, image.fb, nullptr); + image.fb = VK_NULL_HANDLE; + } + if (image.imageView) { + devFuncs->vkDestroyImageView(dev, image.imageView, nullptr); + image.imageView = VK_NULL_HANDLE; + } + if (image.cmdBuf) { + devFuncs->vkFreeCommandBuffers(dev, cmdPool, 1, &image.cmdBuf); + image.cmdBuf = VK_NULL_HANDLE; + } + if (image.presTransCmdBuf) { + devFuncs->vkFreeCommandBuffers(dev, presCmdPool, 1, &image.presTransCmdBuf); + image.presTransCmdBuf = VK_NULL_HANDLE; + } + if (image.msaaImageView) { + devFuncs->vkDestroyImageView(dev, image.msaaImageView, nullptr); + image.msaaImageView = VK_NULL_HANDLE; + } + if (image.msaaImage) { + devFuncs->vkDestroyImage(dev, image.msaaImage, nullptr); + image.msaaImage = VK_NULL_HANDLE; + } + } + + if (msaaImageMem) { + devFuncs->vkFreeMemory(dev, msaaImageMem, nullptr); + msaaImageMem = VK_NULL_HANDLE; + } + + if (dsView) { + devFuncs->vkDestroyImageView(dev, dsView, nullptr); + dsView = VK_NULL_HANDLE; + } + if (dsImage) { + devFuncs->vkDestroyImage(dev, dsImage, nullptr); + dsImage = VK_NULL_HANDLE; + } + if (dsMem) { + devFuncs->vkFreeMemory(dev, dsMem, nullptr); + dsMem = VK_NULL_HANDLE; + } + + if (swapChain) { + vkDestroySwapchainKHR(dev, swapChain, nullptr); + swapChain = VK_NULL_HANDLE; + } + + if (status == StatusReady) + status = StatusDeviceReady; +} + +/*! + \internal + */ +void QVulkanWindow::exposeEvent(QExposeEvent *) +{ + Q_D(QVulkanWindow); + + if (isExposed()) { + d->ensureStarted(); + } else { + if (!d->flags.testFlag(PersistentResources)) { + d->releaseSwapChain(); + d->reset(); + } + } +} + +void QVulkanWindowPrivate::ensureStarted() +{ + Q_Q(QVulkanWindow); + if (status == QVulkanWindowPrivate::StatusFailRetry) + status = QVulkanWindowPrivate::StatusUninitialized; + if (status == QVulkanWindowPrivate::StatusUninitialized) { + init(); + if (status == QVulkanWindowPrivate::StatusDeviceReady) + recreateSwapChain(); + } + if (status == QVulkanWindowPrivate::StatusReady) + q->requestUpdate(); +} + +/*! + \internal + */ +void QVulkanWindow::resizeEvent(QResizeEvent *) +{ + // Nothing to do here - recreating the swapchain is handled when building the next frame. +} + +/*! + \internal + */ +bool QVulkanWindow::event(QEvent *e) +{ + Q_D(QVulkanWindow); + + switch (e->type()) { + case QEvent::UpdateRequest: + d->beginFrame(); + break; + + // The swapchain must be destroyed before the surface as per spec. This is + // not ideal for us because the surface is managed by the QPlatformWindow + // which may be gone already when the unexpose comes, making the validation + // layer scream. The solution is to listen to the PlatformSurface events. + case QEvent::PlatformSurface: + if (static_cast(e)->surfaceEventType() == QPlatformSurfaceEvent::SurfaceAboutToBeDestroyed) { + d->releaseSwapChain(); + d->reset(); + } + break; + + default: + break; + } + + return QWindow::event(e); +} + +/*! + \return true if this window has successfully initialized all Vulkan + resources, including the swapchain. + + \note Initialization happens on the first expose event after the window is + made visible. + */ +bool QVulkanWindow::isValid() const +{ + Q_D(const QVulkanWindow); + return d->status == QVulkanWindowPrivate::StatusReady; +} + +/*! + \return a new instance of QVulkanWindowRenderer. + + This virtual function is called once during the lifetime of the window, at + some point after making it visible for the first time. + + The default implementation returns null and so no rendering will be + performed apart from clearing the buffers. + + The window takes ownership of the returned renderer object. + */ +QVulkanWindowRenderer *QVulkanWindow::createRenderer() +{ + return nullptr; +} + +/*! + Virtual destructor. + */ +QVulkanWindowRenderer::~QVulkanWindowRenderer() +{ +} + +/*! + This virtual function is called right before graphics initialization, that + ends up in calling initResources(), is about to begin. + + Normally there is no need to reimplement this function. However, there are + cases that involve decisions based on both the physical device and the + surface. These cannot normally be performed before making the QVulkanWindow + visible since the Vulkan surface is not retrievable at that stage. + + Instead, applications can reimplement this function. Here both + QVulkanWindow::physicalDevice() and QVulkanInstance::surfaceForWindow() are + functional, but no further logical device initialization has taken place + yet. + + The default implementation is empty. + */ +void QVulkanWindowRenderer::preInitResources() +{ +} + +/*! + This virtual function is called when it is time to create the renderer's + graphics resources. + + Depending on the QVulkanWindow::PersistentResources flag, device lost + situations, etc. this function may be called more than once during the + lifetime of a QVulkanWindow. However, subsequent invocations are always + preceded by a call to releaseResources(). + + Accessors like device(), graphicsQueue() and graphicsCommandPool() are only + guaranteed to return valid values inside this function and afterwards, up + until releaseResources() is called. + + The default implementation is empty. + */ +void QVulkanWindowRenderer::initResources() +{ +} + +/*! + This virtual function is called when swapchain, framebuffer or renderpass + related initialization can be performed. Swapchain and related resources + are reset and then recreated in response to window resize events, and + therefore a pair of calls to initResources() and releaseResources() can + have multiple calls to initSwapChainResources() and + releaseSwapChainResources() calls in-between. + + Accessors like swapChainImageSize() are only guaranteed to return valid + values inside this function and afterwards, up until + releaseSwapChainResources() is called. + + This is also the place where size-dependent calculations (for example, the + projection matrix) should be made since this function is called effectively + on every resize. + + The default implementation is empty. + */ +void QVulkanWindowRenderer::initSwapChainResources() +{ +} + +/*! + This virtual function is called when swapchain, framebuffer or renderpass + related resources must be released. + + The implementation must be prepared that a call to this function may be + followed by a new call to initSwapChainResources() at a later point. + + QVulkanWindow takes care of waiting for the device to become idle before + invoking this function. + + The default implementation is empty. + */ +void QVulkanWindowRenderer::releaseSwapChainResources() +{ +} + +/*! + This virtual function is called when the renderer's graphics resources must be + released. + + The implementation must be prepared that a call to this function may be + followed by an initResources() at a later point. + + QVulkanWindow takes care of waiting for the device to become idle before + invoking this function. + + The default implementation is empty. + */ +void QVulkanWindowRenderer::releaseResources() +{ +} + +/*! + \fn QVulkanWindowRenderer::startNextFrame() + + This virtual function is called when the draw calls for the next frame are + to be added to the command buffer. + + Each call to this function must be followed by a call to + QVulkanWindow::frameReady(). Failing to do so will stall the rendering + loop. The call can also be made at a later time, after returning from this + function. This means that it is possible to kick off asynchronous work, and + only update the command buffer and notify QVulkanWindow when that work has + finished. + + All Vulkan resources are initialized and ready when this function is + invoked. The current framebuffer and main command buffer can be retrieved + via QVulkanWindow::currentFramebuffer() and + QVulkanWindow::currentCommandBuffer(). The logical device and the active + graphics queue are available via QVulkanWindow::device() and + QVulkanWindow::graphicsQueue(). Implementations can create additional + command buffers from the pool returned by + QVulkanWindow::graphicsCommandPool(). For convenience, the index of the + best performing host visible memory type index is exposed via + QVulkanWindow::hostVisibleMemoryIndex(). All these accessors are safe to + invoke from any thread. + + \sa QVulkanWindow::frameReady(), QVulkanWindow + */ + +/*! + This virtual function is called when the physical device is lost, meaning + the creation of the logical device fails with \c{VK_ERROR_DEVICE_LOST}. + + The default implementation is empty. + + There is typically no need to perform anything special in this function + because QVulkanWindow will automatically retry to initialize itself after a + certain amount of time. + + \sa logicalDeviceLost() + */ +void QVulkanWindowRenderer::physicalDeviceLost() +{ +} + +/*! + This virtual function is called when the logical device (VkDevice) is lost, + meaning some operation failed with \c{VK_ERROR_DEVICE_LOST}. + + The default implementation is empty. + + There is typically no need to perform anything special in this function. + QVulkanWindow will automatically release all resources (invoking + releaseSwapChainResources() and releaseResources() as necessary) and will + attempt to reinitialize, acquiring a new device. When the physical device + was also lost, this reinitialization attempt may then result in + physicalDeviceLost(). + + \sa physicalDeviceLost() + */ +void QVulkanWindowRenderer::logicalDeviceLost() +{ +} + +void QVulkanWindowPrivate::beginFrame() +{ + if (!swapChain || framePending) + return; + + Q_Q(QVulkanWindow); + if (q->size() * q->devicePixelRatio() != swapChainImageSize) { + recreateSwapChain(); + if (!swapChain) + return; + } + + FrameResources &frame(frameRes[currentFrame]); + + if (!frame.imageAcquired) { + // Wait if we are too far ahead, i.e. the thread gets throttled based on the presentation rate + // (note that we are using FIFO mode -> vsync) + if (frame.fenceWaitable) { + devFuncs->vkWaitForFences(dev, 1, &frame.fence, VK_TRUE, UINT64_MAX); + devFuncs->vkResetFences(dev, 1, &frame.fence); + frame.fenceWaitable = false; + } + + // move on to next swapchain image + VkResult err = vkAcquireNextImageKHR(dev, swapChain, UINT64_MAX, + frame.imageSem, frame.fence, ¤tImage); + if (err == VK_SUCCESS || err == VK_SUBOPTIMAL_KHR) { + frame.imageSemWaitable = true; + frame.imageAcquired = true; + frame.fenceWaitable = true; + } else if (err == VK_ERROR_OUT_OF_DATE_KHR) { + recreateSwapChain(); + q->requestUpdate(); + return; + } else { + if (!checkDeviceLost(err)) + qWarning("QVulkanWindow: Failed to acquire next swapchain image: %d", err); + q->requestUpdate(); + return; + } + } + + // make sure the previous draw for the same image has finished + ImageResources &image(imageRes[currentImage]); + if (image.cmdFenceWaitable) { + devFuncs->vkWaitForFences(dev, 1, &image.cmdFence, VK_TRUE, UINT64_MAX); + devFuncs->vkResetFences(dev, 1, &image.cmdFence); + image.cmdFenceWaitable = false; + } + + // build new draw command buffer + if (image.cmdBuf) { + devFuncs->vkFreeCommandBuffers(dev, cmdPool, 1, &image.cmdBuf); + image.cmdBuf = 0; + } + + VkCommandBufferAllocateInfo cmdBufInfo = { + VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, nullptr, cmdPool, VK_COMMAND_BUFFER_LEVEL_PRIMARY, 1 }; + VkResult err = devFuncs->vkAllocateCommandBuffers(dev, &cmdBufInfo, &image.cmdBuf); + if (err != VK_SUCCESS) { + if (!checkDeviceLost(err)) + qWarning("QVulkanWindow: Failed to allocate frame command buffer: %d", err); + return; + } + + VkCommandBufferBeginInfo cmdBufBeginInfo = { + VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, nullptr, 0, nullptr }; + err = devFuncs->vkBeginCommandBuffer(image.cmdBuf, &cmdBufBeginInfo); + if (err != VK_SUCCESS) { + if (!checkDeviceLost(err)) + qWarning("QVulkanWindow: Failed to begin frame command buffer: %d", err); + return; + } + + if (frameGrabbing) + frameGrabTargetImage = QImage(swapChainImageSize, QImage::Format_RGBA8888); + + if (renderer) { + framePending = true; + renderer->startNextFrame(); + // done for now - endFrame() will get invoked when frameReady() is called back + } else { + VkClearColorValue clearColor = { 0.0f, 0.0f, 0.0f, 1.0f }; + VkClearDepthStencilValue clearDS = { 1.0f, 0 }; + VkClearValue clearValues[3]; + memset(clearValues, 0, sizeof(clearValues)); + clearValues[0].color = clearValues[2].color = clearColor; + clearValues[1].depthStencil = clearDS; + + VkRenderPassBeginInfo rpBeginInfo; + memset(&rpBeginInfo, 0, sizeof(rpBeginInfo)); + rpBeginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; + rpBeginInfo.renderPass = defaultRenderPass; + rpBeginInfo.framebuffer = image.fb; + rpBeginInfo.renderArea.extent.width = swapChainImageSize.width(); + rpBeginInfo.renderArea.extent.height = swapChainImageSize.height(); + rpBeginInfo.clearValueCount = sampleCount > VK_SAMPLE_COUNT_1_BIT ? 3 : 2; + rpBeginInfo.pClearValues = clearValues; + devFuncs->vkCmdBeginRenderPass(image.cmdBuf, &rpBeginInfo, VK_SUBPASS_CONTENTS_INLINE); + devFuncs->vkCmdEndRenderPass(image.cmdBuf); + + endFrame(); + } +} + +void QVulkanWindowPrivate::endFrame() +{ + Q_Q(QVulkanWindow); + + FrameResources &frame(frameRes[currentFrame]); + ImageResources &image(imageRes[currentImage]); + + if (gfxQueueFamilyIdx != presQueueFamilyIdx && !frameGrabbing) { + // Add the swapchain image release to the command buffer that will be + // submitted to the graphics queue. + VkImageMemoryBarrier presTrans; + memset(&presTrans, 0, sizeof(presTrans)); + presTrans.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + presTrans.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + presTrans.oldLayout = presTrans.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; + presTrans.srcQueueFamilyIndex = gfxQueueFamilyIdx; + presTrans.dstQueueFamilyIndex = presQueueFamilyIdx; + presTrans.image = image.image; + presTrans.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + presTrans.subresourceRange.levelCount = presTrans.subresourceRange.layerCount = 1; + devFuncs->vkCmdPipelineBarrier(image.cmdBuf, + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, + 0, 0, nullptr, 0, nullptr, + 1, &presTrans); + } + + // When grabbing a frame, add a readback at the end and skip presenting. + if (frameGrabbing) + addReadback(); + + VkResult err = devFuncs->vkEndCommandBuffer(image.cmdBuf); + if (err != VK_SUCCESS) { + if (!checkDeviceLost(err)) + qWarning("QVulkanWindow: Failed to end frame command buffer: %d", err); + return; + } + + // submit draw calls + VkSubmitInfo submitInfo; + memset(&submitInfo, 0, sizeof(submitInfo)); + submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + submitInfo.commandBufferCount = 1; + submitInfo.pCommandBuffers = &image.cmdBuf; + if (frame.imageSemWaitable) { + submitInfo.waitSemaphoreCount = 1; + submitInfo.pWaitSemaphores = &frame.imageSem; + } + if (!frameGrabbing) { + submitInfo.signalSemaphoreCount = 1; + submitInfo.pSignalSemaphores = &frame.drawSem; + } + VkPipelineStageFlags psf = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + submitInfo.pWaitDstStageMask = &psf; + + Q_ASSERT(!image.cmdFenceWaitable); + + err = devFuncs->vkQueueSubmit(gfxQueue, 1, &submitInfo, image.cmdFence); + if (err == VK_SUCCESS) { + frame.imageSemWaitable = false; + image.cmdFenceWaitable = true; + } else { + if (!checkDeviceLost(err)) + qWarning("QVulkanWindow: Failed to submit to graphics queue: %d", err); + return; + } + + // block and then bail out when grabbing + if (frameGrabbing) { + finishBlockingReadback(); + frameGrabbing = false; + // Leave frame.imageAcquired set to true. + // Do not change currentFrame. + emit q->frameGrabbed(frameGrabTargetImage); + return; + } + + if (gfxQueueFamilyIdx != presQueueFamilyIdx) { + // Submit the swapchain image acquire to the present queue. + submitInfo.pWaitSemaphores = &frame.drawSem; + submitInfo.pSignalSemaphores = &frame.presTransSem; + submitInfo.pCommandBuffers = &image.presTransCmdBuf; // must be USAGE_SIMULTANEOUS + err = devFuncs->vkQueueSubmit(presQueue, 1, &submitInfo, VK_NULL_HANDLE); + if (err != VK_SUCCESS) { + if (!checkDeviceLost(err)) + qWarning("QVulkanWindow: Failed to submit to present queue: %d", err); + return; + } + } + + // queue present + VkPresentInfoKHR presInfo; + memset(&presInfo, 0, sizeof(presInfo)); + presInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; + presInfo.swapchainCount = 1; + presInfo.pSwapchains = &swapChain; + presInfo.pImageIndices = ¤tImage; + presInfo.waitSemaphoreCount = 1; + presInfo.pWaitSemaphores = gfxQueueFamilyIdx == presQueueFamilyIdx ? &frame.drawSem : &frame.presTransSem; + + err = vkQueuePresentKHR(gfxQueue, &presInfo); + if (err != VK_SUCCESS) { + if (err == VK_ERROR_OUT_OF_DATE_KHR) { + recreateSwapChain(); + q->requestUpdate(); + return; + } else if (err != VK_SUBOPTIMAL_KHR) { + if (!checkDeviceLost(err)) + qWarning("QVulkanWindow: Failed to present: %d", err); + return; + } + } + + frame.imageAcquired = false; + + inst->presentQueued(q); + + currentFrame = (currentFrame + 1) % frameLag; +} + +/*! + This function must be called exactly once in response to each invocation of + the QVulkanWindowRenderer::startNextFrame() implementation. At the time of + this call, the main command buffer, exposed via currentCommandBuffer(), + must have all necessary rendering commands added to it since this function + will trigger submitting the commands and queuing the present command. + + \note This function must only be called from the gui/main thread, which is + where QVulkanWindowRenderer's functions are invoked and where the + QVulkanWindow instance lives. + + \sa QVulkanWindowRenderer::startNextFrame() + */ +void QVulkanWindow::frameReady() +{ + Q_ASSERT_X(QThread::currentThread() == QCoreApplication::instance()->thread(), + "QVulkanWindow", "frameReady() can only be called from the GUI (main) thread"); + + Q_D(QVulkanWindow); + + if (!d->framePending) { + qWarning("QVulkanWindow: frameReady() called without a corresponding startNextFrame()"); + return; + } + + d->framePending = false; + + d->endFrame(); +} + +bool QVulkanWindowPrivate::checkDeviceLost(VkResult err) +{ + if (err == VK_ERROR_DEVICE_LOST) { + qWarning("QVulkanWindow: Device lost"); + if (renderer) + renderer->logicalDeviceLost(); + qCDebug(lcVk, "Releasing all resources due to device lost"); + releaseSwapChain(); + reset(); + qCDebug(lcVk, "Restarting"); + ensureStarted(); + return true; + } + return false; +} + +void QVulkanWindowPrivate::addReadback() +{ + VkImageCreateInfo imageInfo; + memset(&imageInfo, 0, sizeof(imageInfo)); + imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + imageInfo.imageType = VK_IMAGE_TYPE_2D; + imageInfo.format = VK_FORMAT_R8G8B8A8_UNORM; + imageInfo.extent.width = frameGrabTargetImage.width(); + imageInfo.extent.height = frameGrabTargetImage.height(); + imageInfo.extent.depth = 1; + imageInfo.mipLevels = 1; + imageInfo.arrayLayers = 1; + imageInfo.samples = VK_SAMPLE_COUNT_1_BIT; + imageInfo.tiling = VK_IMAGE_TILING_LINEAR; + imageInfo.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT; + imageInfo.initialLayout = VK_IMAGE_LAYOUT_PREINITIALIZED; + + VkResult err = devFuncs->vkCreateImage(dev, &imageInfo, nullptr, &frameGrabImage); + if (err != VK_SUCCESS) { + qWarning("QVulkanWindow: Failed to create image for readback: %d", err); + return; + } + + VkMemoryRequirements memReq; + devFuncs->vkGetImageMemoryRequirements(dev, frameGrabImage, &memReq); + + VkMemoryAllocateInfo allocInfo = { + VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, + nullptr, + memReq.size, + hostVisibleMemIndex + }; + + err = devFuncs->vkAllocateMemory(dev, &allocInfo, nullptr, &frameGrabImageMem); + if (err != VK_SUCCESS) { + qWarning("QVulkanWindow: Failed to allocate memory for readback image: %d", err); + return; + } + + err = devFuncs->vkBindImageMemory(dev, frameGrabImage, frameGrabImageMem, 0); + if (err != VK_SUCCESS) { + qWarning("QVulkanWindow: Failed to bind readback image memory: %d", err); + return; + } + + ImageResources &image(imageRes[currentImage]); + + VkImageMemoryBarrier barrier; + memset(&barrier, 0, sizeof(barrier)); + barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + barrier.subresourceRange.levelCount = barrier.subresourceRange.layerCount = 1; + + barrier.oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; + barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; + barrier.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT; + barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; + barrier.image = image.image; + + devFuncs->vkCmdPipelineBarrier(image.cmdBuf, + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, + 0, 0, nullptr, 0, nullptr, + 1, &barrier); + + barrier.oldLayout = VK_IMAGE_LAYOUT_PREINITIALIZED; + barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + barrier.srcAccessMask = 0; + barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + barrier.image = frameGrabImage; + + devFuncs->vkCmdPipelineBarrier(image.cmdBuf, + VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, + 0, 0, nullptr, 0, nullptr, + 1, &barrier); + + VkImageCopy copyInfo; + memset(©Info, 0, sizeof(copyInfo)); + copyInfo.srcSubresource.aspectMask = copyInfo.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + copyInfo.srcSubresource.layerCount = copyInfo.dstSubresource.layerCount = 1; + copyInfo.extent.width = frameGrabTargetImage.width(); + copyInfo.extent.height = frameGrabTargetImage.height(); + copyInfo.extent.depth = 1; + + devFuncs->vkCmdCopyImage(image.cmdBuf, image.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + frameGrabImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©Info); + + barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + barrier.newLayout = VK_IMAGE_LAYOUT_GENERAL; + barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + barrier.dstAccessMask = VK_ACCESS_HOST_READ_BIT; + barrier.image = frameGrabImage; + + devFuncs->vkCmdPipelineBarrier(image.cmdBuf, + VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, + 0, 0, nullptr, 0, nullptr, + 1, &barrier); +} + +void QVulkanWindowPrivate::finishBlockingReadback() +{ + ImageResources &image(imageRes[currentImage]); + + // Block until the current frame is done. Normally this wait would only be + // done in current + concurrentFrameCount(). + devFuncs->vkWaitForFences(dev, 1, &image.cmdFence, VK_TRUE, UINT64_MAX); + devFuncs->vkResetFences(dev, 1, &image.cmdFence); + // will reuse the same image for the next "real" frame, do not wait then + image.cmdFenceWaitable = false; + + VkImageSubresource subres = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0 }; + VkSubresourceLayout layout; + devFuncs->vkGetImageSubresourceLayout(dev, frameGrabImage, &subres, &layout); + + uchar *p; + VkResult err = devFuncs->vkMapMemory(dev, frameGrabImageMem, layout.offset, layout.size, 0, reinterpret_cast(&p)); + if (err != VK_SUCCESS) { + qWarning("QVulkanWindow: Failed to map readback image memory after transfer: %d", err); + return; + } + + for (int y = 0; y < frameGrabTargetImage.height(); ++y) { + memcpy(frameGrabTargetImage.scanLine(y), p, frameGrabTargetImage.width() * 4); + p += layout.rowPitch; + } + + devFuncs->vkUnmapMemory(dev, frameGrabImageMem); + + devFuncs->vkDestroyImage(dev, frameGrabImage, nullptr); + frameGrabImage = VK_NULL_HANDLE; + devFuncs->vkFreeMemory(dev, frameGrabImageMem, nullptr); + frameGrabImageMem = VK_NULL_HANDLE; +} + +/*! + \return the active physical device. + + \note Calling this function is only valid from the invocation of + QVulkanWindowRenderer::preInitResources() up until + QVulkanWindowRenderer::releaseResources(). + */ +VkPhysicalDevice QVulkanWindow::physicalDevice() const +{ + Q_D(const QVulkanWindow); + if (d->physDevIndex < d->physDevs.count()) + return d->physDevs[d->physDevIndex]; + qWarning("QVulkanWindow: Physical device not available"); + return VK_NULL_HANDLE; +} + +/*! + \return a pointer to the properties for the active physical device. + + \note Calling this function is only valid from the invocation of + QVulkanWindowRenderer::preInitResources() up until + QVulkanWindowRenderer::releaseResources(). + */ +const VkPhysicalDeviceProperties *QVulkanWindow::physicalDeviceProperties() const +{ + Q_D(const QVulkanWindow); + if (d->physDevIndex < d->physDevProps.count()) + return &d->physDevProps[d->physDevIndex]; + qWarning("QVulkanWindow: Physical device properties not available"); + return nullptr; +} + +/*! + \return the active logical device. + + \note Calling this function is only valid from the invocation of + QVulkanWindowRenderer::initResources() up until + QVulkanWindowRenderer::releaseResources(). + */ +VkDevice QVulkanWindow::device() const +{ + Q_D(const QVulkanWindow); + return d->dev; +} + +/*! + \return the active graphics queue. + + \note Calling this function is only valid from the invocation of + QVulkanWindowRenderer::initResources() up until + QVulkanWindowRenderer::releaseResources(). + */ +VkQueue QVulkanWindow::graphicsQueue() const +{ + Q_D(const QVulkanWindow); + return d->gfxQueue; +} + +/*! + \return the active graphics command pool. + + \note Calling this function is only valid from the invocation of + QVulkanWindowRenderer::initResources() up until + QVulkanWindowRenderer::releaseResources(). + */ +VkCommandPool QVulkanWindow::graphicsCommandPool() const +{ + Q_D(const QVulkanWindow); + return d->cmdPool; +} + +/*! + \return a host visible memory type index suitable for general use. + + The returned memory type will be both host visible and coherent. In + addition, it will also be cached, if possible. + + \note Calling this function is only valid from the invocation of + QVulkanWindowRenderer::initResources() up until + QVulkanWindowRenderer::releaseResources(). + */ +uint32_t QVulkanWindow::hostVisibleMemoryIndex() const +{ + Q_D(const QVulkanWindow); + return d->hostVisibleMemIndex; +} + +/*! + \return a device local memory type index suitable for general use. + + \note Calling this function is only valid from the invocation of + QVulkanWindowRenderer::initResources() up until + QVulkanWindowRenderer::releaseResources(). + */ +uint32_t QVulkanWindow::deviceLocalMemoryIndex() const +{ + Q_D(const QVulkanWindow); + return d->deviceLocalMemIndex; +} + +/*! + \return a typical render pass with one sub-pass. + + \note Applications are not required to use this render pass. However, they + are then responsible for ensuring the current swap chain and depth-stencil + images get transitioned from \c{VK_IMAGE_LAYOUT_UNDEFINED} to + \c{VK_IMAGE_LAYOUT_PRESENT_SRC_KHR} and + \c{VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL} either via the + application's custom render pass or by other means. + + \note Stencil read/write is not enabled in this render pass. + + \note Calling this function is only valid from the invocation of + QVulkanWindowRenderer::initResources() up until + QVulkanWindowRenderer::releaseResources(). + + \sa currentFramebuffer() + */ +VkRenderPass QVulkanWindow::defaultRenderPass() const +{ + Q_D(const QVulkanWindow); + return d->defaultRenderPass; +} + +/*! + \return the color buffer format used by the swapchain. + + \note Calling this function is only valid from the invocation of + QVulkanWindowRenderer::initResources() up until + QVulkanWindowRenderer::releaseResources(). + + \sa setPreferredColorFormats() + */ +VkFormat QVulkanWindow::colorFormat() const +{ + Q_D(const QVulkanWindow); + return d->colorFormat; +} + +/*! + \return the format used by the depth-stencil buffer(s). + + \note Calling this function is only valid from the invocation of + QVulkanWindowRenderer::initResources() up until + QVulkanWindowRenderer::releaseResources(). + */ +VkFormat QVulkanWindow::depthStencilFormat() const +{ + Q_D(const QVulkanWindow); + return d->dsFormat; +} + +/*! + \return the image size of the swapchain. + + This usually matches the size of the window, but may also differ in case + \c vkGetPhysicalDeviceSurfaceCapabilitiesKHR reports a fixed size. + + \note Calling this function is only valid from the invocation of + QVulkanWindowRenderer::initSwapChainResources() up until + QVulkanWindowRenderer::releaseSwapChainResources(). + */ +QSize QVulkanWindow::swapChainImageSize() const +{ + Q_D(const QVulkanWindow); + return d->swapChainImageSize; +} + +/*! + \return The active command buffer for the current swap chain image. + Implementations of QVulkanWindowRenderer::startNextFrame() are expected to + add commands to this command buffer. + + \note This function must only be called from within startNextFrame() and, in + case of asynchronous command generation, up until the call to frameReady(). + */ +VkCommandBuffer QVulkanWindow::currentCommandBuffer() const +{ + Q_D(const QVulkanWindow); + if (!d->framePending) { + qWarning("QVulkanWindow: Attempted to call currentCommandBuffer() without an active frame"); + return VK_NULL_HANDLE; + } + return d->imageRes[d->currentImage].cmdBuf; +} + +/*! + \return a VkFramebuffer for the current swapchain image using the default + render pass. + + The framebuffer has two attachments (color, depth-stencil) when + multisampling is not in use, and three (color resolve, depth-stencil, + multisample color) when sampleCountFlagBits() is greater than + \c{VK_SAMPLE_COUNT_1_BIT}. Renderers must take this into account, for + example when providing clear values. + + \note Applications are not required to use this framebuffer in case they + provide their own render pass instead of using the one returned from + defaultRenderPass(). + + \note This function must only be called from within startNextFrame() and, in + case of asynchronous command generation, up until the call to frameReady(). + + \sa defaultRenderPass() + */ +VkFramebuffer QVulkanWindow::currentFramebuffer() const +{ + Q_D(const QVulkanWindow); + if (!d->framePending) { + qWarning("QVulkanWindow: Attempted to call currentFramebuffer() without an active frame"); + return VK_NULL_HANDLE; + } + return d->imageRes[d->currentImage].fb; +} + +/*! + \return the current frame index in the range [0, concurrentFrameCount() - 1]. + + Renderer implementations will have to ensure that uniform data and other + dynamic resources exist in multiple copies, in order to prevent frame N + altering the data used by the still-active frames N - 1, N - 2, ... N - + concurrentFrameCount() + 1. + + To avoid relying on dynamic array sizes, applications can use + MAX_CONCURRENT_FRAME_COUNT when declaring arrays. This is guaranteed to be + always equal to or greater than the value returned from + concurrentFrameCount(). Such arrays can then be indexed by the value + returned from this function. + + \code + class Renderer { + ... + VkDescriptorBufferInfo m_uniformBufInfo[QVulkanWindow::MAX_CONCURRENT_FRAME_COUNT]; + }; + + void Renderer::startNextFrame() + { + VkDescriptorBufferInfo &uniformBufInfo(m_uniformBufInfo[m_window->currentFrame()]); + ... + } + \endcode + + \note This function must only be called from within startNextFrame() and, in + case of asynchronous command generation, up until the call to frameReady(). + + \sa concurrentFrameCount() + */ +int QVulkanWindow::currentFrame() const +{ + Q_D(const QVulkanWindow); + if (!d->framePending) + qWarning("QVulkanWindow: Attempted to call currentFrame() without an active frame"); + return d->currentFrame; +} + +/*! + \variable QVulkanWindow::MAX_CONCURRENT_FRAME_COUNT + + \brief A constant value that is always equal to or greater than the maximum value + of concurrentFrameCount(). + */ + +/*! + \return the number of frames that can be potentially active at the same time. + + \note The value is constant for the entire lifetime of the QVulkanWindow. + + \code + class Renderer { + ... + VkDescriptorBufferInfo m_uniformBufInfo[QVulkanWindow::MAX_CONCURRENT_FRAME_COUNT]; + }; + + void Renderer::startNextFrame() + { + const int count = m_window->concurrentFrameCount(); + for (int i = 0; i < count; ++i) + m_uniformBufInfo[i] = ... + ... + } + \endcode + + \sa currentFrame() + */ +int QVulkanWindow::concurrentFrameCount() const +{ + Q_D(const QVulkanWindow); + return d->frameLag; +} + +/*! + \return the number of images in the swap chain. + + \note Accessing this is necessary when providing a custom render pass and + framebuffer. The framebuffer is specific to the current swapchain image and + hence the application must provide multiple framebuffers. + + \note Calling this function is only valid from the invocation of + QVulkanWindowRenderer::initSwapChainResources() up until + QVulkanWindowRenderer::releaseSwapChainResources(). + */ +int QVulkanWindow::swapChainImageCount() const +{ + Q_D(const QVulkanWindow); + return d->swapChainBufferCount; +} + +/*! + \return the current swap chain image index in the range [0, swapChainImageCount() - 1]. + + \note This function must only be called from within startNextFrame() and, in + case of asynchronous command generation, up until the call to frameReady(). + */ +int QVulkanWindow::currentSwapChainImageIndex() const +{ + Q_D(const QVulkanWindow); + if (!d->framePending) + qWarning("QVulkanWindow: Attempted to call currentSwapChainImageIndex() without an active frame"); + return d->currentImage; +} + +/*! + \return the specified swap chain image. + + \a idx must be in the range [0, swapChainImageCount() - 1]. + + \note Calling this function is only valid from the invocation of + QVulkanWindowRenderer::initSwapChainResources() up until + QVulkanWindowRenderer::releaseSwapChainResources(). + */ +VkImage QVulkanWindow::swapChainImage(int idx) const +{ + Q_D(const QVulkanWindow); + return idx >= 0 && idx < d->swapChainBufferCount ? d->imageRes[idx].image : VK_NULL_HANDLE; +} + +/*! + \return the specified swap chain image view. + + \a idx must be in the range [0, swapChainImageCount() - 1]. + + \note Calling this function is only valid from the invocation of + QVulkanWindowRenderer::initSwapChainResources() up until + QVulkanWindowRenderer::releaseSwapChainResources(). + */ +VkImageView QVulkanWindow::swapChainImageView(int idx) const +{ + Q_D(const QVulkanWindow); + return idx >= 0 && idx < d->swapChainBufferCount ? d->imageRes[idx].imageView : VK_NULL_HANDLE; +} + +/*! + \return the depth-stencil image. + + \note Calling this function is only valid from the invocation of + QVulkanWindowRenderer::initSwapChainResources() up until + QVulkanWindowRenderer::releaseSwapChainResources(). + */ +VkImage QVulkanWindow::depthStencilImage() const +{ + Q_D(const QVulkanWindow); + return d->dsImage; +} + +/*! + \return the depth-stencil image view. + + \note Calling this function is only valid from the invocation of + QVulkanWindowRenderer::initSwapChainResources() up until + QVulkanWindowRenderer::releaseSwapChainResources(). + */ +VkImageView QVulkanWindow::depthStencilImageView() const +{ + Q_D(const QVulkanWindow); + return d->dsView; +} + +/*! + \return the current sample count as a \c VkSampleCountFlagBits value. + + When targeting the default render target, the \c rasterizationSamples field + of \c VkPipelineMultisampleStateCreateInfo must be set to this value. + + \sa setSampleCount(), supportedSampleCounts() + */ +VkSampleCountFlagBits QVulkanWindow::sampleCountFlagBits() const +{ + Q_D(const QVulkanWindow); + return d->sampleCount; +} + +/*! + \return the specified multisample color image, or \c{VK_NULL_HANDLE} if + multisampling is not in use. + + \a idx must be in the range [0, swapChainImageCount() - 1]. + + \note Calling this function is only valid from the invocation of + QVulkanWindowRenderer::initSwapChainResources() up until + QVulkanWindowRenderer::releaseSwapChainResources(). + */ +VkImage QVulkanWindow::msaaColorImage(int idx) const +{ + Q_D(const QVulkanWindow); + return idx >= 0 && idx < d->swapChainBufferCount ? d->imageRes[idx].msaaImage : VK_NULL_HANDLE; +} + +/*! + \return the specified multisample color image view, or \c{VK_NULL_HANDLE} if + multisampling is not in use. + + \a idx must be in the range [0, swapChainImageCount() - 1]. + + \note Calling this function is only valid from the invocation of + QVulkanWindowRenderer::initSwapChainResources() up until + QVulkanWindowRenderer::releaseSwapChainResources(). + */ +VkImageView QVulkanWindow::msaaColorImageView(int idx) const +{ + Q_D(const QVulkanWindow); + return idx >= 0 && idx < d->swapChainBufferCount ? d->imageRes[idx].msaaImageView : VK_NULL_HANDLE; +} + +/*! + \return true if the swapchain supports usage as transfer source, meaning + grab() is functional. + + \note Calling this function is only valid from the invocation of + QVulkanWindowRenderer::initSwapChainResources() up until + QVulkanWindowRenderer::releaseSwapChainResources(). + */ +bool QVulkanWindow::supportsGrab() const +{ + Q_D(const QVulkanWindow); + return d->swapChainSupportsReadBack; +} + +/*! + Builds and renders the next frame without presenting it, then performs a + blocking readback of the image content. + + \return the image if the renderer's + \l{QVulkanWindowRenderer::startNextFrame()}{startNextFrame()} + implementation calls back frameReady() directly. Otherwise, returns an + incomplete image, that has the correct size but not the content yet. The + content will be delivered via the frameGrabbed() signal in the latter case. + + \note This function should not be called when a frame is in progress + (that is, frameReady() has not yet been called back by the application). + + \note This function is potentially expensive due to the additional, + blocking readback. + + \note This function currently requires that the swapchain supports usage as + a transfer source (\c{VK_IMAGE_USAGE_TRANSFER_SRC_BIT}), and will fail otherwise. + */ +QImage QVulkanWindow::grab() +{ + Q_D(QVulkanWindow); + if (!d->swapChain) { + qWarning("QVulkanWindow: Attempted to call grab() without a swapchain"); + return QImage(); + } + if (d->framePending) { + qWarning("QVulkanWindow: Attempted to call grab() while a frame is still pending"); + return QImage(); + } + if (!d->swapChainSupportsReadBack) { + qWarning("QVulkanWindow: Attempted to call grab() with a swapchain that does not support usage as transfer source"); + return QImage(); + } + + d->frameGrabbing = true; + d->beginFrame(); + + return d->frameGrabTargetImage; +} + +/*! + \return a pointer to a QMatrix4x4 that can be used to correct for coordinate + system differences between OpenGl and Vulkan. + + By pre-multiplying the projection matrix with this matrix, applications can + continue to assume OpenGL-style Y coordinates in clip space (i.e. Y pointing + upwards), and can set minDepth and maxDepth to 0 and 1, respectively, + without any further corrections to the vertex Z positions, while using the + projection matrices retrieved from the QMatrix4x4 functions, such as + QMatrix4x4::perspective(), as-is. + */ +const QMatrix4x4 *QVulkanWindow::clipCorrectionMatrix() +{ + Q_D(QVulkanWindow); + if (d->m_clipCorrect.isIdentity()) { + // NB the ctor takes row-major + d->m_clipCorrect = QMatrix4x4(1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, -1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 0.5f, 0.5f, + 0.0f, 0.0f, 0.0f, 1.0f); + } + return &d->m_clipCorrect; +} + +QT_END_NAMESPACE diff --git a/src/gui/vulkan/qvulkanwindow.h b/src/gui/vulkan/qvulkanwindow.h new file mode 100644 index 0000000000..854da81b05 --- /dev/null +++ b/src/gui/vulkan/qvulkanwindow.h @@ -0,0 +1,161 @@ +/**************************************************************************** +** +** Copyright (C) 2017 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QVULKANWINDOW_H +#define QVULKANWINDOW_H + +#include + +#if QT_CONFIG(vulkan) + +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +class QVulkanWindowPrivate; + +class Q_GUI_EXPORT QVulkanWindowRenderer +{ +public: + virtual ~QVulkanWindowRenderer(); + + virtual void preInitResources(); + virtual void initResources(); + virtual void initSwapChainResources(); + virtual void releaseSwapChainResources(); + virtual void releaseResources(); + + virtual void startNextFrame() = 0; + + virtual void physicalDeviceLost(); + virtual void logicalDeviceLost(); +}; + +class Q_GUI_EXPORT QVulkanWindow : public QWindow +{ + Q_OBJECT + Q_DECLARE_PRIVATE(QVulkanWindow) + +public: + enum Flag { + PersistentResources = 0x01 + }; + Q_DECLARE_FLAGS(Flags, Flag) + + explicit QVulkanWindow(QWindow *parent = nullptr); + ~QVulkanWindow(); + + void setFlags(Flags flags); + Flags flags() const; + + QVector availablePhysicalDevices(); + void setPhysicalDeviceIndex(int idx); + + QVulkanInfoVector supportedDeviceExtensions(); + void setDeviceExtensions(const QByteArrayList &extensions); + + void setPreferredColorFormats(const QVector &formats); + + QSet supportedSampleCounts(); + void setSampleCount(int sampleCount); + + bool isValid() const; + + virtual QVulkanWindowRenderer *createRenderer(); + void frameReady(); + + VkPhysicalDevice physicalDevice() const; + const VkPhysicalDeviceProperties *physicalDeviceProperties() const; + VkDevice device() const; + VkQueue graphicsQueue() const; + VkCommandPool graphicsCommandPool() const; + uint32_t hostVisibleMemoryIndex() const; + uint32_t deviceLocalMemoryIndex() const; + VkRenderPass defaultRenderPass() const; + + VkFormat colorFormat() const; + VkFormat depthStencilFormat() const; + QSize swapChainImageSize() const; + + VkCommandBuffer currentCommandBuffer() const; + VkFramebuffer currentFramebuffer() const; + int currentFrame() const; + + static const int MAX_CONCURRENT_FRAME_COUNT = 3; + int concurrentFrameCount() const; + + int swapChainImageCount() const; + int currentSwapChainImageIndex() const; + VkImage swapChainImage(int idx) const; + VkImageView swapChainImageView(int idx) const; + VkImage depthStencilImage() const; + VkImageView depthStencilImageView() const; + + VkSampleCountFlagBits sampleCountFlagBits() const; + VkImage msaaColorImage(int idx) const; + VkImageView msaaColorImageView(int idx) const; + + bool supportsGrab() const; + QImage grab(); + + const QMatrix4x4 *clipCorrectionMatrix(); + +Q_SIGNALS: + void frameGrabbed(const QImage &image); + +protected: + void exposeEvent(QExposeEvent *) override; + void resizeEvent(QResizeEvent *) override; + bool event(QEvent *) override; + +private: + Q_DISABLE_COPY(QVulkanWindow) +}; + +Q_DECLARE_OPERATORS_FOR_FLAGS(QVulkanWindow::Flags) + +QT_END_NAMESPACE + +#endif // QT_CONFIG(vulkan) + +#endif diff --git a/src/gui/vulkan/qvulkanwindow_p.h b/src/gui/vulkan/qvulkanwindow_p.h new file mode 100644 index 0000000000..9d2f13c87e --- /dev/null +++ b/src/gui/vulkan/qvulkanwindow_p.h @@ -0,0 +1,188 @@ +/**************************************************************************** +** +** Copyright (C) 2017 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QVULKANWINDOW_P_H +#define QVULKANWINDOW_P_H + +#include + +#if QT_CONFIG(vulkan) + +#include "qvulkanwindow.h" +#include +#include + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of a number of Qt sources files. This header file may change from +// version to version without notice, or even be removed. +// +// We mean it. +// + +QT_BEGIN_NAMESPACE + +class QVulkanWindowPrivate : public QWindowPrivate +{ + Q_DECLARE_PUBLIC(QVulkanWindow) + +public: + ~QVulkanWindowPrivate(); + + void ensureStarted(); + void init(); + void reset(); + bool createDefaultRenderPass(); + void recreateSwapChain(); + uint32_t chooseTransientImageMemType(VkImage img, uint32_t startIndex); + bool createTransientImage(VkFormat format, VkImageUsageFlags usage, VkImageAspectFlags aspectMask, + VkImage *images, VkDeviceMemory *mem, VkImageView *views, int count); + void releaseSwapChain(); + void beginFrame(); + void endFrame(); + bool checkDeviceLost(VkResult err); + void addReadback(); + void finishBlockingReadback(); + + enum Status { + StatusUninitialized, + StatusFail, + StatusFailRetry, + StatusDeviceReady, + StatusReady + }; + Status status = StatusUninitialized; + QVulkanWindowRenderer *renderer = nullptr; + QVulkanInstance *inst = nullptr; + VkSurfaceKHR surface = VK_NULL_HANDLE; + int physDevIndex = 0; + QVector physDevs; + QVector physDevProps; + QVulkanWindow::Flags flags = 0; + QByteArrayList requestedDevExtensions; + QHash > supportedDevExtensions; + QVector requestedColorFormats; + VkSampleCountFlagBits sampleCount = VK_SAMPLE_COUNT_1_BIT; + + VkDevice dev = VK_NULL_HANDLE; + QVulkanDeviceFunctions *devFuncs; + uint32_t gfxQueueFamilyIdx; + uint32_t presQueueFamilyIdx; + VkQueue gfxQueue; + VkQueue presQueue; + VkCommandPool cmdPool = VK_NULL_HANDLE; + VkCommandPool presCmdPool = VK_NULL_HANDLE; + uint32_t hostVisibleMemIndex; + uint32_t deviceLocalMemIndex; + VkFormat colorFormat; + VkColorSpaceKHR colorSpace; + VkFormat dsFormat = VK_FORMAT_D24_UNORM_S8_UINT; + + PFN_vkCreateSwapchainKHR vkCreateSwapchainKHR = nullptr; + PFN_vkDestroySwapchainKHR vkDestroySwapchainKHR; + PFN_vkGetSwapchainImagesKHR vkGetSwapchainImagesKHR; + PFN_vkAcquireNextImageKHR vkAcquireNextImageKHR; + PFN_vkQueuePresentKHR vkQueuePresentKHR; + PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR vkGetPhysicalDeviceSurfaceCapabilitiesKHR = nullptr; + PFN_vkGetPhysicalDeviceSurfaceFormatsKHR vkGetPhysicalDeviceSurfaceFormatsKHR; + + static const int MAX_SWAPCHAIN_BUFFER_COUNT = 3; + static const int MAX_FRAME_LAG = QVulkanWindow::MAX_CONCURRENT_FRAME_COUNT; + // QVulkanWindow only supports the always available FIFO mode. The + // rendering thread will get throttled to the presentation rate (vsync). + // This is in effect Example 5 from the VK_KHR_swapchain spec. + VkPresentModeKHR presentMode = VK_PRESENT_MODE_FIFO_KHR; + int swapChainBufferCount = 2; + int frameLag = 2; + + QSize swapChainImageSize; + VkSwapchainKHR swapChain = VK_NULL_HANDLE; + bool swapChainSupportsReadBack = false; + + struct ImageResources { + VkImage image = VK_NULL_HANDLE; + VkImageView imageView = VK_NULL_HANDLE; + VkCommandBuffer cmdBuf = VK_NULL_HANDLE; + VkFence cmdFence = VK_NULL_HANDLE; + bool cmdFenceWaitable = false; + VkFramebuffer fb = VK_NULL_HANDLE; + VkCommandBuffer presTransCmdBuf = VK_NULL_HANDLE; + VkImage msaaImage = VK_NULL_HANDLE; + VkImageView msaaImageView = VK_NULL_HANDLE; + } imageRes[MAX_SWAPCHAIN_BUFFER_COUNT]; + + VkDeviceMemory msaaImageMem = VK_NULL_HANDLE; + + uint32_t currentImage; + + struct FrameResources { + VkFence fence = VK_NULL_HANDLE; + bool fenceWaitable = false; + VkSemaphore imageSem = VK_NULL_HANDLE; + VkSemaphore drawSem = VK_NULL_HANDLE; + VkSemaphore presTransSem = VK_NULL_HANDLE; + bool imageAcquired = false; + bool imageSemWaitable = false; + } frameRes[MAX_FRAME_LAG]; + + uint32_t currentFrame; + + VkRenderPass defaultRenderPass = VK_NULL_HANDLE; + + VkDeviceMemory dsMem = VK_NULL_HANDLE; + VkImage dsImage = VK_NULL_HANDLE; + VkImageView dsView = VK_NULL_HANDLE; + + bool framePending = false; + bool frameGrabbing = false; + QImage frameGrabTargetImage; + VkImage frameGrabImage = VK_NULL_HANDLE; + VkDeviceMemory frameGrabImageMem = VK_NULL_HANDLE; + + QMatrix4x4 m_clipCorrect; +}; + +QT_END_NAMESPACE + +#endif // QT_CONFIG(vulkan) + +#endif diff --git a/src/gui/vulkan/vulkan.pri b/src/gui/vulkan/vulkan.pri index 25635a84c4..b9d2a9b4b5 100644 --- a/src/gui/vulkan/vulkan.pri +++ b/src/gui/vulkan/vulkan.pri @@ -1,12 +1,15 @@ qtConfig(vulkan) { HEADERS += \ vulkan/qvulkaninstance.h \ - vulkan/qplatformvulkaninstance.h + vulkan/qplatformvulkaninstance.h \ + vulkan/qvulkanwindow.h \ + vulkan/qvulkanwindow_p.h SOURCES += \ vulkan/qvulkaninstance.cpp \ vulkan/qplatformvulkaninstance.cpp \ - vulkan/qvulkanfunctions.cpp + vulkan/qvulkanfunctions.cpp \ + vulkan/qvulkanwindow.cpp # Applications must inherit the Vulkan header include path. QMAKE_USE += vulkan/nolink diff --git a/tests/auto/gui/qvulkan/tst_qvulkan.cpp b/tests/auto/gui/qvulkan/tst_qvulkan.cpp index 2803b84e8c..8027935003 100644 --- a/tests/auto/gui/qvulkan/tst_qvulkan.cpp +++ b/tests/auto/gui/qvulkan/tst_qvulkan.cpp @@ -28,7 +28,7 @@ #include #include -#include +#include #include @@ -41,8 +41,11 @@ class tst_QVulkan : public QObject private slots: void vulkanInstance(); void vulkanCheckSupported(); - void vulkanWindow(); + void vulkanPlainWindow(); void vulkanVersionRequest(); + void vulkanWindow(); + void vulkanWindowRenderer(); + void vulkanWindowGrab(); }; void tst_QVulkan::vulkanInstance() @@ -102,7 +105,7 @@ void tst_QVulkan::vulkanCheckSupported() } } -void tst_QVulkan::vulkanWindow() +void tst_QVulkan::vulkanPlainWindow() { QVulkanInstance inst; if (!inst.create()) @@ -154,6 +157,279 @@ void tst_QVulkan::vulkanVersionRequest() QCOMPARE(inst.errorCode(), VK_ERROR_INCOMPATIBLE_DRIVER); } +static void waitForUnexposed(QWindow *w) +{ + QElapsedTimer timer; + timer.start(); + while (w->isExposed()) { + int remaining = 5000 - int(timer.elapsed()); + if (remaining <= 0) + break; + QCoreApplication::processEvents(QEventLoop::AllEvents, remaining); + QCoreApplication::sendPostedEvents(Q_NULLPTR, QEvent::DeferredDelete); + QTest::qSleep(10); + } +} + +void tst_QVulkan::vulkanWindow() +{ + QVulkanInstance inst; + if (!inst.create()) + QSKIP("Vulkan init failed; skip"); + + // First let's forget to set the instance. + QVulkanWindow w; + QVERIFY(!w.isValid()); + w.resize(1024, 768); + w.show(); + QTest::qWaitForWindowExposed(&w); + QVERIFY(!w.isValid()); + + // Now set it. A simple hide - show should be enough to correct, this, no + // need for a full destroy - create. + w.hide(); + waitForUnexposed(&w); + w.setVulkanInstance(&inst); + QVector pdevs = w.availablePhysicalDevices(); + if (pdevs.isEmpty()) + QSKIP("No Vulkan physical devices; skip"); + w.show(); + QTest::qWaitForWindowExposed(&w); + QVERIFY(w.isValid()); + QCOMPARE(w.vulkanInstance(), &inst); + QVulkanInfoVector exts = w.supportedDeviceExtensions(); + + // Now destroy and recreate. + w.destroy(); + waitForUnexposed(&w); + QVERIFY(!w.isValid()); + // check that flags can be set between a destroy() - show() + w.setFlags(QVulkanWindow::PersistentResources); + // supported lists can be queried before expose too + QVERIFY(w.supportedDeviceExtensions() == exts); + w.show(); + QTest::qWaitForWindowExposed(&w); + QVERIFY(w.isValid()); + QVERIFY(w.flags().testFlag(QVulkanWindow::PersistentResources)); + + QVERIFY(w.physicalDevice() != VK_NULL_HANDLE); + QVERIFY(w.physicalDeviceProperties() != nullptr); + QVERIFY(w.device() != VK_NULL_HANDLE); + QVERIFY(w.graphicsQueue() != VK_NULL_HANDLE); + QVERIFY(w.graphicsCommandPool() != VK_NULL_HANDLE); + QVERIFY(w.defaultRenderPass() != VK_NULL_HANDLE); + + QVERIFY(w.concurrentFrameCount() > 0); + QVERIFY(w.concurrentFrameCount() <= QVulkanWindow::MAX_CONCURRENT_FRAME_COUNT); +} + +class TestVulkanRenderer; + +class TestVulkanWindow : public QVulkanWindow +{ +public: + QVulkanWindowRenderer *createRenderer() override; + +private: + TestVulkanRenderer *m_renderer = nullptr; +}; + +struct TestVulkan { + int preInitResCount = 0; + int initResCount = 0; + int initSwcResCount = 0; + int releaseResCount = 0; + int releaseSwcResCount = 0; + int startNextFrameCount = 0; +} testVulkan; + +class TestVulkanRenderer : public QVulkanWindowRenderer +{ +public: + TestVulkanRenderer(QVulkanWindow *w) : m_window(w) { } + + void preInitResources() override; + void initResources() override; + void initSwapChainResources() override; + void releaseSwapChainResources() override; + void releaseResources() override; + + void startNextFrame() override; + +private: + QVulkanWindow *m_window; + QVulkanDeviceFunctions *m_devFuncs; +}; + +void TestVulkanRenderer::preInitResources() +{ + if (testVulkan.initResCount) { + qWarning("initResources called before preInitResources?!"); + testVulkan.preInitResCount = -1; + return; + } + + // Ensure the physical device and the surface are available at this stage. + VkPhysicalDevice physDev = m_window->physicalDevice(); + if (physDev == VK_NULL_HANDLE) { + qWarning("No physical device in preInitResources"); + testVulkan.preInitResCount = -1; + return; + } + VkSurfaceKHR surface = m_window->vulkanInstance()->surfaceForWindow(m_window); + if (surface == VK_NULL_HANDLE) { + qWarning("No surface in preInitResources"); + testVulkan.preInitResCount = -1; + return; + } + + ++testVulkan.preInitResCount; +} + +void TestVulkanRenderer::initResources() +{ + m_devFuncs = m_window->vulkanInstance()->deviceFunctions(m_window->device()); + ++testVulkan.initResCount; +} + +void TestVulkanRenderer::initSwapChainResources() +{ + ++testVulkan.initSwcResCount; +} + +void TestVulkanRenderer::releaseSwapChainResources() +{ + ++testVulkan.releaseSwcResCount; +} + +void TestVulkanRenderer::releaseResources() +{ + ++testVulkan.releaseResCount; +} + +void TestVulkanRenderer::startNextFrame() +{ + ++testVulkan.startNextFrameCount; + + VkClearColorValue clearColor = { 0, 1, 0, 1 }; + VkClearDepthStencilValue clearDS = { 1, 0 }; + VkClearValue clearValues[2]; + memset(clearValues, 0, sizeof(clearValues)); + clearValues[0].color = clearColor; + clearValues[1].depthStencil = clearDS; + + VkRenderPassBeginInfo rpBeginInfo; + memset(&rpBeginInfo, 0, sizeof(rpBeginInfo)); + rpBeginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; + rpBeginInfo.renderPass = m_window->defaultRenderPass(); + rpBeginInfo.framebuffer = m_window->currentFramebuffer(); + const QSize sz = m_window->swapChainImageSize(); + rpBeginInfo.renderArea.extent.width = sz.width(); + rpBeginInfo.renderArea.extent.height = sz.height(); + rpBeginInfo.clearValueCount = 2; + rpBeginInfo.pClearValues = clearValues; + VkCommandBuffer cmdBuf = m_window->currentCommandBuffer(); + m_devFuncs->vkCmdBeginRenderPass(cmdBuf, &rpBeginInfo, VK_SUBPASS_CONTENTS_INLINE); + + m_devFuncs->vkCmdEndRenderPass(cmdBuf); + + m_window->frameReady(); +} + +QVulkanWindowRenderer *TestVulkanWindow::createRenderer() +{ + Q_ASSERT(!m_renderer); + m_renderer = new TestVulkanRenderer(this); + return m_renderer; +} + +void tst_QVulkan::vulkanWindowRenderer() +{ + QVulkanInstance inst; + if (!inst.create()) + QSKIP("Vulkan init failed; skip"); + + testVulkan = TestVulkan(); + + TestVulkanWindow w; + w.setVulkanInstance(&inst); + w.resize(1024, 768); + w.show(); + QTest::qWaitForWindowExposed(&w); + + if (w.availablePhysicalDevices().isEmpty()) + QSKIP("No Vulkan physical devices; skip"); + + QVERIFY(testVulkan.preInitResCount == 1); + QVERIFY(testVulkan.initResCount == 1); + QVERIFY(testVulkan.initSwcResCount == 1); + // this has to be QTRY due to the async update in QVulkanWindowPrivate::ensureStarted() + QTRY_VERIFY(testVulkan.startNextFrameCount >= 1); + + QVERIFY(!w.swapChainImageSize().isEmpty()); + QVERIFY(w.colorFormat() != VK_FORMAT_UNDEFINED); + QVERIFY(w.depthStencilFormat() != VK_FORMAT_UNDEFINED); + + w.destroy(); + waitForUnexposed(&w); + QVERIFY(testVulkan.releaseSwcResCount == 1); + QVERIFY(testVulkan.releaseResCount == 1); +} + +void tst_QVulkan::vulkanWindowGrab() +{ + QVulkanInstance inst; + inst.setLayers(QByteArrayList() << "VK_LAYER_LUNARG_standard_validation"); + if (!inst.create()) + QSKIP("Vulkan init failed; skip"); + + testVulkan = TestVulkan(); + + TestVulkanWindow w; + w.setVulkanInstance(&inst); + w.resize(1024, 768); + w.show(); + QTest::qWaitForWindowExposed(&w); + + if (w.availablePhysicalDevices().isEmpty()) + QSKIP("No Vulkan physical devices; skip"); + + if (!w.supportsGrab()) + QSKIP("No grab support; skip"); + + QVERIFY(!w.swapChainImageSize().isEmpty()); + + QImage img1 = w.grab(); + QImage img2 = w.grab(); + QImage img3 = w.grab(); + + QVERIFY(!img1.isNull()); + QVERIFY(!img2.isNull()); + QVERIFY(!img3.isNull()); + + QCOMPARE(img1.size(), w.swapChainImageSize()); + QCOMPARE(img2.size(), w.swapChainImageSize()); + QCOMPARE(img3.size(), w.swapChainImageSize()); + + QRgb a = img1.pixel(10, 20); + QRgb b = img2.pixel(5, 5); + QRgb c = img3.pixel(50, 30); + + QCOMPARE(a, b); + QCOMPARE(b, c); + QRgb refPixel = qRgb(0, 255, 0); + + int redFuzz = qAbs(qRed(a) - qRed(refPixel)); + int greenFuzz = qAbs(qGreen(a) - qGreen(refPixel)); + int blueFuzz = qAbs(qBlue(a) - qBlue(refPixel)); + + QVERIFY(redFuzz <= 1); + QVERIFY(blueFuzz <= 1); + QVERIFY(greenFuzz <= 1); + + w.destroy(); +} + QTEST_MAIN(tst_QVulkan) #include "tst_qvulkan.moc" -- cgit v1.2.3