summaryrefslogtreecommitdiffstats
path: root/src/imports/studio3d/q3dsstudio3ditem.cpp
blob: 25a4d8cfceb05cddbbf0a5b51648d2b3ea059358 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
/****************************************************************************
**
** Copyright (C) 2017 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of Qt 3D Studio.
**
** $QT_BEGIN_LICENSE:GPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 or (at your option) any later version
** approved by the KDE Free Qt Foundation. The licenses are as published by
** the Free Software Foundation and appearing in the file LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "q3dsstudio3ditem_p.h"
#include "q3dsstudio3drenderer_p.h"
#include "q3dsstudio3dview_p.h"
#include "q3dspresentationitem_p.h"
#include <QSGNode>
#include <QLoggingCategory>
#include <QThread>
#include <QRunnable>
#include <QQuickWindow>
#include <QQuickRenderControl>
#include <QOffscreenSurface>
#include <QQmlFile>
#include <QQmlEngine>
#include <QQmlContext>
#include <QGuiApplication>
#include <private/q3dslayer3dsgnode_p.h>
#include <private/q3dsviewersettings_p.h>
#include <private/q3dsengine_p.h>
#include <private/q3dsutils_p.h>
#include <private/q3dslogging_p.h>
#include <Qt3DCore/QEntity>
#include <Qt3DRender/QRenderSurfaceSelector>
#include <Qt3DRender/private/qrendersurfaceselector_p.h>

QT_BEGIN_NAMESPACE

/*!
    \qmltype Studio3D
    \instantiates Q3DSStudio3DItem
    \inqmlmodule QtStudio3D
    \ingroup 3dstudioruntime2
    \inherits Item
    \keyword Studio3D

    \brief Qt 3D Studio presentation viewer.

    This type enables developers to embed Qt 3D Studio presentations in Qt
    Quick.

    \section2 Example usage

    \qml
    Studio3D {
        id: studio3D
        anchors.fill: parent

        Presentation {
            source: "qrc:///presentation.uia"
            SceneElement {
                id: scene
                elementPath: "Scene"
                currentSlideIndex: 2
            }
            Element {
                id: textLabel
                elementPath: "Scene.Layer.myLabel"
            }
        }
        ViewerSettings {
            showRenderStats: true
        }
        onRunningChanged: {
            console.log("Presentation ready!");
        }
    }
    \endqml

    \section2 Alternative usage

    The above example shows the 3D content in the Studio3D item. Qt 3D Studio
    presentations consist of one or more layers, each of which is a 3D scene
    with its own camera and lights. The output of each layer is then composed
    together into a final image, taking layer position, size, and blending into
    account. Studio3D shows this final image by default.

    In many cases it can be beneficial to follow a different model: instead of
    displaying the final, composed content in a single Studio3D item, it is
    also possible to manage the Qt 3D Studio layers individually as Qt Quick
    items, thus moving the layer composition into Qt Quick's domain. The 3D
    engine's final image is not generated at all in this case. The key enabler
    for this approach is the \l View3D type.

    \qml
    Studio3D {
        id: studio3D
        Presentation {
            source: "qrc:///presentation.uia"
            SceneElement {
                id: scene
                elementPath: "Scene"
                currentSlideIndex: 2
            }
            Element {
                id: textLabel
                elementPath: "Scene.Layer.myLabel"
            }
        }
        onRunningChanged: {
            console.log("Presentation ready!");
        }
    }

    View3D {
        engine: studio3D
        source: "LayerName"
        anchors.fill: parent
    }
    \endqml

    In this modified example the Studio3D item does not display any content,
    while the View3D item displays only the content of a single layer,
    referenced by the name set in the Qt 3D Studio application. This approach
    enables creating interfaces where multiple different pieces of 3D content
    is blended with the 2D user interface, instead of being restricted to a
    single rectangular area defined by the Studio3D item.

    \note Multiple Studio3D items should be avoided. Prefer using \l View3D
    whenever there is a need to display 3D content in multiple areas of the
    screen.

    \section2 Controlling the presentation

    Like the example above suggests, Studio3D and the other types under the
    QtStudio3D import offer more than simply rendering the animated Qt 3D
    Studio presentation. They also offer scene manipulation, including

    \list

    \li querying and changing scene object properties (for example, the
    transform of a model, colors and other settings of a material, etc.) via
    Presentation::getAttribute(), Presentation::setAttribute(), \l Element, and
    \l DataInput,

    \li changing slides (and thus starting the relevant animations and applying
    the scene object property changes associated with the new slide) via
    Presentation::goToSlide(), \l SceneElement, and \l DataInput,

    \li and controlling the timeline (the current playback position for the
    key-frame based animations) both on the main scene and on individual
    Component nodes via Presentation::goToTime(), \l SceneElement, and \l DataInput.

    \endlist

    \sa View3D, Presentation
*/

