summaryrefslogtreecommitdiffstats
path: root/src/runtime/dragon/dragonrenderer.cpp
blob: 2fef519d8d0751b89c41ac95d94ffb2335942746 (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
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
/****************************************************************************
**
** Copyright (C) 2015 Klaralvdalens Datakonsult AB (KDAB).
** Copyright (C) 2017 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of Qt 3D Studio.
**
** $QT_BEGIN_LICENSE:GPL$
** 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 or (at your option) any later version
** approved by the KDE Free Qt Foundation. The licenses are as published by
** the Free Software Foundation and appearing in the file LICENSE.GPL3
** 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 "dragonrenderer_p.h"

#include <private/dragonactivatedsurface_p.h>
#include <private/dragondraw_p.h>
#include <private/dragongltexture_p.h>
#include <private/dragongraphicshelperinterface_p.h>
#include <private/dragonopenglvertexarrayobject_p.h>
#include <private/dragontexture_p.h>
#include <private/dragonrendertarget_p.h>
#include <private/dragonblitframebuffer_p.h>
#include <private/dragonrenderview_p.h>
#include <private/dragonscene2d_p.h>

// For Qt3DRender::Render::SurfaceLocker (private export)
#include <Qt3DRender/private/platformsurfacefilter_p.h>

#include <QtGui/private/qopenglcontext_p.h>

#include <QCoreApplication>
#include <QOffscreenSurface>
#include <QOpenGLExtraFunctions>
#include <QOpenGLPixelTransferOptions>
#include <QOpenGLTexture>

QT_BEGIN_NAMESPACE

using namespace Qt3DCore;

namespace Qt3DRender {
namespace Dragon {

using GraphicsHelperInterface = Dragon::GraphicsHelperInterface;

GraphicsApiFilterData contextInfo(const QOpenGLContext &m_gl)
{
    GraphicsApiFilterData m_contextInfo;
    QStringList extensions;
    const auto exts = m_gl.extensions();
    for (const QByteArray &ext : exts)
        extensions << QString::fromUtf8(ext);
    m_contextInfo.m_major = m_gl.format().version().first;
    m_contextInfo.m_minor = m_gl.format().version().second;
    m_contextInfo.m_api = m_gl.isOpenGLES() ? QGraphicsApiFilter::OpenGLES
                                            : QGraphicsApiFilter::OpenGL;
    m_contextInfo.m_profile = static_cast<QGraphicsApiFilter::OpenGLProfile>(
            m_gl.format().profile());
    m_contextInfo.m_extensions = extensions;
    m_contextInfo.m_vendor = QString::fromUtf8(
            reinterpret_cast<const char *>(m_gl.functions()->glGetString(GL_VENDOR)));
    return m_contextInfo;
}

/*!
 \brief Renderer lives on a separate thread performs the actual rendering of the RenderCommands
from each RenderView.

The Renderer is intended to hold a thin abstraction layer around OpenGL (or other) backend
functions with the following properties:

- No OpenGL functions should be possible to call out of order when using the abstraction layer.
- That means, each function should take the state it expects explicitly as input.
- We should never allow a function to depend on OpenGL state that is implicit,
  which for instance means that no command should depend on a buffer being bound by a previous command.
- We should have a class or struct that holds relevant OpenGL state information,
  which allows us to avoid calling certain OpenGL functions when the correct state is already set.
- The abstractions should be fairly simple and specific to our purposes.
  We do not want to create a general OpenGL library.
- That means, we may very well call multiple OpenGL functions within one function that has
  complete control over its state.

This abstraction layer could be the same for all render backends or we might need to implement
a Renderer for each backend.

*/

Renderer::Renderer(RenderType renderType)
        : nextFrameSemaphore(1)
        , m_renderThread(renderType == Threaded ? new RenderThread(this) : nullptr)
        , m_running(1)
        , m_renderType(renderType)
{
    if (m_renderThread)
        m_renderThread->waitForStart();
}

Renderer::~Renderer()
{
    m_running.store(0);
    if (m_renderThread) {
        // Make sure the render thread is not stuck in the Renderer::render() call
        m_waitForInitializationToBeCompleted.release(1);
        m_renderThread->wait();
    }
    m_offscreenHelper->deleteLater();
    if (m_ownedContext)
        m_glContext->deleteLater();
    if (m_ownedShareContext)
        m_shareContext->deleteLater();
}

/*!
 * \internal
 * \brief Renderer::initialize
 *
 * If a context is provided to this function, it will be used for rendering,
 * which is the case for Studio3D and Scene3D items.
 */
void Renderer::initialize(QOpenGLContext *context)
{
    if (context != nullptr) {
        m_glContext = context;
    } else {
        m_glContext = new QOpenGLContext;
        m_glContext->setShareContext(qt_gl_global_share_context());

        if (!m_glContext->create())
            qWarning() << Q_FUNC_INFO << "OpenGL context creation failed";

        m_ownedContext = true;
    }

    if (!m_glContext->shareContext()) {
        m_shareContext = new QOpenGLContext;
        m_shareContext->setFormat(m_glContext->format());
        m_shareContext->setShareContext(m_glContext);
        m_shareContext->create();
        m_ownedShareContext = true;
    } else {
        m_shareContext = m_glContext->shareContext();
    }

    m_offscreenHelper = new OffscreenSurfaceHelper(m_glContext->format());
    m_offscreenHelper->moveToThread(QCoreApplication::instance()->thread());

    QMetaObject::invokeMethod(m_offscreenHelper, "createOffscreenSurface");

    m_waitForInitializationToBeCompleted.release();
}

QOpenGLContext *Renderer::openGLContext() const
{
    return m_glContext;
}

QOpenGLContext *Renderer::shareContext() const
{
    return m_shareContext;
}

void Renderer::addLatestData(FrameInput data)
{
    QMutexLocker lock(&m_latestDataMutex);
    m_latestData.enqueue(data);
}

/*!
 * \brief Renderer::contextInfo
 *
 * Blocks until doRender has gotten context info for us.
 *
 * \param views
 * \return
 */
GraphicsApiFilterData Renderer::contextInfo(RenderViews views)
{
    {
        QMutexLocker lock(&m_latestDataMutex);
        m_contextInfoRequested = true;
        m_requestedContextInfoViews = views;
        m_writeContextInfoSemaphore.release();
    }
    m_readContextInfoSemaphore.acquire();
    GraphicsApiFilterData result = [this]() {
        QMutexLocker lock(&m_latestDataMutex);
        return m_contextInfo;
    }();
    return result;
}

void Renderer::render()
{
    m_waitForInitializationToBeCompleted.acquire();

    Q_ASSERT(m_glContext != nullptr);

    Frame frame;
    while (m_running.load() > 0) {
        // TODO we probably need to move this inside doRender...
        // TODO we should wait for render views to appear :)
        frame = doRender(std::move(frame));
    }
    // Make sure there is a context to use for the cleanup of resources
    Q_ASSERT(m_offscreenHelper->offscreenSurface());
    m_glContext->makeCurrent(m_offscreenHelper->offscreenSurface());
}

void Renderer::checkContextInfoRequested()
{
    QMutexLocker lock(&m_latestDataMutex);
    if (m_contextInfoRequested) {
        // This is the only input/output we allow the renderer
        // to perform with the aspect apart from the render views.
        // Everything else, such as uploading textures or shaders
        // needs to be submitted with the views and happens below,
        // while preparing rendering.
        m_writeContextInfoSemaphore.acquire();
        const RenderViews views = m_requestedContextInfoViews;
        for (const auto &view : views) {
            auto *surface = view->surface;
            Render::SurfaceLocker lock(surface);
            if (!lock.isSurfaceValid()) {
                continue;
            }
            ActivatedSurface gl(surface, m_glContext, &lock);
            if (!gl.isValid()) {
                continue;
            }
            m_contextInfo = gl.contextInfo();
            break;
        }
        m_contextInfoRequested = false;
        m_requestedContextInfoViews = {};
        m_readContextInfoSemaphore.release();
    }
}

// Render and run commands of the frame
Renderer::Frame Renderer::doRender(Renderer::Frame frame)
{
    Q_ASSERT(m_glContext != nullptr);

    // In case someone has requested context info, we gather context info
    checkContextInfoRequested();

    // TODO jobs expect us to receive and upload textures, if that fails below,
    // we're in a position where we do not know about said data anymore...
    // Make sure to not remove frames from the queue until we are ready to render!
    // That is, implement an actual queue and don't remove elements unless they will be rendered
    FrameInput frameInput = [this]() {
        QMutexLocker lock(&m_latestDataMutex);
        if (m_latestData.size() == 0) {
            return FrameInput();
        }
        nextFrameSemaphore.release();
        return m_latestData.dequeue();
    }();

    // Convenience aliases
    const auto &renderViews = frameInput.renderViews;
    const auto &loadedTextures = frameInput.loadedTextures;
    const auto &shaders = frameInput.shaders;
    const auto &attributes = frameInput.attributes;
    const auto &loadedBuffers = frameInput.loadedBuffers;
    const auto &leafNodes = frameInput.frameGraph.leafNodes;
    const auto &scene2ds = frameInput.scene2ds;

    if (renderViews.size() == 0) {
        // TODO make throttle target a max FPS
        QThread::msleep(1); // throttle to avoid looping too fast
        return frame;
    }

    // TODO this could be done before being passed to doRender
    // TODO after all, we know the leaf node id when building the RenderView
    struct SurfaceInfo {
        QNodeId leafNodeId;
        Immutable<RenderView> renderView;
    };

    QVector<QNodeId> texturesUsedInRenderTargets;
    QHash<QSurface *, QVector<SurfaceInfo>> surfaceViews; // ordered
    for (const auto &leafNodeId : leafNodes) {
        // TODO IMPORTANT make sure the views are ordered correctly regardless of surface differences
        const auto &renderView = renderViews[leafNodeId];
        SurfaceInfo info { leafNodeId, renderView };
        surfaceViews[renderView->surface].push_back(info);

        // We need a list of texture IDs that are used in render targets and hence cannot be shared
        for (const auto &renderTarget : renderView->attachmentPack.outputs) {
            if (!texturesUsedInRenderTargets.contains(renderTarget->textureUuid))
                texturesUsedInRenderTargets.push_back(renderTarget->textureUuid);
        }
    }
    for (const auto &scene2d : scene2ds) {
        if (scene2d->m_texture.id() != 0
                && !texturesUsedInRenderTargets.contains(scene2d->m_texture)) {
            texturesUsedInRenderTargets.push_back(scene2d->m_texture);
        }
    }

    // Start with empty state, to force default state set
    RenderStateSet stateSet;

    bool preparationsComplete = false;

    QHashIterator<QSurface *, QVector<SurfaceInfo>> surfaceViewsIterator(surfaceViews);
    while (surfaceViewsIterator.hasNext()) {

        const auto view = surfaceViewsIterator.next();
        auto *surface = view.key();

        // Preparations need an OpenGL context, but it can be any, so let's pick the first valid surface
        const auto &surfaceInfos = view.value();

        Render::SurfaceLocker lock(surface);
        if (!lock.isSurfaceValid()) {
            continue;
        }

        ActivatedSurface activeSurface(surface, m_glContext, &lock);
        if (!activeSurface.isValid()) {
            continue;
        }

        // Make sure to reset to defaults before starting frame
        stateSet = activeSurface.applyStateSet(stateSet, RenderStateSet::defaultRenderStateSet());

        const GLuint fboBeforeRender = activeSurface.glHelper()->boundFrameBufferObject();

        // We only need to do preparations such as uploading textures for one surface
        if (!preparationsComplete) {
            {
                // TODO strictly only necessary to do once?
                // Find the max number of texture units
                GLint maxTextureUnits = 0;
                m_glContext->functions()->glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS,
                                                        &maxTextureUnits);
                frame.maxTextureImageUnits = maxTextureUnits;
            }

            // TODO not nice to have to take this by reference, but what can we do?
            auto createGLTextureHelper =
                    [&activeSurface](const QNodeId &id, const Immutable<LoadedTexture> &loadedTexture) {
                    Q_UNUSED(id);
                    return Mutable<GLTexture>(createGlTexture(loadedTexture, activeSurface.openGLContext()));
            };

            auto compareGLTexture = [texturesUsedInRenderTargets](const GLTexture &glTexture, const Immutable<LoadedTexture> &loaded){
                // If a texture is used in a render target, it cannot share GLTexture with other textures
                // TODO Consider separating the concept of any texture and one that is being rendered to, at least on the backend
                if (texturesUsedInRenderTargets.contains(glTexture.loadedTexture->texture->peerId())
                        || texturesUsedInRenderTargets.contains(loaded->texture->peerId()))
                    return false;

                return glTexture.loadedTexture == loaded;
            };

            frame.uploadedTextures = synchronizeNew(std::move(frame.uploadedTextures),
                                                    loadedTextures,
                                                    compareGLTexture,
                                                    createGLTextureHelper);

            auto updateGLTextureHelper = [&activeSurface](const QNodeId &id, Mutable<GLTexture> glTexture,
                                                          const Immutable<LoadedTexture> &loadedTexture) {
                Q_UNUSED(id);
                auto result = glTexture.take([&activeSurface, loadedTexture](GLTexture tmp) {
                    // TODO this is unnecessary - we could have derived properties when we first loaded instead
                    const auto loadedProperties = deriveProperties(loadedTexture);
                    // Test if we can reuse the previous texture
                    if (tmp.properties == loadedProperties && tmp.parameters == loadedTexture->texture->parameters)
                        tmp = reloadGLTexture(std::move(tmp), loadedTexture);
                    else
                        tmp = createGlTexture(loadedTexture, activeSurface.openGLContext());
                    return tmp;
                });
                return result;
            };

            frame.uploadedTextures = synchronizeDirty(std::move(frame.uploadedTextures),
                                                      loadedTextures,
                                                      updateGLTextureHelper);

            if (frame.uploadedTextures.anythingDirty()) {
                for (auto &tex : qAsConst(frame.uploadedTextures)) {
                    if (!tex->openGLTexture.isNull()) {
                        m_snaggedTextures[tex->loadedTexture->texture->peerId()]
                                = tex->openGLTexture;
                    }
                }
            }

            auto createGLShaderHelper = [&activeSurface](const QNodeId &id,
                                                         const Immutable<Shader> &shader) {
                Q_UNUSED(id);
                return GLShader(activeSurface, shader);
            };

            frame.uploadedShaders = synchronizeKeys(std::move(frame.uploadedShaders),
                                                    shaders,
                                                    createGLShaderHelper);

            auto createGLBufferHelper = [&activeSurface](const QNodeId &id,
                                                         const Immutable<LoadedBuffer> &buffer) {
                Q_UNUSED(id);
                return GLBuffer(activeSurface, buffer);
            };

            frame.uploadedBuffers = synchronizeNew(std::move(frame.uploadedBuffers),
                                                   loadedBuffers,
                                                   createGLBufferHelper);

            auto reloadGLBufferHelper = [](const QNodeId &id,
                                           Mutable<GLBuffer> glBuffer,
                                           const Immutable<LoadedBuffer> &loadedBuffer) {
                Q_UNUSED(id);
                // TODO the reload function could perhaps be moved to become a free function?
                // TODO the reload function could take gl as argument to ensure we have an active surface
                auto result = glBuffer.take([loadedBuffer](GLBuffer tmp) {
                    tmp.reload(loadedBuffer);
                    return tmp;
                });
                return result;
            };

            frame.uploadedBuffers = synchronizeDirty(std::move(frame.uploadedBuffers),
                                                     loadedBuffers,
                                                     reloadGLBufferHelper);

            // Per-view preparations
            for (const auto &surfaceInfo : surfaceInfos) {
                const auto &view = surfaceInfo.renderView;
                const auto &leafNodeId = surfaceInfo.leafNodeId;
                const auto &commands = frameInput.renderCommands[leafNodeId]->commands;
                for (const auto &acommand : commands) {
                    const auto &command = *acommand;
                    if (command.m_type == RenderCommand::Compute) {
                        qWarning() << "WARNING: Compute commands are not implemented in Dragon renderer yet";
                        continue;
                    }

                    // TODO consider storing VAOs in a TrackingChangesContainer
                    // and loop over dirty shaders and geometries to update vaos
                    const VAOIdentifier vaoKey(command.m_geometry->peerId(),
                                               command.m_shader->peerId());

                    // TODO actually check if attributes changed (see requiresVAOAttributeUpdate and requiresFullVAOUpdate)
                    if (!frame.uploadedVaos.contains(vaoKey)) {
                        // TODO make createVertexArrayObject take the shader and geometry (or just command) and return a complete VAO instead
                        const auto &glShader = frame.uploadedShaders.get(command.m_shader->peerId());
                        const auto &geometry = command.m_geometry;
                        const auto &vao = activeSurface.createVertexArrayObject(
                                vaoKey, glShader, geometry, attributes, frame.uploadedBuffers);
                        frame.uploadedVaos[vaoKey] = vao;
                    }
                }

                {
                    GLRenderTarget renderTarget;
                    renderTarget.frameBufferObjectId = fboBeforeRender;
                    frame.createdRenderTargets[QNodeId()] = renderTarget;
                }

                // Create render target
                if (!view->renderTargetId.isNull()) {
                    auto defaultFBO = m_glContext->defaultFramebufferObject();
                    // TODO consider why this is here, iOS apparently
                    auto lastBoundFBOId = activeSurface.glHelper()->boundFrameBufferObject();
                    const auto &renderTargetNodeId = view->renderTargetId;
                    const auto &attachments = view->attachmentPack;

                    if (!frame.createdRenderTargets.contains(renderTargetNodeId)) {
                        GLRenderTarget renderTarget;
                        if (defaultFBO != 0 && lastBoundFBOId == defaultFBO) {
                            // this is the default fbo that some platforms create (iOS),
                            // we just register it
                            renderTarget.frameBufferObjectId = defaultFBO;
                        } else {
                            renderTarget.frameBufferObjectId = activeSurface.glHelper()
                                                                       ->createFrameBufferObject();
                            if (!renderTarget.frameBufferObjectId) {
                                qCritical("Failed to create FBO");
                                continue;
                            }
                            // Bind FBO
                            activeSurface.glHelper()
                                    ->bindFrameBufferObject(renderTarget.frameBufferObjectId,
                                                            GraphicsHelperInterface::FBODraw);
                            activeSurface
                                    .bindFrameBufferAttachmentHelper(renderTarget.frameBufferObjectId,
                                                                     attachments,
                                                                     frame.uploadedTextures);
                        }
                        frame.createdRenderTargets[renderTargetNodeId] = renderTarget;
                    } else {
                        GLRenderTarget renderTarget = frame.createdRenderTargets.value(
                                renderTargetNodeId);
                        const QSize s = renderTarget.size;
                        const auto attachments_ = attachments.outputs;
                        bool needsResize = false;
                        for (const auto &attachment : attachments_) {
                            // ### TODO QTBUG-64757 this check is insufficient since the
                            // texture may have changed to another one with the same size. That
                            // case is not handled atm.
                            if (!frame.uploadedTextures.contains(attachment->textureUuid)) {
                                qWarning() << "ERROR: Could not find texture attachment"
                                           << attachment->textureUuid;
                                continue;
                            }
                            const auto &glTexture = frame.uploadedTextures[attachment->textureUuid];
                            needsResize |= (glTexture->size() != s);
                        }

                        if (needsResize) {
                            activeSurface.glHelper()
                                    ->bindFrameBufferObject(renderTarget.frameBufferObjectId,
                                                            GraphicsHelperInterface::FBODraw);
                            activeSurface
                                    .bindFrameBufferAttachmentHelper(renderTarget.frameBufferObjectId,
                                                                     attachments,
                                                                     frame.uploadedTextures);
                        }
                        frame.createdRenderTargets[view->renderTargetId] = renderTarget;
                    }
                }
            }

            preparationsComplete = true;
        }

        Q_ASSERT(preparationsComplete);

        // TODO might be better to just have to call swapBuffers manually
        bool autoSwapBuffers = m_renderType == RenderType::Threaded;
        activeSurface.beginDrawing(autoSwapBuffers);

        // TODO consider doing preparation and submission in one go

        // Lock scene2ds as they might be rendering simultaniously otherwise
        for (const auto &scene2d : scene2ds) {
            if (scene2d->m_texture.id() != 0 && scene2d->m_mutex)
                scene2d->m_mutex->lock();
        }

        // Submission
        for (const auto &surfaceInfo : surfaceInfos) {
            const auto &view = surfaceInfo.renderView;
            const auto &leafNodeId = surfaceInfo.leafNodeId;
            const auto &commands = frameInput.renderCommands[leafNodeId]->commands;
            const auto &cameraMatrices = frameInput.renderViewCameraMatrices[leafNodeId];

            stateSet = activeSurface.applyStateSet(stateSet, view->renderStateSet.get());

            activeSurface.memoryBarrier(view->memoryBarrier);
            // TODO clear colors for individual buffers

            // TODO consider having this function return a render target that is passed to the following functions
            activeSurface.activateRenderTarget(frame.createdRenderTargets[view->renderTargetId].frameBufferObjectId, view->attachmentPack);

            activeSurface.clearBackBuffer(view->clearBackBufferInfo);
            // TODO make it return a viewport, used by other functions that need one

            activeSurface.setViewport(view->viewport, view->surfaceSize * view->devicePixelRatio);

            for (const auto &acommand : commands) {
                const auto &command = *acommand;
                if (command.m_type == RenderCommand::Compute) {
                    qWarning() << "WARNING: Compute commands are not implemented in Dragon renderer yet";
                    continue;
                }

                // TODO upload geometry data (in a job)
                // TODO prepare shader uniforms
                // TODO check if anything is missing from commands (see old prepareCommandSubmission)
                const auto &glShader = frame.uploadedShaders.get(command.m_shader->peerId());

                stateSet = activeSurface.applyStateSet(stateSet, command.m_renderStateSet.get());

                // TODO execute command submission

                const VAOIdentifier vaoKey(command.m_geometry->peerId(), command.m_shader->peerId());
                Q_ASSERT(frame.uploadedVaos.contains(vaoKey));
                const auto &vao = frame.uploadedVaos[vaoKey];

                Commands::draw(activeSurface,
                               view,
                               cameraMatrices,
                               frame.uploadedBuffers,
                               frame.uploadedTextures,
                               frame.maxTextureImageUnits,
                               acommand,
                               glShader,
                               frameInput.attributes,
                               frameInput.parameters,
                               frameInput.worldTransforms,
                               vao);

                //      - build info for render command
                //      - bind buffer (indirect or direct)
                //      - draw (elements or arrays)
                //  - TODO release vao (consider RAII)
                //  - TODO reset state set (consider RAII)
            }

            if (view->blitFrameBufferInfo.has_value()) {
                // TODO verify that this is the right value to use for the default fbo id
                auto defaultFboId = frame.createdRenderTargets[view->renderTargetId].frameBufferObjectId;
                activeSurface.blitFramebuffer(view->blitFrameBufferInfo.get(),
                                              defaultFboId, frame.uploadedTextures);
            }

            // TODO consider render capture
            // TODO consider download GL buffers
            // TODO consider blit framebuffer info
            // TODO bind framebuffer
        }

        // Unlock scene2ds
        for (const auto &scene2d : scene2ds) {
            if (scene2d->m_texture.id() != 0 && scene2d->m_mutex)
                scene2d->m_mutex->unlock();
        }

        // Make sure to reset to defaults before finishing frame
        stateSet = activeSurface.applyStateSet(stateSet, RenderStateSet::defaultRenderStateSet());
    }

    frame.number += 1;
    return frame;
}

