Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qquick3dscenemanager.cpp
Go to the documentation of this file.
1// Copyright (C) 2019 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5
10
11#include <QtQuick/QQuickWindow>
12
13#include <QtQuick3DRuntimeRender/private/qssgrenderlayer_p.h>
14#include <ssg/qssgrendercontextcore.h>
15#include <QtQuick3DRuntimeRender/private/qssgrendermodel_p.h>
16#include <QtQuick3DRuntimeRender/private/qssgrenderer_p.h>
17#include <QtQuick3DRuntimeRender/private/qssgrenderimage_p.h>
18#include <QtQuick3DRuntimeRender/private/qssgrenderlayer_p.h>
19#include <QtQuick3DRuntimeRender/private/qssgrenderroot_p.h>
20#include <QtQuick3DRuntimeRender/ssg/qssgrenderextensions.h>
21#include <QtQuick3DRuntimeRender/private/qssgrenderuserpass_p.h>
22
23#include <QtQuick3DUtils/private/qssgassert_p.h>
24
26
28
29// NOTE: Another indiraction to try to clean-up resource in a nice way.
30QSSGCleanupObject::QSSGCleanupObject(std::shared_ptr<QSSGRenderContextInterface> rci, QList<QSSGRenderGraphObject *> resourceCleanupQueue, QQuickWindow *window)
31 : QObject(window)
32 , m_rci(rci)
33 , m_window(window)
34 , m_resourceCleanupQueue(resourceCleanupQueue)
35{
36 Q_ASSERT(window != nullptr && rci); // We need a window and a rci for this!
37
38 if (QSGRenderContext *rc = QQuickWindowPrivate::get(window)->context) {
39 connect(rc, &QSGRenderContext::releaseCachedResourcesRequested, this, &QSSGCleanupObject::cleanupResources, Qt::DirectConnection);
40 connect(rc, &QSGRenderContext::invalidated, this, &QSSGCleanupObject::cleanupResources, Qt::DirectConnection);
41 } else {
42 qWarning() << "No QSGRenderContext, cannot cleanup resources!";
43 }
44}
45
47{
48 QSSG_CHECK(QSSG_DEBUG_COND(m_resourceCleanupQueue.isEmpty()));
49}
50
52{
53 m_rci->renderer()->cleanupResources(m_resourceCleanupQueue);
54 deleteLater();
55}
56
57static constexpr char qtQQ3DWAPropName[] { "_qtquick3dWindowAttachment" };
58
59static void detachDirtyList(QQuick3DObject **head, size_t count)
60{
61 for (size_t i = 0; i < count; ++i) {
62 QQuick3DObject *item = head[i];
63 while (item) {
64 QQuick3DObjectPrivate *p = QQuick3DObjectPrivate::get(item);
65 QQuick3DObject *next = p->nextDirtyItem;
66 p->prevDirtyItem = nullptr;
67 p->nextDirtyItem = nullptr;
68 item = next;
69 }
70 head[i] = nullptr;
71 }
72}
73
74QQuick3DSceneManager::QQuick3DSceneManager(QObject *parent)
75 : QObject(parent)
76{
77}
78
79// Should be deleted by QQuick3DWindowAttachment to ensure it's done
80// on the render thread.
81QQuick3DSceneManager::~QQuick3DSceneManager()
82{
83 cleanupNodes();
84 if (wattached)
85 wattached->unregisterSceneManager(*this);
86
87 // Objects still on one of our dirty lists hold a 'prevDirtyItem' pointer into the arrays
88 // below, which are freed together with this manager. Detach them now so a later
89 // removeFromDirtyList(), e.g. when the front-end object is itself destroyed, is a safe
90 // no-op instead of writing through a stale pointer. The normal per-frame drain only
91 // happens for active managers in synchronize(), not for one that was queued for cleanup.
92 //
93 // NOTE!!!: If these dirty objects are shared they will be re-queued by the surviving manager,
94 // but if they are not shared they will be dropped on the floor, which is fine, because they're not
95 // active and will either be destroyed or added to a new scene.
96 // The re-adoption happens because the destroyed() signal of this manager is connected to
97 // QQuick3DViewport::updateSceneManagerForImportScene(), which calls refSceneManager() on any
98 // surviving view, which in turn calls dirty() on any shared objects, which adds them to the
99 // dirty list if they're not already in one.
100 detachDirtyList(dirtyResources, std::size(dirtyResources));
101 detachDirtyList(dirtyNodes, std::size(dirtyNodes));
102 detachDirtyList(dirtyExtensions, std::size(dirtyExtensions));
103}
104
105void QQuick3DSceneManager::setWindow(QQuickWindow *window)
106{
107 if (window == m_window)
108 return;
109
110 if (window != m_window) {
111 if (wattached) {
112 // Unregister from old windows attached object
113 wattached->unregisterSceneManager(*this);
114 wattached = nullptr;
115 }
116 m_window = window;
117 if (m_window) {
118 wattached = getOrSetWindowAttachment(*m_window);
119 if (wattached)
120 wattached->registerSceneManager(*this);
121 }
122
123 emit windowChanged();
124 }
125}
126
127QQuickWindow *QQuick3DSceneManager::window()
128{
129 return m_window;
130}
131
132void QQuick3DSceneManager::dirtyItem(QQuick3DObject *item)
133{
134 Q_UNUSED(item);
135 emit needsUpdate();
136}
137
138void QQuick3DSceneManager::requestUpdate()
139{
140 emit needsUpdate();
141}
142
143void QQuick3DSceneManager::cleanup(QSSGRenderGraphObject *item)
144{
145 cleanupNodeList.insert(item);
146
147 if (auto front = m_nodeMap[item]) {
148 auto *po = QQuick3DObjectPrivate::get(front);
149 sharedResourceRemoved |= po->sharedResource;
150 po->spatialNode = nullptr;
151
152 // The front-end object is no longer reachable (destroyed) so make sure we don't return it
153 // when doing a node look-up.
154 m_nodeMap[item] = nullptr;
155 }
156}
157
158void QQuick3DSceneManager::polishItems()
159{
160
161}
162
163void QQuick3DSceneManager::forcePolish()
164{
165
166}
167
168void QQuick3DSceneManager::sync()
169{
170
171}
172
173void QQuick3DSceneManager::updateBoundingBoxes(QSSGBufferManager &mgr)
174{
175 if (lightmapSourceTracker.isDirty) {
176 mgr.setLightmapSource(lightmapSourceTracker.lightmapSource);
177 lightmapSourceTracker.isDirty = false;
178 }
179
180 for (auto *object : std::as_const(dirtyBoundingBoxList)) {
181 QQuick3DObjectPrivate *itemPriv = QQuick3DObjectPrivate::get(object);
182 if (itemPriv->sceneManager == nullptr)
183 continue;
184 auto model = static_cast<QSSGRenderModel *>(itemPriv->spatialNode);
185 if (model) {
186 QSSGBounds3 bounds = mgr.getModelBounds(model);
187 static_cast<QQuick3DModel *>(object)->setBounds(bounds.minimum, bounds.maximum);
188 }
189 }
190
191 dirtyBoundingBoxList.clear();
192}
193
194QQuick3DSceneManager::SyncResult QQuick3DSceneManager::updateDirtyResourceNodes()
195{
196 SyncResult ret = SyncResultFlag::None;
197
198 auto it = std::begin(dirtyResources);
199 const auto end = std::end(dirtyResources);
200 for (; it != end; ++it)
201 ret |= updateResources(it);
202
203 return ret;
204}
205
206void QQuick3DSceneManager::updateDirtySpatialNodes()
207{
208 auto it = std::begin(dirtyNodes);
209 const auto end = std::end(dirtyNodes);
210 for (; it != end; ++it)
211 updateNodes(it);
212}
213
214QQuick3DSceneManager::SyncResult QQuick3DSceneManager::updateDiryExtensions()
215{
216 SyncResult ret = SyncResultFlag::None;
217
218 auto it = std::begin(dirtyExtensions);
219 const auto end = std::end(dirtyExtensions);
220 for (; it != end; ++it)
221 ret |= updateExtensions(it);
222
223 return ret;
224}
225
226QQuick3DSceneManager::SyncResult QQuick3DSceneManager::updateDirtyResourceSecondPass()
227{
228 const auto updateDirtyResourceNode = [this](QQuick3DObject *resource) {
229 QQuick3DObjectPrivate *po = QQuick3DObjectPrivate::get(resource);
230 po->dirtyAttributes = 0; // Not used, but we should still reset it.
231 po->secondaryUpdateRequested = false;
232 QSSGRenderGraphObject *node = po->spatialNode;
233 po->spatialNode = resource->updateSpatialNode(node);
234 if (po->spatialNode)
235 m_nodeMap.insert(po->spatialNode, resource);
236 return po->sharedResource ? SyncResultFlag::SharedResourcesDirty : SyncResultFlag::None;
237 };
238
239 SyncResult res = SyncResultFlag::None;
240 auto it = dirtySecondPassResources.constBegin();
241 const auto end = dirtySecondPassResources.constEnd();
242 for (; it != end; ++it)
243 res |= updateDirtyResourceNode(*it);
244
245 // Expectation is that we won't get here often, for other updates the
246 // backend nodes should have been realized and we won't get here, so
247 // just release space used by the set.
248 dirtySecondPassResources = {};
249
250 return res;
251}
252
253void QQuick3DSceneManager::updateDirtyResource(QQuick3DObject *resourceObject)
254{
255 QQuick3DObjectPrivate *itemPriv = QQuick3DObjectPrivate::get(resourceObject);
256 quint32 dirty = itemPriv->dirtyAttributes;
257 Q_UNUSED(dirty);
258 itemPriv->dirtyAttributes = 0;
259 QSSGRenderGraphObject *oldNode = itemPriv->spatialNode;
260 QSSGRenderGraphObject *newNode = resourceObject->updateSpatialNode(itemPriv->spatialNode);
261
262 const bool backendNodeChanged = oldNode != newNode;
263
264 // If the backend resource object changed, we need to clean up the old one.
265 if (oldNode && backendNodeChanged)
266 cleanup(oldNode);
267
268 // NOTE: cleanup() will remove the item from the node map and set the spatial node to nullptr.
269 // so we need to set it here.
270 itemPriv->spatialNode = newNode;
271
272 if (itemPriv->spatialNode) {
273 m_nodeMap.insert(itemPriv->spatialNode, resourceObject);
274 if (itemPriv->spatialNode->type == QSSGRenderGraphObject::Type::ResourceLoader) {
275 resourceLoaders.insert(itemPriv->spatialNode);
276 } else if (itemPriv->spatialNode->type == QQuick3DObjectPrivate::Type::Image2D && backendNodeChanged) {
277 ++inputHandlingEnabled;
278 } else if (QSSGRenderGraphObjectUtils::isUserRenderPass(itemPriv->type) && itemPriv->spatialNode) {
279 auto *userRenderPass = static_cast<QSSGRenderUserPass *>(itemPriv->spatialNode);
280 if (const auto idx = userRenderPasses.indexOf(userRenderPass); idx == -1)
281 userRenderPasses.push_back(userRenderPass);
282 }
283 }
284
285 if (itemPriv->hasFlag(QQuick3DObjectPrivate::Flags::RequiresSecondaryUpdate) && itemPriv->secondaryUpdateRequested)
286 dirtySecondPassResources.insert(resourceObject);
287
288 // resource nodes dont go in the tree, so we dont need to parent them
289}
290
291void QQuick3DSceneManager::updateDirtySpatialNode(QQuick3DNode *spatialNode)
292{
293 const auto prepNewSpatialNode = [this](QSSGRenderNode *node) {
294 if (node) {
295 node->rootNodeRef = wattached->rootNode()->rootNodeRef;
296 Q_ASSERT(QSSGRenderRoot::get(node->rootNodeRef) != nullptr);
297 }
298 };
299
300 QQuick3DObjectPrivate *itemPriv = QQuick3DObjectPrivate::get(spatialNode);
301 quint32 dirty = itemPriv->dirtyAttributes;
302 itemPriv->dirtyAttributes = 0;
303 QSSGRenderGraphObject *oldNode = itemPriv->spatialNode;
304 QSSGRenderGraphObject *newNode = spatialNode->updateSpatialNode(oldNode);
305
306 const bool backendNodeChanged = oldNode != newNode;
307
308 // If the backend node changed, we need to clean up the old one.
309 if (oldNode && backendNodeChanged)
310 cleanup(oldNode);
311
312 // NOTE: cleanup() will remove the item from the node map and set the spatial node to nullptr.
313 // so we need to set it here.
314 itemPriv->spatialNode = newNode;
315 prepNewSpatialNode(static_cast<QSSGRenderNode *>(itemPriv->spatialNode));
316
317 // NOTE: We always update the node map, as we can end-up with the a node map where the mapping
318 // has been 'disconnected', e.g., the front-end object removed from the scene only to be later
319 // re-used.
320 if (itemPriv->spatialNode) {
321 m_nodeMap.insert(itemPriv->spatialNode, spatialNode);
322 if (itemPriv->type == QQuick3DObjectPrivate::Type::Item2D && itemPriv->spatialNode != oldNode)
323 ++inputHandlingEnabled;
324 }
325
326 QSSGRenderNode *graphNode = static_cast<QSSGRenderNode *>(itemPriv->spatialNode);
327
328 if (graphNode && graphNode->parent && dirty & QQuick3DObjectPrivate::ParentChanged) {
329 QQuick3DNode *nodeParent = qobject_cast<QQuick3DNode *>(spatialNode->parentItem());
330 if (nodeParent) {
331 QSSGRenderNode *parentGraphNode = static_cast<QSSGRenderNode *>(
332 QQuick3DObjectPrivate::get(nodeParent)->spatialNode);
333 if (parentGraphNode) {
334 graphNode->parent->removeChild(*graphNode);
335 parentGraphNode->addChild(*graphNode);
336 }
337 }
338 }
339
340 if (graphNode && graphNode->parent == nullptr) {
341 QQuick3DNode *nodeParent = qobject_cast<QQuick3DNode *>(spatialNode->parentItem());
342 if (nodeParent) {
343 QSSGRenderNode *parentGraphNode = static_cast<QSSGRenderNode *>(QQuick3DObjectPrivate::get(nodeParent)->spatialNode);
344 if (!parentGraphNode) {
345 // The parent spatial node hasn't been created yet
346 auto parentNode = QQuick3DObjectPrivate::get(nodeParent);
347 parentNode->spatialNode = nodeParent->updateSpatialNode(parentNode->spatialNode);
348 if (parentNode->spatialNode)
349 m_nodeMap.insert(parentNode->spatialNode, nodeParent);
350 parentGraphNode = static_cast<QSSGRenderNode *>(parentNode->spatialNode);
351 prepNewSpatialNode(parentGraphNode);
352 }
353 if (parentGraphNode)
354 parentGraphNode->addChild(*graphNode);
355 } else {
356 QQuick3DViewport *viewParent = qobject_cast<QQuick3DViewport *>(spatialNode->parent());
357 if (viewParent) {
358 auto sceneRoot = QQuick3DObjectPrivate::get(viewParent->scene());
359 if (!sceneRoot->spatialNode) // must have a scene root spatial node first
360 sceneRoot->spatialNode = viewParent->scene()->updateSpatialNode(sceneRoot->spatialNode);
361 if (sceneRoot->spatialNode) {
362 auto *sceneRootNode = static_cast<QSSGRenderNode *>(sceneRoot->spatialNode);
363 prepNewSpatialNode(sceneRootNode);
364 m_nodeMap.insert(sceneRootNode, viewParent->scene());
365 sceneRootNode->addChild(*graphNode);
366 }
367 }
368 }
369 }
370}
371
372QQuick3DObject *QQuick3DSceneManager::lookUpNode(const QSSGRenderGraphObject *node) const
373{
374 return m_nodeMap[const_cast<QSSGRenderGraphObject *>(node)];
375}
376
377QQuick3DWindowAttachment *QQuick3DSceneManager::getOrSetWindowAttachment(QQuickWindow &window)
378{
379
380 QQuick3DWindowAttachment *wa = nullptr;
381 if (auto aProperty = window.property(qtQQ3DWAPropName); aProperty.isValid())
382 wa = aProperty.value<QQuick3DWindowAttachment *>();
383
384 if (!wa) {
385 // WindowAttachment will not be created under 'window'.
386 // It should be deleted after all the cleanups related with 'window',
387 // otherwise some resourses deleted after it, will not be cleaned correctly.
388 wa = new QQuick3DWindowAttachment(&window);
389 window.setProperty(qtQQ3DWAPropName, QVariant::fromValue(wa));
390 }
391
392 return wa;
393}
394
395QQuick3DSceneManager::SyncResult QQuick3DSceneManager::cleanupNodes()
396{
397 SyncResult res = sharedResourceRemoved ? SyncResultFlag::SharedResourcesDirty : SyncResultFlag::None;
398 // Reset the shared resource removed value.
399 sharedResourceRemoved = false;
400 for (auto node : std::as_const(cleanupNodeList)) {
401 // Remove "spatial" nodes from scenegraph
402 if (QSSGRenderGraphObject::isNodeType(node->type)) {
403 QSSGRenderNode *spatialNode = static_cast<QSSGRenderNode *>(node);
404 spatialNode->removeFromGraph();
405 }
406
407 if (node->type == QQuick3DObjectPrivate::Type::Item2D) {
408 --inputHandlingEnabled;
409 } else if (node->type == QQuick3DObjectPrivate::Type::Image2D) {
410 auto image = static_cast<QSSGRenderImage *>(node);
411 if (image && image->m_qsgTexture != nullptr ) {
412 --inputHandlingEnabled;
413 }
414 }
415
416 // Remove all nodes from the node map because they will no
417 // longer be usable from this point from the frontend
418 m_nodeMap.remove(node);
419
420 if (QSSGRenderGraphObjectUtils::hasInternalFlag(*node, QSSGRenderGraphObjectUtils::InternalFlags::AutoRegisterExtension)) {
421 autoRegisteredExtensions.removeAll(node);
422 autoRegisteredExtensionsDirty = true;
423 }
424
425 if (QSSGRenderGraphObjectUtils::isUserRenderPass(node->type)) {
426 auto *userRenderPass = static_cast<QSSGRenderUserPass *>(node);
427 if (qsizetype idx = userRenderPasses.indexOf(userRenderPass); idx != -1)
428 userRenderPasses.remove(idx);
429 }
430
431 // Some nodes will trigger resource cleanups that need to
432 // happen at a specified time (when graphics backend is active)
433 // So build another queue for graphics assets marked for removal
434 if (node->hasGraphicsResources()) {
435 wattached->queueForCleanup(node);
436 if (node->type == QSSGRenderGraphObject::Type::ResourceLoader)
437 resourceLoaders.remove(node);
438 } else {
439 delete node;
440 }
441 }
442
443 // Nodes are now "cleaned up" so clear the cleanup list
444 cleanupNodeList.clear();
445
446 return res;
447}
448
449QQuick3DSceneManager::SyncResult QQuick3DSceneManager::updateResources(QQuick3DObject **listHead)
450{
451 SyncResult res = SyncResultFlag::None;
452
453 // Detach the current list head first, and consume all reachable entries.
454 // New entries may be added to the new list while traversing, which will be
455 // visited on the next updateDirtyNodes() call.
456 bool hasSharedResources = false;
457 QQuick3DObject *updateList = *listHead;
458 *listHead = nullptr;
459 if (updateList)
460 QQuick3DObjectPrivate::get(updateList)->prevDirtyItem = &updateList;
461
462 QQuick3DObject *item = updateList;
463 while (item) {
464 // Different processing for resource nodes vs hierarchical nodes etc.
465 Q_ASSERT(!QSSGRenderGraphObject::isNodeType(QQuick3DObjectPrivate::get(item)->type) || !QSSGRenderGraphObject::isExtension(QQuick3DObjectPrivate::get(item)->type));
466 // handle hierarchical nodes
467 auto *po = QQuick3DObjectPrivate::get(item);
468 // Unlink before calling updateSpatialNode() below: if that call re-enters dirty() on
469 // this very object (e.g. via a QML binding evaluated as a side effect of the update),
470 // dirty() needs prevDirtyItem to already be null so it re-links the object via its own
471 // addToDirtyList() call, onto the (already emptied) scene manager list.
472 po->removeFromDirtyList();
473 updateDirtyResource(item);
474 hasSharedResources |= po->sharedResource;
475 item = updateList;
476 }
477
478 if (hasSharedResources)
479 res |= SyncResultFlag::SharedResourcesDirty;
480
481 return res;
482}
483
484void QQuick3DSceneManager::updateNodes(QQuick3DObject **listHead)
485{
486 // Detach the current list head first, and consume all reachable entries.
487 // New entries may be added to the new list while traversing, which will be
488 // visited on the next updateDirtyNodes() call.
489 QQuick3DObject *updateList = *listHead;
490 *listHead = nullptr;
491 if (updateList)
492 QQuick3DObjectPrivate::get(updateList)->prevDirtyItem = &updateList;
493
494 QQuick3DObject *item = updateList;
495 while (item) {
496 // Different processing for resource nodes vs hierarchical nodes (anything that's _not_ a resource)
497 Q_ASSERT(QSSGRenderGraphObject::isNodeType(QQuick3DObjectPrivate::get(item)->type));
498 // handle hierarchical nodes
499 // See the matching comment in updateResources() about the removeFromDirtyList()/
500 // updateSpatialNode() ordering.
501 QQuick3DObjectPrivate::get(item)->removeFromDirtyList();
502 updateDirtySpatialNode(static_cast<QQuick3DNode *>(item));
503 item = updateList;
504 }
505}
506
507QQuick3DSceneManager::SyncResult QQuick3DSceneManager::updateExtensions(QQuick3DObject **listHead)
508{
509 SyncResult ret = SyncResultFlag::None;
510
511 const auto updateDirtyExtensionNode = [this, &ret](QQuick3DObject *extension) {
512 QQuick3DObjectPrivate *po = QQuick3DObjectPrivate::get(extension);
513 po->dirtyAttributes = 0; // Not used, but we should still reset it.
514 QSSGRenderGraphObject *oldNode = po->spatialNode;
515 QSSGRenderGraphObject *newNode = extension->updateSpatialNode(oldNode);
516
517 const bool backendNodeChanged = oldNode != newNode;
518
519 if (backendNodeChanged)
520 ret |= SyncResultFlag::ExtensionsDiry;
521
522 // If the backend node changed, we need to clean up the old one.
523 if (oldNode && backendNodeChanged)
524 cleanup(oldNode);
525
526 // NOTE: cleanup() will remove the item from the node map and set the spatial node to nullptr.
527 // so we need to set it here.
528 po->spatialNode = newNode;
529
530 if (po->spatialNode)
531 m_nodeMap.insert(po->spatialNode, extension);
532
533 if (newNode && QSSGRenderGraphObjectUtils::hasInternalFlag(*newNode, QSSGRenderGraphObjectUtils::InternalFlags::AutoRegisterExtension)) {
534 const bool shouldInsert = autoRegisteredExtensions.indexOf(static_cast<QSSGRenderExtension *>(newNode)) == -1;
535 if (shouldInsert) {
536 autoRegisteredExtensions.push_back(static_cast<QSSGRenderExtension *>(newNode));
537 autoRegisteredExtensionsDirty = true;
538 }
539 }
540 };
541
542 // Detach the current list head first, and consume all reachable entries.
543 // New entries may be added to the new list while traversing, which will be
544 // visited on the next updateDirtyNodes() call.
545 QQuick3DObject *updateList = *listHead;
546 *listHead = nullptr;
547 if (updateList)
548 QQuick3DObjectPrivate::get(updateList)->prevDirtyItem = &updateList;
549
550 QQuick3DObject *item = updateList;
551 while (item) {
552 // Different processing for resource nodes vs hierarchical nodes (anything that's _not_ a resource)
553 Q_ASSERT(QSSGRenderGraphObject::isExtension(QQuick3DObjectPrivate::get(item)->type));
554 // handle hierarchical nodes
555 // See the matching comment in updateResources() about the removeFromDirtyList()/
556 // updateSpatialNode() ordering.
557 QQuick3DObjectPrivate::get(item)->removeFromDirtyList();
558 updateDirtyExtensionNode(item);
559 item = updateList;
560 }
561
562 return ret;
563}
564
565void QQuick3DSceneManager::preSync()
566{
567 for (auto it = std::begin(dirtyResources), end = std::end(dirtyResources); it != end; ++it) {
568 QQuick3DObject *next = *it;
569 while (next) {
570 next->preSync();
571 next = QQuick3DObjectPrivate::get(next)->nextDirtyItem;
572 }
573 }
574
575 for (auto it = std::begin(dirtyNodes), end = std::end(dirtyNodes); it != end; ++it) {
576 QQuick3DObject *next = *it;
577 while (next) {
578 next->preSync();
579 next = QQuick3DObjectPrivate::get(next)->nextDirtyItem;
580 }
581 }
582
583 for (auto it = std::begin(dirtyExtensions), end = std::end(dirtyExtensions); it != end; ++it) {
584 QQuick3DObject *next = *it;
585 while (next) {
586 next->preSync();
587 next = QQuick3DObjectPrivate::get(next)->nextDirtyItem;
588 }
589 }
590}
591
592////////
593/// QQuick3DWindowAttachment
594////////
595
596QQuick3DWindowAttachment::QQuick3DWindowAttachment(QQuickWindow *window)
597 : m_window(window)
598 , m_rootNode(new QSSGRenderRoot)
599{
600 if (window) {
601 // Act when the application calls window->releaseResources() and the
602 // render loop emits the corresponding signal in order to forward the
603 // event to us as well. (do not confuse with other release-resources
604 // type of functions, this is about dropping pipeline and other resource
605 // caches than can be automatically recreated if needed on the next frame)
606 QQuickWindowPrivate *wd = QQuickWindowPrivate::get(window);
607 QSGRenderContext *rc = wd->context;
608 if (QSSG_GUARD_X(rc, "QQuickWindow has no QSGRenderContext, this should not happen")) {
609 // QSGRenderContext signals are emitted on the render thread, if there is one; use DirectConnection
610 connect(rc, &QSGRenderContext::releaseCachedResourcesRequested, this, &QQuick3DWindowAttachment::onReleaseCachedResources, Qt::DirectConnection);
611 connect(rc, &QSGRenderContext::invalidated, this, &QQuick3DWindowAttachment::onInvalidated, Qt::DirectConnection);
612 }
613
614 // Do a final lifetime eval when the window is destroyed.
615 connect(window, &QQuickWindow::destroyed, this, &QQuick3DWindowAttachment::evaluateEol);
616 // afterAnimating is emitted on the main thread.
617 connect(window, &QQuickWindow::afterAnimating, this, &QQuick3DWindowAttachment::preSync);
618 // afterFrameEnd is emitted on render thread.
619 connect(window, &QQuickWindow::afterFrameEnd, this, &QQuick3DWindowAttachment::cleanupResources, Qt::DirectConnection);
620 }
621}
622
623QQuick3DWindowAttachment::~QQuick3DWindowAttachment()
624{
625 for (auto *manager : std::as_const(sceneManagerCleanupQueue)) {
626 sceneManagers.removeOne(manager);
627 delete manager;
628 }
629 // remaining sceneManagers should also be removed
630 qDeleteAll(sceneManagers);
631 QSSG_CHECK(QSSG_DEBUG_COND(resourceCleanupQueue.isEmpty()));
632
633 if (!pendingResourceCleanupQueue.isEmpty()) {
634 // Let's try to recover from this situation. Most likely this is some loader usage
635 // situation, where all View3Ds have been destroyed while the window still lives and might
636 // eventually just create a new View3D. We cannot release the resources here, as we'll need
637 // to do that on the render thread. Instaed we'll transform the pendingResourceCleanupQueue
638 // to a cleanup object that can be called on the render thread.
639 if (m_rci && m_window) {
640 new QSSGCleanupObject(m_rci, std::move(pendingResourceCleanupQueue), m_window);
641 QMetaObject::invokeMethod(m_window, &QQuickWindow::releaseResources, Qt::QueuedConnection);
642 } else {
643 qWarning() << "Pending resource cleanup queue not empty, but no RCI or window to clean it up!";
644 }
645 }
646
647 if (m_window)
648 m_window->setProperty(qtQQ3DWAPropName, QVariant());
649
650 delete m_rootNode;
651}
652
653void QQuick3DWindowAttachment::preSync()
654{
655 for (auto &sceneManager : std::as_const(sceneManagers))
656 sceneManager->preSync();
657}
658
659// Called from the render thread
660void QQuick3DWindowAttachment::cleanupResources()
661{
662 // Pass the scene managers list of resources marked for
663 // removal to the render context for deletion
664 // The render context will take ownership of the nodes
665 // and clear the list
666
667 // In special cases there is no rci because synchronize() is never called.
668 // This can happen when running with the software backend of Qt Quick.
669 // Handle this gracefully.
670 if (!m_rci)
671 return;
672
673 // Check if there's orphaned resources that needs to be
674 // cleaned out first.
675 if (resourceCleanupQueue.size() != 0)
676 m_rci->renderer()->cleanupResources(resourceCleanupQueue);
677}
678
679// Called on the render thread, if there is one
680void QQuick3DWindowAttachment::onReleaseCachedResources()
681{
682 if (m_rci)
683 m_rci->releaseCachedResources();
684 Q_EMIT releaseCachedResources();
685}
686
687void QQuick3DWindowAttachment::onInvalidated()
688{
689 // Find all objects that have graphics resources and queue them
690 // for cleanup.
691 // 1. We'll need to manually go through the nodes of each scene manager and mark
692 // objects with graphics resources for deletion.
693 // The scene graph is invalidated so we need to release graphics resources now, on the render thread.
694 for (auto &sceneManager : std::as_const(sceneManagers)) {
695 const auto objects = sceneManager->m_nodeMap.keys();
696 for (QSSGRenderGraphObject *obj : objects) {
697 if (obj->hasGraphicsResources())
698 sceneManager->cleanup(obj);
699 }
700 }
701
702 // Start: follow the normal clean-up procedure
703 for (auto &sceneManager : std::as_const(sceneManagers))
704 sceneManager->cleanupNodes();
705
706 for (QSSGRenderLayer *layers : std::as_const(pendingLayerCleanupQueue))
707 delete layers;
708 pendingLayerCleanupQueue.clear();
709
710 for (const auto &pr : std::as_const(pendingResourceCleanupQueue))
711 resourceCleanupQueue.insert(pr);
712 pendingResourceCleanupQueue.clear();
713
714 // NOTE!: It's essential that we release the cached resources before we
715 // call cleanupResources(), to avoid the expensive bookkeeping code involved
716 // for models. This is achieved by dropping the data to avoid expensive look-ups; it's going away anyways.
717 // (In the future, if/when cleanupDrawCallData() is improved, then this step might not be necessary).
718 onReleaseCachedResources();
719
720 cleanupResources();
721 // end
722
723 // If the SG RenderContex is invalidated and we're the only one holding onto the SSG
724 // RenderContextInterface then just release it. If the application is not going down
725 // a new RCI will be created/set during the next sync.
726 if (m_rci.use_count() == 1) {
727 m_rci.reset();
728 emit renderContextInterfaceChanged();
729 }
730}
731
732QQuick3DWindowAttachment::SyncResult QQuick3DWindowAttachment::synchronize(QSet<QSSGRenderGraphObject *> &resourceLoaders)
733{
734 // Terminate old scene managers
735 for (auto *manager : std::as_const(sceneManagerCleanupQueue)) {
736 sceneManagers.removeOne(manager);
737 delete manager;
738 }
739 // Terminate old scene managers
740 sceneManagerCleanupQueue = {};
741
742 SyncResult syncResult = SyncResultFlag::None;
743
744 // Cleanup
745 for (auto &sceneManager : std::as_const(sceneManagers))
746 syncResult |= sceneManager->cleanupNodes();
747
748 for (QSSGRenderLayer *layers : std::as_const(pendingLayerCleanupQueue))
749 delete layers;
750 pendingLayerCleanupQueue.clear();
751
752 // Resources
753 for (auto &sceneManager : std::as_const(sceneManagers))
754 syncResult |= sceneManager->updateDirtyResourceNodes();
755 // Spatial Nodes
756 for (auto &sceneManager : std::as_const(sceneManagers))
757 sceneManager->updateDirtySpatialNodes();
758 for (auto &sceneManager : std::as_const(sceneManagers))
759 syncResult |= sceneManager->updateDiryExtensions();
760 for (auto &sceneManager : std::as_const(sceneManagers))
761 syncResult |= sceneManager->updateDirtyResourceSecondPass();
762 // Bounding Boxes
763 for (auto &sceneManager : std::as_const(sceneManagers))
764 sceneManager->updateBoundingBoxes(*m_rci->bufferManager());
765 // Resource Loaders
766 for (auto &sceneManager : std::as_const(sceneManagers))
767 resourceLoaders.unite(sceneManager->resourceLoaders);
768
769 if ((syncResult & SyncResultFlag::SharedResourcesDirty)) {
770 // We know there are shared resources in the scene, so notify the "world".
771 // Ideally we should be more targeted, but for now this will do the job.
772 for (auto &sceneManager : std::as_const(sceneManagers))
773 sceneManager->requestUpdate();
774 }
775
776 // Prepare pending (adopted) resources for clean-up (will happen as a result of afterFrameEnd()).
777 for (const auto &pr : std::as_const(pendingResourceCleanupQueue))
778 resourceCleanupQueue.insert(pr);
779 pendingResourceCleanupQueue.clear();
780
781 return syncResult;
782}
783
784void QQuick3DWindowAttachment::requestUpdate()
785{
786 for (const auto &sm : std::as_const(sceneManagers))
787 sm->requestUpdate();
788}
789
790void QQuick3DWindowAttachment::evaluateEol()
791{
792 // NOTE: We'll re-iterate this list either on the next sync or if there's no sceneManagers left.
793 // See: sync and dtor.
794 for (QQuick3DSceneManager *manager : std::as_const(sceneManagerCleanupQueue))
795 sceneManagers.removeOne(manager);
796
797 // Keep the attachment, and the QSSGRenderRoot it owns, alive for as long as the window is,
798 // even when no scene managers remain. Nodes reference the root via rootNodeRef (e.g. imported
799 // scenes shared across views), and those references must stay valid across View3D create and
800 // destroy cycles within the same window; deleting the root here would leave them dangling.
801 // When the window goes away the attachment is deleted through the QQuickWindow::destroyed ->
802 // evaluateEol connection set up in the constructor
803 // (NOTE: QPointers are cleared out before the destroyed signal is sent).
804 if (sceneManagers.isEmpty() && m_window.isNull())
805 delete this;
806}
807
808QQuickWindow *QQuick3DWindowAttachment::window() const { return m_window; }
809
810void QQuick3DWindowAttachment::setRci(const std::shared_ptr<QSSGRenderContextInterface> &rciptr)
811{
812 QSSG_CHECK_X(m_rci == nullptr || m_rci.use_count() == 1, "Old render context was not released!");
813 m_rci = rciptr;
814
815 // For convenience we'll also set the SG rendere context here.
816 if (m_rci && m_window)
817 QSSGRendererPrivate::setSgRenderContext(*m_rci->renderer(), QQuickWindowPrivate::get(m_window)->context);
818
819 emit renderContextInterfaceChanged();
820}
821
822void QQuick3DWindowAttachment::registerSceneManager(QQuick3DSceneManager &manager)
823{
824 if (!sceneManagers.contains(&manager))
825 sceneManagers.push_back(&manager);
826}
827
828void QQuick3DWindowAttachment::unregisterSceneManager(QQuick3DSceneManager &manager)
829{
830 sceneManagers.removeOne(&manager);
831}
832
833void QQuick3DWindowAttachment::queueForCleanup(QSSGRenderGraphObject *obj)
834{
835 Q_ASSERT(obj->hasGraphicsResources());
836 pendingResourceCleanupQueue.push_back(obj);
837}
838
839void QQuick3DWindowAttachment::queueForCleanup(QQuick3DSceneManager *manager)
840{
841 if (!sceneManagerCleanupQueue.contains(manager))
842 sceneManagerCleanupQueue.push_back(manager);
843}
844
845void QQuick3DWindowAttachment::queueForCleanup(QSSGRenderLayer *layer)
846{
847 if (QSSGRenderRoot *lr = QSSGRenderRoot::get(layer->rootNodeRef); lr != m_rootNode) {
848 qWarning("Attempted to queue layer for cleanup that is not part of the current window!");
849 return;
850 }
851
852 if (!pendingLayerCleanupQueue.contains(layer)) {
853 layer->removeFromGraph();
854 pendingLayerCleanupQueue.push_back(layer);
855 }
856}
857
858QT_END_NAMESPACE
Q_INVOKABLE void cleanupResources()
Combined button and popup list for selecting options.
static void detachDirtyList(QQuick3DObject **head, size_t count)
static constexpr char qtQQ3DWAPropName[]