/*!
    \qmlsignal Studio3D::frameUpdate()

    This signal is emitted each time a frame has been rendered.
*/

/*!
    \qmlsignal Studio3D::presentationLoaded()

    This signal is emitted when the presentation has been loaded and is ready
    to be shown.
*/

/*!
    \qmlsignal Studio3D::presentationReady()

    This signal is emitted when the presentation has fully initialized its 3D
    scene for the first frame.

    The difference to presentationLoaded() is that this signal is emitted only
    when the asynchronous operations needed to build to 3D scene and the first
    frame have completed.

    When implementing splash screens via Loader items and the Item::visible
    property, this is the signal that should be used to trigger hiding the
    splash screen.
*/

static bool engineCleanerRegistered = false;
static QSet<Q3DSEngine *> engineTracker;
static void engineCleaner()
{
    // We cannot go down with engines alive, mainly because some Qt 3D stuff
    // uses threads which need proper shutdown.
    QSet<Q3DSEngine *> strayEngines = std::move(engineTracker);
    for (Q3DSEngine *engine : strayEngines)
        delete engine;
}

Q3DSStudio3DItem::Q3DSStudio3DItem(QQuickItem *parent)
    : QQuickItem(parent)
{
    if (!engineCleanerRegistered) {
        qAddPostRoutine(engineCleaner);
        engineCleanerRegistered = true;
    }

    setFlag(QQuickItem::ItemHasContents, true);

    // not strictly needed since we'll use Q3DSUtilsMessageRedirect but just in case
    Q3DSUtils::setDialogsEnabled(false);

    updateEventMasks();
}

Q3DSStudio3DItem::~Q3DSStudio3DItem()
{
}

/*!
    \qmlproperty Presentation Studio3D::presentation

    Accessor for the presentation. Applications are expected to create a single
    Presentation child object for Studio3D. If this is omitted, a presentation
    is created automatically.

    This property is read-only.
*/

Q3DSPresentationItem *Q3DSStudio3DItem::presentation() const
{
    return m_presentation;
}

/*!
    \qmlproperty bool Studio3D::running

    The value of this property is \c true when the presentation has been loaded
    and is ready to be shown.

    This property is read-only.
*/

bool Q3DSStudio3DItem::isRunning() const
{
    return m_running;
}

/*!
    \qmlproperty string Studio3D::error

    Contains the text for the error message that was generated during the
    loading of the presentation. When no error occurred or there is no
    presentation loaded, the value is an empty string.

    This property is read-only.
*/

QString Q3DSStudio3DItem::error() const
{
    return m_error;
}

Q3DSStudio3DItem::EventIgnoreFlags Q3DSStudio3DItem::ignoredEvents() const
{
    return m_eventIgnoreFlags;
}

void Q3DSStudio3DItem::setIgnoredEvents(EventIgnoreFlags flags)
{
    if (m_eventIgnoreFlags == flags)
        return;

    m_eventIgnoreFlags = flags;
    updateEventMasks();
    emit ignoredEventsChanged();
}

