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 updateDirtyResource(item);
468 auto *po = QQuick3DObjectPrivate::get(item);
469 hasSharedResources |= po->sharedResource;
470 po->removeFromDirtyList();
471 item = updateList;
472 }
473
474 if (hasSharedResources)
475 res |= SyncResultFlag::SharedResourcesDirty;
476
477 return res;
478}
479
480void QQuick3DSceneManager::updateNodes(QQuick3DObject **listHead)
481{
482 // Detach the current list head first, and consume all reachable entries.
483 // New entries may be added to the new list while traversing, which will be
484 // visited on the next updateDirtyNodes() call.
485 QQuick3DObject *updateList = *listHead;
486 *listHead = nullptr;
487 if (updateList)
488 QQuick3DObjectPrivate::get(updateList)->prevDirtyItem = &updateList;
489
490 QQuick3DObject *item = updateList;
491 while (item) {
492 // Different processing for resource nodes vs hierarchical nodes (anything that's _not_ a resource)
493 Q_ASSERT(QSSGRenderGraphObject::isNodeType(QQuick3DObjectPrivate::get(item)->type));
494 // handle hierarchical nodes
495 updateDirtySpatialNode(static_cast<QQuick3DNode *>(item));
496 QQuick3DObjectPrivate::get(item)->removeFromDirtyList();
497 item = updateList;
498 }
499}
500
501QQuick3DSceneManager::SyncResult QQuick3DSceneManager::updateExtensions(QQuick3DObject **listHead)
502{
503 SyncResult ret = SyncResultFlag::None;
504
505 const auto updateDirtyExtensionNode = [this, &ret](QQuick3DObject *extension) {
506 QQuick3DObjectPrivate *po = QQuick3DObjectPrivate::get(extension);
507 po->dirtyAttributes = 0; // Not used, but we should still reset it.
508 QSSGRenderGraphObject *oldNode = po->spatialNode;
509 QSSGRenderGraphObject *newNode = extension->updateSpatialNode(oldNode);
510
511 const bool backendNodeChanged = oldNode != newNode;
512
513 if (backendNodeChanged)
514 ret |= SyncResultFlag::ExtensionsDiry;
515
516 // If the backend node changed, we need to clean up the old one.
517 if (oldNode && backendNodeChanged)
518 cleanup(oldNode);
519
520 // NOTE: cleanup() will remove the item from the node map and set the spatial node to nullptr.
521 // so we need to set it here.
522 po->spatialNode = newNode;
523
524 if (po->spatialNode)
525 m_nodeMap.insert(po->spatialNode, extension);
526
527 if (newNode && QSSGRenderGraphObjectUtils::hasInternalFlag(*newNode, QSSGRenderGraphObjectUtils::InternalFlags::AutoRegisterExtension)) {
528 const bool shouldInsert = autoRegisteredExtensions.indexOf(static_cast<QSSGRenderExtension *>(newNode)) == -1;
529 if (shouldInsert) {
530 autoRegisteredExtensions.push_back(static_cast<QSSGRenderExtension *>(newNode));
531 autoRegisteredExtensionsDirty = true;
532 }
533 }
534 };
535
536 // Detach the current list head first, and consume all reachable entries.
537 // New entries may be added to the new list while traversing, which will be
538 // visited on the next updateDirtyNodes() call.
539 QQuick3DObject *updateList = *listHead;
540 *listHead = nullptr;
541 if (updateList)
542 QQuick3DObjectPrivate::get(updateList)->prevDirtyItem = &updateList;
543
544 QQuick3DObject *item = updateList;
545 while (item) {
546 // Different processing for resource nodes vs hierarchical nodes (anything that's _not_ a resource)
547 Q_ASSERT(QSSGRenderGraphObject::isExtension(QQuick3DObjectPrivate::get(item)->type));
548 // handle hierarchical nodes
549 updateDirtyExtensionNode(item);
550 QQuick3DObjectPrivate::get(item)->removeFromDirtyList();
551 item = updateList;
552 }
553
554 return ret;
555}
556
557void QQuick3DSceneManager::preSync()
558{
559 for (auto it = std::begin(dirtyResources), end = std::end(dirtyResources); it != end; ++it) {
560 QQuick3DObject *next = *it;
561 while (next) {
562 next->preSync();
563 next = QQuick3DObjectPrivate::get(next)->nextDirtyItem;
564 }
565 }
566
567 for (auto it = std::begin(dirtyNodes), end = std::end(dirtyNodes); 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(dirtyExtensions), end = std::end(dirtyExtensions); it != end; ++it) {
576 QQuick3DObject *next = *it;
577 while (next) {
578 next->preSync();
579 next = QQuick3DObjectPrivate::get(next)->nextDirtyItem;
580 }
581 }
582}
583
584////////
585/// QQuick3DWindowAttachment
586////////
587
588QQuick3DWindowAttachment::QQuick3DWindowAttachment(QQuickWindow *window)
589 : m_window(window)
590 , m_rootNode(new QSSGRenderRoot)
591{
592 if (window) {
593 // Act when the application calls window->releaseResources() and the
594 // render loop emits the corresponding signal in order to forward the
595 // event to us as well. (do not confuse with other release-resources
596 // type of functions, this is about dropping pipeline and other resource
597 // caches than can be automatically recreated if needed on the next frame)
598 QQuickWindowPrivate *wd = QQuickWindowPrivate::get(window);
599 QSGRenderContext *rc = wd->context;
600 if (QSSG_GUARD_X(rc, "QQuickWindow has no QSGRenderContext, this should not happen")) {
601 // QSGRenderContext signals are emitted on the render thread, if there is one; use DirectConnection
602 connect(rc, &QSGRenderContext::releaseCachedResourcesRequested, this, &QQuick3DWindowAttachment::onReleaseCachedResources, Qt::DirectConnection);
603 connect(rc, &QSGRenderContext::invalidated, this, &QQuick3DWindowAttachment::onInvalidated, Qt::DirectConnection);
604 }
605
606 // Do a final lifetime eval when the window is destroyed.
607 connect(window, &QQuickWindow::destroyed, this, &QQuick3DWindowAttachment::evaluateEol);
608 // afterAnimating is emitted on the main thread.
609 connect(window, &QQuickWindow::afterAnimating, this, &QQuick3DWindowAttachment::preSync);
610 // afterFrameEnd is emitted on render thread.
611 connect(window, &QQuickWindow::afterFrameEnd, this, &QQuick3DWindowAttachment::cleanupResources, Qt::DirectConnection);
612 }
613}
614
615QQuick3DWindowAttachment::~QQuick3DWindowAttachment()
616{
617 for (auto *manager : std::as_const(sceneManagerCleanupQueue)) {
618 sceneManagers.removeOne(manager);
619 delete manager;
620 }
621 // remaining sceneManagers should also be removed
622 qDeleteAll(sceneManagers);
623 QSSG_CHECK(QSSG_DEBUG_COND(resourceCleanupQueue.isEmpty()));
624
625 if (!pendingResourceCleanupQueue.isEmpty()) {
626 // Let's try to recover from this situation. Most likely this is some loader usage
627 // situation, where all View3Ds have been destroyed while the window still lives and might
628 // eventually just create a new View3D. We cannot release the resources here, as we'll need
629 // to do that on the render thread. Instaed we'll transform the pendingResourceCleanupQueue
630 // to a cleanup object that can be called on the render thread.
631 if (m_rci && m_window) {
632 new QSSGCleanupObject(m_rci, std::move(pendingResourceCleanupQueue), m_window);
633 QMetaObject::invokeMethod(m_window, &QQuickWindow::releaseResources, Qt::QueuedConnection);
634 } else {
635 qWarning() << "Pending resource cleanup queue not empty, but no RCI or window to clean it up!";
636 }
637 }
638
639 if (m_window)
640 m_window->setProperty(qtQQ3DWAPropName, QVariant());
641
642 delete m_rootNode;
643}
644
645void QQuick3DWindowAttachment::preSync()
646{
647 for (auto &sceneManager : std::as_const(sceneManagers))
648 sceneManager->preSync();
649}
650
651// Called from the render thread
652void QQuick3DWindowAttachment::cleanupResources()
653{
654 // Pass the scene managers list of resources marked for
655 // removal to the render context for deletion
656 // The render context will take ownership of the nodes
657 // and clear the list
658
659 // In special cases there is no rci because synchronize() is never called.
660 // This can happen when running with the software backend of Qt Quick.
661 // Handle this gracefully.
662 if (!m_rci)
663 return;
664
665 // Check if there's orphaned resources that needs to be
666 // cleaned out first.
667 if (resourceCleanupQueue.size() != 0)
668 m_rci->renderer()->cleanupResources(resourceCleanupQueue);
669}
670
671// Called on the render thread, if there is one
672void QQuick3DWindowAttachment::onReleaseCachedResources()
673{
674 if (m_rci)
675 m_rci->releaseCachedResources();
676 Q_EMIT releaseCachedResources();
677}
678
679void QQuick3DWindowAttachment::onInvalidated()
680{
681 // Find all objects that have graphics resources and queue them
682 // for cleanup.
683 // 1. We'll need to manually go through the nodes of each scene manager and mark
684 // objects with graphics resources for deletion.
685 // The scene graph is invalidated so we need to release graphics resources now, on the render thread.
686 for (auto &sceneManager : std::as_const(sceneManagers)) {
687 const auto objects = sceneManager->m_nodeMap.keys();
688 for (QSSGRenderGraphObject *obj : objects) {
689 if (obj->hasGraphicsResources())
690 sceneManager->cleanup(obj);
691 }
692 }
693
694 // Start: follow the normal clean-up procedure
695 for (auto &sceneManager : std::as_const(sceneManagers))
696 sceneManager->cleanupNodes();
697
698 for (QSSGRenderLayer *layers : std::as_const(pendingLayerCleanupQueue))
699 delete layers;
700 pendingLayerCleanupQueue.clear();
701
702 for (const auto &pr : std::as_const(pendingResourceCleanupQueue))
703 resourceCleanupQueue.insert(pr);
704 pendingResourceCleanupQueue.clear();
705
706 // NOTE!: It's essential that we release the cached resources before we
707 // call cleanupResources(), to avoid the expensive bookkeeping code involved
708 // for models. This is achieved by dropping the data to avoid expensive look-ups; it's going away anyways.
709 // (In the future, if/when cleanupDrawCallData() is improved, then this step might not be necessary).
710 onReleaseCachedResources();
711
712 cleanupResources();
713 // end
714
715 // If the SG RenderContex is invalidated and we're the only one holding onto the SSG
716 // RenderContextInterface then just release it. If the application is not going down
717 // a new RCI will be created/set during the next sync.
718 if (m_rci.use_count() == 1) {
719 m_rci.reset();
720 emit renderContextInterfaceChanged();
721 }
722}
723
724QQuick3DWindowAttachment::SyncResult QQuick3DWindowAttachment::synchronize(QSet<QSSGRenderGraphObject *> &resourceLoaders)
725{
726 // Terminate old scene managers
727 for (auto *manager : std::as_const(sceneManagerCleanupQueue)) {
728 sceneManagers.removeOne(manager);
729 delete manager;
730 }
731 // Terminate old scene managers
732 sceneManagerCleanupQueue = {};
733
734 SyncResult syncResult = SyncResultFlag::None;
735
736 // Cleanup
737 for (auto &sceneManager : std::as_const(sceneManagers))
738 syncResult |= sceneManager->cleanupNodes();
739
740 for (QSSGRenderLayer *layers : std::as_const(pendingLayerCleanupQueue))
741 delete layers;
742 pendingLayerCleanupQueue.clear();
743
744 // Resources
745 for (auto &sceneManager : std::as_const(sceneManagers))
746 syncResult |= sceneManager->updateDirtyResourceNodes();
747 // Spatial Nodes
748 for (auto &sceneManager : std::as_const(sceneManagers))
749 sceneManager->updateDirtySpatialNodes();
750 for (auto &sceneManager : std::as_const(sceneManagers))
751 syncResult |= sceneManager->updateDiryExtensions();
752 for (auto &sceneManager : std::as_const(sceneManagers))
753 syncResult |= sceneManager->updateDirtyResourceSecondPass();
754 // Bounding Boxes
755 for (auto &sceneManager : std::as_const(sceneManagers))
756 sceneManager->updateBoundingBoxes(*m_rci->bufferManager());
757 // Resource Loaders
758 for (auto &sceneManager : std::as_const(sceneManagers))
759 resourceLoaders.unite(sceneManager->resourceLoaders);
760
761 if ((syncResult & SyncResultFlag::SharedResourcesDirty)) {
762 // We know there are shared resources in the scene, so notify the "world".
763 // Ideally we should be more targeted, but for now this will do the job.
764 for (auto &sceneManager : std::as_const(sceneManagers))
765 sceneManager->requestUpdate();
766 }
767
768 // Prepare pending (adopted) resources for clean-up (will happen as a result of afterFrameEnd()).
769 for (const auto &pr : std::as_const(pendingResourceCleanupQueue))
770 resourceCleanupQueue.insert(pr);
771 pendingResourceCleanupQueue.clear();
772
773 return syncResult;
774}
775
776void QQuick3DWindowAttachment::requestUpdate()
777{
778 for (const auto &sm : std::as_const(sceneManagers))
779 sm->requestUpdate();
780}
781
782void QQuick3DWindowAttachment::evaluateEol()
783{
784 // NOTE: We'll re-iterate this list either on the next sync or if there's no sceneManagers left.
785 // See: sync and dtor.
786 for (QQuick3DSceneManager *manager : std::as_const(sceneManagerCleanupQueue))
787 sceneManagers.removeOne(manager);
788
789 // Keep the attachment, and the QSSGRenderRoot it owns, alive for as long as the window is,
790 // even when no scene managers remain. Nodes reference the root via rootNodeRef (e.g. imported
791 // scenes shared across views), and those references must stay valid across View3D create and
792 // destroy cycles within the same window; deleting the root here would leave them dangling.
793 // When the window goes away the attachment is deleted through the QQuickWindow::destroyed ->
794 // evaluateEol connection set up in the constructor
795 // (NOTE: QPointers are cleared out before the destroyed signal is sent).
796 if (sceneManagers.isEmpty() && m_window.isNull())
797 delete this;
798}
799
800QQuickWindow *QQuick3DWindowAttachment::window() const { return m_window; }
801
802void QQuick3DWindowAttachment::setRci(const std::shared_ptr<QSSGRenderContextInterface> &rciptr)
803{
804 QSSG_CHECK_X(m_rci == nullptr || m_rci.use_count() == 1, "Old render context was not released!");
805 m_rci = rciptr;
806
807 // For convenience we'll also set the SG rendere context here.
808 if (m_rci && m_window)
809 QSSGRendererPrivate::setSgRenderContext(*m_rci->renderer(), QQuickWindowPrivate::get(m_window)->context);
810
811 emit renderContextInterfaceChanged();
812}
813
814void QQuick3DWindowAttachment::registerSceneManager(QQuick3DSceneManager &manager)
815{
816 if (!sceneManagers.contains(&manager))
817 sceneManagers.push_back(&manager);
818}
819
820void QQuick3DWindowAttachment::unregisterSceneManager(QQuick3DSceneManager &manager)
821{
822 sceneManagers.removeOne(&manager);
823}
824
825void QQuick3DWindowAttachment::queueForCleanup(QSSGRenderGraphObject *obj)
826{
827 Q_ASSERT(obj->hasGraphicsResources());
828 pendingResourceCleanupQueue.push_back(obj);
829}
830
831void QQuick3DWindowAttachment::queueForCleanup(QQuick3DSceneManager *manager)
832{
833 if (!sceneManagerCleanupQueue.contains(manager))
834 sceneManagerCleanupQueue.push_back(manager);
835}
836
837void QQuick3DWindowAttachment::queueForCleanup(QSSGRenderLayer *layer)
838{
839 if (QSSGRenderRoot *lr = QSSGRenderRoot::get(layer->rootNodeRef); lr != m_rootNode) {
840 qWarning("Attempted to queue layer for cleanup that is not part of the current window!");
841 return;
842 }
843
844 if (!pendingLayerCleanupQueue.contains(layer)) {
845 layer->removeFromGraph();
846 pendingLayerCleanupQueue.push_back(layer);
847 }
848}
849
850QT_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[]