multiwindow_threaded.cpp 25.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
/****************************************************************************
**
** Copyright (C) 2018 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 <QApplication>
#include <QWidget>
#include <QLabel>
#include <QPlainTextEdit>
#include <QPushButton>
56
#include <QCheckBox>
57 58 59
#include <QVBoxLayout>

#include <QThread>
60
#include <QMutex>
61
#include <QWaitCondition>
62 63
#include <QQueue>
#include <QEvent>
64 65 66 67 68
#include <QCommandLineParser>
#include <QElapsedTimer>

#include <QBakedShader>
#include <QFile>
69
#include <QRhiProfiler>
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88

#ifndef QT_NO_OPENGL
#include <QRhiGles2InitParams>
#include <QOffscreenSurface>
#endif

#if QT_CONFIG(vulkan)
#include <QLoggingCategory>
#include <QRhiVulkanInitParams>
#endif

#ifdef Q_OS_WIN
#include <QRhiD3D11InitParams>
#endif

#ifdef Q_OS_DARWIN
#include <QRhiMetalInitParams>
#endif

89 90
#include "window.h"

91 92 93 94 95 96 97 98 99 100 101
#include "../shared/cube.h"

static QBakedShader getShader(const QString &name)
{
    QFile f(name);
    if (f.open(QIODevice::ReadOnly))
        return QBakedShader::fromSerialized(f.readAll());

    return QBakedShader();
}

102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
static GraphicsApi graphicsApi;

static QString graphicsApiName()
{
    switch (graphicsApi) {
    case OpenGL:
        return QLatin1String("OpenGL 2.x");
    case Vulkan:
        return QLatin1String("Vulkan");
    case D3D11:
        return QLatin1String("Direct3D 11");
    case Metal:
        return QLatin1String("Metal");
    default:
        break;
    }
    return QString();
}

#if QT_CONFIG(vulkan)
QVulkanInstance *instance = nullptr;
#endif

125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
// Window (main thread) emit signals -> Renderer::send* (main thread) -> event queue (add on main, process on render thread) -> Renderer::renderEvent (render thread)

// event queue is taken from the Qt Quick scenegraph as-is
// all this below is conceptually the same as the QSG threaded render loop
class RenderThreadEventQueue : public QQueue<QEvent *>
{
public:
    RenderThreadEventQueue()
        : waiting(false)
    {
    }

    void addEvent(QEvent *e) {
        mutex.lock();
        enqueue(e);
        if (waiting)
            condition.wakeOne();
        mutex.unlock();
    }

    QEvent *takeEvent(bool wait) {
        mutex.lock();
        if (isEmpty() && wait) {
            waiting = true;
            condition.wait(&mutex);
            waiting = false;
        }
        QEvent *e = dequeue();
        mutex.unlock();
        return e;
    }

    bool hasMoreEvents() {
        mutex.lock();
        bool has = !isEmpty();
        mutex.unlock();
        return has;
    }

private:
    QMutex mutex;
    QWaitCondition condition;
    bool waiting;
};

170 171 172 173 174 175 176 177 178 179 180 181 182 183
struct Renderer;

struct Thread : public QThread
{
    Thread(Renderer *renderer_)
        : renderer(renderer_)
    {
        active = true;
        start();
    }
    void run() override;

    Renderer *renderer;
    bool active;
184 185 186 187 188 189
    RenderThreadEventQueue eventQueue;
    bool sleeping = false;
    bool stopEventProcessing = false;
    bool pendingRender = false;
    bool pendingRenderIsNewExpose = false;
    // mutex and cond used to allow the main thread waiting until something completes on the render thread
190 191 192 193
    QMutex mutex;
    QWaitCondition cond;
};

194 195 196 197 198 199 200 201 202 203 204 205 206 207
class RenderThreadEvent : public QEvent
{
public:
    RenderThreadEvent(QEvent::Type type) : QEvent(type) { }
};

class InitEvent : public RenderThreadEvent
{
public:
    static const QEvent::Type TYPE = QEvent::Type(QEvent::User + 1);
    InitEvent() : RenderThreadEvent(TYPE)
    { }
};

208
class RequestRenderEvent : public RenderThreadEvent
209 210 211
{
public:
    static const QEvent::Type TYPE = QEvent::Type(QEvent::User + 2);
212
    RequestRenderEvent(bool newlyExposed_) : RenderThreadEvent(TYPE), newlyExposed(newlyExposed_)
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
    { }
    bool newlyExposed;
};

class SurfaceCleanupEvent : public RenderThreadEvent
{
public:
    static const QEvent::Type TYPE = QEvent::Type(QEvent::User + 3);
    SurfaceCleanupEvent() : RenderThreadEvent(TYPE)
    { }
};

class CloseEvent : public RenderThreadEvent
{
public:
    static const QEvent::Type TYPE = QEvent::Type(QEvent::User + 4);
    CloseEvent() : RenderThreadEvent(TYPE)
    { }
};

233 234 235 236 237 238 239 240
class SyncSurfaceSizeEvent : public RenderThreadEvent
{
public:
    static const QEvent::Type TYPE = QEvent::Type(QEvent::User + 5);
    SyncSurfaceSizeEvent() : RenderThreadEvent(TYPE)
    { }
};

241 242
struct Renderer
{
243 244
    // ctor and dtor and send* are called main thread, rest on the render thread

245
    Renderer(QWindow *w, const QColor &bgColor, int rotationAxis);
246 247
    ~Renderer();

248 249 250
    void sendInit();
    void sendRender(bool newlyExposed);
    void sendSurfaceGoingAway();
251
    void sendSyncSurfaceSize();
252

253 254 255 256 257 258 259 260 261
    QWindow *window;
    Thread *thread;
    QRhi *r = nullptr;
#ifndef QT_NO_OPENGL
    QOffscreenSurface *fallbackSurface = nullptr;
#endif

    void createRhi();
    void destroyRhi();
262 263 264 265
    void renderEvent(QEvent *e);
    void init();
    void releaseSwapChain();
    void releaseResources();
266
    void render(bool newlyExposed, bool wakeBeforePresent);
267

268 269 270
    QColor m_bgColor;
    int m_rotationAxis;

271 272 273 274 275
    QVector<QRhiResource *> m_releasePool;
    bool m_hasSwapChain = false;
    QRhiSwapChain *m_sc = nullptr;
    QRhiRenderBuffer *m_ds = nullptr;
    QRhiRenderPassDescriptor *m_rp = nullptr;
276 277 278 279 280 281 282 283 284 285 286

    QRhiBuffer *m_vbuf = nullptr;
    QRhiBuffer *m_ubuf = nullptr;
    QRhiTexture *m_tex = nullptr;
    QRhiSampler *m_sampler = nullptr;
    QRhiShaderResourceBindings *m_srb = nullptr;
    QRhiGraphicsPipeline *m_ps = nullptr;
    QRhiResourceUpdateBatch *m_initialUpdates = nullptr;

    QMatrix4x4 m_proj;
    float m_rotation = 0;
287
    int m_frameCount = 0;
288 289 290 291 292
};

void Thread::run()
{
    while (active) {
293 294
        if (pendingRender) {
            pendingRender = false;
295
            renderer->render(pendingRenderIsNewExpose, false);
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
        }

        while (eventQueue.hasMoreEvents()) {
            QEvent *e = eventQueue.takeEvent(false);
            renderer->renderEvent(e);
            delete e;
        }

        if (active && !pendingRender) {
            sleeping = true;
            stopEventProcessing = false;
            while (!stopEventProcessing) {
                QEvent *e = eventQueue.takeEvent(true);
                renderer->renderEvent(e);
                delete e;
            }
            sleeping = false;
        }
314 315 316
    }
}

317 318 319 320
Renderer::Renderer(QWindow *w, const QColor &bgColor, int rotationAxis)
    : window(w),
      m_bgColor(bgColor),
      m_rotationAxis(rotationAxis)
321
{ // main thread
322 323 324
    thread = new Thread(this);

#ifndef QT_NO_OPENGL
325 326
    if (graphicsApi == OpenGL)
        fallbackSurface = QRhiGles2InitParams::newFallbackSurface();
327 328 329 330
#endif
}

Renderer::~Renderer()
331 332
{ // main thread
    thread->eventQueue.addEvent(new CloseEvent);
333 334 335 336 337 338 339 340
    thread->wait();
    delete thread;

#ifndef QT_NO_OPENGL
    delete fallbackSurface;
#endif
}

341
bool useRsh = false;
Laszlo Agocs's avatar
Laszlo Agocs committed
342 343
QRhiResourceSharingHost *rsh = nullptr;

344 345
void Renderer::createRhi()
{
346 347 348
    if (r)
        return;

349
    qDebug() << "renderer" << this << "creating rhi";
350
    QRhi::Flags rhiFlags = QRhi::EnableProfiling;
351

352 353 354 355 356
    if (useRsh) {
        qDebug("Using QRhiResourceSharingHost");
        if (!rsh)
            rsh = new QRhiResourceSharingHost;
    }
Laszlo Agocs's avatar
Laszlo Agocs committed
357

358 359 360
#ifndef QT_NO_OPENGL
    if (graphicsApi == OpenGL) {
        QRhiGles2InitParams params;
361 362
        if (useRsh)
            params.resourceSharingHost = rsh;
363
        params.fallbackSurface = fallbackSurface;
364
        params.window = window;
365
        r = QRhi::create(QRhi::OpenGLES2, &params, rhiFlags);
366 367 368 369 370 371
    }
#endif

#if QT_CONFIG(vulkan)
    if (graphicsApi == Vulkan) {
        QRhiVulkanInitParams params;
372 373
        if (useRsh)
            params.resourceSharingHost = rsh;
374 375
        params.inst = instance;
        params.window = window;
376
        r = QRhi::create(QRhi::Vulkan, &params, rhiFlags);
377 378 379 380 381 382
    }
#endif

#ifdef Q_OS_WIN
    if (graphicsApi == D3D11) {
        QRhiD3D11InitParams params;
383 384
        if (useRsh)
            params.resourceSharingHost = rsh;
385
        params.enableDebugLayer = true;
386
        r = QRhi::create(QRhi::D3D11, &params, rhiFlags);
387 388 389 390 391 392
    }
#endif

#ifdef Q_OS_DARWIN
    if (graphicsApi == Metal) {
        QRhiMetalInitParams params;
393 394
        if (useRsh)
            params.resourceSharingHost = rsh;
395
        r = QRhi::create(QRhi::Metal, &params, rhiFlags);
396 397 398 399 400 401 402 403 404
    }
#endif

    if (!r)
        qFatal("Failed to create RHI backend");
}

void Renderer::destroyRhi()
{
405
    qDebug() << "renderer" << this << "destroying rhi";
406
    delete r;
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
    r = nullptr;
}

void Renderer::renderEvent(QEvent *e)
{
    Q_ASSERT(QThread::currentThread() == thread);

    if (thread->sleeping)
        thread->stopEventProcessing = true;

    switch (e->type()) {
    case InitEvent::TYPE:
        qDebug() << "renderer" << this << "for window" << window << "is initializing";
        createRhi();
        init();
        break;
423
    case RequestRenderEvent::TYPE:
424
        thread->pendingRender = true;
425
        thread->pendingRenderIsNewExpose = static_cast<RequestRenderEvent *>(e)->newlyExposed;
426 427 428 429
        break;
    case SurfaceCleanupEvent::TYPE: // when the QWindow is closed, before QPlatformWindow goes away
        thread->mutex.lock();
        qDebug() << "renderer" << this << "for window" << window << "is destroying swapchain";
430
        thread->pendingRender = false;
431 432 433 434 435 436
        releaseSwapChain();
        thread->cond.wakeOne();
        thread->mutex.unlock();
        break;
    case CloseEvent::TYPE: // when destroying the window+renderer (NB not the same as hitting X on the window, that's just QWindow close)
        qDebug() << "renderer" << this << "for window" << window << "is shutting down";
437
        thread->pendingRender = false;
438 439 440 441 442
        thread->active = false;
        thread->stopEventProcessing = true;
        releaseResources();
        destroyRhi();
        break;
443 444 445
    case SyncSurfaceSizeEvent::TYPE:
        thread->mutex.lock();
        thread->pendingRender = false;
446
        render(false, true);
447
        break;
448 449 450 451 452 453 454 455 456 457 458
    default:
        break;
    }
}

void Renderer::init()
{
    m_sc = r->newSwapChain();
    m_ds = r->newRenderBuffer(QRhiRenderBuffer::DepthStencil,
                              QSize(), // no need to set the size yet
                              1,
459
                              QRhiRenderBuffer::UsedWithSwapChainOnly);
460 461 462 463 464 465
    m_releasePool << m_ds;
    m_sc->setWindow(window);
    m_sc->setDepthStencil(m_ds);
    m_rp = m_sc->newCompatibleRenderPassDescriptor();
    m_releasePool << m_rp;
    m_sc->setRenderPassDescriptor(m_rp);
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508

    m_vbuf = r->newBuffer(QRhiBuffer::Immutable, QRhiBuffer::VertexBuffer, sizeof(cube));
    m_releasePool << m_vbuf;
    m_vbuf->build();

    m_ubuf = r->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::UniformBuffer, 64 + 4);
    m_releasePool << m_ubuf;
    m_ubuf->build();

    QImage image = QImage(QLatin1String(":/qt256.png")).convertToFormat(QImage::Format_RGBA8888);
    m_tex = r->newTexture(QRhiTexture::RGBA8, image.size());
    m_releasePool << m_tex;
    m_tex->build();

    m_sampler = r->newSampler(QRhiSampler::Linear, QRhiSampler::Linear, QRhiSampler::None,
                                QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge);
    m_releasePool << m_sampler;
    m_sampler->build();

    m_srb = r->newShaderResourceBindings();
    m_releasePool << m_srb;
    m_srb->setBindings({
        QRhiShaderResourceBinding::uniformBuffer(0, QRhiShaderResourceBinding::VertexStage | QRhiShaderResourceBinding::FragmentStage, m_ubuf),
        QRhiShaderResourceBinding::sampledTexture(1, QRhiShaderResourceBinding::FragmentStage, m_tex, m_sampler)
    });
    m_srb->build();

    m_ps = r->newGraphicsPipeline();
    m_releasePool << m_ps;

    m_ps->setDepthTest(true);
    m_ps->setDepthWrite(true);
    m_ps->setDepthOp(QRhiGraphicsPipeline::Less);

    m_ps->setCullMode(QRhiGraphicsPipeline::Back);
    m_ps->setFrontFace(QRhiGraphicsPipeline::CCW);

    m_ps->setShaderStages({
        { QRhiGraphicsShaderStage::Vertex, getShader(QLatin1String(":/texture.vert.qsb")) },
        { QRhiGraphicsShaderStage::Fragment, getShader(QLatin1String(":/texture.frag.qsb")) }
    });

    QRhiVertexInputLayout inputLayout;
Laszlo Agocs's avatar
Laszlo Agocs committed
509
    inputLayout.setBindings({
510 511
        { 3 * sizeof(float) },
        { 2 * sizeof(float) }
Laszlo Agocs's avatar
Laszlo Agocs committed
512 513 514 515 516
    });
    inputLayout.setAttributes({
        { 0, 0, QRhiVertexInputAttribute::Float3, 0 },
        { 1, 1, QRhiVertexInputAttribute::Float2, 0 }
    });
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531

    m_ps->setVertexInputLayout(inputLayout);
    m_ps->setShaderResourceBindings(m_srb);
    m_ps->setRenderPassDescriptor(m_rp);

    m_ps->build();

    m_initialUpdates = r->nextResourceUpdateBatch();

    m_initialUpdates->uploadStaticBuffer(m_vbuf, cube);

    qint32 flip = 0;
    m_initialUpdates->updateDynamicBuffer(m_ubuf, 64, 4, &flip);

    m_initialUpdates->uploadTexture(m_tex, image);
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
}

void Renderer::releaseSwapChain()
{
    if (m_hasSwapChain) {
        m_hasSwapChain = false;
        m_sc->release();
    }
}

void Renderer::releaseResources()
{
    for (QRhiResource *res : m_releasePool)
        res->releaseAndDestroy();

    m_releasePool.clear();

    if (m_sc) {
        m_sc->releaseAndDestroy();
        m_sc = nullptr;
    }
}

555
void Renderer::render(bool newlyExposed, bool wakeBeforePresent)
556
{
557 558 559 560
    // This function handles both resizing and rendering. Resizes have some
    // complications due to the threaded model (check exposeEvent and
    // sendSyncSurfaceSize) but don't have to worry about that in here.

561 562 563 564 565 566 567
    auto buildOrResizeSwapChain = [this] {
        qDebug() << "renderer" << this << "build or resize swapchain for window" << window;
        const QSize outputSize = m_sc->surfacePixelSize();
        qDebug() << "  size is" << outputSize;
        m_ds->setPixelSize(outputSize);
        m_ds->build();
        m_hasSwapChain = m_sc->buildOrResize();
568 569 570
        m_proj = r->clipSpaceCorrMatrix();
        m_proj.perspective(45.0f, outputSize.width() / (float) outputSize.height(), 0.01f, 100.0f);
        m_proj.translate(0, 0, -4);
571 572
    };

573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
    auto wakeUpIfNeeded = [wakeBeforePresent, this] {
        // make sure the main/gui thread is not blocked when issuing the Present (or equivalent)
        if (wakeBeforePresent) {
            thread->cond.wakeOne();
            thread->mutex.unlock();
        }
    };

    const QSize surfaceSize = m_sc->surfacePixelSize();
    if (surfaceSize.isEmpty()) {
        wakeUpIfNeeded();
        return;
    }

    if (newlyExposed || m_sc->currentPixelSize() != surfaceSize)
588 589
        buildOrResizeSwapChain();

590 591
    if (!m_hasSwapChain) {
        wakeUpIfNeeded();
592
        return;
593
    }
594 595 596 597

    QRhi::FrameOpResult result = r->beginFrame(m_sc);
    if (result == QRhi::FrameOpSwapChainOutOfDate) {
        buildOrResizeSwapChain();
598 599
        if (!m_hasSwapChain) {
            wakeUpIfNeeded();
600
            return;
601
        }
602 603
        result = r->beginFrame(m_sc);
    }
604 605
    if (result != QRhi::FrameOpSuccess) {
        wakeUpIfNeeded();
606
        return;
607
    }
608 609

    QRhiCommandBuffer *cb = m_sc->currentFrameCommandBuffer();
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
    const QSize outputSize = m_sc->currentPixelSize();

    QRhiResourceUpdateBatch *u = r->nextResourceUpdateBatch();
    if (m_initialUpdates) {
        u->merge(m_initialUpdates);
        m_initialUpdates->release();
        m_initialUpdates = nullptr;
    }

    m_rotation += 1.0f;
    QMatrix4x4 mvp = m_proj;
    mvp.scale(0.5f);
    mvp.rotate(m_rotation, m_rotationAxis == 0 ? 1 : 0, m_rotationAxis == 1 ? 1 : 0, m_rotationAxis == 2 ? 1 : 0);
    u->updateDynamicBuffer(m_ubuf, 0, 64, mvp.constData());

    cb->beginPass(m_sc->currentFrameRenderTarget(),
                  { float(m_bgColor.redF()), float(m_bgColor.greenF()), float(m_bgColor.blueF()), 1.0f },
                  { 1.0f, 0 },
                  u);

    cb->setGraphicsPipeline(m_ps);
    cb->setViewport(QRhiViewport(0, 0, outputSize.width(), outputSize.height()));
    cb->setVertexInput(0, { { m_vbuf, 0 }, { m_vbuf, 36 * 3 * sizeof(float) } });
    cb->draw(36);
634 635 636

    cb->endPass();

637
    wakeUpIfNeeded();
638

639
    r->endFrame(m_sc);
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661

    m_frameCount += 1;
    if ((m_frameCount % 300) == 0) {
        const QRhiProfiler::CpuTime ff = r->profiler()->frameToFrameTimes(m_sc);
        const QRhiProfiler::CpuTime be = r->profiler()->frameBuildTimes(m_sc);
        const QRhiProfiler::GpuTime gp = r->profiler()->gpuFrameTimes(m_sc);
        if (r->isFeatureSupported(QRhi::Timestamps)) {
            qDebug("[renderer %p] frame-to-frame: min %lld max %lld avg %f. "
                   "frame build: min %lld max %lld avg %f. "
                   "gpu frame time: min %f max %f avg %f",
                   this,
                   ff.minTime, ff.maxTime, ff.avgTime,
                   be.minTime, be.maxTime, be.avgTime,
                   gp.minTime, gp.maxTime, gp.avgTime);
        } else {
            qDebug("[renderer %p] frame-to-frame: min %lld max %lld avg %f. "
                   "frame build: min %lld max %lld avg %f. ",
                   this,
                   ff.minTime, ff.maxTime, ff.avgTime,
                   be.minTime, be.maxTime, be.avgTime);
        }
    }
662 663 664 665 666 667 668 669 670 671
}

void Renderer::sendInit()
{ // main thread
    InitEvent *e = new InitEvent;
    thread->eventQueue.addEvent(e);
}

void Renderer::sendRender(bool newlyExposed)
{ // main thread
672
    RequestRenderEvent *e = new RequestRenderEvent(newlyExposed);
673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
    thread->eventQueue.addEvent(e);
}

void Renderer::sendSurfaceGoingAway()
{ // main thread
    SurfaceCleanupEvent *e = new SurfaceCleanupEvent;

    // cannot let this thread to proceed with tearing down the native window
    // before the render thread completes the swapchain release
    thread->mutex.lock();

    thread->eventQueue.addEvent(e);

    thread->cond.wait(&thread->mutex);
    thread->mutex.unlock();
688 689
}

690 691 692 693 694 695 696 697 698 699 700 701
void Renderer::sendSyncSurfaceSize()
{ // main thread
    SyncSurfaceSizeEvent *e = new SyncSurfaceSizeEvent;
    // must block to prevent surface size mess. the render thread will do a
    // full rendering round before it unlocks which is good since it can thus
    // pick up and the surface (window) size atomically.
    thread->mutex.lock();
    thread->eventQueue.addEvent(e);
    thread->cond.wait(&thread->mutex);
    thread->mutex.unlock();
}

702 703 704 705 706 707 708 709 710 711 712 713
struct WindowAndRenderer
{
    QWindow *window;
    Renderer *renderer;
};

QVector<WindowAndRenderer> windows;

void createWindow()
{
    static QColor colors[] = { Qt::red, Qt::green, Qt::blue, Qt::yellow, Qt::cyan, Qt::gray };
    const int n = windows.count();
714
    Window *w = new Window(QString::asprintf("Window+Thread #%d (%s)", n, qPrintable(graphicsApiName())), graphicsApi);
715
    Renderer *renderer = new Renderer(w, colors[n % 6], n % 3);;
716 717 718 719 720 721 722 723 724 725
    QObject::connect(w, &Window::initRequested, w, [renderer] {
        renderer->sendInit();
    });
    QObject::connect(w, &Window::renderRequested, w, [w, renderer](bool newlyExposed) {
        renderer->sendRender(newlyExposed);
        w->requestUpdate();
    });
    QObject::connect(w, &Window::surfaceGoingAway, w, [renderer] {
        renderer->sendSurfaceGoingAway();
    });
726 727 728
    QObject::connect(w, &Window::syncSurfaceSizeRequested, w, [renderer] {
        renderer->sendSyncSurfaceSize();
    });
729
    windows.append({ w, renderer });
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806
    w->show();
}

void closeWindow()
{
    WindowAndRenderer wr = windows.takeLast();
    delete wr.renderer;
    delete wr.window;
}

int main(int argc, char **argv)
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QApplication app(argc, argv);

#if defined(Q_OS_WIN)
    graphicsApi = D3D11;
#elif defined(Q_OS_DARWIN)
    graphicsApi = Metal;
#elif QT_CONFIG(vulkan)
    graphicsApi = Vulkan;
#else
    graphicsApi = OpenGL;
#endif

    QCommandLineParser cmdLineParser;
    cmdLineParser.addHelpOption();
    QCommandLineOption glOption({ "g", "opengl" }, QLatin1String("OpenGL (2.x)"));
    cmdLineParser.addOption(glOption);
    QCommandLineOption vkOption({ "v", "vulkan" }, QLatin1String("Vulkan"));
    cmdLineParser.addOption(vkOption);
    QCommandLineOption d3dOption({ "d", "d3d11" }, QLatin1String("Direct3D 11"));
    cmdLineParser.addOption(d3dOption);
    QCommandLineOption mtlOption({ "m", "metal" }, QLatin1String("Metal"));
    cmdLineParser.addOption(mtlOption);
    cmdLineParser.process(app);
    if (cmdLineParser.isSet(glOption))
        graphicsApi = OpenGL;
    if (cmdLineParser.isSet(vkOption))
        graphicsApi = Vulkan;
    if (cmdLineParser.isSet(d3dOption))
        graphicsApi = D3D11;
    if (cmdLineParser.isSet(mtlOption))
        graphicsApi = Metal;

    qDebug("Selected graphics API is %s", qPrintable(graphicsApiName()));
    qDebug("This is a multi-api example, use command line arguments to override:\n%s", qPrintable(cmdLineParser.helpText()));

#if QT_CONFIG(vulkan)
    instance = new QVulkanInstance;
    if (graphicsApi == Vulkan) {
#ifndef Q_OS_ANDROID
        instance->setLayers({ "VK_LAYER_LUNARG_standard_validation" });
#else
        instance->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 (!instance->create()) {
            qWarning("Failed to create Vulkan instance, switching to OpenGL");
            graphicsApi = OpenGL;
        }
    }
#endif

    int winCount = 0;
    QWidget w;
    w.resize(800, 600);
    w.setWindowTitle(QCoreApplication::applicationName() + QLatin1String(" - ") + graphicsApiName());
    QVBoxLayout *layout = new QVBoxLayout(&w);

    QPlainTextEdit *info = new QPlainTextEdit(
807
                QLatin1String("This application tests rendering on a separate thread per window, with dedicated QRhi instances and resources. "
808 809
                              "\n\nThis is the same concept as the Qt Quick Scenegraph's threaded render loop. This should allow rendering to the different windows "
                              "without unintentionally throttling each other's threads."
810 811
                              "\n\nCan also be used to exercise creating sets of windows that can \"see\" each others' resources by using the same graphics device. "
                              "(although no application-side QRhiResource is reused here)"
812 813 814
                              "\n\nUsing API: ") + graphicsApiName());
    info->setReadOnly(true);
    layout->addWidget(info);
Laszlo Agocs's avatar
gl: rsh  
Laszlo Agocs committed
815 816
    QCheckBox *rshCb = new QCheckBox(QLatin1String("Use QRhiResourceSharingHost for new window\n(use same device, "
                                                   "e.g. VkDevice+VkQueue on Vulkan, ID3D11Device+Context on D3D; or sharing contexts on OpenGL)"));
817 818
    rshCb->setChecked(false);
    layout->addWidget(rshCb);
819
    QLabel *label = new QLabel(QLatin1String("Window and thread count: 0"));
820 821
    layout->addWidget(label);
    QPushButton *btn = new QPushButton(QLatin1String("New window"));
822 823
    QObject::connect(btn, &QPushButton::clicked, btn, [label, &winCount, rshCb] {
        useRsh = rshCb->isChecked();
824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846
        winCount += 1;
        label->setText(QString::asprintf("Window count: %d", winCount));
        createWindow();
    });
    layout->addWidget(btn);
    btn = new QPushButton(QLatin1String("Close window"));
    QObject::connect(btn, &QPushButton::clicked, btn, [label, &winCount] {
        if (winCount > 0) {
            winCount -= 1;
            label->setText(QString::asprintf("Window count: %d", winCount));
            closeWindow();
        }
    });
    layout->addWidget(btn);
    w.show();

    int result = app.exec();

    for (const WindowAndRenderer &wr : windows) {
        delete wr.renderer;
        delete wr.window;
    }

Laszlo Agocs's avatar
Laszlo Agocs committed
847 848
    delete rsh;

849 850 851 852 853 854
#if QT_CONFIG(vulkan)
    delete instance;
#endif

    return result;
}