void Q3DSStudio3DItem::setupSeparateViews(bool isAfterPresentationLoad)
{
    if (m_engine && window()) {
        m_separateViewSetupPending = false;

        const bool hasSeparateViews = !m_views.isEmpty();

        // turn off (or re-enable) layer composition via the 3D engine
        m_engine->setMainLayerComposition(!hasSeparateViews);

        // use the silly but convenient legacy API to disable input processing
        // in case it is taken over by the View3D items
        setIgnoredEvents(hasSeparateViews ? IgnoreAllInputEvents : EnableAllEvents);

        const qreal dpr = window()->effectiveDevicePixelRatio();
        for (Q3DSStudio3DView *view : m_views) {
            // set the explicit layer size
            handleViewGeometryChange(view, view->size().toSize() * dpr);
            // Qt 3D is not able to provide frames right away so we must make
            // the sg node reverts to showing something sensible.
            if (isAfterPresentationLoad)
                view->resetToDummy();
            // trigger an eventual updatePaintNode() for the view
            view->update();
        }

        update();
    } else {
        m_separateViewSetupPending = true;
    }
}

void Q3DSStudio3DItem::updateEventMasks()
{
    if (m_eventIgnoreFlags.testFlag(IgnoreMouseEvents)) {
        setAcceptedMouseButtons(Qt::NoButton);
        setAcceptHoverEvents(false);
    } else {
        setAcceptedMouseButtons(Qt::MouseButtonMask);
        setAcceptHoverEvents(true);
    }
}

void Q3DSStudio3DItem::componentComplete()
{
    const auto childObjs = children();
    for (QObject *child : childObjs) {
        if (Q3DSPresentationItem *presentation = qobject_cast<Q3DSPresentationItem *>(child)) {
            if (m_presentation)
                qWarning("Studio3D: Duplicate Presentation");
            else
                m_presentation = presentation;
        } else if (Q3DSViewerSettings *viewerSettings = qobject_cast<Q3DSViewerSettings *>(child)) {
            if (m_viewerSettings) {
                qWarning("Studio3D: Duplicate ViewerSettings");
            } else {
                m_viewerSettings = viewerSettings;
                if (m_engine)
                    m_engine->setViewportSettings(Q3DSViewerSettingsPrivate::get(m_viewerSettings)->createViewportSettingsProxy());
            }
        }
    }

    if (!m_presentation)
        m_presentation = new Q3DSPresentationItem(this);

    // setController may lead to creating the engine hence this must happen before
    m_presentation->preStudio3DPresentationLoaded();

    Q3DSPresentationPrivate::get(m_presentation)->setController(this);

    QQuickItem::componentComplete();
}

void Q3DSStudio3DItem::handlePresentationSource(const QUrl &source,
                                                SourceFlags flags,
                                                const QVector<Q3DSInlineQmlSubPresentation *> &inlineSubPres)
{
    if (source == m_source)
        return;

    if (!m_source.isEmpty())
        releaseEngineAndRenderer();

    m_source = source;
    m_sourceFlags = flags;
    m_inlineQmlSubPresentations = inlineSubPres;

    if (window()) // else defer to itemChange()
        createEngine();
}

void Q3DSStudio3DItem::handlePresentationReload()
{
    if (m_source.isEmpty())
        return;

    releaseEngineAndRenderer();

    if (window())
        createEngine();
}

