Debian Codegraph @

tests/manual/rhi/shared/examplefw.h

raw
1 // Copyright (C) 2018 The Qt Company Ltd.
2 // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
3
4 // Adapted from hellominimalcrossgfxtriangle with the frame rendering stripped out.
5 // Include this file and implement Window::customInit, release and render.
6 // Debug/validation layer is enabled for D3D and Vulkan.
7
8 #include <QGuiApplication>
9 #include <QCommandLineParser>
10 #include <QWindow>
11 #include <QPlatformSurfaceEvent>
12 #include <QElapsedTimer>
13 #include <QTimer>
14 #include <QLoggingCategory>
15 #include <QColorSpace>
16 #include <QFile>
17 #include <QOffscreenSurface>
18 #include <rhi/qrhi.h>
19
20 #ifdef EXAMPLEFW_IMGUI
21 #include "qrhiimgui.h"
22 #include "imgui.h"
23 #endif
24
25 QShader getShader(const QString &name)
26 {
27 QFile f(name);
28 if (f.open(QIODevice::ReadOnly))
29 return QShader::fromSerialized(f.readAll());
30
31 return QShader();
32 }
33
34 QByteArray getResource(const QString &name)
35 {
36 QFile f(name);
37 if (f.open(QIODevice::ReadOnly))
38 return f.readAll();
39
40 return QByteArray();
41 }
42
43 enum GraphicsApi
44 {
45 Null,
46 OpenGL,
47 Vulkan,
48 D3D11,
49 D3D12,
50 Metal
51 };
52
53 GraphicsApi graphicsApi;
54
55 QString graphicsApiName()
56 {
57 switch (graphicsApi) {
58 case Null:
59 return QLatin1String("Null (no output)");
60 case OpenGL:
61 return QLatin1String("OpenGL");
62 case Vulkan:
63 return QLatin1String("Vulkan");
64 case D3D11:
65 return QLatin1String("Direct3D 11");
66 case D3D12:
67 return QLatin1String("Direct3D 12");
68 case Metal:
69 return QLatin1String("Metal");
70 default:
71 break;
72 }
73 return QString();
74 }
75
76 QRhi::Flags rhiFlags = QRhi::EnableDebugMarkers | QRhi::EnableTimestamps;
77 int sampleCount = 1;
78 QRhiSwapChain::Flags scFlags;
79 QRhi::BeginFrameFlags beginFrameFlags;
80 QRhi::EndFrameFlags endFrameFlags;
81 bool transparentBackground = false;
82 bool debugLayer = true;
83 QRhiSwapChain::Format swapchainFormat = QRhiSwapChain::SDR;
84 float imguiHDRMultiplier = 0.0f;
85
86 class Window : public QWindow
87 {
88 public:
89 Window();
90 ~Window();
91
92 protected:
93 void init();
94 void releaseResources();
95 void resizeSwapChain();
96 void releaseSwapChain();
97 void render();
98
99 void customInit();
100 void customRelease();
101 #ifdef EXAMPLEFW_BEFORE_FRAME
102 void customBeforeFrame();
103 #endif
104 void customRender();
105 #ifdef EXAMPLEFW_IMGUI
106 void customGui();
107 #endif
108
109 void exposeEvent(QExposeEvent *) override;
110 bool event(QEvent *) override;
111 #ifdef EXAMPLEFW_KEYPRESS_EVENTS
112 void keyPressEvent(QKeyEvent *e) override;
113 #endif
114
115 bool m_running = false;
116 bool m_notExposed = false;
117 bool m_newlyExposed = false;
118
119 QRhi *m_r = nullptr;
120 bool m_hasSwapChain = false;
121 QRhiSwapChain *m_sc = nullptr;
122 QRhiRenderBuffer *m_ds = nullptr;
123 QRhiRenderPassDescriptor *m_rp = nullptr;
124
125 QMatrix4x4 m_proj;
126
127 QElapsedTimer m_timer;
128 int m_frameCount;
129
130 #ifndef QT_NO_OPENGL
131 QOffscreenSurface *m_fallbackSurface = nullptr;
132 #endif
133
134 QColor m_clearColor;
135
136 #ifdef EXAMPLEFW_IMGUI
137 QRhiImguiRenderer *m_imguiRenderer;
138 QRhiImgui m_imgui;
139 #endif
140
141 friend int main(int, char**);
142 };
143
144 Window::Window()
145 {
146 // Tell the platform plugin what we want.
147 switch (graphicsApi) {
148 case OpenGL:
149 setSurfaceType(OpenGLSurface);
150 break;
151 case Vulkan:
152 setSurfaceType(VulkanSurface);
153 break;
154 case D3D11:
155 case D3D12:
156 setSurfaceType(Direct3DSurface);
157 break;
158 case Metal:
159 setSurfaceType(MetalSurface);
160 break;
161 default:
162 break;
163 }
164
165 m_clearColor = transparentBackground ? Qt::transparent : QColor::fromRgbF(0.4f, 0.7f, 0.0f, 1.0f);
166 }
167
168 Window::~Window()
169 {
170 releaseResources();
171 }
172
173 void Window::exposeEvent(QExposeEvent *)
174 {
175 // initialize and start rendering when the window becomes usable for graphics purposes
176 if (isExposed() && !m_running) {
177 m_running = true;
178 init();
179 resizeSwapChain();
180 }
181
182 const QSize surfaceSize = m_hasSwapChain ? m_sc->surfacePixelSize() : QSize();
183
184 // stop pushing frames when not exposed (or size is 0)
185 if ((!isExposed() || (m_hasSwapChain && surfaceSize.isEmpty())) && m_running)
186 m_notExposed = true;
187
188 // continue when exposed again and the surface has a valid size.
189 // note that the surface size can be (0, 0) even though size() reports a valid one...
190 if (isExposed() && m_running && m_notExposed && !surfaceSize.isEmpty()) {
191 m_notExposed = false;
192 m_newlyExposed = true;
193 }
194
195 // always render a frame on exposeEvent() (when exposed) in order to update
196 // immediately on window resize.
197 if (isExposed() && !surfaceSize.isEmpty())
198 render();
199 }
200
201 bool Window::event(QEvent *e)
202 {
203 switch (e->type()) {
204 case QEvent::UpdateRequest:
205 render();
206 break;
207
208 case QEvent::PlatformSurface:
209 // this is the proper time to tear down the swapchain (while the native window and surface are still around)
210 if (static_cast<QPlatformSurfaceEvent *>(e)->surfaceEventType() == QPlatformSurfaceEvent::SurfaceAboutToBeDestroyed)
211 releaseSwapChain();
212 break;
213
214 default:
215 #ifdef EXAMPLEFW_IMGUI
216 if (m_imgui.processEvent(e))
217 return true;
218 #endif
219 break;
220 }
221
222 return QWindow::event(e);
223 }
224
225 void Window::init()
226 {
227 QRhi::AdapterList adapters;
228
229 if (graphicsApi == Null) {
230 QRhiNullInitParams params;
231 m_r = QRhi::create(QRhi::Null, &params, rhiFlags);
232 }
233
234 #ifndef QT_NO_OPENGL
235 if (graphicsApi == OpenGL) {
236 m_fallbackSurface = QRhiGles2InitParams::newFallbackSurface();
237 QRhiGles2InitParams params;
238 params.fallbackSurface = m_fallbackSurface;
239 params.window = this;
240 m_r = QRhi::create(QRhi::OpenGLES2, &params, rhiFlags);
241 }
242 #endif
243
244 #if QT_CONFIG(vulkan)
245 if (graphicsApi == Vulkan) {
246 QRhiVulkanInitParams params;
247 params.inst = vulkanInstance();
248 params.window = this;
249 adapters = QRhi::enumerateAdapters(QRhi::Vulkan, &params);
250 m_r = QRhi::create(QRhi::Vulkan, &params, rhiFlags);
251 }
252 #endif
253
254 #ifdef Q_OS_WIN
255 if (graphicsApi == D3D11) {
256 QRhiD3D11InitParams params;
257 if (debugLayer)
258 qDebug("Enabling D3D11 debug layer");
259 params.enableDebugLayer = debugLayer;
260 adapters = QRhi::enumerateAdapters(QRhi::D3D11, &params);
261 m_r = QRhi::create(QRhi::D3D11, &params, rhiFlags);
262 } else if (graphicsApi == D3D12) {
263 QRhiD3D12InitParams params;
264 if (debugLayer)
265 qDebug("Enabling D3D12 debug layer");
266 params.enableDebugLayer = debugLayer;
267 adapters = QRhi::enumerateAdapters(QRhi::D3D12, &params);
268 m_r = QRhi::create(QRhi::D3D12, &params, rhiFlags);
269 }
270 #endif
271
272 #if QT_CONFIG(metal)
273 if (graphicsApi == Metal) {
274 QRhiMetalInitParams params;
275 m_r = QRhi::create(QRhi::Metal, &params, rhiFlags);
276 }
277 #endif
278
279 if (!adapters.isEmpty()) {
280 qDebug() << "For information, enumerateAdapters() reports:";
281 for (qsizetype i = 0; i < adapters.count(); ++i)
282 qDebug() << " QRhiAdapter #" << i << ":" << adapters[i]->info();
283 }
284
285 if (!m_r)
286 qFatal("Failed to create RHI backend");
287
288 // now onto the backend-independent init
289
290 m_sc = m_r->newSwapChain();
291 m_ds = m_r->newRenderBuffer(QRhiRenderBuffer::DepthStencil,
292 QSize(), // no need to set the size here, due to UsedWithSwapChainOnly
293 sampleCount,
294 QRhiRenderBuffer::UsedWithSwapChainOnly);
295 m_sc->setWindow(this);
296 m_sc->setDepthStencil(m_ds);
297 m_sc->setSampleCount(sampleCount);
298 m_sc->setFlags(scFlags);
299 if (!m_sc->isFormatSupported(swapchainFormat))
300 qWarning("Swapchain reports that requested format %d is not supported", int(swapchainFormat));
301 else
302 m_sc->setFormat(swapchainFormat);
303 m_rp = m_sc->newCompatibleRenderPassDescriptor();
304 m_sc->setRenderPassDescriptor(m_rp);
305
306 #ifdef EXAMPLEFW_IMGUI
307 ImGuiIO &io(ImGui::GetIO());
308 io.FontAllowUserScaling = true; // enable ctrl+wheel on windows
309 io.IniFilename = nullptr; // no imgui.ini
310
311 QByteArray font = getResource(QLatin1String(":/fonts/RobotoMono-Medium.ttf"));
312 ImFontConfig fontCfg;
313 fontCfg.FontDataOwnedByAtlas = false;
314 io.Fonts->Clear();
315 io.Fonts->AddFontFromMemoryTTF(font.data(), font.size(), 20.0f, &fontCfg);
316 m_imgui.rebuildFontAtlas();
317
318 m_imguiRenderer = new QRhiImguiRenderer;
319 #endif
320
321 customInit();
322 }
323
324 void Window::releaseResources()
325 {
326 customRelease();
327
328 delete m_rp;
329 m_rp = nullptr;
330
331 delete m_ds;
332 m_ds = nullptr;
333
334 delete m_sc;
335 m_sc = nullptr;
336
337 #ifdef EXAMPLEFW_IMGUI
338 delete m_imguiRenderer;
339 m_imguiRenderer = nullptr;
340 #endif
341
342 delete m_r;
343 m_r = nullptr;
344
345 #ifndef QT_NO_OPENGL
346 delete m_fallbackSurface;
347 m_fallbackSurface = nullptr;
348 #endif
349 }
350
351 void Window::resizeSwapChain()
352 {
353 m_hasSwapChain = m_sc->createOrResize(); // also handles m_ds
354
355 m_frameCount = 0;
356 m_timer.restart();
357
358 const QSize outputSize = m_sc->currentPixelSize();
359 m_proj = m_r->clipSpaceCorrMatrix();
360 m_proj.perspective(45.0f, outputSize.width() / (float) outputSize.height(), 0.01f, 1000.0f);
361 m_proj.translate(0, 0, -4);
362 }
363
364 void Window::releaseSwapChain()
365 {
366 if (m_hasSwapChain) {
367 m_hasSwapChain = false;
368 m_sc->destroy();
369 }
370 }
371
372 void Window::render()
373 {
374 if (!m_hasSwapChain || m_notExposed)
375 return;
376
377 #ifdef EXAMPLEFW_BEFORE_FRAME
378 customBeforeFrame();
379 #endif
380
381 // If the window got resized or got newly exposed, resize the swapchain.
382 // (the newly-exposed case is not actually required by some
383 // platforms/backends, but f.ex. Vulkan on Windows seems to need it)
384 if (m_sc->currentPixelSize() != m_sc->surfacePixelSize() || m_newlyExposed) {
385 resizeSwapChain();
386 if (!m_hasSwapChain)
387 return;
388 m_newlyExposed = false;
389 }
390
391 // Start a new frame. This is where we block when too far ahead of
392 // GPU/present, and that's what throttles the thread to the refresh rate.
393 // (except for OpenGL where it happens either in endFrame or somewhere else
394 // depending on the GL implementation)
395 QRhi::FrameOpResult r = m_r->beginFrame(m_sc, beginFrameFlags);
396 if (r == QRhi::FrameOpSwapChainOutOfDate) {
397 resizeSwapChain();
398 if (!m_hasSwapChain)
399 return;
400 r = m_r->beginFrame(m_sc);
401 }
402 if (r != QRhi::FrameOpSuccess) {
403 requestUpdate();
404 return;
405 }
406
407 m_frameCount += 1;
408 if (m_timer.elapsed() > 1000) {
409 qDebug("ca. %d fps", m_frameCount);
410 m_timer.restart();
411 m_frameCount = 0;
412 }
413
414 #ifdef EXAMPLEFW_IMGUI
415 m_imgui.nextFrame(size(), devicePixelRatio(), QPointF(0, 0), std::bind(&Window::customGui, this));
416 m_imgui.syncRenderer(m_imguiRenderer);
417
418 QRhiCommandBuffer *cb = m_sc->currentFrameCommandBuffer();
419 QRhiRenderTarget *rt = m_sc->currentFrameRenderTarget();
420 const QSize outputSizeInPixels = m_sc->currentPixelSize();
421 const float dpr = devicePixelRatio();
422
423 QMatrix4x4 guiMvp = m_r->clipSpaceCorrMatrix();
424 guiMvp.ortho(0, outputSizeInPixels.width() / dpr, outputSizeInPixels.height() / dpr, 0, 1, -1);
425 m_imguiRenderer->prepare(m_r, rt, cb, guiMvp, 1.0f, imguiHDRMultiplier);
426 #endif
427
428 customRender();
429
430 m_r->endFrame(m_sc, endFrameFlags);
431
432 if (!scFlags.testFlag(QRhiSwapChain::NoVSync))
433 requestUpdate();
434 else // try prevent all delays when NoVSync
435 QCoreApplication::postEvent(this, new QEvent(QEvent::UpdateRequest));
436 }
437
438 int main(int argc, char **argv)
439 {
440 QGuiApplication app(argc, argv);
441
442 QLoggingCategory::setFilterRules(QLatin1String("qt.rhi.general=true"));
443
444 // Defaults.
445 #if defined(Q_OS_WIN)
446 graphicsApi = D3D11;
447 #elif QT_CONFIG(metal)
448 graphicsApi = Metal;
449 #elif QT_CONFIG(vulkan)
450 graphicsApi = Vulkan;
451 #else
452 graphicsApi = OpenGL;
453 #endif
454
455 // Allow overriding via the command line.
456 QCommandLineParser cmdLineParser;
457 cmdLineParser.addHelpOption();
458 QCommandLineOption nullOption({ "n", "null" }, QLatin1String("Null"));
459 cmdLineParser.addOption(nullOption);
460 QCommandLineOption glOption({ "g", "opengl" }, QLatin1String("OpenGL"));
461 cmdLineParser.addOption(glOption);
462 QCommandLineOption vkOption({ "v", "vulkan" }, QLatin1String("Vulkan"));
463 cmdLineParser.addOption(vkOption);
464 QCommandLineOption d3d11Option({ "d", "d3d11" }, QLatin1String("Direct3D 11"));
465 cmdLineParser.addOption(d3d11Option);
466 QCommandLineOption d3d12Option({ "D", "d3d12" }, QLatin1String("Direct3D 12"));
467 cmdLineParser.addOption(d3d12Option);
468 QCommandLineOption mtlOption({ "m", "metal" }, QLatin1String("Metal"));
469 cmdLineParser.addOption(mtlOption);
470 // Testing cleanup both with QWindow::close() (hitting X or Alt-F4) and
471 // QCoreApplication::quit() (e.g. what a menu widget would do) is important.
472 // Use this parameter for the latter.
473 QCommandLineOption sdOption({ "s", "self-destruct" }, QLatin1String("Self-destruct after 5 seconds."));
474 cmdLineParser.addOption(sdOption);
475 QCommandLineOption coreProfOption({ "c", "core" }, QLatin1String("Request a core profile context for OpenGL"));
476 cmdLineParser.addOption(coreProfOption);
477 // Allow testing preferring the software adapter (D3D, Vulkan).
478 QCommandLineOption swOption(QLatin1String("software"), QLatin1String("Prefer a software renderer when choosing the adapter. "
479 "Only applicable with some APIs and platforms."));
480 cmdLineParser.addOption(swOption);
481 // Allow testing having a semi-transparent window.
482 QCommandLineOption transparentOption(QLatin1String("transparent"), QLatin1String("Make background transparent"));
483 cmdLineParser.addOption(transparentOption);
484
485 cmdLineParser.process(app);
486 if (cmdLineParser.isSet(nullOption))
487 graphicsApi = Null;
488 if (cmdLineParser.isSet(glOption))
489 graphicsApi = OpenGL;
490 if (cmdLineParser.isSet(vkOption))
491 graphicsApi = Vulkan;
492 if (cmdLineParser.isSet(d3d11Option))
493 graphicsApi = D3D11;
494 if (cmdLineParser.isSet(d3d12Option))
495 graphicsApi = D3D12;
496 if (cmdLineParser.isSet(mtlOption))
497 graphicsApi = Metal;
498
499 qDebug("Selected graphics API is %s", qPrintable(graphicsApiName()));
500 qDebug("This is a multi-api example, use command line arguments to override:\n%s", qPrintable(cmdLineParser.helpText()));
501
502 if (cmdLineParser.isSet(transparentOption)) {
503 transparentBackground = true;
504 scFlags |= QRhiSwapChain::SurfaceHasPreMulAlpha;
505 }
506
507 #ifdef EXAMPLEFW_PREINIT
508 void preInit();
509 preInit();
510 #endif
511
512 // OpenGL specifics.
513 QSurfaceFormat fmt;
514 fmt.setDepthBufferSize(24);
515 fmt.setStencilBufferSize(8);
516 if (cmdLineParser.isSet(coreProfOption)) {
517 #ifdef Q_OS_DARWIN
518 fmt.setVersion(4, 1);
519 #else
520 fmt.setVersion(4, 3);
521 #endif
522 fmt.setProfile(QSurfaceFormat::CoreProfile);
523 }
524 if (sampleCount > 1)
525 fmt.setSamples(sampleCount);
526 if (scFlags.testFlag(QRhiSwapChain::NoVSync))
527 fmt.setSwapInterval(0);
528 if (scFlags.testFlag(QRhiSwapChain::sRGB))
529 fmt.setColorSpace(QColorSpace::SRgb);
530 // Exception: The alpha size is not necessarily OpenGL specific.
531 if (transparentBackground)
532 fmt.setAlphaBufferSize(8);
533 QSurfaceFormat::setDefaultFormat(fmt);
534
535 // Vulkan setup.
536 #if QT_CONFIG(vulkan)
537 QVulkanInstance inst;
538 if (graphicsApi == Vulkan) {
539 if (debugLayer) {
540 qDebug("Enabling Vulkan validation layer (if available)");
541 inst.setLayers({ "VK_LAYER_KHRONOS_validation" });
542 }
543 const QVersionNumber supportedVersion = inst.supportedApiVersion();
544 if (supportedVersion >= QVersionNumber(1, 3))
545 inst.setApiVersion(QVersionNumber(1, 3));
546 else if (supportedVersion >= QVersionNumber(1, 2))
547 inst.setApiVersion(QVersionNumber(1, 2));
548 else if (supportedVersion >= QVersionNumber(1, 1))
549 inst.setApiVersion(QVersionNumber(1, 1));
550 qDebug() << "Requesting Vulkan API" << inst.apiVersion().toString();
551 qDebug() << "Instance-level version was reported as" << supportedVersion.toString();
552 inst.setExtensions(QRhiVulkanInitParams::preferredInstanceExtensions());
553 if (!inst.create()) {
554 qWarning("Failed to create Vulkan instance, switching to OpenGL");
555 graphicsApi = OpenGL;
556 }
557 }
558 #endif
559
560 if (cmdLineParser.isSet(swOption))
561 rhiFlags |= QRhi::PreferSoftwareRenderer;
562
563 // Create and show the window.
564 Window w;
565 #if QT_CONFIG(vulkan)
566 if (graphicsApi == Vulkan)
567 w.setVulkanInstance(&inst);
568 #endif
569 w.resize(1280, 720);
570 w.setTitle(QCoreApplication::applicationName() + QLatin1String(" - ") + graphicsApiName());
571 w.show();
572
573 if (cmdLineParser.isSet(sdOption))
574 QTimer::singleShot(5000, qGuiApp, SLOT(quit()));
575
576 int ret = app.exec();
577
578 // Window::event() will not get invoked when the
579 // PlatformSurfaceAboutToBeDestroyed event is sent during the QWindow
580 // destruction. That happens only when exiting via app::quit() instead of
581 // the more common QWindow::close(). Take care of it: if the
582 // QPlatformWindow is still around (there was no close() yet), get rid of
583 // the swapchain while it's not too late.
584 if (w.handle())
585 w.releaseSwapChain();
586
587 return ret;
588 }