Debian Codegraph @

tests/manual/rhi/multiwindow/multiwindow.cpp

raw
1 // Copyright (C) 2018 The Qt Company Ltd.
2 // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
3
4 #include <QApplication>
5 #include <QWidget>
6 #include <QLabel>
7 #include <QPlainTextEdit>
8 #include <QPushButton>
9 #include <QCheckBox>
10 #include <QVBoxLayout>
11
12 #include <QCommandLineParser>
13 #include <QWindow>
14 #include <QPlatformSurfaceEvent>
15 #include <QElapsedTimer>
16 #include <QFile>
17 #include <QLoggingCategory>
18 #include <QOffscreenSurface>
19 #include <rhi/qrhi.h>
20
21 enum GraphicsApi
22 {
23 OpenGL,
24 Vulkan,
25 D3D11,
26 D3D12,
27 Metal
28 };
29
30 static GraphicsApi graphicsApi;
31
32 static QString graphicsApiName()
33 {
34 switch (graphicsApi) {
35 case OpenGL:
36 return QLatin1String("OpenGL 2.x");
37 case Vulkan:
38 return QLatin1String("Vulkan");
39 case D3D11:
40 return QLatin1String("Direct3D 11");
41 case D3D12:
42 return QLatin1String("Direct3D 12");
43 case Metal:
44 return QLatin1String("Metal");
45 default:
46 break;
47 }
48 return QString();
49 }
50
51 static struct {
52 #if QT_CONFIG(vulkan)
53 QVulkanInstance *instance = nullptr;
54 #endif
55 QRhi *r = nullptr;
56 #ifndef QT_NO_OPENGL
57 QOffscreenSurface *fallbackSurface = nullptr;
58 #endif
59 } r;
60
61 void createRhi()
62 {
63 #ifndef QT_NO_OPENGL
64 if (graphicsApi == OpenGL) {
65 r.fallbackSurface = QRhiGles2InitParams::newFallbackSurface();
66 QRhiGles2InitParams params;
67 params.fallbackSurface = r.fallbackSurface;
68 //params.window = this;
69 r.r = QRhi::create(QRhi::OpenGLES2, &params);
70 }
71 #endif
72
73 #if QT_CONFIG(vulkan)
74 if (graphicsApi == Vulkan) {
75 QRhiVulkanInitParams params;
76 params.inst = r.instance;
77 //params.window = this;
78 r.r = QRhi::create(QRhi::Vulkan, &params);
79 }
80 #endif
81
82 #ifdef Q_OS_WIN
83 if (graphicsApi == D3D11) {
84 QRhiD3D11InitParams params;
85 params.enableDebugLayer = true;
86 r.r = QRhi::create(QRhi::D3D11, &params);
87 } else if (graphicsApi == D3D12) {
88 QRhiD3D12InitParams params;
89 params.enableDebugLayer = true;
90 r.r = QRhi::create(QRhi::D3D12, &params);
91 }
92 #endif
93
94 #if QT_CONFIG(metal)
95 if (graphicsApi == Metal) {
96 QRhiMetalInitParams params;
97 r.r = QRhi::create(QRhi::Metal, &params);
98 }
99 #endif
100
101 if (!r.r)
102 qFatal("Failed to create RHI backend");
103 }
104
105 void destroyRhi()
106 {
107 delete r.r;
108
109 #ifndef QT_NO_OPENGL
110 delete r.fallbackSurface;
111 #endif
112 }
113
114 struct {
115 QList<QWindow *> windows;
116
117 QRhiBuffer *vbuf = nullptr;
118 QRhiBuffer *ubuf = nullptr;
119 QRhiShaderResourceBindings *srb = nullptr;
120 QRhiGraphicsPipeline *ps = nullptr;
121 QRhiResourceUpdateBatch *initialUpdates = nullptr;
122 } d;
123
124 static float vertexData[] = {
125 0.0f, 0.5f, 1.0f, 0.0f, 0.0f,
126 -0.5f, -0.5f, 0.0f, 1.0f, 0.0f,
127 0.5f, -0.5f, 0.0f, 0.0f, 1.0f,
128 };
129
130 static QShader getShader(const QString &name)
131 {
132 QFile f(name);
133 if (f.open(QIODevice::ReadOnly))
134 return QShader::fromSerialized(f.readAll());
135
136 return QShader();
137 }
138
139 // can use just one rpd from whichever window comes first since they are
140 // actually compatible due to all windows using the same config (have
141 // depth-stencil, sample count 1, same format). this means the same pso can be
142 // reused too.
143 void ensureSharedResources(QRhiRenderPassDescriptor *rp)
144 {
145 if (!d.vbuf) {
146 d.vbuf = r.r->newBuffer(QRhiBuffer::Immutable, QRhiBuffer::VertexBuffer, sizeof(vertexData));
147 d.vbuf->create();
148 d.initialUpdates = r.r->nextResourceUpdateBatch();
149 d.initialUpdates->uploadStaticBuffer(d.vbuf, vertexData);
150 }
151
152 if (!d.ubuf) {
153 d.ubuf = r.r->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::UniformBuffer, 68);
154 d.ubuf->create();
155 }
156
157 if (!d.srb) {
158 d.srb = r.r->newShaderResourceBindings();
159 d.srb->setBindings({
160 QRhiShaderResourceBinding::uniformBuffer(0, QRhiShaderResourceBinding::VertexStage | QRhiShaderResourceBinding::FragmentStage, d.ubuf)
161 });
162 d.srb->create();
163 }
164
165 if (!d.ps) {
166 d.ps = r.r->newGraphicsPipeline();
167
168 QRhiGraphicsPipeline::TargetBlend premulAlphaBlend;
169 premulAlphaBlend.enable = true;
170 d.ps->setTargetBlends({ premulAlphaBlend });
171
172 const QShader vs = getShader(QLatin1String(":/color.vert.qsb"));
173 if (!vs.isValid())
174 qFatal("Failed to load shader pack (vertex)");
175 const QShader fs = getShader(QLatin1String(":/color.frag.qsb"));
176 if (!fs.isValid())
177 qFatal("Failed to load shader pack (fragment)");
178
179 d.ps->setShaderStages({
180 { QRhiShaderStage::Vertex, vs },
181 { QRhiShaderStage::Fragment, fs }
182 });
183
184 QRhiVertexInputLayout inputLayout;
185 inputLayout.setBindings({
186 { 5 * sizeof(float) }
187 });
188 inputLayout.setAttributes({
189 { 0, 0, QRhiVertexInputAttribute::Float2, 0 },
190 { 0, 1, QRhiVertexInputAttribute::Float3, 2 * sizeof(float) }
191 });
192
193 d.ps->setVertexInputLayout(inputLayout);
194 d.ps->setShaderResourceBindings(d.srb);
195 d.ps->setRenderPassDescriptor(rp);
196
197 d.ps->create();
198 }
199 }
200
201 void destroySharedResources()
202 {
203 delete d.ps;
204 d.ps = nullptr;
205
206 delete d.srb;
207 d.srb = nullptr;
208
209 delete d.vbuf;
210 d.vbuf = nullptr;
211
212 delete d.ubuf;
213 d.ubuf = nullptr;
214 }
215
216 class Window : public QWindow
217 {
218 public:
219 Window(const QString &title, const QColor &bgColor, int axis, bool noVSync);
220 ~Window();
221
222 protected:
223 void init();
224 void releaseResources();
225 void resizeSwapChain();
226 void releaseSwapChain();
227 void render();
228
229 void exposeEvent(QExposeEvent *) override;
230 bool event(QEvent *) override;
231
232 QColor m_bgColor;
233 int m_rotationAxis;
234 bool m_noVSync;
235
236 bool m_running = false;
237 bool m_notExposed = false;
238 bool m_newlyExposed = false;
239
240 QMatrix4x4 m_proj;
241 QList<QRhiResource *> m_releasePool;
242
243 bool m_hasSwapChain = false;
244 QRhiSwapChain *m_sc = nullptr;
245 QRhiRenderBuffer *m_ds = nullptr;
246 QRhiRenderPassDescriptor *m_rp = nullptr;
247
248 float m_rotation = 0;
249 float m_opacity = 1;
250 int m_opacityDir = -1;
251 };
252
253 Window::Window(const QString &title, const QColor &bgColor, int axis, bool noVSync)
254 : m_bgColor(bgColor),
255 m_rotationAxis(axis),
256 m_noVSync(noVSync)
257 {
258 switch (graphicsApi) {
259 case OpenGL:
260 {
261 setSurfaceType(OpenGLSurface);
262 QSurfaceFormat fmt = QSurfaceFormat::defaultFormat();
263 fmt.setSwapInterval(noVSync ? 0 : 1);
264 setFormat(fmt);
265 }
266 break;
267 case Vulkan:
268 setSurfaceType(VulkanSurface);
269 #if QT_CONFIG(vulkan)
270 setVulkanInstance(r.instance);
271 #endif
272 break;
273 case D3D11:
274 case D3D12:
275 setSurfaceType(Direct3DSurface);
276 break;
277 case Metal:
278 setSurfaceType(MetalSurface);
279 break;
280 default:
281 break;
282 }
283
284 resize(800, 600);
285 setTitle(title);
286 }
287
288 Window::~Window()
289 {
290 releaseResources();
291 }
292
293 void Window::exposeEvent(QExposeEvent *)
294 {
295 // initialize and start rendering when the window becomes usable for graphics purposes
296 if (isExposed() && !m_running) {
297 m_running = true;
298 init();
299 resizeSwapChain();
300 }
301
302 // stop pushing frames when not exposed (or size is 0)
303 if ((!isExposed() || (m_hasSwapChain && m_sc->surfacePixelSize().isEmpty())) && m_running)
304 m_notExposed = true;
305
306 // continue when exposed again and the surface has a valid size.
307 // note that the surface size can be (0, 0) even though size() reports a valid one...
308 if (isExposed() && m_running && m_notExposed && !m_sc->surfacePixelSize().isEmpty()) {
309 m_notExposed = false;
310 m_newlyExposed = true;
311 }
312
313 // always render a frame on exposeEvent() (when exposed) in order to update
314 // immediately on window resize.
315 if (isExposed() && !m_sc->surfacePixelSize().isEmpty())
316 render();
317 }
318
319 bool Window::event(QEvent *e)
320 {
321 switch (e->type()) {
322 case QEvent::UpdateRequest:
323 render();
324 break;
325
326 case QEvent::PlatformSurface:
327 // this is the proper time to tear down the swapchain (while the native window and surface are still around)
328 if (static_cast<QPlatformSurfaceEvent *>(e)->surfaceEventType() == QPlatformSurfaceEvent::SurfaceAboutToBeDestroyed)
329 releaseSwapChain();
330 break;
331
332 default:
333 break;
334 }
335
336 return QWindow::event(e);
337 }
338
339 void Window::init()
340 {
341 m_sc = r.r->newSwapChain();
342 m_ds = r.r->newRenderBuffer(QRhiRenderBuffer::DepthStencil,
343 QSize(),
344 1,
345 QRhiRenderBuffer::UsedWithSwapChainOnly);
346 m_releasePool << m_ds;
347 m_sc->setWindow(this);
348 m_sc->setDepthStencil(m_ds);
349 if (m_noVSync)
350 m_sc->setFlags(QRhiSwapChain::NoVSync);
351
352 m_rp = m_sc->newCompatibleRenderPassDescriptor();
353 m_releasePool << m_rp;
354 m_sc->setRenderPassDescriptor(m_rp);
355
356 ensureSharedResources(m_rp);
357 }
358
359 void Window::releaseResources()
360 {
361 qDeleteAll(m_releasePool);
362 m_releasePool.clear();
363
364 delete m_sc;
365 m_sc = nullptr;
366 }
367
368 void Window::resizeSwapChain()
369 {
370 m_hasSwapChain = m_sc->createOrResize();
371
372 const QSize outputSize = m_sc->currentPixelSize();
373 m_proj = r.r->clipSpaceCorrMatrix();
374 m_proj.perspective(45.0f, outputSize.width() / (float) outputSize.height(), 0.01f, 1000.0f);
375 m_proj.translate(0, 0, -4);
376 }
377
378 void Window::releaseSwapChain()
379 {
380 if (m_hasSwapChain) {
381 m_hasSwapChain = false;
382 m_sc->destroy();
383 }
384 }
385
386 void Window::render()
387 {
388 if (!m_hasSwapChain || m_notExposed)
389 return;
390
391 // If the window got resized or got newly exposed, resize the swapchain.
392 // (the newly-exposed case is not actually required by some
393 // platforms/backends, but f.ex. Vulkan on Windows seems to need it)
394 if (m_sc->currentPixelSize() != m_sc->surfacePixelSize() || m_newlyExposed) {
395 resizeSwapChain();
396 if (!m_hasSwapChain)
397 return;
398 m_newlyExposed = false;
399 }
400
401 QRhi::FrameOpResult result = r.r->beginFrame(m_sc);
402 if (result == QRhi::FrameOpSwapChainOutOfDate) {
403 resizeSwapChain();
404 if (!m_hasSwapChain)
405 return;
406 result = r.r->beginFrame(m_sc);
407 }
408 if (result != QRhi::FrameOpSuccess) {
409 requestUpdate();
410 return;
411 }
412
413 QRhiCommandBuffer *cb = m_sc->currentFrameCommandBuffer();
414 const QSize outputSizeInPixels = m_sc->currentPixelSize();
415
416 QRhiResourceUpdateBatch *u = r.r->nextResourceUpdateBatch();
417 if (d.initialUpdates) {
418 u->merge(d.initialUpdates);
419 d.initialUpdates->release();
420 d.initialUpdates = nullptr;
421 }
422
423 m_rotation += 1.0f;
424 QMatrix4x4 mvp = m_proj;
425 mvp.rotate(m_rotation, m_rotationAxis == 0 ? 1 : 0, m_rotationAxis == 1 ? 1 : 0, m_rotationAxis == 2 ? 1 : 0);
426 u->updateDynamicBuffer(d.ubuf, 0, 64, mvp.constData());
427 m_opacity += m_opacityDir * 0.005f;
428 if (m_opacity < 0.0f || m_opacity > 1.0f) {
429 m_opacityDir *= -1;
430 m_opacity = qBound(0.0f, m_opacity, 1.0f);
431 }
432 u->updateDynamicBuffer(d.ubuf, 64, 4, &m_opacity);
433
434 cb->beginPass(m_sc->currentFrameRenderTarget(),
435 QColor::fromRgbF(float(m_bgColor.redF()), float(m_bgColor.greenF()), float(m_bgColor.blueF()), 1.0f),
436 { 1.0f, 0 },
437 u);
438
439 cb->setGraphicsPipeline(d.ps);
440 cb->setViewport({ 0, 0, float(outputSizeInPixels.width()), float(outputSizeInPixels.height()) });
441 cb->setShaderResources();
442 const QRhiCommandBuffer::VertexInput vbufBinding(d.vbuf, 0);
443 cb->setVertexInput(0, 1, &vbufBinding);
444 cb->draw(3);
445
446 cb->endPass();
447
448 r.r->endFrame(m_sc);
449
450 requestUpdate();
451 }
452
453 void createWindow(bool noVSync)
454 {
455 static QColor colors[] = { Qt::red, Qt::green, Qt::blue, Qt::yellow, Qt::cyan, Qt::gray };
456 const int n = d.windows.count();
457 d.windows.append(new Window(QString::asprintf("Window #%d%s", n, noVSync ? " (no vsync)" : ""), colors[n % 6], n % 3, noVSync));
458 d.windows.last()->show();
459 }
460
461 void closeWindow()
462 {
463 delete d.windows.takeLast();
464 }
465
466 int main(int argc, char **argv)
467 {
468 QApplication app(argc, argv);
469
470 #if defined(Q_OS_WIN)
471 graphicsApi = D3D11;
472 #elif QT_CONFIG(metal)
473 graphicsApi = Metal;
474 #elif QT_CONFIG(vulkan)
475 graphicsApi = Vulkan;
476 #else
477 graphicsApi = OpenGL;
478 #endif
479
480 QCommandLineParser cmdLineParser;
481 cmdLineParser.addHelpOption();
482 QCommandLineOption glOption({ "g", "opengl" }, QLatin1String("OpenGL (2.x)"));
483 cmdLineParser.addOption(glOption);
484 QCommandLineOption vkOption({ "v", "vulkan" }, QLatin1String("Vulkan"));
485 cmdLineParser.addOption(vkOption);
486 QCommandLineOption d3dOption({ "d", "d3d11" }, QLatin1String("Direct3D 11"));
487 cmdLineParser.addOption(d3dOption);
488 QCommandLineOption d3d12Option({ "D", "d3d12" }, QLatin1String("Direct3D 12"));
489 cmdLineParser.addOption(d3d12Option);
490 QCommandLineOption mtlOption({ "m", "metal" }, QLatin1String("Metal"));
491 cmdLineParser.addOption(mtlOption);
492 cmdLineParser.process(app);
493 if (cmdLineParser.isSet(glOption))
494 graphicsApi = OpenGL;
495 if (cmdLineParser.isSet(vkOption))
496 graphicsApi = Vulkan;
497 if (cmdLineParser.isSet(d3dOption))
498 graphicsApi = D3D11;
499 if (cmdLineParser.isSet(d3d12Option))
500 graphicsApi = D3D12;
501 if (cmdLineParser.isSet(mtlOption))
502 graphicsApi = Metal;
503
504 qDebug("Selected graphics API is %s", qPrintable(graphicsApiName()));
505 qDebug("This is a multi-api example, use command line arguments to override:\n%s", qPrintable(cmdLineParser.helpText()));
506
507 QSurfaceFormat fmt;
508 fmt.setDepthBufferSize(24);
509 QSurfaceFormat::setDefaultFormat(fmt);
510
511 #if QT_CONFIG(vulkan)
512 r.instance = new QVulkanInstance;
513 if (graphicsApi == Vulkan) {
514 r.instance->setLayers({ "VK_LAYER_KHRONOS_validation" });
515 r.instance->setExtensions(QRhiVulkanInitParams::preferredInstanceExtensions());
516 if (!r.instance->create()) {
517 qWarning("Failed to create Vulkan instance, switching to OpenGL");
518 graphicsApi = OpenGL;
519 }
520 }
521 #endif
522
523 createRhi();
524
525 int winCount = 0;
526 QWidget w;
527 w.resize(800, 600);
528 w.setWindowTitle(QCoreApplication::applicationName() + QLatin1String(" - ") + graphicsApiName());
529 QVBoxLayout *layout = new QVBoxLayout(&w);
530
531 QPlainTextEdit *info = new QPlainTextEdit(
532 QLatin1String("This application tests rendering with the same QRhi instance (and so the same Vulkan/Metal/D3D device or OpenGL context) "
533 "to multiple windows via multiple QRhiSwapChain objects, from the same one thread. Some resources are shared across all windows.\n"
534 "\nNote that the behavior may differ depending on the underlying graphics API implementation and the number of windows. "
535 "One challenge here is the vsync throttling: with the default vsync/fifo presentation mode the behavior may differ between "
536 "platforms, drivers, and APIs as we present different swapchains' images in a row on the same thread. As a potential solution, "
537 "setting NoVSync on the second, third, and later window swapchains is offered as an option.\n"
538 "\n\nUsing API: ") + graphicsApiName());
539 info->setReadOnly(true);
540 layout->addWidget(info);
541 QLabel *label = new QLabel(QLatin1String("Window count: 0"));
542 layout->addWidget(label);
543 QCheckBox *vsCb = new QCheckBox(QLatin1String("Set NoVSync on all swapchains except the first"));
544 vsCb->setChecked(false);
545 layout->addWidget(vsCb);
546 QPushButton *btn = new QPushButton(QLatin1String("New window"));
547 QObject::connect(btn, &QPushButton::clicked, btn, [label, vsCb, &winCount] {
548 winCount += 1;
549 label->setText(QString::asprintf("Window count: %d", winCount));
550 const bool noVSync = vsCb->isChecked() && winCount > 1;
551 createWindow(noVSync);
552 });
553 layout->addWidget(btn);
554 btn = new QPushButton(QLatin1String("Close window"));
555 QObject::connect(btn, &QPushButton::clicked, btn, [label, &winCount] {
556 if (winCount > 0) {
557 winCount -= 1;
558 label->setText(QString::asprintf("Window count: %d", winCount));
559 closeWindow();
560 }
561 });
562 layout->addWidget(btn);
563 w.show();
564
565 int result = app.exec();
566
567 qDeleteAll(d.windows);
568
569 destroySharedResources();
570 destroyRhi();
571
572 #if QT_CONFIG(vulkan)
573 delete r.instance;
574 #endif
575
576 return result;
577 }