Debian Codegraph @

tests/manual/rhi/multiwindow_threaded/multiwindow_threaded.cpp

raw
1 /****************************************************************************
2 **
3 ** Copyright (C) 2018 The Qt Company Ltd.
4 ** Contact: https://www.qt.io/licensing/
5 **
6 ** This file is part of the examples of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:BSD$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and The Qt Company. For licensing terms
14 ** and conditions see https://www.qt.io/terms-conditions. For further
15 ** information use the contact form at https://www.qt.io/contact-us.
16 **
17 ** BSD License Usage
18 ** Alternatively, you may use this file under the terms of the BSD license
19 ** as follows:
20 **
21 ** "Redistribution and use in source and binary forms, with or without
22 ** modification, are permitted provided that the following conditions are
23 ** met:
24 ** * Redistributions of source code must retain the above copyright
25 ** notice, this list of conditions and the following disclaimer.
26 ** * Redistributions in binary form must reproduce the above copyright
27 ** notice, this list of conditions and the following disclaimer in
28 ** the documentation and/or other materials provided with the
29 ** distribution.
30 ** * Neither the name of The Qt Company Ltd nor the names of its
31 ** contributors may be used to endorse or promote products derived
32 ** from this software without specific prior written permission.
33 **
34 **
35 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
36 ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37 ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
38 ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
39 ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41 ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
42 ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
43 ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
44 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
45 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
46 **
47 ** $QT_END_LICENSE$
48 **
49 ****************************************************************************/
50
51 #include <QApplication>
52 #include <QWidget>
53 #include <QLabel>
54 #include <QPlainTextEdit>
55 #include <QPushButton>
56 #include <QCheckBox>
57 #include <QVBoxLayout>
58
59 #include <QThread>
60 #include <QMutex>
61 #include <QWaitCondition>
62 #include <QQueue>
63 #include <QEvent>
64 #include <QCommandLineParser>
65 #include <QElapsedTimer>
66
67 #include <QtGui/private/qshader_p.h>
68 #include <QFile>
69 #include <QtGui/private/qrhiprofiler_p.h>
70
71 #ifndef QT_NO_OPENGL
72 #include <QtGui/private/qrhigles2_p.h>
73 #include <QOffscreenSurface>
74 #endif
75
76 #if QT_CONFIG(vulkan)
77 #include <QLoggingCategory>
78 #include <QtGui/private/qrhivulkan_p.h>
79 #endif
80
81 #ifdef Q_OS_WIN
82 #include <QtGui/private/qrhid3d11_p.h>
83 #endif
84
85 #if defined(Q_OS_MACOS) || defined(Q_OS_IOS)
86 #include <QtGui/private/qrhimetal_p.h>
87 #endif
88
89 #include "window.h"
90
91 #include "../shared/cube.h"
92
93 static QShader getShader(const QString &name)
94 {
95 QFile f(name);
96 if (f.open(QIODevice::ReadOnly))
97 return QShader::fromSerialized(f.readAll());
98
99 return QShader();
100 }
101
102 static GraphicsApi graphicsApi;
103
104 static QString graphicsApiName()
105 {
106 switch (graphicsApi) {
107 case OpenGL:
108 return QLatin1String("OpenGL 2.x");
109 case Vulkan:
110 return QLatin1String("Vulkan");
111 case D3D11:
112 return QLatin1String("Direct3D 11");
113 case Metal:
114 return QLatin1String("Metal");
115 default:
116 break;
117 }
118 return QString();
119 }
120
121 #if QT_CONFIG(vulkan)
122 QVulkanInstance *instance = nullptr;
123 #endif
124
125 // Window (main thread) emit signals -> Renderer::send* (main thread) -> event queue (add on main, process on render thread) -> Renderer::renderEvent (render thread)
126
127 // event queue is taken from the Qt Quick scenegraph as-is
128 // all this below is conceptually the same as the QSG threaded render loop
129 class RenderThreadEventQueue : public QQueue<QEvent *>
130 {
131 public:
132 RenderThreadEventQueue()
133 : waiting(false)
134 {
135 }
136
137 void addEvent(QEvent *e) {
138 mutex.lock();
139 enqueue(e);
140 if (waiting)
141 condition.wakeOne();
142 mutex.unlock();
143 }
144
145 QEvent *takeEvent(bool wait) {
146 mutex.lock();
147 if (isEmpty() && wait) {
148 waiting = true;
149 condition.wait(&mutex);
150 waiting = false;
151 }
152 QEvent *e = dequeue();
153 mutex.unlock();
154 return e;
155 }
156
157 bool hasMoreEvents() {
158 mutex.lock();
159 bool has = !isEmpty();
160 mutex.unlock();
161 return has;
162 }
163
164 private:
165 QMutex mutex;
166 QWaitCondition condition;
167 bool waiting;
168 };
169
170 struct Renderer;
171
172 struct Thread : public QThread
173 {
174 Thread(Renderer *renderer_)
175 : renderer(renderer_)
176 {
177 active = true;
178 start();
179 }
180 void run() override;
181
182 Renderer *renderer;
183 bool active;
184 RenderThreadEventQueue eventQueue;
185 bool sleeping = false;
186 bool stopEventProcessing = false;
187 bool pendingRender = false;
188 bool pendingRenderIsNewExpose = false;
189 // mutex and cond used to allow the main thread waiting until something completes on the render thread
190 QMutex mutex;
191 QWaitCondition cond;
192 };
193
194 class RenderThreadEvent : public QEvent
195 {
196 public:
197 RenderThreadEvent(QEvent::Type type) : QEvent(type) { }
198 };
199
200 class InitEvent : public RenderThreadEvent
201 {
202 public:
203 static const QEvent::Type TYPE = QEvent::Type(QEvent::User + 1);
204 InitEvent() : RenderThreadEvent(TYPE)
205 { }
206 };
207
208 class RequestRenderEvent : public RenderThreadEvent
209 {
210 public:
211 static const QEvent::Type TYPE = QEvent::Type(QEvent::User + 2);
212 RequestRenderEvent(bool newlyExposed_) : RenderThreadEvent(TYPE), newlyExposed(newlyExposed_)
213 { }
214 bool newlyExposed;
215 };
216
217 class SurfaceCleanupEvent : public RenderThreadEvent
218 {
219 public:
220 static const QEvent::Type TYPE = QEvent::Type(QEvent::User + 3);
221 SurfaceCleanupEvent() : RenderThreadEvent(TYPE)
222 { }
223 };
224
225 class CloseEvent : public RenderThreadEvent
226 {
227 public:
228 static const QEvent::Type TYPE = QEvent::Type(QEvent::User + 4);
229 CloseEvent() : RenderThreadEvent(TYPE)
230 { }
231 };
232
233 class SyncSurfaceSizeEvent : public RenderThreadEvent
234 {
235 public:
236 static const QEvent::Type TYPE = QEvent::Type(QEvent::User + 5);
237 SyncSurfaceSizeEvent() : RenderThreadEvent(TYPE)
238 { }
239 };
240
241 struct Renderer
242 {
243 // ctor and dtor and send* are called main thread, rest on the render thread
244
245 Renderer(QWindow *w, const QColor &bgColor, int rotationAxis);
246 ~Renderer();
247
248 void sendInit();
249 void sendRender(bool newlyExposed);
250 void sendSurfaceGoingAway();
251 void sendSyncSurfaceSize();
252
253 QWindow *window;
254 Thread *thread;
255 QRhi *r = nullptr;
256 #ifndef QT_NO_OPENGL
257 QOffscreenSurface *fallbackSurface = nullptr;
258 #endif
259
260 void createRhi();
261 void destroyRhi();
262 void renderEvent(QEvent *e);
263 void init();
264 void releaseSwapChain();
265 void releaseResources();
266 void render(bool newlyExposed, bool wakeBeforePresent);
267
268 QColor m_bgColor;
269 int m_rotationAxis;
270
271 QVector<QRhiResource *> m_releasePool;
272 bool m_hasSwapChain = false;
273 QRhiSwapChain *m_sc = nullptr;
274 QRhiRenderBuffer *m_ds = nullptr;
275 QRhiRenderPassDescriptor *m_rp = nullptr;
276
277 QRhiBuffer *m_vbuf = nullptr;
278 QRhiBuffer *m_ubuf = nullptr;
279 QRhiTexture *m_tex = nullptr;
280 QRhiSampler *m_sampler = nullptr;
281 QRhiShaderResourceBindings *m_srb = nullptr;
282 QRhiGraphicsPipeline *m_ps = nullptr;
283 QRhiResourceUpdateBatch *m_initialUpdates = nullptr;
284
285 QMatrix4x4 m_proj;
286 float m_rotation = 0;
287 int m_frameCount = 0;
288 };
289
290 void Thread::run()
291 {
292 while (active) {
293 #ifdef Q_OS_DARWIN
294 QMacAutoReleasePool autoReleasePool;
295 #endif
296
297 if (pendingRender) {
298 pendingRender = false;
299 renderer->render(pendingRenderIsNewExpose, false);
300 }
301
302 while (eventQueue.hasMoreEvents()) {
303 QEvent *e = eventQueue.takeEvent(false);
304 renderer->renderEvent(e);
305 delete e;
306 }
307
308 if (active && !pendingRender) {
309 sleeping = true;
310 stopEventProcessing = false;
311 while (!stopEventProcessing) {
312 QEvent *e = eventQueue.takeEvent(true);
313 renderer->renderEvent(e);
314 delete e;
315 }
316 sleeping = false;
317 }
318 }
319 }
320
321 Renderer::Renderer(QWindow *w, const QColor &bgColor, int rotationAxis)
322 : window(w),
323 m_bgColor(bgColor),
324 m_rotationAxis(rotationAxis)
325 { // main thread
326 thread = new Thread(this);
327
328 #ifndef QT_NO_OPENGL
329 if (graphicsApi == OpenGL)
330 fallbackSurface = QRhiGles2InitParams::newFallbackSurface();
331 #endif
332 }
333
334 Renderer::~Renderer()
335 { // main thread
336 thread->eventQueue.addEvent(new CloseEvent);
337 thread->wait();
338 delete thread;
339
340 #ifndef QT_NO_OPENGL
341 delete fallbackSurface;
342 #endif
343 }
344
345 void Renderer::createRhi()
346 {
347 if (r)
348 return;
349
350 qDebug() << "renderer" << this << "creating rhi";
351 QRhi::Flags rhiFlags = QRhi::EnableProfiling;
352
353 #ifndef QT_NO_OPENGL
354 if (graphicsApi == OpenGL) {
355 QRhiGles2InitParams params;
356 params.fallbackSurface = fallbackSurface;
357 params.window = window;
358 r = QRhi::create(QRhi::OpenGLES2, &params, rhiFlags);
359 }
360 #endif
361
362 #if QT_CONFIG(vulkan)
363 if (graphicsApi == Vulkan) {
364 QRhiVulkanInitParams params;
365 params.inst = instance;
366 params.window = window;
367 r = QRhi::create(QRhi::Vulkan, &params, rhiFlags);
368 }
369 #endif
370
371 #ifdef Q_OS_WIN
372 if (graphicsApi == D3D11) {
373 QRhiD3D11InitParams params;
374 params.enableDebugLayer = true;
375 r = QRhi::create(QRhi::D3D11, &params, rhiFlags);
376 }
377 #endif
378
379 #if defined(Q_OS_MACOS) || defined(Q_OS_IOS)
380 if (graphicsApi == Metal) {
381 QRhiMetalInitParams params;
382 r = QRhi::create(QRhi::Metal, &params, rhiFlags);
383 }
384 #endif
385
386 if (!r)
387 qFatal("Failed to create RHI backend");
388 }
389
390 void Renderer::destroyRhi()
391 {
392 qDebug() << "renderer" << this << "destroying rhi";
393 delete r;
394 r = nullptr;
395 }
396
397 void Renderer::renderEvent(QEvent *e)
398 {
399 Q_ASSERT(QThread::currentThread() == thread);
400
401 if (thread->sleeping)
402 thread->stopEventProcessing = true;
403
404 switch (int(e->type())) {
405 case InitEvent::TYPE:
406 qDebug() << "renderer" << this << "for window" << window << "is initializing";
407 createRhi();
408 init();
409 break;
410 case RequestRenderEvent::TYPE:
411 thread->pendingRender = true;
412 thread->pendingRenderIsNewExpose = static_cast<RequestRenderEvent *>(e)->newlyExposed;
413 break;
414 case SurfaceCleanupEvent::TYPE: // when the QWindow is closed, before QPlatformWindow goes away
415 thread->mutex.lock();
416 qDebug() << "renderer" << this << "for window" << window << "is destroying swapchain";
417 thread->pendingRender = false;
418 releaseSwapChain();
419 thread->cond.wakeOne();
420 thread->mutex.unlock();
421 break;
422 case CloseEvent::TYPE: // when destroying the window+renderer (NB not the same as hitting X on the window, that's just QWindow close)
423 qDebug() << "renderer" << this << "for window" << window << "is shutting down";
424 thread->pendingRender = false;
425 thread->active = false;
426 thread->stopEventProcessing = true;
427 releaseResources();
428 destroyRhi();
429 break;
430 case SyncSurfaceSizeEvent::TYPE:
431 thread->mutex.lock();
432 thread->pendingRender = false;
433 render(false, true);
434 break;
435 default:
436 break;
437 }
438 }
439
440 void Renderer::init()
441 {
442 m_sc = r->newSwapChain();
443 m_ds = r->newRenderBuffer(QRhiRenderBuffer::DepthStencil,
444 QSize(),
445 1,
446 QRhiRenderBuffer::UsedWithSwapChainOnly);
447 m_releasePool << m_ds;
448 m_sc->setWindow(window);
449 m_sc->setDepthStencil(m_ds);
450 m_rp = m_sc->newCompatibleRenderPassDescriptor();
451 m_releasePool << m_rp;
452 m_sc->setRenderPassDescriptor(m_rp);
453
454 m_vbuf = r->newBuffer(QRhiBuffer::Immutable, QRhiBuffer::VertexBuffer, sizeof(cube));
455 m_releasePool << m_vbuf;
456 m_vbuf->build();
457
458 m_ubuf = r->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::UniformBuffer, 64 + 4);
459 m_releasePool << m_ubuf;
460 m_ubuf->build();
461
462 QImage image = QImage(QLatin1String(":/qt256.png")).convertToFormat(QImage::Format_RGBA8888);
463 m_tex = r->newTexture(QRhiTexture::RGBA8, image.size());
464 m_releasePool << m_tex;
465 m_tex->build();
466
467 m_sampler = r->newSampler(QRhiSampler::Linear, QRhiSampler::Linear, QRhiSampler::None,
468 QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge);
469 m_releasePool << m_sampler;
470 m_sampler->build();
471
472 m_srb = r->newShaderResourceBindings();
473 m_releasePool << m_srb;
474 m_srb->setBindings({
475 QRhiShaderResourceBinding::uniformBuffer(0, QRhiShaderResourceBinding::VertexStage | QRhiShaderResourceBinding::FragmentStage, m_ubuf),
476 QRhiShaderResourceBinding::sampledTexture(1, QRhiShaderResourceBinding::FragmentStage, m_tex, m_sampler)
477 });
478 m_srb->build();
479
480 m_ps = r->newGraphicsPipeline();
481 m_releasePool << m_ps;
482
483 m_ps->setDepthTest(true);
484 m_ps->setDepthWrite(true);
485 m_ps->setDepthOp(QRhiGraphicsPipeline::Less);
486
487 m_ps->setCullMode(QRhiGraphicsPipeline::Back);
488 m_ps->setFrontFace(QRhiGraphicsPipeline::CCW);
489
490 m_ps->setShaderStages({
491 { QRhiShaderStage::Vertex, getShader(QLatin1String(":/texture.vert.qsb")) },
492 { QRhiShaderStage::Fragment, getShader(QLatin1String(":/texture.frag.qsb")) }
493 });
494
495 QRhiVertexInputLayout inputLayout;
496 inputLayout.setBindings({
497 { 3 * sizeof(float) },
498 { 2 * sizeof(float) }
499 });
500 inputLayout.setAttributes({
501 { 0, 0, QRhiVertexInputAttribute::Float3, 0 },
502 { 1, 1, QRhiVertexInputAttribute::Float2, 0 }
503 });
504
505 m_ps->setVertexInputLayout(inputLayout);
506 m_ps->setShaderResourceBindings(m_srb);
507 m_ps->setRenderPassDescriptor(m_rp);
508
509 m_ps->build();
510
511 m_initialUpdates = r->nextResourceUpdateBatch();
512
513 m_initialUpdates->uploadStaticBuffer(m_vbuf, cube);
514
515 qint32 flip = 0;
516 m_initialUpdates->updateDynamicBuffer(m_ubuf, 64, 4, &flip);
517
518 m_initialUpdates->uploadTexture(m_tex, image);
519 }
520
521 void Renderer::releaseSwapChain()
522 {
523 if (m_hasSwapChain) {
524 m_hasSwapChain = false;
525 m_sc->release();
526 }
527 }
528
529 void Renderer::releaseResources()
530 {
531 qDeleteAll(m_releasePool);
532 m_releasePool.clear();
533
534 delete m_sc;
535 m_sc = nullptr;
536 }
537
538 void Renderer::render(bool newlyExposed, bool wakeBeforePresent)
539 {
540 // This function handles both resizing and rendering. Resizes have some
541 // complications due to the threaded model (check exposeEvent and
542 // sendSyncSurfaceSize) but don't have to worry about that in here.
543
544 auto buildOrResizeSwapChain = [this] {
545 qDebug() << "renderer" << this << "build or resize swapchain for window" << window;
546 m_hasSwapChain = m_sc->buildOrResize();
547 const QSize outputSize = m_sc->currentPixelSize();
548 qDebug() << " size is" << outputSize;
549 m_proj = r->clipSpaceCorrMatrix();
550 m_proj.perspective(45.0f, outputSize.width() / (float) outputSize.height(), 0.01f, 100.0f);
551 m_proj.translate(0, 0, -4);
552 };
553
554 auto wakeUpIfNeeded = [wakeBeforePresent, this] {
555 // make sure the main/gui thread is not blocked when issuing the Present (or equivalent)
556 if (wakeBeforePresent) {
557 thread->cond.wakeOne();
558 thread->mutex.unlock();
559 }
560 };
561
562 const QSize surfaceSize = m_sc->surfacePixelSize();
563 if (surfaceSize.isEmpty()) {
564 wakeUpIfNeeded();
565 return;
566 }
567
568 if (newlyExposed || m_sc->currentPixelSize() != surfaceSize)
569 buildOrResizeSwapChain();
570
571 if (!m_hasSwapChain) {
572 wakeUpIfNeeded();
573 return;
574 }
575
576 QRhi::FrameOpResult result = r->beginFrame(m_sc);
577 if (result == QRhi::FrameOpSwapChainOutOfDate) {
578 buildOrResizeSwapChain();
579 if (!m_hasSwapChain) {
580 wakeUpIfNeeded();
581 return;
582 }
583 result = r->beginFrame(m_sc);
584 }
585 if (result != QRhi::FrameOpSuccess) {
586 wakeUpIfNeeded();
587 return;
588 }
589
590 QRhiCommandBuffer *cb = m_sc->currentFrameCommandBuffer();
591 const QSize outputSize = m_sc->currentPixelSize();
592
593 QRhiResourceUpdateBatch *u = r->nextResourceUpdateBatch();
594 if (m_initialUpdates) {
595 u->merge(m_initialUpdates);
596 m_initialUpdates->release();
597 m_initialUpdates = nullptr;
598 }
599
600 m_rotation += 1.0f;
601 QMatrix4x4 mvp = m_proj;
602 mvp.scale(0.5f);
603 mvp.rotate(m_rotation, m_rotationAxis == 0 ? 1 : 0, m_rotationAxis == 1 ? 1 : 0, m_rotationAxis == 2 ? 1 : 0);
604 u->updateDynamicBuffer(m_ubuf, 0, 64, mvp.constData());
605
606 cb->beginPass(m_sc->currentFrameRenderTarget(),
607 QColor::fromRgbF(float(m_bgColor.redF()), float(m_bgColor.greenF()), float(m_bgColor.blueF()), 1.0f),
608 { 1.0f, 0 },
609 u);
610
611 cb->setGraphicsPipeline(m_ps);
612 cb->setViewport(QRhiViewport(0, 0, outputSize.width(), outputSize.height()));
613 cb->setShaderResources();
614 const QRhiCommandBuffer::VertexInput vbufBindings[] = {
615 { m_vbuf, 0 },
616 { m_vbuf, 36 * 3 * sizeof(float) }
617 };
618 cb->setVertexInput(0, 2, vbufBindings);
619 cb->draw(36);
620
621 cb->endPass();
622
623 wakeUpIfNeeded();
624
625 r->endFrame(m_sc);
626
627 m_frameCount += 1;
628 if ((m_frameCount % 300) == 0) {
629 const QRhiProfiler::CpuTime ff = r->profiler()->frameToFrameTimes(m_sc);
630 const QRhiProfiler::CpuTime be = r->profiler()->frameBuildTimes(m_sc);
631 const QRhiProfiler::GpuTime gp = r->profiler()->gpuFrameTimes(m_sc);
632 if (r->isFeatureSupported(QRhi::Timestamps)) {
633 qDebug("[renderer %p] frame-to-frame: min %lld max %lld avg %f. "
634 "frame build: min %lld max %lld avg %f. "
635 "gpu frame time: min %f max %f avg %f",
636 this,
637 ff.minTime, ff.maxTime, ff.avgTime,
638 be.minTime, be.maxTime, be.avgTime,
639 gp.minTime, gp.maxTime, gp.avgTime);
640 } else {
641 qDebug("[renderer %p] frame-to-frame: min %lld max %lld avg %f. "
642 "frame build: min %lld max %lld avg %f. ",
643 this,
644 ff.minTime, ff.maxTime, ff.avgTime,
645 be.minTime, be.maxTime, be.avgTime);
646 }
647 }
648 }
649
650 void Renderer::sendInit()
651 { // main thread
652 InitEvent *e = new InitEvent;
653 thread->eventQueue.addEvent(e);
654 }
655
656 void Renderer::sendRender(bool newlyExposed)
657 { // main thread
658 RequestRenderEvent *e = new RequestRenderEvent(newlyExposed);
659 thread->eventQueue.addEvent(e);
660 }
661
662 void Renderer::sendSurfaceGoingAway()
663 { // main thread
664 SurfaceCleanupEvent *e = new SurfaceCleanupEvent;
665
666 // cannot let this thread to proceed with tearing down the native window
667 // before the render thread completes the swapchain release
668 thread->mutex.lock();
669
670 thread->eventQueue.addEvent(e);
671
672 thread->cond.wait(&thread->mutex);
673 thread->mutex.unlock();
674 }
675
676 void Renderer::sendSyncSurfaceSize()
677 { // main thread
678 SyncSurfaceSizeEvent *e = new SyncSurfaceSizeEvent;
679 // must block to prevent surface size mess. the render thread will do a
680 // full rendering round before it unlocks which is good since it can thus
681 // pick up and the surface (window) size atomically.
682 thread->mutex.lock();
683 thread->eventQueue.addEvent(e);
684 thread->cond.wait(&thread->mutex);
685 thread->mutex.unlock();
686 }
687
688 struct WindowAndRenderer
689 {
690 QWindow *window;
691 Renderer *renderer;
692 };
693
694 QVector<WindowAndRenderer> windows;
695
696 void createWindow()
697 {
698 static QColor colors[] = { Qt::red, Qt::green, Qt::blue, Qt::yellow, Qt::cyan, Qt::gray };
699 const int n = windows.count();
700 Window *w = new Window(QString::asprintf("Window+Thread #%d (%s)", n, qPrintable(graphicsApiName())), graphicsApi);
701 Renderer *renderer = new Renderer(w, colors[n % 6], n % 3);;
702 QObject::connect(w, &Window::initRequested, w, [renderer] {
703 renderer->sendInit();
704 });
705 QObject::connect(w, &Window::renderRequested, w, [w, renderer](bool newlyExposed) {
706 renderer->sendRender(newlyExposed);
707 w->requestUpdate();
708 });
709 QObject::connect(w, &Window::surfaceGoingAway, w, [renderer] {
710 renderer->sendSurfaceGoingAway();
711 });
712 QObject::connect(w, &Window::syncSurfaceSizeRequested, w, [renderer] {
713 renderer->sendSyncSurfaceSize();
714 });
715 windows.append({ w, renderer });
716 w->show();
717 }
718
719 void closeWindow()
720 {
721 WindowAndRenderer wr = windows.takeLast();
722 delete wr.renderer;
723 delete wr.window;
724 }
725
726 int main(int argc, char **argv)
727 {
728 QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
729 QApplication app(argc, argv);
730
731 #if defined(Q_OS_WIN)
732 graphicsApi = D3D11;
733 #elif defined(Q_OS_MACOS) || defined(Q_OS_IOS)
734 graphicsApi = Metal;
735 #elif QT_CONFIG(vulkan)
736 graphicsApi = Vulkan;
737 #else
738 graphicsApi = OpenGL;
739 #endif
740
741 QCommandLineParser cmdLineParser;
742 cmdLineParser.addHelpOption();
743 QCommandLineOption glOption({ "g", "opengl" }, QLatin1String("OpenGL (2.x)"));
744 cmdLineParser.addOption(glOption);
745 QCommandLineOption vkOption({ "v", "vulkan" }, QLatin1String("Vulkan"));
746 cmdLineParser.addOption(vkOption);
747 QCommandLineOption d3dOption({ "d", "d3d11" }, QLatin1String("Direct3D 11"));
748 cmdLineParser.addOption(d3dOption);
749 QCommandLineOption mtlOption({ "m", "metal" }, QLatin1String("Metal"));
750 cmdLineParser.addOption(mtlOption);
751 cmdLineParser.process(app);
752 if (cmdLineParser.isSet(glOption))
753 graphicsApi = OpenGL;
754 if (cmdLineParser.isSet(vkOption))
755 graphicsApi = Vulkan;
756 if (cmdLineParser.isSet(d3dOption))
757 graphicsApi = D3D11;
758 if (cmdLineParser.isSet(mtlOption))
759 graphicsApi = Metal;
760
761 qDebug("Selected graphics API is %s", qPrintable(graphicsApiName()));
762 qDebug("This is a multi-api example, use command line arguments to override:\n%s", qPrintable(cmdLineParser.helpText()));
763
764 #if QT_CONFIG(vulkan)
765 instance = new QVulkanInstance;
766 if (graphicsApi == Vulkan) {
767 #ifndef Q_OS_ANDROID
768 instance->setLayers({ "VK_LAYER_LUNARG_standard_validation" });
769 #else
770 instance->setLayers(QByteArrayList()
771 << "VK_LAYER_GOOGLE_threading"
772 << "VK_LAYER_LUNARG_parameter_validation"
773 << "VK_LAYER_LUNARG_object_tracker"
774 << "VK_LAYER_LUNARG_core_validation"
775 << "VK_LAYER_LUNARG_image"
776 << "VK_LAYER_LUNARG_swapchain"
777 << "VK_LAYER_GOOGLE_unique_objects");
778 #endif
779 if (!instance->create()) {
780 qWarning("Failed to create Vulkan instance, switching to OpenGL");
781 graphicsApi = OpenGL;
782 }
783 }
784 #endif
785
786 int winCount = 0;
787 QWidget w;
788 w.resize(800, 600);
789 w.setWindowTitle(QCoreApplication::applicationName() + QLatin1String(" - ") + graphicsApiName());
790 QVBoxLayout *layout = new QVBoxLayout(&w);
791
792 QPlainTextEdit *info = new QPlainTextEdit(
793 QLatin1String("This application tests rendering on a separate thread per window, with dedicated QRhi instances and resources. "
794 "\n\nThis is the same concept as the Qt Quick Scenegraph's threaded render loop. This should allow rendering to the different windows "
795 "without unintentionally throttling each other's threads."
796 "\n\nUsing API: ") + graphicsApiName());
797 info->setReadOnly(true);
798 layout->addWidget(info);
799 QLabel *label = new QLabel(QLatin1String("Window and thread count: 0"));
800 layout->addWidget(label);
801 QPushButton *btn = new QPushButton(QLatin1String("New window"));
802 QObject::connect(btn, &QPushButton::clicked, btn, [label, &winCount] {
803 winCount += 1;
804 label->setText(QString::asprintf("Window count: %d", winCount));
805 createWindow();
806 });
807 layout->addWidget(btn);
808 btn = new QPushButton(QLatin1String("Close window"));
809 QObject::connect(btn, &QPushButton::clicked, btn, [label, &winCount] {
810 if (winCount > 0) {
811 winCount -= 1;
812 label->setText(QString::asprintf("Window count: %d", winCount));
813 closeWindow();
814 }
815 });
816 layout->addWidget(btn);
817 w.show();
818
819 int result = app.exec();
820
821 for (const WindowAndRenderer &wr : windows) {
822 delete wr.renderer;
823 delete wr.window;
824 }
825
826 #if QT_CONFIG(vulkan)
827 delete instance;
828 #endif
829
830 return result;
831 }