aboutsummaryrefslogtreecommitdiffstats
path: root/src/runtimerender/rendererimpl/qssgrenderdata.cpp
blob: 37143d54b8e588b3e212e9b5361ce55632bb6527 (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
// Copyright (C) 2025 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only

#include "qssgrenderdata_p.h"

#if QT_CONFIG(thread)
#include <QtCore/qthreadpool.h>
#endif // QT_CONFIG(thread)

#include "graphobjects/qssgrenderroot_p.h"
#include "graphobjects/qssgrenderlayer_p.h"
#include "qssgrendercontextcore.h"
#include "qssgrenderer_p.h"
#include "resourcemanager/qssgrenderbuffermanager_p.h"

QT_BEGIN_NAMESPACE

static void reindexChildNodes(QSSGRenderNode &node, const quint32 version, quint32 &dfsIdx, size_t &count)
{
    Q_ASSERT(node.type != QSSGRenderNode::Type::Layer);
    if (node.type != QSSGRenderNode::Type::Layer) {
        // Note: In the case of import scenes the version and index might already
        // have been set. We therefore assume nodes with same version is already
        // indexed.
        if (node.h.version() != version)
            node.h = QSSGRenderNodeHandle(0, version, dfsIdx);
        for (QSSGRenderNode &chld : node.children)
            reindexChildNodes(chld, version, ++dfsIdx, ++count);
    }
}

static void reindexLayerChildNodes(QSSGRenderLayer &layer, const quint32 version, quint32 &dfsIdx, size_t &count)
{
    Q_ASSERT(layer.type == QSSGRenderNode::Type::Layer);
    if (layer.type == QSSGRenderNode::Type::Layer) {
        layer.h = QSSGRenderNodeHandle(0, version, 0); // Layer nodes are always indexed at 0;
        for (QSSGRenderNode &chld : layer.children)
            reindexChildNodes(chld, version, ++dfsIdx, ++count);
    }
}

static void reindex(QSSGRenderRoot *rootNode, const quint32 version, quint32 &dfsIdx, size_t &count)
{
    if (rootNode) {
        Q_ASSERT(rootNode->type == QSSGRenderNode::Type::Root);
        Q_ASSERT(dfsIdx == 0);
        rootNode->h = QSSGRenderNodeHandle(0, version, 0);
        for (QSSGRenderNode &chld : rootNode->children) // These should be layer nodes
            reindexLayerChildNodes(static_cast<QSSGRenderLayer &>(chld), version, dfsIdx, count);
    }
}

enum class Insert { Back, Indexed };
template <Insert insert = Insert::Back>
static void collectChildNodesFirst(QSSGRenderNode &node, QSSGGlobalRenderNodeData::NodeStore &outList, [[maybe_unused]] size_t &idx)
{
    Q_ASSERT_X(node.type != QSSGRenderNode::Type::Layer, Q_FUNC_INFO, "Unexpected Layer node in child list!");
    if constexpr (insert == Insert::Indexed)
        outList[idx++] = &node;
    else
        outList.push_back(&node);
    for (QSSGRenderNode &chld : node.children)
        collectChildNodesFirst<insert>(chld, outList, idx);
}

template <Insert insert = Insert::Back>
static void collectChildNodesSecond(QSSGRenderNode &node, QSSGGlobalRenderNodeData::NodeStore &outList, [[maybe_unused]] size_t &idx)
{
    if (node.getGlobalState(QSSGRenderNode::GlobalState::Active)) {
        if constexpr (insert == Insert::Indexed)
            outList[idx++] = &node;
        else
            outList.push_back(&node);
        for (QSSGRenderNode &chld : node.children)
            collectChildNodesSecond<insert>(chld, outList, idx);
    }
}

enum class Discard { None, Inactive };
template <Discard discard = Discard::None, Insert insert = Insert::Back>
static void collectLayerChildNodes(QSSGRenderLayer *layer, QSSGGlobalRenderNodeData::NodeStore &outList, [[maybe_unused]] size_t &idx)
{
    Q_ASSERT(layer->type == QSSGRenderNode::Type::Layer);
    if (layer) {
        for (QSSGRenderNode &chld : layer->children) {
            if constexpr (discard == Discard::Inactive)
                collectChildNodesSecond<insert>(chld, outList, idx);
            else
                collectChildNodesFirst<insert>(chld, outList, idx);
        }
    }

    if  constexpr (insert == Insert::Back)
        idx = outList.size();
}

template <QSSGRenderDataHelpers::Strategy Strategy>
static bool calcGlobalNodeDataIndexedImpl(QSSGRenderNode *node,
                                          const quint32 version,
                                          QSSGGlobalRenderNodeData::GlobalTransformStore &globalTransforms,
                                          QSSGGlobalRenderNodeData::GlobalOpacityStore &globalOpacities)
{
    using DirtyFlag = QSSGRenderNode::DirtyFlag;
    using FlagT = QSSGRenderNode::FlagT;
    constexpr DirtyFlag TransformAndOpacityDirty = DirtyFlag(FlagT(DirtyFlag::TransformDirty) | FlagT(DirtyFlag::OpacityDirty));

    if (Q_UNLIKELY(!node || (node->h.version() != version)))
        return false;

    constexpr bool forcedRebuilf = (Strategy == QSSGRenderDataHelpers::Strategy::Initial);
    bool retval = forcedRebuilf || node->isDirty(TransformAndOpacityDirty);

    if (retval) {
        const auto idx = node->h.index();

        auto &globalTransform = globalTransforms[idx];
        auto &globalOpacity = globalOpacities[idx];
        globalOpacity = node->localOpacity;
        globalTransform = node->localTransform;

        if (QSSGRenderNode *parent = node->parent) {
            const auto pidx = parent->h.index();
            const auto pOpacity = globalOpacities[pidx];
            globalOpacity *= pOpacity;

            if (parent->type != QSSGRenderGraphObject::Type::Layer) {
                const auto pTransform = globalTransforms[pidx];
                globalTransform = pTransform * node->localTransform;
            }
        }
        // Clear dirty flags (Transform, Opacity, Active, Pickable)
        node->clearDirty(TransformAndOpacityDirty);
    }

    // We always clear dirty in a reasonable manner but if we aren't active
    // there is no reason to tell the universe if we are dirty or not.
    return retval;
}

QSSGRenderDataHelpers::GlobalStateResult QSSGRenderDataHelpers::updateGlobalNodeState(QSSGRenderNode *node, const quint32 version)
{
    using LocalState = QSSGRenderNode::LocalState;
    using GlobalState = QSSGRenderNode::GlobalState;
    using DirtyFlag = QSSGRenderNode::DirtyFlag;
    using FlagT = QSSGRenderNode::FlagT;

    constexpr DirtyFlag ActiveOrPickableDirty = DirtyFlag(FlagT(DirtyFlag::ActiveDirty) | FlagT(DirtyFlag::PickableDirty));

    if (Q_UNLIKELY(!node || (node->h.version() != version)))
        return GlobalStateResult::None;

    const bool activeDirty = node->isDirty(DirtyFlag::ActiveDirty);
    const bool pickableDirty = node->isDirty(DirtyFlag::PickableDirty);

    const bool updateState = activeDirty || pickableDirty;

    if (updateState) {
        const QSSGRenderNode *parent = node->parent;
        const bool hasParent = (parent != nullptr);
        const bool globallyActive = node->getLocalState(LocalState::Active) && (!hasParent || parent->getGlobalState(GlobalState::Active));
        node->flags = globallyActive ? (node->flags | FlagT(GlobalState::Active)) : (node->flags & ~FlagT(GlobalState::Active));
        const bool globallyPickable = node->getLocalState(LocalState::Pickable) || (hasParent && parent->getGlobalState(GlobalState::Pickable));
        node->flags = globallyPickable ? (node->flags | FlagT(GlobalState::Pickable)) : (node->flags & ~FlagT(GlobalState::Pickable));

        // Clear dirty flags (Transform, Opacity, Active, Pickable)
        node->clearDirty(ActiveOrPickableDirty);
    }

    return GlobalStateResult((activeDirty << 1) | (pickableDirty << 2));
}

bool QSSGRenderDataHelpers::calcInstanceTransforms(QSSGRenderNode *node,
                                                   const quint32 version,
                                                   QSSGGlobalRenderNodeData::GlobalTransformStore &globalTransforms,
                                                   QSSGGlobalRenderNodeData::InstanceTransformStore &instanceTransforms)
{
    if (Q_UNLIKELY(!node || (node->h.version() != version)))
        return false;

    constexpr bool retval = true;

    // NOTE: We've already calculated the global states and transforms at this point
    // so if the node isn't active we don't need to do anything.
    // We're also assuming the node list is stored depth first order.
    const auto idx = node->h.index();
    QSSGRenderNode *parent = node->parent;
    if (parent && parent->type != QSSGRenderGraphObject::Type::Layer && node->getLocalState(QSSGRenderNode::LocalState::Active)) {
        const auto pidx = parent->h.index();
        const auto &pGlobalTransform = globalTransforms[pidx];
        QSSGRenderNode *instanceRoot = node->instanceRoot;
        if (instanceRoot == node) {
            instanceTransforms[idx] = { node->localTransform, pGlobalTransform };
        } else if (instanceRoot) {
            auto &[nodeInstanceLocalTransform, nodeInstanceGlobalTransform] = instanceTransforms[idx];
            auto &[instanceRootLocalTransform, instanceRootGlobalTransform] = instanceTransforms[instanceRoot->h.index()];
            nodeInstanceGlobalTransform = instanceRootGlobalTransform;
            //### technically O(n^2) -- we could cache localInstanceTransform if every node in the
            // tree is guaranteed to have the same instance root. That would require an API change.
            nodeInstanceLocalTransform = node->localTransform;
            auto *p = parent;
            while (p) {
                if (p == instanceRoot) {
                    nodeInstanceLocalTransform = instanceRootLocalTransform * nodeInstanceLocalTransform;
                    break;
                }
                nodeInstanceLocalTransform = p->localTransform * nodeInstanceLocalTransform;
                p = p->parent;
            }
        } else {
            // By default, we do magic: translation is applied to the global instance transform,
            // while scale/rotation is local
            QMatrix4x4 globalInstanceTransform = globalTransforms[pidx];
            QMatrix4x4 localInstanceTransform = node->localTransform;
            auto &localInstanceMatrix = *reinterpret_cast<float (*)[4][4]>(localInstanceTransform.data());
            QVector3D localPos{localInstanceMatrix[3][0], localInstanceMatrix[3][1], localInstanceMatrix[3][2]};
            localInstanceMatrix[3][0] = 0;
            localInstanceMatrix[3][1] = 0;
            localInstanceMatrix[3][2] = 0;
            globalInstanceTransform = pGlobalTransform;
            globalInstanceTransform.translate(localPos);
            instanceTransforms[idx] = { localInstanceTransform, globalInstanceTransform };
        }
    } else {
        instanceTransforms[idx] = { node->localTransform, {} };
    }

    return retval;
}

QSSGGlobalRenderNodeData::QSSGGlobalRenderNodeData()
#if QT_CONFIG(thread)
    : m_threadPool(new QThreadPool)
#endif // QT_CONFIG(thread)
{

}

QSSGGlobalRenderNodeData::~QSSGGlobalRenderNodeData()
{

}

void QSSGGlobalRenderNodeData::reindex(QSSGRenderRoot *rootNode)
{
    if (rootNode) {
        quint32 dfsIdx = 0;
        m_nodeCount = 0;

        // If the window changes the window root node changes as well,
        // this check ensures we accidentally don't reindex with the
        // same version, as that can cause problems.
        // The start version should be set to the last layer's last version.
        if (m_version == rootNode->startVersion())
            m_version = rootNode->startVersion() + 1;
        else
            ++m_version;

        ::reindex(rootNode, m_version, dfsIdx, m_nodeCount);

        // Actual storage size (Some nodes, like the layers, will all use index 0).
        // NOTE: This can differ from the node count, as nodes are collected for each
        // layer. Since layers can reference nodes outside their view the node list
        // will contain duplicate nodes when import scene is used!
        m_size = dfsIdx + 1;

        globalTransforms.resize(m_size, QMatrix4x4{ Qt::Uninitialized });
        globalOpacities.resize(m_size, 1.0f);
        instanceTransforms.resize(m_size, { QMatrix4x4{ Qt::Uninitialized }, QMatrix4x4{ Qt::Uninitialized } });

        collectNodes(rootNode);
        // NOTE: If the tree was dirty we force a full rebuild of the global transforms etc. since
        //       the stored data is invalid for the new index order.
        updateGlobalState();
    }
}

QMatrix4x4 QSSGGlobalRenderNodeData::getGlobalTransform(QSSGRenderNodeHandle h, QMatrix4x4 defaultValue) const
{
    // Ensure we have an valid index.
    const bool hasId = h.hasId();
    const bool validVersion = hasId && (h.version() == m_version);
    const auto index = h.index();

    // NOTE: In effect we are returning the local transform here in some cases, which
    // is why we don't assert or have hints about the likelyhood of branching here.
    if (!validVersion || !(globalTransforms.size() > index))
        return defaultValue;

    return globalTransforms[index];
}

QMatrix4x4 QSSGGlobalRenderNodeData::getGlobalTransform(QSSGRenderNodeHandle h) const
{
    return getGlobalTransform(h, QMatrix4x4{ Qt::Uninitialized });
}

QMatrix4x4 QSSGGlobalRenderNodeData::getGlobalTransform(const QSSGRenderNode &node) const
{
    return getGlobalTransform(node.h, node.localTransform);
}

float QSSGGlobalRenderNodeData::getGlobalOpacity(QSSGRenderNodeHandle h, float defaultValue) const
{
    const bool hasId = h.hasId();
    const bool validVersion = hasId && (h.version() == m_version);
    const auto index = h.index();

    if (!validVersion || !(globalOpacities.size() > index))
        return defaultValue;

    return globalOpacities[index];
}

float QSSGGlobalRenderNodeData::getGlobalOpacity(const QSSGRenderNode &node) const
{
    return getGlobalOpacity(node.h, node.localOpacity);
}

#if QT_CONFIG(thread)
const std::unique_ptr<QThreadPool> &QSSGGlobalRenderNodeData::threadPool() const { return m_threadPool; }
#endif // QT_CONFIG(thread)

QSSGGlobalRenderNodeData::LayerNodeView QSSGGlobalRenderNodeData::getLayerNodeView(QSSGRenderLayerHandle h) const
{
    const bool hasId = h.hasId();
    const bool validVersion = hasId && (h.version() == m_version);
    const auto index = h.index();

    if (!validVersion || !(layerNodes.size() > index))
        return { };

    auto &seciont = layerNodes[index];

    return { nodes.data() + seciont.offset, qsizetype(seciont.size) };
}

QSSGGlobalRenderNodeData::LayerNodeView QSSGGlobalRenderNodeData::getLayerNodeView(const QSSGRenderLayer &layer) const
{
    return getLayerNodeView(layer.lh);
}

void QSSGGlobalRenderNodeData::collectNodes(QSSGRenderRoot *rootNode)
{
    // 1. Collect all the nodes and create views into the node storage for each layer
    // 2. Update the global state
    // 3. Update the global data
    Q_ASSERT(rootNode != nullptr);

    nodes.clear();
    nodes.resize(m_nodeCount, nullptr);
    layerNodes.clear();

    size_t idx = 0;
    quint32 layerIdx = 0;
    for (QSSGRenderNode &chld : rootNode->children) {
        Q_ASSERT(chld.type == QSSGRenderNode::Type::Layer);
        QSSGRenderLayer *layer = static_cast<QSSGRenderLayer *>(&chld);
        const size_t offset = idx;
        collectLayerChildNodes<Discard::None, Insert::Indexed>(layer, nodes, idx);
        layer->lh = QSSGRenderLayerHandle(layer->h.context(), m_version, layerIdx++);
        layerNodes.emplace_back(LayerNodeSection{offset , idx - offset});
    }

    nodes.resize(idx /* idx == next_idx == size */);
}

void QSSGGlobalRenderNodeData::updateGlobalState()
{
    // Update the active and pickable state
    for (QSSGRenderNode *node : nodes)
        QSSGRenderDataHelpers::updateGlobalNodeState(node, m_version);

    // Recalculate ALL the global transforms and opacities.
    for (QSSGRenderNode *node : nodes)
        calcGlobalNodeDataIndexedImpl<QSSGRenderDataHelpers::Strategy::Initial>(node, m_version, globalTransforms, globalOpacities);

    // FIXME: We shouldn't need to re-create all the instance transforms even when instancing isn't used...
    for (QSSGRenderNode *node : nodes)
        QSSGRenderDataHelpers::calcInstanceTransforms(node, m_version, globalTransforms, instanceTransforms);
}

QSSGGlobalRenderNodeData::InstanceTransforms QSSGGlobalRenderNodeData::getInstanceTransforms(const QSSGRenderNode &node) const
{
    return getInstanceTransforms(node.h);
}

QSSGGlobalRenderNodeData::InstanceTransforms QSSGGlobalRenderNodeData::getInstanceTransforms(QSSGRenderNodeHandle h) const
{
    const bool hasId = h.hasId();
    const bool validVersion = hasId && (h.version() == m_version);
    const auto index = h.index();

    if (!validVersion || !(instanceTransforms.size() > index))
        return { };

    return instanceTransforms[index];
}

QSSGRenderModelData::QSSGRenderModelData(const QSSGGlobalRenderNodeDataPtr &globalNodeData)
    : m_gnd(globalNodeData)
    , m_version(globalNodeData->version())
{

}

QMatrix3x3 QSSGRenderModelData::getNormalMatrix(QSSGRenderModelHandle h, QMatrix3x3 defaultValue) const
{
    const bool hasId = h.hasId();
    const bool validVersion = hasId && (h.version() == m_version);
    const auto index = h.index();
    if (!validVersion || !(normalMatrices.size() > index))
        return defaultValue;

    return normalMatrices[index];
}

QMatrix3x3 QSSGRenderModelData::getNormalMatrix(const QSSGRenderModel &model) const
{
    return getNormalMatrix(model.mh, QMatrix3x3{ Qt::Uninitialized });
}

QSSGRenderMesh *QSSGRenderModelData::getMesh(QSSGRenderModelHandle h) const
{
    const bool hasId = h.hasId();
    const bool validVersion = hasId && (h.version() == m_version);
    const auto index = h.index();

    if (!validVersion || !(meshes.size() > index))
        return nullptr;

    return meshes[index];
}

QSSGRenderMesh *QSSGRenderModelData::getMesh(const QSSGRenderModel &model) const
{
    return getMesh(model.mh);
}

QSSGRenderModelData::MaterialList QSSGRenderModelData::getMaterials(QSSGRenderModelHandle h) const
{
    const bool hasId = h.hasId();
    const bool validVersion = hasId && (h.version() == m_version);
    const auto index = h.index();

    if (!validVersion || !(materials.size() > index))
        return {};

    return materials[index];
}

QSSGRenderModelData::MaterialList QSSGRenderModelData::getMaterials(const QSSGRenderModel &model) const
{
    return getMaterials(model.mh);
}

QSSGRenderModelData::ModelViewProjections QSSGRenderModelData::getModelViewProjection(const QSSGRenderModel &model) const
{
    return getModelViewProjection(model.mh);
}

QSSGRenderModelData::ModelViewProjections QSSGRenderModelData::getModelViewProjection(QSSGRenderModelHandle h) const
{
    const bool hasId = h.hasId();
    const bool validVersion = hasId && (h.version() == m_version);
    const auto index = h.index();

    if (!validVersion || !(modelViewProjections.size() > index))
        return {};

    return modelViewProjections[index];
}

void QSSGRenderModelData::prepareMeshData(const QSSGModelsView &models, QSSGRenderer *renderer)
{
    const auto &bufferManager = renderer->contextInterface()->bufferManager();

    const bool globalPickingEnabled = QSSGRendererPrivate::isGlobalPickingEnabled(*renderer);

    for (auto *model : models) {
        // It's up to the BufferManager to employ the appropriate caching mechanisms, so
        // loadMesh() is expected to be fast if already loaded. Note that preparing
        // the same QSSGRenderModel in different QQuickWindows (possible when a
        // scene is shared between View3Ds where the View3Ds belong to different
        // windows) leads to a different QSSGRenderMesh since the BufferManager is,
        // very correctly, per window, and so per scenegraph render thread.

        // Ensure we have a mesh
        if (auto *theMesh = bufferManager->loadMesh(*model)) {
            meshes[model->mh.index()] = theMesh;
            // Completely transparent models cannot be pickable.  But models with completely
            // transparent materials still are.  This allows the artist to control pickability
            // in a somewhat fine-grained style.
            const float modelGlobalOpacity = m_gnd->getGlobalOpacity(*model);
            const bool canModelBePickable = (modelGlobalOpacity > QSSGRendererPrivate::minimumRenderOpacity)
                    && (globalPickingEnabled
                        || model->getGlobalState(QSSGRenderModel::GlobalState::Pickable));
            if (canModelBePickable) {
                // Check if there is BVH data, if not generate it
                if (!theMesh->bvh) {
                    const QSSGMesh::Mesh mesh = bufferManager->loadLightmapMesh(*model);

                    if (mesh.isValid())
                        theMesh->bvh = bufferManager->loadMeshBVH(mesh);
                    else if (model->geometry)
                        theMesh->bvh = bufferManager->loadMeshBVH(model->geometry);
                    else if (!model->meshPath.isNull())
                        theMesh->bvh = bufferManager->loadMeshBVH(model->meshPath);

                    if (theMesh->bvh) {
                        const auto &roots = theMesh->bvh->roots();
                        for (qsizetype i = 0, end = qsizetype(roots.size()); i < end; ++i)
                            theMesh->subsets[i].bvhRoot = roots[i];
                    }
                }
            }
        } else {
            const size_t index = model->mh.index();
            if (QSSG_GUARD(meshes.size() > index))
                meshes[model->mh.index()] = nullptr;
        }
    }

    // Now is the time to kick off the vertex/index buffer updates for all the
    // new meshes (and their submeshes). This here is the last possible place
    // to kick this off because the rest of the rendering pipeline will only
    // see the individual sub-objects as "renderable objects".
    bufferManager->commitBufferResourceUpdates();
}

void QSSGRenderModelData::prepareMaterials(const QSSGModelsView &models)
{
    for (auto *model : models) {
        const size_t index = model->mh.index();
        if (QSSG_GUARD(materials.size() > index))
            materials[index] = model->materials;
    }
}

void QSSGRenderModelData::updateModelData(QSSGModelsView &models, QSSGRenderer *renderer, const QSSGRenderCameraDataList &renderCameraData)
{
    const auto modelCount = size_t(models.size());
    const bool versionChanged = m_version != m_gnd->version();
    const bool storageSizeChanged = (normalMatrices.size() < modelCount);

    const QMatrix3x3 defaultNormalMatrix;
    const QMatrix4x4 defaultModelViewProjection;

    // resize the storage if needed
    modelViewProjections.resize(modelCount, { defaultModelViewProjection, defaultModelViewProjection });
    normalMatrices.resize(modelCount, defaultNormalMatrix);
    meshes.resize(modelCount, nullptr);
    materials.resize(modelCount, {});

    // If the version or storage size changed we need to re-index the models.
    // NOTE: Node data's version is incremented when the node graph changes and starts at 1.
    if (versionChanged || storageSizeChanged) {
        m_version = m_gnd->version();

        for (quint32 i = 0; i < modelCount; ++i) {
            QSSGRenderModel *model = models[i];
            model->mh = QSSGRenderModelHandle(model->h.context(), model->h.version(), i);
        }
    }

    // - Normal matrices
    const auto doNormalMatrices = [&]() {
        for (const QSSGRenderModel *model : std::as_const(models)) {
            auto &normalMatrix = normalMatrices[model->mh.index()];
            const QMatrix4x4 globalTransform = m_gnd->getGlobalTransform(*model);
            QSSGRenderNode::calculateNormalMatrix(globalTransform, normalMatrix);
        }
    };

    // - MVPs
    const auto doMVPs = [&]() {
        for (const QSSGRenderModel *model : std::as_const(models)) {
            int mvpCount = 0;
            const QMatrix4x4 globalTransform = m_gnd->getGlobalTransform(*model);
            auto &mvp = modelViewProjections[model->mh.index()];
            for (const QSSGRenderCameraData &cameraData : renderCameraData)
                QSSGRenderNode::calculateMVP(globalTransform, cameraData.viewProjection, mvp[mvpCount++]);
        }
    };

#if QT_CONFIG(thread)
    const auto &threadPool = m_gnd->threadPool();
#define qssgTryThreadedStart(func) \
    if (!threadPool->tryStart(func)) { \
        qWarning("Unable to start thread for %s!", #func); \
        func(); \
    }
#define qssgTryWaitForDone() \
    threadPool->waitForDone();
#else
#define qssgTryThreadedStart(func) \
    func();
#define qssgTryWaitForDone() \
    /* no-op */
#endif // QT_CONFIG(thread)

    qssgTryThreadedStart(doNormalMatrices);
    qssgTryThreadedStart(doMVPs);

    // While we are waiting for the threads to finish, we can also prepare and update
    // the materials and meshes.
    prepareMaterials(models);
    prepareMeshData(models, renderer);

    // Wait for the threads to finish
    qssgTryWaitForDone();
}

bool QSSGRenderDataHelpers::updateGlobalNodeDataIndexed(QSSGRenderNode *node, const quint32 version, QSSGGlobalRenderNodeData::GlobalTransformStore &globalTransforms, QSSGGlobalRenderNodeData::GlobalOpacityStore &globalOpacities)
{
    return calcGlobalNodeDataIndexedImpl<Strategy::Update>(node, version, globalTransforms, globalOpacities);
}

bool QSSGRenderDataHelpers::calcGlobalVariablesIndexed(QSSGRenderNode *node, const quint32 version, QSSGGlobalRenderNodeData::GlobalTransformStore &globalTransforms, QSSGGlobalRenderNodeData::GlobalOpacityStore &globalOpacities)
{
    return calcGlobalNodeDataIndexedImpl<Strategy::Initial>(node, version, globalTransforms, globalOpacities);
}

QT_END_NAMESPACE