void Q3DSStudio3DItem::createEngine()
{
    // note: cannot have an engine without the source set
    // (since once we assume m_engine!=nullptr, m_engine->renderAspect() must be valid as well)

    if (!m_engine) {
        qCDebug(lcStudio3D, "creating engine");
        QQuickWindow *w = window();
        Q_ASSERT(w);

        if (w->rendererInterface()->graphicsApi() != QSGRendererInterface::OpenGL) {
            qWarning("Studio3D: Qt Quick not running with OpenGL; this is not supported atm");
            m_error = QLatin1String("Studio3D requires OpenGL");
            emit errorChanged();
            return;
        }

        const QSurfaceFormat wformat = w->format();
        const QSurfaceFormat eformat = Q3DS::surfaceFormat();
        if (wformat.version() != eformat.version() || wformat.profile() != eformat.profile()) {
            qCDebug(lcStudio3D) << "Adopting surface format from QQuickWindow:" << wformat;
            Q3DS::adoptSurfaceFormat(wformat);
        }

        m_engine = new Q3DSEngine;
        engineTracker.insert(m_engine);

        // Rendering will be driven manually from the Quick render thread via the QRenderAspect.
        // We create the render aspect ourselves on the Quick render thread.
        Q3DSEngine::Flags flags = Q3DSEngine::WithoutRenderAspect;
        if (m_sourceFlags.testFlag(Q3DSPresentationController::Profiling))
            flags |= Q3DSEngine::EnableProfiling;

        m_engine->setFlags(flags);
        m_engine->setAutoToggleProfileUi(false); // up to the app to control this via the API instead

        // Use our QQmlEngine for QML subpresentations and behavior scripts.
        QQmlEngine *qmlEngine = QQmlEngine::contextForObject(this)->engine();
        m_engine->setSharedSubPresentationQmlEngine(qmlEngine);
        m_engine->setSharedBehaviorQmlEngine(qmlEngine);

        initializePresentationController(m_engine, m_presentation);

        if (QWindow *rw = QQuickRenderControl::renderWindowFor(w)) {
            // rw is the top-level window that is backed by a native window. Do
            // not use that though since we must not clash with e.g. the widget
            // backingstore compositor in the gui thread.
            QOffscreenSurface *dummySurface = new QOffscreenSurface;
            dummySurface->setParent(qGuiApp); // parent to something suitably long-living
            dummySurface->setFormat(rw->format());
            dummySurface->create();
            m_engine->setSurface(dummySurface);
        } else {
            m_engine->setSurface(w);
        }

        if (m_viewerSettings)
            m_engine->setViewportSettings(Q3DSViewerSettingsPrivate::get(m_viewerSettings)->createViewportSettingsProxy());

        qCDebug(lcStudio3D, "created engine %p", m_engine);

        connect(m_engine, &Q3DSEngine::presentationLoaded, this, [this]() {
            m_presentation->studio3DPresentationLoaded();
            if (!m_running) {
                m_running = true;
                emit runningChanged();
            }
            emit presentationLoaded();
        });
        connect(m_engine, &Q3DSEngine::nextFrameStarting, this, [this]() {
            if (m_needsPresReadySignal) {
                m_needsPresReadySignal = false;
                emit presentationReady();
            }
            emit frameUpdate();
        });

        connect(m_engine, &Q3DSEngine::layerResized, this, [this](Q3DSLayerNode *) {
            m_pendingViewSend = true;
            update();
        });

        connect(m_engine, &Q3DSEngine::layerTextureNodeChanged, this, [this](Q3DSLayerNode *) {
            m_pendingViewSend = true;
            update();
        });
    }

    m_needsPresReadySignal = true;

    const QString fn = QQmlFile::urlToLocalFileOrQrc(m_source);
    qCDebug(lcStudio3D) << "source is now" << fn;
    const QSize sz(width(), height());
    const qreal dpr = window()->effectiveDevicePixelRatio();
    if (!sz.isEmpty())
        m_engine->resize(sz, dpr);

    QString err;
    m_sourceLoaded = m_engine->setSource(fn, &err, m_inlineQmlSubPresentations);
    if (m_sourceLoaded) {
        if (!m_error.isEmpty()) {
            m_error.clear();
            emit errorChanged();
        }

        if (!sz.isEmpty())
            sendResizeToQt3D(sz, dpr);

        setupSeparateViews(true);

        // cannot start() here, that must be deferred

    } else {
        qWarning("Studio3D: Failed to load %s\n%s", qPrintable(fn), qPrintable(err));
        m_error = err;
        emit errorChanged();
    }

    update();
}

