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