summaryrefslogtreecommitdiffstats
path: root/examples/gui/rhiwindow
diff options
context:
space:
mode:
Diffstat (limited to 'examples/gui/rhiwindow')
-rw-r--r--examples/gui/rhiwindow/CMakeLists.txt60
-rw-r--r--examples/gui/rhiwindow/main.cpp110
-rw-r--r--examples/gui/rhiwindow/rhiwindow.cpp436
-rw-r--r--examples/gui/rhiwindow/rhiwindow.h78
-rw-r--r--examples/gui/rhiwindow/rhiwindow.pri4
-rw-r--r--examples/gui/rhiwindow/rhiwindow.pro9
-rw-r--r--examples/gui/rhiwindow/rhiwindow.qrc8
-rw-r--r--examples/gui/rhiwindow/shaders/color.frag15
-rw-r--r--examples/gui/rhiwindow/shaders/color.vert17
-rw-r--r--examples/gui/rhiwindow/shaders/prebuilt/color.frag.qsbbin0 -> 1035 bytes
-rw-r--r--examples/gui/rhiwindow/shaders/prebuilt/color.vert.qsbbin0 -> 1131 bytes
-rw-r--r--examples/gui/rhiwindow/shaders/prebuilt/quad.frag.qsbbin0 -> 1023 bytes
-rw-r--r--examples/gui/rhiwindow/shaders/prebuilt/quad.vert.qsbbin0 -> 982 bytes
-rw-r--r--examples/gui/rhiwindow/shaders/quad.frag11
-rw-r--r--examples/gui/rhiwindow/shaders/quad.vert10
15 files changed, 758 insertions, 0 deletions
diff --git a/examples/gui/rhiwindow/CMakeLists.txt b/examples/gui/rhiwindow/CMakeLists.txt
new file mode 100644
index 0000000000..49b36286ee
--- /dev/null
+++ b/examples/gui/rhiwindow/CMakeLists.txt
@@ -0,0 +1,60 @@
+# Copyright (C) 2023 The Qt Company Ltd.
+# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
+
+cmake_minimum_required(VERSION 3.16)
+project(rhiwindow LANGUAGES CXX)
+
+find_package(Qt6 REQUIRED COMPONENTS Core Gui)
+
+qt_standard_project_setup()
+
+qt_add_executable(rhiwindow
+ main.cpp
+ rhiwindow.cpp rhiwindow.h
+)
+
+set_target_properties(rhiwindow PROPERTIES
+ WIN32_EXECUTABLE TRUE
+ MACOSX_BUNDLE TRUE
+)
+
+target_link_libraries(rhiwindow PRIVATE
+ Qt6::Core
+ Qt6::Gui
+ Qt6::GuiPrivate
+)
+
+set_source_files_properties("shaders/prebuilt/color.vert.qsb"
+ PROPERTIES QT_RESOURCE_ALIAS "color.vert.qsb"
+)
+set_source_files_properties("shaders/prebuilt/color.frag.qsb"
+ PROPERTIES QT_RESOURCE_ALIAS "color.frag.qsb"
+)
+set_source_files_properties("shaders/prebuilt/quad.vert.qsb"
+ PROPERTIES QT_RESOURCE_ALIAS "quad.vert.qsb"
+)
+set_source_files_properties("shaders/prebuilt/quad.frag.qsb"
+ PROPERTIES QT_RESOURCE_ALIAS "quad.frag.qsb"
+)
+qt_add_resources(rhiwindow "rhiwindow"
+ PREFIX
+ "/"
+ FILES
+ "shaders/prebuilt/color.vert.qsb"
+ "shaders/prebuilt/color.frag.qsb"
+ "shaders/prebuilt/quad.vert.qsb"
+ "shaders/prebuilt/quad.frag.qsb"
+)
+
+install(TARGETS rhiwindow
+ BUNDLE DESTINATION .
+ RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
+ LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
+)
+
+qt_generate_deploy_app_script(
+ TARGET rhiwindow
+ OUTPUT_SCRIPT deploy_script
+ NO_UNSUPPORTED_PLATFORM_ERROR
+)
+install(SCRIPT ${deploy_script})
diff --git a/examples/gui/rhiwindow/main.cpp b/examples/gui/rhiwindow/main.cpp
new file mode 100644
index 0000000000..37977e3a34
--- /dev/null
+++ b/examples/gui/rhiwindow/main.cpp
@@ -0,0 +1,110 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
+
+#include <QGuiApplication>
+#include <QCommandLineParser>
+#include "rhiwindow.h"
+
+int main(int argc, char **argv)
+{
+ QGuiApplication app(argc, argv);
+
+ QRhi::Implementation graphicsApi;
+
+ // Use platform-specific defaults when no command-line arguments given.
+#if defined(Q_OS_WIN)
+ graphicsApi = QRhi::D3D11;
+#elif QT_CONFIG(metal)
+ graphicsApi = QRhi::Metal;
+#elif QT_CONFIG(vulkan)
+ graphicsApi = QRhi::Vulkan;
+#else
+ graphicsApi = QRhi::OpenGLES2;
+#endif
+
+ QCommandLineParser cmdLineParser;
+ cmdLineParser.addHelpOption();
+ QCommandLineOption nullOption({ "n", "null" }, QLatin1String("Null"));
+ cmdLineParser.addOption(nullOption);
+ QCommandLineOption glOption({ "g", "opengl" }, QLatin1String("OpenGL"));
+ cmdLineParser.addOption(glOption);
+ QCommandLineOption vkOption({ "v", "vulkan" }, QLatin1String("Vulkan"));
+ cmdLineParser.addOption(vkOption);
+ QCommandLineOption d3d11Option({ "d", "d3d11" }, QLatin1String("Direct3D 11"));
+ cmdLineParser.addOption(d3d11Option);
+ QCommandLineOption d3d12Option({ "D", "d3d12" }, QLatin1String("Direct3D 12"));
+ cmdLineParser.addOption(d3d12Option);
+ QCommandLineOption mtlOption({ "m", "metal" }, QLatin1String("Metal"));
+ cmdLineParser.addOption(mtlOption);
+
+ cmdLineParser.process(app);
+ if (cmdLineParser.isSet(nullOption))
+ graphicsApi = QRhi::Null;
+ if (cmdLineParser.isSet(glOption))
+ graphicsApi = QRhi::OpenGLES2;
+ if (cmdLineParser.isSet(vkOption))
+ graphicsApi = QRhi::Vulkan;
+ if (cmdLineParser.isSet(d3d11Option))
+ graphicsApi = QRhi::D3D11;
+ if (cmdLineParser.isSet(d3d12Option))
+ graphicsApi = QRhi::D3D12;
+ if (cmdLineParser.isSet(mtlOption))
+ graphicsApi = QRhi::Metal;
+
+ //! [api-setup]
+ // For OpenGL, to ensure there is a depth/stencil buffer for the window.
+ // With other APIs this is under the application's control (QRhiRenderBuffer etc.)
+ // and so no special setup is needed for those.
+ QSurfaceFormat fmt;
+ fmt.setDepthBufferSize(24);
+ fmt.setStencilBufferSize(8);
+ // Special case macOS to allow using OpenGL there.
+ // (the default Metal is the recommended approach, though)
+ // gl_VertexID is a GLSL 130 feature, and so the default OpenGL 2.1 context
+ // we get on macOS is not sufficient.
+#ifdef Q_OS_MACOS
+ fmt.setVersion(4, 1);
+ fmt.setProfile(QSurfaceFormat::CoreProfile);
+#endif
+ QSurfaceFormat::setDefaultFormat(fmt);
+
+ // For Vulkan.
+#if QT_CONFIG(vulkan)
+ QVulkanInstance inst;
+ if (graphicsApi == QRhi::Vulkan) {
+ // Request validation, if available. This is completely optional
+ // and has a performance impact, and should be avoided in production use.
+ inst.setLayers({ "VK_LAYER_KHRONOS_validation" });
+ // Play nice with QRhi.
+ inst.setExtensions(QRhiVulkanInitParams::preferredInstanceExtensions());
+ if (!inst.create()) {
+ qWarning("Failed to create Vulkan instance, switching to OpenGL");
+ graphicsApi = QRhi::OpenGLES2;
+ }
+ }
+#endif
+//! [api-setup]
+
+ HelloWindow window(graphicsApi);
+
+#if QT_CONFIG(vulkan)
+ if (graphicsApi == QRhi::Vulkan)
+ window.setVulkanInstance(&inst);
+#endif
+ window.resize(1280, 720);
+ window.setTitle(QCoreApplication::applicationName() + QLatin1String(" - ") + window.graphicsApiName());
+ window.show();
+
+ int ret = app.exec();
+
+ // RhiWindow::event() will not get invoked when the
+ // PlatformSurfaceAboutToBeDestroyed event is sent during the QWindow
+ // destruction. That happens only when exiting via app::quit() instead of
+ // the more common QWindow::close(). Take care of it: if the QPlatformWindow
+ // is still around (there was no close() yet), get rid of the swapchain
+ // while it's not too late.
+ if (window.handle())
+ window.releaseSwapChain();
+
+ return ret;
+}
diff --git a/examples/gui/rhiwindow/rhiwindow.cpp b/examples/gui/rhiwindow/rhiwindow.cpp
new file mode 100644
index 0000000000..3ae6faa802
--- /dev/null
+++ b/examples/gui/rhiwindow/rhiwindow.cpp
@@ -0,0 +1,436 @@
+// Copyright (C) 2020 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
+
+#include "rhiwindow.h"
+#include <QPlatformSurfaceEvent>
+#include <QPainter>
+#include <QFile>
+#include <rhi/qshader.h>
+
+//! [rhiwindow-ctor]
+RhiWindow::RhiWindow(QRhi::Implementation graphicsApi)
+ : m_graphicsApi(graphicsApi)
+{
+ switch (graphicsApi) {
+ case QRhi::OpenGLES2:
+ setSurfaceType(OpenGLSurface);
+ break;
+ case QRhi::Vulkan:
+ setSurfaceType(VulkanSurface);
+ break;
+ case QRhi::D3D11:
+ case QRhi::D3D12:
+ setSurfaceType(Direct3DSurface);
+ break;
+ case QRhi::Metal:
+ setSurfaceType(MetalSurface);
+ break;
+ case QRhi::Null:
+ break; // RasterSurface
+ }
+}
+//! [rhiwindow-ctor]
+
+QString RhiWindow::graphicsApiName() const
+{
+ switch (m_graphicsApi) {
+ case QRhi::Null:
+ return QLatin1String("Null (no output)");
+ case QRhi::OpenGLES2:
+ return QLatin1String("OpenGL");
+ case QRhi::Vulkan:
+ return QLatin1String("Vulkan");
+ case QRhi::D3D11:
+ return QLatin1String("Direct3D 11");
+ case QRhi::D3D12:
+ return QLatin1String("Direct3D 12");
+ case QRhi::Metal:
+ return QLatin1String("Metal");
+ }
+ return QString();
+}
+
+//! [expose]
+void RhiWindow::exposeEvent(QExposeEvent *)
+{
+ // initialize and start rendering when the window becomes usable for graphics purposes
+ if (isExposed() && !m_initialized) {
+ init();
+ resizeSwapChain();
+ m_initialized = true;
+ }
+
+ const QSize surfaceSize = m_hasSwapChain ? m_sc->surfacePixelSize() : QSize();
+
+ // stop pushing frames when not exposed (or size is 0)
+ if ((!isExposed() || (m_hasSwapChain && surfaceSize.isEmpty())) && m_initialized && !m_notExposed)
+ m_notExposed = true;
+
+ // Continue when exposed again and the surface has a valid size. Note that
+ // surfaceSize can be (0, 0) even though size() reports a valid one, hence
+ // trusting surfacePixelSize() and not QWindow.
+ if (isExposed() && m_initialized && m_notExposed && !surfaceSize.isEmpty()) {
+ m_notExposed = false;
+ m_newlyExposed = true;
+ }
+
+ // always render a frame on exposeEvent() (when exposed) in order to update
+ // immediately on window resize.
+ if (isExposed() && !surfaceSize.isEmpty())
+ render();
+}
+//! [expose]
+
+//! [event]
+bool RhiWindow::event(QEvent *e)
+{
+ switch (e->type()) {
+ case QEvent::UpdateRequest:
+ render();
+ break;
+
+ case QEvent::PlatformSurface:
+ // this is the proper time to tear down the swapchain (while the native window and surface are still around)
+ if (static_cast<QPlatformSurfaceEvent *>(e)->surfaceEventType() == QPlatformSurfaceEvent::SurfaceAboutToBeDestroyed)
+ releaseSwapChain();
+ break;
+
+ default:
+ break;
+ }
+
+ return QWindow::event(e);
+}
+//! [event]
+
+//! [rhi-init]
+void RhiWindow::init()
+{
+ if (m_graphicsApi == QRhi::Null) {
+ QRhiNullInitParams params;
+ m_rhi.reset(QRhi::create(QRhi::Null, &params));
+ }
+
+#if QT_CONFIG(opengl)
+ if (m_graphicsApi == QRhi::OpenGLES2) {
+ m_fallbackSurface.reset(QRhiGles2InitParams::newFallbackSurface());
+ QRhiGles2InitParams params;
+ params.fallbackSurface = m_fallbackSurface.get();
+ params.window = this;
+ m_rhi.reset(QRhi::create(QRhi::OpenGLES2, &params));
+ }
+#endif
+
+#if QT_CONFIG(vulkan)
+ if (m_graphicsApi == QRhi::Vulkan) {
+ QRhiVulkanInitParams params;
+ params.inst = vulkanInstance();
+ params.window = this;
+ m_rhi.reset(QRhi::create(QRhi::Vulkan, &params));
+ }
+#endif
+
+#ifdef Q_OS_WIN
+ if (m_graphicsApi == QRhi::D3D11) {
+ QRhiD3D11InitParams params;
+ // Enable the debug layer, if available. This is optional
+ // and should be avoided in production builds.
+ params.enableDebugLayer = true;
+ m_rhi.reset(QRhi::create(QRhi::D3D11, &params));
+ } else if (m_graphicsApi == QRhi::D3D12) {
+ QRhiD3D12InitParams params;
+ // Enable the debug layer, if available. This is optional
+ // and should be avoided in production builds.
+ params.enableDebugLayer = true;
+ m_rhi.reset(QRhi::create(QRhi::D3D12, &params));
+ }
+#endif
+
+#if QT_CONFIG(metal)
+ if (m_graphicsApi == QRhi::Metal) {
+ QRhiMetalInitParams params;
+ m_rhi.reset(QRhi::create(QRhi::Metal, &params));
+ }
+#endif
+
+ if (!m_rhi)
+ qFatal("Failed to create RHI backend");
+//! [rhi-init]
+
+//! [swapchain-init]
+ m_sc.reset(m_rhi->newSwapChain());
+ m_ds.reset(m_rhi->newRenderBuffer(QRhiRenderBuffer::DepthStencil,
+ QSize(), // no need to set the size here, due to UsedWithSwapChainOnly
+ 1,
+ QRhiRenderBuffer::UsedWithSwapChainOnly));
+ m_sc->setWindow(this);
+ m_sc->setDepthStencil(m_ds.get());
+ m_rp.reset(m_sc->newCompatibleRenderPassDescriptor());
+ m_sc->setRenderPassDescriptor(m_rp.get());
+//! [swapchain-init]
+
+ customInit();
+}
+
+//! [swapchain-resize]
+void RhiWindow::resizeSwapChain()
+{
+ m_hasSwapChain = m_sc->createOrResize(); // also handles m_ds
+
+ const QSize outputSize = m_sc->currentPixelSize();
+ m_viewProjection = m_rhi->clipSpaceCorrMatrix();
+ m_viewProjection.perspective(45.0f, outputSize.width() / (float) outputSize.height(), 0.01f, 1000.0f);
+ m_viewProjection.translate(0, 0, -4);
+}
+//! [swapchain-resize]
+
+void RhiWindow::releaseSwapChain()
+{
+ if (m_hasSwapChain) {
+ m_hasSwapChain = false;
+ m_sc->destroy();
+ }
+}
+
+//! [render-precheck]
+void RhiWindow::render()
+{
+ if (!m_hasSwapChain || m_notExposed)
+ return;
+//! [render-precheck]
+
+//! [render-resize]
+ // If the window got resized or newly exposed, resize the swapchain. (the
+ // newly-exposed case is not actually required by some platforms, but is
+ // here for robustness and portability)
+ //
+ // This (exposeEvent + the logic here) is the only safe way to perform
+ // resize handling. Note the usage of the RHI's surfacePixelSize(), and
+ // never QWindow::size(). (the two may or may not be the same under the hood,
+ // depending on the backend and platform)
+ //
+ if (m_sc->currentPixelSize() != m_sc->surfacePixelSize() || m_newlyExposed) {
+ resizeSwapChain();
+ if (!m_hasSwapChain)
+ return;
+ m_newlyExposed = false;
+ }
+//! [render-resize]
+
+//! [beginframe]
+ QRhi::FrameOpResult result = m_rhi->beginFrame(m_sc.get());
+ if (result == QRhi::FrameOpSwapChainOutOfDate) {
+ resizeSwapChain();
+ if (!m_hasSwapChain)
+ return;
+ result = m_rhi->beginFrame(m_sc.get());
+ }
+ if (result != QRhi::FrameOpSuccess) {
+ qWarning("beginFrame failed with %d, will retry", result);
+ requestUpdate();
+ return;
+ }
+
+ customRender();
+//! [beginframe]
+
+//! [request-update]
+ m_rhi->endFrame(m_sc.get());
+
+ // Always request the next frame via requestUpdate(). On some platforms this is backed
+ // by a platform-specific solution, e.g. CVDisplayLink on macOS, which is potentially
+ // more efficient than a timer, queued metacalls, etc.
+ requestUpdate();
+}
+//! [request-update]
+
+static float vertexData[] = {
+ // Y up (note clipSpaceCorrMatrix in m_viewProjection), CCW
+ 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,
+};
+
+//! [getshader]
+static QShader getShader(const QString &name)
+{
+ QFile f(name);
+ if (f.open(QIODevice::ReadOnly))
+ return QShader::fromSerialized(f.readAll());
+
+ return QShader();
+}
+//! [getshader]
+
+HelloWindow::HelloWindow(QRhi::Implementation graphicsApi)
+ : RhiWindow(graphicsApi)
+{
+}
+
+//! [ensure-texture]
+void HelloWindow::ensureFullscreenTexture(const QSize &pixelSize, QRhiResourceUpdateBatch *u)
+{
+ if (m_texture && m_texture->pixelSize() == pixelSize)
+ return;
+
+ if (!m_texture)
+ m_texture.reset(m_rhi->newTexture(QRhiTexture::RGBA8, pixelSize));
+ else
+ m_texture->setPixelSize(pixelSize);
+
+ m_texture->create();
+
+ QImage image(pixelSize, QImage::Format_RGBA8888_Premultiplied);
+ image.setDevicePixelRatio(devicePixelRatio());
+//! [ensure-texture]
+ QPainter painter(&image);
+ painter.fillRect(QRectF(QPointF(0, 0), size()), QColor::fromRgbF(0.4f, 0.7f, 0.0f, 1.0f));
+ painter.setPen(Qt::transparent);
+ painter.setBrush({ QGradient(QGradient::DeepBlue) });
+ painter.drawRoundedRect(QRectF(QPointF(20, 20), size() - QSize(40, 40)), 16, 16);
+ painter.setPen(Qt::black);
+ QFont font;
+ font.setPixelSize(0.05 * qMin(width(), height()));
+ painter.setFont(font);
+ painter.drawText(QRectF(QPointF(60, 60), size() - QSize(120, 120)), 0,
+ QLatin1String("Rendering with QRhi to a resizable QWindow.\nThe 3D API is %1.\nUse the command-line options to choose a different API.")
+ .arg(graphicsApiName()));
+ painter.end();
+
+ if (m_rhi->isYUpInNDC())
+ image = image.mirrored();
+
+//! [ensure-texture-2]
+ u->uploadTexture(m_texture.get(), image);
+//! [ensure-texture-2]
+}
+
+//! [render-init-1]
+void HelloWindow::customInit()
+{
+ m_initialUpdates = m_rhi->nextResourceUpdateBatch();
+
+ m_vbuf.reset(m_rhi->newBuffer(QRhiBuffer::Immutable, QRhiBuffer::VertexBuffer, sizeof(vertexData)));
+ m_vbuf->create();
+ m_initialUpdates->uploadStaticBuffer(m_vbuf.get(), vertexData);
+
+ static const quint32 UBUF_SIZE = 68;
+ m_ubuf.reset(m_rhi->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::UniformBuffer, UBUF_SIZE));
+ m_ubuf->create();
+//! [render-init-1]
+
+ ensureFullscreenTexture(m_sc->surfacePixelSize(), m_initialUpdates);
+
+ m_sampler.reset(m_rhi->newSampler(QRhiSampler::Linear, QRhiSampler::Linear, QRhiSampler::None,
+ QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge));
+ m_sampler->create();
+
+ //! [render-init-2]
+ m_colorTriSrb.reset(m_rhi->newShaderResourceBindings());
+ static const QRhiShaderResourceBinding::StageFlags visibility =
+ QRhiShaderResourceBinding::VertexStage | QRhiShaderResourceBinding::FragmentStage;
+ m_colorTriSrb->setBindings({
+ QRhiShaderResourceBinding::uniformBuffer(0, visibility, m_ubuf.get())
+ });
+ m_colorTriSrb->create();
+
+ m_colorPipeline.reset(m_rhi->newGraphicsPipeline());
+ // Enable depth testing; not quite needed for a simple triangle, but we
+ // have a depth-stencil buffer so why not.
+ m_colorPipeline->setDepthTest(true);
+ m_colorPipeline->setDepthWrite(true);
+ // Blend factors default to One, OneOneMinusSrcAlpha, which is convenient.
+ QRhiGraphicsPipeline::TargetBlend premulAlphaBlend;
+ premulAlphaBlend.enable = true;
+ m_colorPipeline->setTargetBlends({ premulAlphaBlend });
+ m_colorPipeline->setShaderStages({
+ { QRhiShaderStage::Vertex, getShader(QLatin1String(":/color.vert.qsb")) },
+ { QRhiShaderStage::Fragment, getShader(QLatin1String(":/color.frag.qsb")) }
+ });
+ QRhiVertexInputLayout inputLayout;
+ inputLayout.setBindings({
+ { 5 * sizeof(float) }
+ });
+ inputLayout.setAttributes({
+ { 0, 0, QRhiVertexInputAttribute::Float2, 0 },
+ { 0, 1, QRhiVertexInputAttribute::Float3, 2 * sizeof(float) }
+ });
+ m_colorPipeline->setVertexInputLayout(inputLayout);
+ m_colorPipeline->setShaderResourceBindings(m_colorTriSrb.get());
+ m_colorPipeline->setRenderPassDescriptor(m_rp.get());
+ m_colorPipeline->create();
+//! [render-init-2]
+
+ m_fullscreenQuadSrb.reset(m_rhi->newShaderResourceBindings());
+ m_fullscreenQuadSrb->setBindings({
+ QRhiShaderResourceBinding::sampledTexture(0, QRhiShaderResourceBinding::FragmentStage,
+ m_texture.get(), m_sampler.get())
+ });
+ m_fullscreenQuadSrb->create();
+
+ m_fullscreenQuadPipeline.reset(m_rhi->newGraphicsPipeline());
+ m_fullscreenQuadPipeline->setShaderStages({
+ { QRhiShaderStage::Vertex, getShader(QLatin1String(":/quad.vert.qsb")) },
+ { QRhiShaderStage::Fragment, getShader(QLatin1String(":/quad.frag.qsb")) }
+ });
+ m_fullscreenQuadPipeline->setVertexInputLayout({});
+ m_fullscreenQuadPipeline->setShaderResourceBindings(m_fullscreenQuadSrb.get());
+ m_fullscreenQuadPipeline->setRenderPassDescriptor(m_rp.get());
+ m_fullscreenQuadPipeline->create();
+}
+
+//! [render-1]
+void HelloWindow::customRender()
+{
+ QRhiResourceUpdateBatch *resourceUpdates = m_rhi->nextResourceUpdateBatch();
+
+ if (m_initialUpdates) {
+ resourceUpdates->merge(m_initialUpdates);
+ m_initialUpdates->release();
+ m_initialUpdates = nullptr;
+ }
+//! [render-1]
+
+//! [render-rotation]
+ m_rotation += 1.0f;
+ QMatrix4x4 modelViewProjection = m_viewProjection;
+ modelViewProjection.rotate(m_rotation, 0, 1, 0);
+ resourceUpdates->updateDynamicBuffer(m_ubuf.get(), 0, 64, modelViewProjection.constData());
+//! [render-rotation]
+
+//! [render-opacity]
+ m_opacity += m_opacityDir * 0.005f;
+ if (m_opacity < 0.0f || m_opacity > 1.0f) {
+ m_opacityDir *= -1;
+ m_opacity = qBound(0.0f, m_opacity, 1.0f);
+ }
+ resourceUpdates->updateDynamicBuffer(m_ubuf.get(), 64, 4, &m_opacity);
+//! [render-opacity]
+
+//! [render-cb]
+ QRhiCommandBuffer *cb = m_sc->currentFrameCommandBuffer();
+ const QSize outputSizeInPixels = m_sc->currentPixelSize();
+//! [render-cb]
+
+ // (re)create the texture with a size matching the output surface size, when necessary.
+ ensureFullscreenTexture(outputSizeInPixels, resourceUpdates);
+
+//! [render-pass]
+ cb->beginPass(m_sc->currentFrameRenderTarget(), Qt::black, { 1.0f, 0 }, resourceUpdates);
+//! [render-pass]
+
+ cb->setGraphicsPipeline(m_fullscreenQuadPipeline.get());
+ cb->setViewport({ 0, 0, float(outputSizeInPixels.width()), float(outputSizeInPixels.height()) });
+ cb->setShaderResources();
+ cb->draw(3);
+
+//! [render-pass-record]
+ cb->setGraphicsPipeline(m_colorPipeline.get());
+ cb->setShaderResources();
+ const QRhiCommandBuffer::VertexInput vbufBinding(m_vbuf.get(), 0);
+ cb->setVertexInput(0, 1, &vbufBinding);
+ cb->draw(3);
+
+ cb->endPass();
+//! [render-pass-record]
+}
diff --git a/examples/gui/rhiwindow/rhiwindow.h b/examples/gui/rhiwindow/rhiwindow.h
new file mode 100644
index 0000000000..520c3e8c0a
--- /dev/null
+++ b/examples/gui/rhiwindow/rhiwindow.h
@@ -0,0 +1,78 @@
+// Copyright (C) 2020 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
+
+#ifndef WINDOW_H
+#define WINDOW_H
+
+#include <QWindow>
+#include <QOffscreenSurface>
+#include <rhi/qrhi.h>
+
+class RhiWindow : public QWindow
+{
+public:
+ RhiWindow(QRhi::Implementation graphicsApi);
+ QString graphicsApiName() const;
+ void releaseSwapChain();
+
+protected:
+ virtual void customInit() = 0;
+ virtual void customRender() = 0;
+
+ // destruction order matters to a certain degree: the fallbackSurface must
+ // outlive the rhi, the rhi must outlive all other resources. The resources
+ // need no special order when destroying.
+#if QT_CONFIG(opengl)
+ std::unique_ptr<QOffscreenSurface> m_fallbackSurface;
+#endif
+ std::unique_ptr<QRhi> m_rhi;
+//! [swapchain-data]
+ std::unique_ptr<QRhiSwapChain> m_sc;
+ std::unique_ptr<QRhiRenderBuffer> m_ds;
+ std::unique_ptr<QRhiRenderPassDescriptor> m_rp;
+//! [swapchain-data]
+ bool m_hasSwapChain = false;
+ QMatrix4x4 m_viewProjection;
+
+private:
+ void init();
+ void resizeSwapChain();
+ void render();
+
+ void exposeEvent(QExposeEvent *) override;
+ bool event(QEvent *) override;
+
+ QRhi::Implementation m_graphicsApi;
+ bool m_initialized = false;
+ bool m_notExposed = false;
+ bool m_newlyExposed = false;
+};
+
+class HelloWindow : public RhiWindow
+{
+public:
+ HelloWindow(QRhi::Implementation graphicsApi);
+
+ void customInit() override;
+ void customRender() override;
+
+private:
+ void ensureFullscreenTexture(const QSize &pixelSize, QRhiResourceUpdateBatch *u);
+
+ std::unique_ptr<QRhiBuffer> m_vbuf;
+ std::unique_ptr<QRhiBuffer> m_ubuf;
+ std::unique_ptr<QRhiTexture> m_texture;
+ std::unique_ptr<QRhiSampler> m_sampler;
+ std::unique_ptr<QRhiShaderResourceBindings> m_colorTriSrb;
+ std::unique_ptr<QRhiGraphicsPipeline> m_colorPipeline;
+ std::unique_ptr<QRhiShaderResourceBindings> m_fullscreenQuadSrb;
+ std::unique_ptr<QRhiGraphicsPipeline> m_fullscreenQuadPipeline;
+
+ QRhiResourceUpdateBatch *m_initialUpdates = nullptr;
+
+ float m_rotation = 0;
+ float m_opacity = 1;
+ int m_opacityDir = -1;
+};
+
+#endif
diff --git a/examples/gui/rhiwindow/rhiwindow.pri b/examples/gui/rhiwindow/rhiwindow.pri
new file mode 100644
index 0000000000..d0ef7a2699
--- /dev/null
+++ b/examples/gui/rhiwindow/rhiwindow.pri
@@ -0,0 +1,4 @@
+INCLUDEPATH += $$PWD
+SOURCES += $$PWD/rhiwindow.cpp
+HEADERS += $$PWD/rhiwindow.h
+RESOURCES += $$PWD/rhiwindow.qrc
diff --git a/examples/gui/rhiwindow/rhiwindow.pro b/examples/gui/rhiwindow/rhiwindow.pro
new file mode 100644
index 0000000000..18f259aaf6
--- /dev/null
+++ b/examples/gui/rhiwindow/rhiwindow.pro
@@ -0,0 +1,9 @@
+include(rhiwindow.pri)
+
+QT += gui-private
+
+SOURCES += \
+ main.cpp
+
+target.path = $$[QT_INSTALL_EXAMPLES]/gui/rhiwindow
+INSTALLS += target
diff --git a/examples/gui/rhiwindow/rhiwindow.qrc b/examples/gui/rhiwindow/rhiwindow.qrc
new file mode 100644
index 0000000000..1009ec5dda
--- /dev/null
+++ b/examples/gui/rhiwindow/rhiwindow.qrc
@@ -0,0 +1,8 @@
+<!DOCTYPE RCC><RCC version="1.0">
+<qresource>
+ <file alias="color.vert.qsb">shaders/prebuilt/color.vert.qsb</file>
+ <file alias="color.frag.qsb">shaders/prebuilt/color.frag.qsb</file>
+ <file alias="quad.vert.qsb">shaders/prebuilt/quad.vert.qsb</file>
+ <file alias="quad.frag.qsb">shaders/prebuilt/quad.frag.qsb</file>
+</qresource>
+</RCC>
diff --git a/examples/gui/rhiwindow/shaders/color.frag b/examples/gui/rhiwindow/shaders/color.frag
new file mode 100644
index 0000000000..6e0a3bc91f
--- /dev/null
+++ b/examples/gui/rhiwindow/shaders/color.frag
@@ -0,0 +1,15 @@
+#version 440
+
+layout(location = 0) in vec3 v_color;
+
+layout(location = 0) out vec4 fragColor;
+
+layout(std140, binding = 0) uniform buf {
+ mat4 mvp;
+ float opacity;
+};
+
+void main()
+{
+ fragColor = vec4(v_color * opacity, opacity);
+}
diff --git a/examples/gui/rhiwindow/shaders/color.vert b/examples/gui/rhiwindow/shaders/color.vert
new file mode 100644
index 0000000000..70852ab86c
--- /dev/null
+++ b/examples/gui/rhiwindow/shaders/color.vert
@@ -0,0 +1,17 @@
+#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;
+ float opacity;
+};
+
+void main()
+{
+ v_color = color;
+ gl_Position = mvp * position;
+}
diff --git a/examples/gui/rhiwindow/shaders/prebuilt/color.frag.qsb b/examples/gui/rhiwindow/shaders/prebuilt/color.frag.qsb
new file mode 100644
index 0000000000..b4db470e5b
--- /dev/null
+++ b/examples/gui/rhiwindow/shaders/prebuilt/color.frag.qsb
Binary files differ
diff --git a/examples/gui/rhiwindow/shaders/prebuilt/color.vert.qsb b/examples/gui/rhiwindow/shaders/prebuilt/color.vert.qsb
new file mode 100644
index 0000000000..ab046b77f8
--- /dev/null
+++ b/examples/gui/rhiwindow/shaders/prebuilt/color.vert.qsb
Binary files differ
diff --git a/examples/gui/rhiwindow/shaders/prebuilt/quad.frag.qsb b/examples/gui/rhiwindow/shaders/prebuilt/quad.frag.qsb
new file mode 100644
index 0000000000..c2ea3cf251
--- /dev/null
+++ b/examples/gui/rhiwindow/shaders/prebuilt/quad.frag.qsb
Binary files differ
diff --git a/examples/gui/rhiwindow/shaders/prebuilt/quad.vert.qsb b/examples/gui/rhiwindow/shaders/prebuilt/quad.vert.qsb
new file mode 100644
index 0000000000..f0b64f7500
--- /dev/null
+++ b/examples/gui/rhiwindow/shaders/prebuilt/quad.vert.qsb
Binary files differ
diff --git a/examples/gui/rhiwindow/shaders/quad.frag b/examples/gui/rhiwindow/shaders/quad.frag
new file mode 100644
index 0000000000..65882a4292
--- /dev/null
+++ b/examples/gui/rhiwindow/shaders/quad.frag
@@ -0,0 +1,11 @@
+#version 440
+
+layout(location = 0) in vec2 v_uv;
+layout(location = 0) out vec4 fragColor;
+layout(binding = 0) uniform sampler2D tex;
+
+void main()
+{
+ vec4 c = texture(tex, v_uv);
+ fragColor = vec4(c.rgb * c.a, c.a);
+}
diff --git a/examples/gui/rhiwindow/shaders/quad.vert b/examples/gui/rhiwindow/shaders/quad.vert
new file mode 100644
index 0000000000..359896d080
--- /dev/null
+++ b/examples/gui/rhiwindow/shaders/quad.vert
@@ -0,0 +1,10 @@
+#version 440
+
+layout (location = 0) out vec2 v_uv;
+
+void main()
+{
+ // https://www.saschawillems.de/blog/2016/08/13/vulkan-tutorial-on-rendering-a-fullscreen-quad-without-buffers/
+ v_uv = vec2((gl_VertexIndex << 1) & 2, gl_VertexIndex & 2);
+ gl_Position = vec4(v_uv * 2.0 - 1.0, 0.0, 1.0);
+}