aboutsummaryrefslogtreecommitdiffstats
path: root/tests/auto/quick/qquickrendercontrol/tst_qquickrendercontrol.cpp
blob: d81c40f5b646f4f5f5fdb79c97ec4818645a2f92 (plain)
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
/****************************************************************************
**
** Copyright (C) 2020 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** 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.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <qtest.h>

#include <QAnimationDriver>

#include <QQuickWindow>
#include <QQuickRenderControl>
#include <QQuickRenderTarget>
#include <QQuickGraphicsDevice>
#include <QQuickItem>
#include <QQmlEngine>
#include <QQmlComponent>

#include "../../shared/util.h"

#include <QtGui/private/qguiapplication_p.h>
#include <QtGui/qpa/qplatformintegration.h>

#include <QtGui/private/qrhi_p.h>
#include <QtQuick/private/qquickrendercontrol_p.h>

#if QT_CONFIG(vulkan)
#include <QVulkanInstance>
#include <QVulkanFunctions>
#endif

#include <QOperatingSystemVersion>

class AnimationDriver : public QAnimationDriver
{
public:
    AnimationDriver(int msPerStep) : m_step(msPerStep) { }

    void advance() override
    {
        m_elapsed += m_step;
        advanceAnimation();
    }

    qint64 elapsed() const override
    {
        return m_elapsed;
    }

private:
    int m_step;
    qint64 m_elapsed = 0;
};

class tst_RenderControl : public QQmlDataTest
{
    Q_OBJECT

private slots:
    void initTestCase();
    void cleanupTestCase();
    void renderAndReadBackWithRhi_data();
    void renderAndReadBackWithRhi();
    void renderAndReadBackWithVulkanNative();

private:
#if QT_CONFIG(vulkan)
    QVulkanInstance vulkanInstance;
#endif
    AnimationDriver *animDriver;
};

void tst_RenderControl::initTestCase()
{
    QQmlDataTest::initTestCase();

#if QT_CONFIG(vulkan)
    vulkanInstance.setLayers({ "VK_LAYER_LUNARG_standard_validation" });
    vulkanInstance.create(); // may fail, that's sometimes ok, we'll check for it later
#endif

    // Install the animation driver once, globally, instead of in the
    // individual tests. This tends to work better as it avoids the need to
    // have more complicated logic when calling advance().

    static const int ANIM_ADVANCE_PER_FRAME = 16; // milliseconds
    animDriver = new AnimationDriver(ANIM_ADVANCE_PER_FRAME);
    animDriver->install();
}

void tst_RenderControl::cleanupTestCase()
{
    delete animDriver;
}

void tst_RenderControl::renderAndReadBackWithRhi_data()
{
    QTest::addColumn<QSGRendererInterface::GraphicsApi>("api");

#if QT_CONFIG(opengl)
    QTest::newRow("OpenGL") << QSGRendererInterface::OpenGLRhi;
#endif
#if QT_CONFIG(vulkan)
    QTest::newRow("Vulkan") << QSGRendererInterface::VulkanRhi;
#endif
#ifdef Q_OS_WIN
    if (QOperatingSystemVersion::current() > QOperatingSystemVersion::Windows7)
        QTest::newRow("D3D11") << QSGRendererInterface::Direct3D11Rhi;
#endif
#if defined(Q_OS_MACOS) || defined(Q_OS_IOS)
    QTest::newRow("Metal") << QSGRendererInterface::MetalRhi;
#endif
}

void tst_RenderControl::renderAndReadBackWithRhi()
{
    QFETCH(QSGRendererInterface::GraphicsApi, api);
#if QT_CONFIG(vulkan)
    if (api == QSGRendererInterface::VulkanRhi && !vulkanInstance.isValid())
        QSKIP("Skipping Vulkan-based QRhi readback test due to failing to create a VkInstance");
#endif

    // Changing the graphics api is not possible once a QQuickWindow et al is
    // created, however we do support changing it once all QQuickWindow,
    // QQuickRenderControl, etc. instances are destroyed, before creating new
    // ones. That's why it is possible to have this test run with multiple QRhi
    // backends.
    QQuickWindow::setGraphicsApi(api);

    QScopedPointer<QQuickRenderControl> renderControl(new QQuickRenderControl);
    QScopedPointer<QQuickWindow> quickWindow(new QQuickWindow(renderControl.data()));
#if QT_CONFIG(vulkan)
    if (api == QSGRendererInterface::VulkanRhi)
        quickWindow->setVulkanInstance(&vulkanInstance);
#endif

    QScopedPointer<QQmlEngine> qmlEngine(new QQmlEngine);
    QScopedPointer<QQmlComponent> qmlComponent(new QQmlComponent(qmlEngine.data(),
                                                                 testFileUrl(QLatin1String("rect.qml"))));
    QVERIFY(!qmlComponent->isLoading());
    if (qmlComponent->isError()) {
        for (const QQmlError &error : qmlComponent->errors())
            qWarning() << error.url() << error.line() << error;
    }
    QVERIFY(!qmlComponent->isError());

    QObject *rootObject = qmlComponent->create();
    if (qmlComponent->isError()) {
        for (const QQmlError &error : qmlComponent->errors())
            qWarning() << error.url() << error.line() << error;
    }
    QVERIFY(!qmlComponent->isError());

    QQuickItem *rootItem = qobject_cast<QQuickItem *>(rootObject);
    QVERIFY(rootItem);
    QCOMPARE(rootItem->size(), QSize(200, 200));

    quickWindow->contentItem()->setSize(rootItem->size());
    quickWindow->setGeometry(0, 0, rootItem->width(), rootItem->height());

    rootItem->setParentItem(quickWindow->contentItem());

    const bool initSuccess = renderControl->initialize();

    // now we cannot just test for initSuccess; it is highly likely that a
    // number of configurations will simply fail in a CI environment (Vulkan,
    // Metal, ...) So the only reasonable choice is to skip if initialize()
    // failed. The exception for now is OpenGL - that should (usually) work.
    if (!initSuccess) {
#if QT_CONFIG(opengl)
        if (api != QSGRendererInterface::OpenGLRhi
                || !QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::OpenGL))
#endif
        {
            QSKIP("Could not initialize graphics, perhaps unsupported graphics API, skipping");
        }
    }

    QVERIFY(initSuccess);

    QCOMPARE(quickWindow->rendererInterface()->graphicsApi(), api);

    // What comes now is technically cheating - as long as QRhi is not a public
    // API this is not something applications can follow doing. However, it
    // allows us to test out the pipeline without having to write 4 different
    // native (Vulkan, Metal, D3D11, OpenGL) implementations of all what's below.

    QQuickRenderControlPrivate *rd = QQuickRenderControlPrivate::get(renderControl.data());
    QRhi *rhi = rd->rhi;
    Q_ASSERT(rhi);

    const QSize size = rootItem->size().toSize();
    QScopedPointer<QRhiTexture> tex(rhi->newTexture(QRhiTexture::RGBA8, size, 1,
                                                    QRhiTexture::RenderTarget | QRhiTexture::UsedAsTransferSource));
    QVERIFY(tex->create());

    // depth-stencil is mandatory with RHI, although strictly speaking the
    // scenegraph could operate without one, but it has no means to figure out
    // the lack of a ds buffer, so just be nice and provide one.
    QScopedPointer<QRhiRenderBuffer> ds(rhi->newRenderBuffer(QRhiRenderBuffer::DepthStencil, size, 1));
    QVERIFY(ds->create());

    QRhiTextureRenderTargetDescription rtDesc(QRhiColorAttachment(tex.data()));
    rtDesc.setDepthStencilBuffer(ds.data());
    QScopedPointer<QRhiTextureRenderTarget> texRt(rhi->newTextureRenderTarget(rtDesc));
    QScopedPointer<QRhiRenderPassDescriptor> rp(texRt->newCompatibleRenderPassDescriptor());
    texRt->setRenderPassDescriptor(rp.data());
    QVERIFY(texRt->create());

    // redirect Qt Quick rendering into our texture
    quickWindow->setRenderTarget(QQuickRenderTarget::fromRhiRenderTarget(texRt.data()));

    for (int frame = 0; frame < 100; ++frame) {
        // have to process events, e.g. to get queued metacalls delivered
        QCoreApplication::processEvents();

        if (frame > 0) {
            // Quick animations will now think that ANIM_ADVANCE_PER_FRAME milliseconds have passed,
            // even though in reality we have a tight loop that generates frames unthrottled.
            animDriver->advance();
        }

        renderControl->polishItems();

        // kick off the next frame on the QRhi (this internally calls QRhi::beginOffscreenFrame())
        renderControl->beginFrame();

        renderControl->sync();
        renderControl->render();

        bool readCompleted = false;
        QRhiReadbackResult readResult;
        QImage result;
        readResult.completed = [&readCompleted, &readResult, &result, &rhi] {
            readCompleted = true;
            QImage wrapperImage(reinterpret_cast<const uchar *>(readResult.data.constData()),
                                readResult.pixelSize.width(), readResult.pixelSize.height(),
                                QImage::Format_RGBA8888_Premultiplied);
            if (rhi->isYUpInFramebuffer())
                result = wrapperImage.mirrored();
            else
                result = wrapperImage.copy();
        };
        QRhiResourceUpdateBatch *readbackBatch = rhi->nextResourceUpdateBatch();
        readbackBatch->readBackTexture(tex.data(), &readResult);
        rd->cb->resourceUpdate(readbackBatch);

        // our frame is done, submit
        renderControl->endFrame();

        // offscreen frames in QRhi are synchronous, meaning the readback has
        // been finished at this point
        QVERIFY(readCompleted);

        QImage img = result;
        QVERIFY(!img.isNull());
        QCOMPARE(img.size(), rootItem->size());

        const int maxFuzz = 2;

        // The scene is: background, rectangle, text
        // where rectangle rotates

        QRgb background = img.pixel(5, 5);
        QVERIFY(qAbs(qRed(background) - 70) < maxFuzz);
        QVERIFY(qAbs(qGreen(background) - 130) < maxFuzz);
        QVERIFY(qAbs(qBlue(background) - 180) < maxFuzz);

        background = img.pixel(195, 195);
        QVERIFY(qAbs(qRed(background) - 70) < maxFuzz);
        QVERIFY(qAbs(qGreen(background) - 130) < maxFuzz);
        QVERIFY(qAbs(qBlue(background) - 180) < maxFuzz);

        // after about 1.25 seconds (animation time, one iteration is 16 ms
        // thanks to our custom animation driver) the rectangle reaches a 90
        // degree rotation, that should be frame 76
        if (frame <= 2 || (frame >= 76 && frame <= 80)) {
            QRgb c = img.pixel(28, 28); // rectangle
            QVERIFY(qAbs(qRed(c) - 152) < maxFuzz);
            QVERIFY(qAbs(qGreen(c) - 251) < maxFuzz);
            QVERIFY(qAbs(qBlue(c) - 152) < maxFuzz);
        } else {
            QRgb c = img.pixel(28, 28); // background because rectangle got rotated so this pixel is not covered by it
            QVERIFY(qAbs(qRed(c) - 70) < maxFuzz);
            QVERIFY(qAbs(qGreen(c) - 130) < maxFuzz);
            QVERIFY(qAbs(qBlue(c) - 180) < maxFuzz);
        }
    }
}

void tst_RenderControl::renderAndReadBackWithVulkanNative()
{
#if QT_CONFIG(vulkan)
    if (!vulkanInstance.isValid())
        QSKIP("Skipping native Vulkan test due to failing to create a VkInstance");

    QQuickWindow::setGraphicsApi(QSGRendererInterface::VulkanRhi);

    // We will create our own VkDevice and friends, which will then get used by
    // Qt Quick as well (instead of creating its own objects), so this is a test
    // of a typical "integrate Qt Quick content into an external (Vulkan-based)
    // rendering engine" case.

    QVulkanFunctions *f = vulkanInstance.functions();

    uint32_t physDevCount = 0;
    f->vkEnumeratePhysicalDevices(vulkanInstance.vkInstance(), &physDevCount, nullptr);
    if (!physDevCount)
        QSKIP("No Vulkan physical devices");

    QVarLengthArray<VkPhysicalDevice, 4> physDevs(physDevCount);
    VkResult err = f->vkEnumeratePhysicalDevices(vulkanInstance.vkInstance(), &physDevCount, physDevs.data());
    QVERIFY(err == VK_SUCCESS);
    QVERIFY(physDevCount);

    // Just use the first physical device for now.
    VkPhysicalDevice physDev = physDevs[0];

    uint32_t queueCount = 0;
    f->vkGetPhysicalDeviceQueueFamilyProperties(physDev, &queueCount, nullptr);
    QVarLengthArray<VkQueueFamilyProperties, 4> queueFamilyProps(queueCount);
    f->vkGetPhysicalDeviceQueueFamilyProperties(physDev, &queueCount, queueFamilyProps.data());

    int gfxQueueFamilyIdx = -1;
    for (int i = 0; i < queueFamilyProps.count(); ++i) {
        if (queueFamilyProps[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) {
            gfxQueueFamilyIdx = i;
            break;
        }
    }
    QVERIFY(gfxQueueFamilyIdx >= 0);

    VkDeviceQueueCreateInfo queueInfo[2] = {};
    const float prio[] = { 0 };
    queueInfo[0].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
    queueInfo[0].queueFamilyIndex = uint32_t(gfxQueueFamilyIdx);
    queueInfo[0].queueCount = 1;
    queueInfo[0].pQueuePriorities = prio;

    VkDevice dev = VK_NULL_HANDLE;
    VkDeviceCreateInfo devInfo = {};
    devInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
    devInfo.queueCreateInfoCount = 1;
    devInfo.pQueueCreateInfos = queueInfo;
    err = f->vkCreateDevice(physDev, &devInfo, nullptr, &dev);
    if (err != VK_SUCCESS || !dev)
        QSKIP("Skipping Vulkan test due to failing to create VkDevice");

    QVulkanDeviceFunctions *df = vulkanInstance.deviceFunctions(dev);
    QVERIFY(df);

    {
        QScopedPointer<QQuickRenderControl> renderControl(new QQuickRenderControl);
        QScopedPointer<QQuickWindow> quickWindow(new QQuickWindow(renderControl.data()));
        quickWindow->setVulkanInstance(&vulkanInstance);

        QScopedPointer<QQmlEngine> qmlEngine(new QQmlEngine);
        QScopedPointer<QQmlComponent> qmlComponent(new QQmlComponent(qmlEngine.data(),
                                                                     testFileUrl(QLatin1String("rect.qml"))));
        QVERIFY(!qmlComponent->isLoading());
        if (qmlComponent->isError()) {
            for (const QQmlError &error : qmlComponent->errors())
                qWarning() << error.url() << error.line() << error;
        }
        QVERIFY(!qmlComponent->isError());

        QObject *rootObject = qmlComponent->create();
        if (qmlComponent->isError()) {
            for (const QQmlError &error : qmlComponent->errors())
                qWarning() << error.url() << error.line() << error;
        }
        QVERIFY(!qmlComponent->isError());

        QQuickItem *rootItem = qobject_cast<QQuickItem *>(rootObject);
        QVERIFY(rootItem);
        QCOMPARE(rootItem->size(), QSize(200, 200));

        // avoid trouble with the image - buffer copy later on
        QVERIFY(int(rootItem->width()) % 4 == 0);
        QVERIFY(int(rootItem->height()) % 4 == 0);

        quickWindow->contentItem()->setSize(rootItem->size());
        quickWindow->setGeometry(0, 0, rootItem->width(), rootItem->height());

        rootItem->setParentItem(quickWindow->contentItem());

        // Let Qt Quick and the underlying QRhi "adopt" our VkDevice, which
        // will conveniently mean resource handles (buffers, images) are valid
        // both there and here in our native Vulkan code as we all use the same
        // device.
        quickWindow->setGraphicsDevice(QQuickGraphicsDevice::fromDeviceObjects(physDev, dev, gfxQueueFamilyIdx));

        const bool initSuccess = renderControl->initialize();
        QVERIFY(initSuccess);
        QCOMPARE(quickWindow->rendererInterface()->graphicsApi(), QSGRendererInterface::VulkanRhi);

        // Will need a command pool/buffer to do the readback.
        VkCommandPool cmdPool = VK_NULL_HANDLE;
        VkCommandPoolCreateInfo poolInfo = {};
        poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
        poolInfo.queueFamilyIndex = uint32_t(gfxQueueFamilyIdx);
        VkResult err = df->vkCreateCommandPool(dev, &poolInfo, nullptr, &cmdPool);
        QCOMPARE(err, VK_SUCCESS);

        // Get a command queue, this is the same as what Qt Quick (QRhi) uses.
        VkQueue cmdQueue = VK_NULL_HANDLE;
        df->vkGetDeviceQueue(dev, uint32_t(gfxQueueFamilyIdx), 0, &cmdQueue);

        // Do some sanity checks
        QCOMPARE(physDev, *reinterpret_cast<VkPhysicalDevice *>(quickWindow->rendererInterface()->getResource(
                                                                    quickWindow.data(), QSGRendererInterface::PhysicalDeviceResource)));
        QCOMPARE(dev, *reinterpret_cast<VkDevice *>(quickWindow->rendererInterface()->getResource(
                                                        quickWindow.data(), QSGRendererInterface::DeviceResource)));
        QCOMPARE(cmdQueue, *reinterpret_cast<VkQueue *>(quickWindow->rendererInterface()->getResource(
                                                            quickWindow.data(), QSGRendererInterface::CommandQueueResource)));

        // Create the VkImage into which Qt Quick should render its contents.

        VkImage img = VK_NULL_HANDLE;
        VkImageCreateInfo imgInfo = {};
        imgInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
        imgInfo.imageType = VK_IMAGE_TYPE_2D;
        imgInfo.format = VK_FORMAT_R8G8B8A8_UNORM;
        imgInfo.extent.width = uint32_t(rootItem->width());
        imgInfo.extent.height = uint32_t(rootItem->height());
        imgInfo.extent.depth = 1;
        imgInfo.mipLevels = imgInfo.arrayLayers = 1;
        imgInfo.samples = VK_SAMPLE_COUNT_1_BIT;
        imgInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
        imgInfo.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
        imgInfo.initialLayout = VK_IMAGE_LAYOUT_PREINITIALIZED;

        err = df->vkCreateImage(dev, &imgInfo, nullptr, &img);
        QCOMPARE(err, VK_SUCCESS);

        VkPhysicalDeviceMemoryProperties memProps;
        f->vkGetPhysicalDeviceMemoryProperties(physDev, &memProps);

        auto findMemTypeIndex = [&memProps](uint32_t wantedBits, const VkMemoryRequirements &memReqs) {
            uint32_t memTypeIndex = 0;
            for (uint32_t i = 0; i < memProps.memoryTypeCount; ++i) {
                if (memReqs.memoryTypeBits & (1 << i)) {
                    if ((memProps.memoryTypes[i].propertyFlags & wantedBits) == wantedBits) {
                        memTypeIndex = i;
                        break;
                    }
                }
            }
            return memTypeIndex;
        };

        VkMemoryRequirements memReq;
        df->vkGetImageMemoryRequirements(dev, img, &memReq);

        VkMemoryAllocateInfo memInfo = {};
        memInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
        memInfo.allocationSize = memReq.size;
        memInfo.memoryTypeIndex = findMemTypeIndex(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, memReq);

        VkDeviceMemory imgMem = VK_NULL_HANDLE;
        err = df->vkAllocateMemory(dev, &memInfo, nullptr, &imgMem);
        QCOMPARE(err, VK_SUCCESS);

        err = df->vkBindImageMemory(dev, img, imgMem, 0);
        QCOMPARE(err, VK_SUCCESS);

        // Tell Qt Quick to target our VkImage.
        quickWindow->setRenderTarget(QQuickRenderTarget::fromVulkanImage(img,
                                                                         VK_IMAGE_LAYOUT_PREINITIALIZED,
                                                                         rootItem->size().toSize()));

        // Create a readback buffer.
        VkBuffer buf = VK_NULL_HANDLE;
        VkDeviceMemory bufMem = VK_NULL_HANDLE;
        VkBufferCreateInfo bufInfo = {};
        bufInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
        bufInfo.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
        const int bufSize = int(rootItem->width()) * int(rootItem->height()) * 4;
        bufInfo.size = bufSize;

        df->vkCreateBuffer(dev, &bufInfo, nullptr, &buf);
        df->vkGetBufferMemoryRequirements(dev, buf, &memReq);
        memInfo.allocationSize = memReq.size;
        memInfo.memoryTypeIndex = findMemTypeIndex(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, memReq);
        err = df->vkAllocateMemory(dev, &memInfo, nullptr, &bufMem);
        QCOMPARE(err, VK_SUCCESS);
        df->vkBindBufferMemory(dev, buf, bufMem, 0);

        for (int frame = 0; frame < 100; ++frame) {
            // have to process events, e.g. to get queued metacalls delivered
            QCoreApplication::processEvents();

            if (frame > 0) {
                // Quick animations will now think that ANIM_ADVANCE_PER_FRAME milliseconds have passed,
                // even though in reality we have a tight loop that generates frames unthrottled.
                animDriver->advance();
            }

            renderControl->polishItems();

            renderControl->beginFrame();
            renderControl->sync();
            renderControl->render();
            renderControl->endFrame(); // submits the command buffer generated by Qt Quick to the command queue
            // ...and, it also waits for completion. This is different from how an on-screen frame would behave,
            // offscreen frames are always synchronous with QRhi. Which is very handy for us here.

            // Now issue a readback.

            VkCommandBuffer cb = VK_NULL_HANDLE;
            VkCommandBufferAllocateInfo cmdBufInfo = {};
            cmdBufInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
            cmdBufInfo.commandPool = cmdPool;
            cmdBufInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
            cmdBufInfo.commandBufferCount = 1;

            VkResult err = df->vkAllocateCommandBuffers(dev, &cmdBufInfo, &cb);
            QCOMPARE(err, VK_SUCCESS);

            VkCommandBufferBeginInfo cmdBufBeginInfo = {};
            cmdBufBeginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;

            err = df->vkBeginCommandBuffer(cb, &cmdBufBeginInfo);
            QCOMPARE(err, VK_SUCCESS);

            // rendering into a VkImage with Qt Quick leaves it in COLOR_ATTACHMENT_OPTIMAL
            VkImageMemoryBarrier barrier = {};
            barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
            barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
            barrier.subresourceRange.levelCount = VK_REMAINING_MIP_LEVELS;
            barrier.subresourceRange.layerCount = VK_REMAINING_ARRAY_LAYERS;
            barrier.oldLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
            barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
            barrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
            barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
            barrier.image = img;

            df->vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
                                     0, 0, nullptr, 0, nullptr,
                                     1, &barrier);

            VkBufferImageCopy copyDesc = {};
            copyDesc.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
            copyDesc.imageSubresource.layerCount = 1;
            copyDesc.imageExtent.width = uint32_t(rootItem->width());
            copyDesc.imageExtent.height = uint32_t(rootItem->height());
            copyDesc.imageExtent.depth = 1;

            df->vkCmdCopyImageToBuffer(cb, img, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, buf, 1, &copyDesc);

            // Must restore the previous layout since nothing is telling Qt
            // here that the layout changed so it will expect it to still be in
            // COLOR_ATTACHMENT_OPTIMAL in the next iteration.
            barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
            barrier.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
            barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
            barrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;

            df->vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
                                     0, 0, nullptr, 0, nullptr,
                                     1, &barrier);

            err = df->vkEndCommandBuffer(cb);
            QCOMPARE(err, VK_SUCCESS);

            VkSubmitInfo submitInfo = {};
            submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
            submitInfo.commandBufferCount = 1;
            submitInfo.pCommandBuffers = &cb;
            VkPipelineStageFlags psf = VK_PIPELINE_STAGE_TRANSFER_BIT;
            submitInfo.pWaitDstStageMask = &psf;

            err = df->vkQueueSubmit(cmdQueue, 1, &submitInfo, VK_NULL_HANDLE);
            QCOMPARE(err, VK_SUCCESS);

            // just block until the image-to-buffer-copy result is available
            df->vkQueueWaitIdle(cmdQueue);

            df->vkFreeCommandBuffers(dev, cmdPool, 1, &cb);

            uchar *p = nullptr;
            df->vkMapMemory(dev, bufMem, 0, bufSize, 0, reinterpret_cast<void **>(&p));
            // create a wrapper QImage
            QImage img(reinterpret_cast<const uchar *>(p), rootItem->width(), rootItem->height(), QImage::Format_RGBA8888_Premultiplied);

            // and the usual verification:

            const int maxFuzz = 2;

            // The scene is: background, rectangle, text
            // where rectangle rotates

            QRgb background = img.pixel(5, 5);
            QVERIFY(qAbs(qRed(background) - 70) < maxFuzz);
            QVERIFY(qAbs(qGreen(background) - 130) < maxFuzz);
            QVERIFY(qAbs(qBlue(background) - 180) < maxFuzz);

            background = img.pixel(195, 195);
            QVERIFY(qAbs(qRed(background) - 70) < maxFuzz);
            QVERIFY(qAbs(qGreen(background) - 130) < maxFuzz);
            QVERIFY(qAbs(qBlue(background) - 180) < maxFuzz);

            // after about 1.25 seconds (animation time, one iteration is 16 ms
            // thanks to our custom animation driver) the rectangle reaches a 90
            // degree rotation, that should be frame 76
            if (frame <= 2 || (frame >= 76 && frame <= 80)) {
                QRgb c = img.pixel(28, 28); // rectangle
                QVERIFY(qAbs(qRed(c) - 152) < maxFuzz);
                QVERIFY(qAbs(qGreen(c) - 251) < maxFuzz);
                QVERIFY(qAbs(qBlue(c) - 152) < maxFuzz);
            } else {
                QRgb c = img.pixel(28, 28); // background because rectangle got rotated so this pixel is not covered by it
                QVERIFY(qAbs(qRed(c) - 70) < maxFuzz);
                QVERIFY(qAbs(qGreen(c) - 130) < maxFuzz);
                QVERIFY(qAbs(qBlue(c) - 180) < maxFuzz);
            }

            img = QImage();
            df->vkUnmapMemory(dev, bufMem);
        }

        df->vkDestroyImage(dev, img, nullptr);
        df->vkFreeMemory(dev, imgMem, nullptr);

        df->vkDestroyBuffer(dev, buf, nullptr);
        df->vkFreeMemory(dev, bufMem, nullptr);

        df->vkDestroyCommandPool(dev, cmdPool, nullptr);
    }

    // now that everything is destroyed, get rid of the VkDevice too
    df->vkDestroyDevice(dev, nullptr);
    vulkanInstance.resetDeviceFunctions(dev);
#else
    QSKIP("No Vulkan support in Qt build, skipping native Vulkan test");
#endif
}

#include "tst_qquickrendercontrol.moc"

QTEST_MAIN(tst_RenderControl)