QSGNode *Q3DSStudio3DItem::updatePaintNode(QSGNode *node, QQuickItem::UpdatePaintNodeData *)
{
    // this on the render thread; the engine lives on the gui thread and should
    // be ready at this point - unless there's no source set yet (or it failed)

    if (!m_engine || !m_sourceLoaded || (size().isEmpty() && m_views.isEmpty())) {
        delete node;
        return nullptr;
    }

    Q3DSLayer3DSGNode *n = static_cast<Q3DSLayer3DSGNode *>(node);
    if (!n && m_views.isEmpty()) {
        n = new Q3DSLayer3DSGNode;
        // could be that m_views got changed from non-empty to empty, communicate the new node then
        if (m_renderer)
            m_renderer->setNode(n);
    }

    if (n)
        n->setRect(QRectF(0, 0, width(), height()));

    if (!m_renderer) {
        m_renderer = new Q3DSStudio3DRenderer(this, n, m_engine->aspectEngine());
        m_pendingViewSend = true; // force pushing the view-layer pairs to the instance
    }

    if (!m_views.isEmpty()) {
        if (m_pendingViewSend) {
            m_pendingViewSend = false;
            QVector<Q3DSStudio3DViewDesc> viewDesc;
            // Gather the layer names (or ids) that need to be exposed.
            for (Q3DSStudio3DView *view : m_views) {
                QString objRef = view->source();
                if (objRef.isEmpty())
                    continue;
                // engine lives on the main thread but is safe here since that is blocked
                Q3DSGraphObject *obj = m_engine->findObjectByHashIdOrNameOrPath(nullptr, m_engine->presentation(0), objRef);
                if (obj && obj->type() == Q3DSGraphObject::Layer) {
                    Q3DSLayerNode *layer3DS = static_cast<Q3DSLayerNode *>(obj);
                    view->notifyLayerNodeChange(layer3DS);
                    Qt3DCore::QNodeId nodeId = m_engine->layerTextureNodeId(layer3DS);
                    if (!nodeId.isNull()) {
                        Q3DSStudio3DViewDesc vd;
                        vd.view = view;
                        vd.textureNodeId = nodeId;
                        Q3DSLayerAttached *layerData = layer3DS->attached<Q3DSLayerAttached>();
                        vd.layerSizePixels = layerData->layerSize * layerData->ssaaScaleFactor;
                        vd.layerSizePixelsWithoutSsaa = layerData->layerSize;
                        vd.layerSampleCount = layerData->msaaSampleCount;
                        vd.viewSizeWithoutDpr = view->size().toSize();
                        vd.dpr = window()->effectiveDevicePixelRatio();
                        viewDesc.append(vd);
                    } else {
                        qWarning("No QNodeId for layer %s texture?", layer3DS->id().constData());
                    }
                } else {
                    view->notifyLayerNodeChange(nullptr);
                    qWarning("%s is not a Layer", qPrintable(objRef));
                }
            }
            m_renderer->setViewDescriptions(viewDesc);
        }

        // With separate views we are still technically a visual item and run
        // the 3D rendering underneath, but there is no SG node and therefore
        // the Studio3D item itself will not display anything.
        if (n) {
            m_renderer->setNode(nullptr);
            delete n;
        }
        return nullptr;
    }

    return n;
}

// Let's do resource handling correctly, which means handling releaseResources
// on the item and connecting to the sceneGraphInvalidated signal. Care must be
// taken to support the case of moving the item from window to another as well.

void Q3DSStudio3DItem::itemChange(QQuickItem::ItemChange change,
                                  const QQuickItem::ItemChangeData &changeData)
{
    if (change == QQuickItem::ItemSceneChange) {
        if (changeData.window) {
            connect(changeData.window, &QQuickWindow::sceneGraphInvalidated, this, [this]() {
                // render thread (or main if non-threaded render loop)
                qCDebug(lcStudio3D, "[R] sceneGraphInvalidated");
                delete m_renderer;
                m_renderer = nullptr;
                QMetaObject::invokeMethod(this, "destroyEngine");
            }, Qt::DirectConnection);

            if (!m_source.isEmpty() && !m_engine)
                createEngine();

            if (m_engine && m_separateViewSetupPending)
                setupSeparateViews();
        }
    }
}

void Q3DSStudio3DItem::startEngine()
{
    // set root entity
    if (m_engine)
        m_engine->start();
    else
        qWarning("No engine (no window for item?), cannot start");
}

void Q3DSStudio3DItem::destroyEngine()
{
    if (m_engine) {
        Q_ASSERT(!m_renderer);
        qCDebug(lcStudio3D, "destroying engine %p", m_engine);
        engineTracker.remove(m_engine);
        delete m_engine; // recreate on next window change - if we are still around, that is
        m_engine = nullptr;
        if (m_running) {
            m_running = false;
            emit runningChanged();
        }
    }
}