void Renderer::beginShutdown()
{
    QMutexLocker lock(&m_latestDataMutex);

    m_running.store(0);
    m_latestData.clear();
    nextFrameSemaphore.release();

    if (m_renderThread) {
        m_renderThread->wait();
    } else {
        Q_ASSERT(m_offscreenHelper->offscreenSurface());
        m_glContext->makeCurrent(m_offscreenHelper->offscreenSurface());
        clear();
    }
}

void Renderer::endShutdown()
{
    if (!m_renderThread)
        m_glContext->doneCurrent();
}

RenderThread::RenderThread(Renderer *renderer)
        : QThread()
        , m_renderer(renderer)
{
}

void RenderThread::run()
{
    // return control to the aspect thread that created us.
    m_semaphore.release();

    // This call to Renderer::initialize() waits for a surface to be set on the
    // renderer in the context of the Aspect Thread
    m_renderer->initialize();

    // Enter the main OpenGL submission loop.
    m_renderer->render();

    m_renderer->clear();
    // Clean up any OpenGL resources
    //    m_renderer->releaseGraphicsResources();

    // qCDebug(Render::Backend) << "Exiting RenderThread";
}

void RenderThread::waitForStart(Priority priority)
{
    start(priority);
    m_semaphore.acquire();
}

} // namespace Dragon
} // namespace Qt3DRender
QT_END_NAMESPACE