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

source code of qtquick3d/src/quick3d/qquick3dscenemanager.cpp