class EngineReleaser : public QObject
{
public:
    EngineReleaser(Q3DSEngine *engine)
        : m_engine(engine)
    { }
    ~EngineReleaser() {
        if (engineTracker.contains(m_engine)) {
            qCDebug(lcStudio3D, "async release: destroying engine %p", m_engine);
            engineTracker.remove(m_engine);
            delete m_engine;
        }

        // Here the destruction of the old engine and the creation of a new one
        // will overlap (if the item survives, that is). So don't bother with
        // m_running.
    }

private:
    Q3DSEngine *m_engine;
};

class RendererReleaser : public QRunnable
{
public:
    RendererReleaser(Q3DSStudio3DRenderer *r, EngineReleaser *er)
        : m_renderer(r),
          m_engineReleaser(er)
    { }
    void run() override {
        delete m_renderer;

        // now, if this is on the render thread (Qt Quick with threaded render
        // loop) and the application is exiting, the deleteLater may not
        // actually be executed ever. Hence the need for the post routine and
        // engineTracker. However, if the application stays alive and we are
        // cleaning up for another reason, this is just fine since the engine
        // will eventually get deleted fine by the main thread.
        m_engineReleaser->deleteLater();
    }

private:
    Q3DSStudio3DRenderer *m_renderer;
    EngineReleaser *m_engineReleaser;
};

void Q3DSStudio3DItem::releaseResources()
{
    qCDebug(lcStudio3D, "releaseResources");

    // this may not be an application exit; if this is just a window change then allow continuing
    // by eventually creating new engine and renderer objects

    releaseEngineAndRenderer();
}

void Q3DSStudio3DItem::releaseEngineAndRenderer()
{
    if (!window() || !m_renderer)
        return;

    // renderer must be destroyed first (on the Quick render thread)
    if (m_renderer->thread() == QThread::currentThread()) {
        delete m_renderer;
        m_renderer = nullptr;
        destroyEngine();
    } else {
        // by the time the runnable runs we (the item) may already be gone; that's fine, just pass the renderer ref
        EngineReleaser *er = new EngineReleaser(m_engine);
        RendererReleaser *rr = new RendererReleaser(m_renderer, er);
        window()->scheduleRenderJob(rr, QQuickWindow::BeforeSynchronizingStage);
        m_renderer->invalidateItem();
        m_renderer = nullptr;
        m_engine = nullptr;
    }
}

void Q3DSStudio3DItem::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry)
{
    QQuickItem::geometryChanged(newGeometry, oldGeometry);

    if (!newGeometry.isEmpty() && m_engine && newGeometry.size() != oldGeometry.size()) {
        const QSize sz = newGeometry.size().toSize();
        const qreal dpr = window()->effectiveDevicePixelRatio();
        m_engine->resize(sz, dpr);
        sendResizeToQt3D(sz, dpr);
    }
}

void Q3DSStudio3DItem::sendResizeToQt3D(const QSize &size, qreal dpr)
{
    Qt3DCore::QEntity *rootEntity = m_engine->rootEntity();
    if (rootEntity) {
        Qt3DRender::QRenderSurfaceSelector *surfaceSelector = Qt3DRender::QRenderSurfaceSelectorPrivate::find(rootEntity);
        qCDebug(lcStudio3D, "Setting external render target size on surface selector %p", surfaceSelector);
        if (surfaceSelector) {
            surfaceSelector->setExternalRenderTargetSize(size);
            surfaceSelector->setSurfacePixelRatio(dpr);
        }
    }
}

void Q3DSStudio3DItem::keyPressEvent(QKeyEvent *event)
{
    if (!m_eventIgnoreFlags.testFlag(IgnoreKeyboardEvents) && m_engine)
        m_engine->handleKeyPressEvent(event);
}

void Q3DSStudio3DItem::keyReleaseEvent(QKeyEvent *event)
{
    if (!m_eventIgnoreFlags.testFlag(IgnoreKeyboardEvents) && m_engine)
        m_engine->handleKeyReleaseEvent(event);
}

void Q3DSStudio3DItem::mousePressEvent(QMouseEvent *event)
{
    if (!m_eventIgnoreFlags.testFlag(IgnoreMouseEvents) && m_engine)
        m_engine->handleMousePressEvent(event);
}

void Q3DSStudio3DItem::mouseMoveEvent(QMouseEvent *event)
{
    if (!m_eventIgnoreFlags.testFlag(IgnoreMouseEvents) && m_engine)
        m_engine->handleMouseMoveEvent(event);
}

void Q3DSStudio3DItem::mouseReleaseEvent(QMouseEvent *event)
{
    if (!m_eventIgnoreFlags.testFlag(IgnoreMouseEvents) && m_engine)
        m_engine->handleMouseReleaseEvent(event);
}

void Q3DSStudio3DItem::mouseDoubleClickEvent(QMouseEvent *event)
{
    if (!m_eventIgnoreFlags.testFlag(IgnoreMouseEvents) && m_engine)
        m_engine->handleMouseDoubleClickEvent(event);
}

#if QT_CONFIG(wheelevent)
void Q3DSStudio3DItem::wheelEvent(QWheelEvent *event)
{
    if (!m_eventIgnoreFlags.testFlag(IgnoreWheelEvents) && m_engine)
        m_engine->handleWheelEvent(event);
}
#endif

void Q3DSStudio3DItem::hoverMoveEvent(QHoverEvent *event)
{
    if (m_eventIgnoreFlags.testFlag(IgnoreMouseEvents) || !m_engine)
        return;

    // Simulate the QWindow behavior, which means sending moves even when no
    // button is down. The profile ui for example depends on this.

    if (QGuiApplication::mouseButtons() != Qt::NoButton)
        return;

    const QPointF sceneOffset = mapToScene(event->pos());
    const QPointF globalOffset = mapToGlobal(event->pos());
    QMouseEvent e(QEvent::MouseMove, event->pos(), event->pos() + sceneOffset, event->pos() + globalOffset,
                  Qt::NoButton, Qt::NoButton, QGuiApplication::keyboardModifiers());
    m_engine->handleMouseMoveEvent(&e);
}

void Q3DSStudio3DItem::touchEvent(QTouchEvent *event)
{
    if (!m_eventIgnoreFlags.testFlag(IgnoreMouseEvents) && m_engine)
        m_engine->handleTouchEvent(event);
}

void Q3DSStudio3DItem::registerView(Q3DSStudio3DView *view)
{
    const bool wasEmpty = m_views.isEmpty();
    m_views.append(view);
    m_pendingViewSend = true;
    if (wasEmpty)
        setupSeparateViews();
}

void Q3DSStudio3DItem::unregisterView(Q3DSStudio3DView *view)
{
    m_views.removeOne(view);
    m_pendingViewSend = true;
    if (m_views.isEmpty())
        setupSeparateViews();
}

void Q3DSStudio3DItem::handleViewGeometryChange(Q3DSStudio3DView *view, const QSize &size)
{
    if (!m_engine)
        return;

    QString objRef = view->source();
    if (objRef.isEmpty())
        return;

    Q3DSGraphObject *obj = m_engine->findObjectByHashIdOrNameOrPath(nullptr, m_engine->presentation(0), objRef);
    if (!obj || obj->type() != Q3DSGraphObject::Layer)
        return;

    Q3DSLayerNode *layer3DS = static_cast<Q3DSLayerNode *>(obj);
    if (!m_views.isEmpty() && view->sizeLayerToView()) {
        if (!layer3DS->hasExplicitSize() || layer3DS->explicitSize() != size) {
            qCDebug(lcScene, "Explicit size for layer %s is %dx%d", layer3DS->id().constData(), size.width(), size.height());
            // Set the desired size and generate a property change. The
            // property name may be something bogus but that's enough to get
            // the scenemanager to recalculate size-related things in the
            // layer. Eventually it will lead to emitting
            // Q3DSEngine::layerResized. Note that this is all asynchronous and
            // may only happen on the next frame action.
            layer3DS->notifyPropertyChanges({ layer3DS->setExplicitSize(true, size) });
        }
    } else {
        if (layer3DS->hasExplicitSize()) {
            qCDebug(lcScene, "Layer %s is no longer explicitly sized", layer3DS->id().constData());
            layer3DS->notifyPropertyChanges({ layer3DS->setExplicitSize(false) });
        }
    }
}

void Q3DSStudio3DItem::handleViewSourceChange(Q3DSStudio3DView *view)
{
    Q_UNUSED(view);

    m_pendingViewSend = true;
    update();
}

QT_END_NAMESPACE