summaryrefslogtreecommitdiffstats
path: root/src/multimedia/qthreadlocalrhi.cpp
blob: 56194d0316320cf569e8622ad0df762946f10ec1 (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
// Copyright (C) 2025 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "qthreadlocalrhi_p.h"

#include <QtCore/qcoreapplication.h>
#include <QtCore/qthreadstorage.h>
#include <QtGui/private/qguiapplication_p.h>
#include <QtGui/qoffscreensurface.h>
#include <QtGui/qpa/qplatformintegration.h>

#if defined(Q_OS_ANDROID)
#  include <QtCore/qmetaobject.h>
#endif

QT_BEGIN_NAMESPACE

namespace {

static thread_local QRhi::Implementation s_preferredBackend = QRhi::Null;

#if QT_CONFIG(opengl)

bool openGLCapsSupported(const QPlatformIntegration &qpa)
{
     return qpa.hasCapability(QPlatformIntegration::OpenGL) &&
            !QCoreApplication::testAttribute(Qt::AA_ForceRasterWidgets) &&
            (QThread::isMainThread() ||
                (qpa.hasCapability(QPlatformIntegration::ThreadedOpenGL) &&
                 qpa.hasCapability(QPlatformIntegration::OffscreenSurface)));
}
#endif

class ThreadLocalRhiHolder
{
public:
    ThreadLocalRhiHolder();
    ~ThreadLocalRhiHolder() { resetRhi(); }

    QRhi *ensureRhi(QRhi *referenceRhi)
    {
        if (m_rhi || m_cpuOnly)
            return m_rhi.get();

        [[maybe_unused]] QRhi::Implementation referenceBackend =
                referenceRhi ? referenceRhi->backend() : QRhi::Null;
        const QPlatformIntegration *qpa = QGuiApplicationPrivate::platformIntegration();

        if (qpa && qpa->hasCapability(QPlatformIntegration::RhiBasedRendering)) {

#if QT_CONFIG(metal)
            if (canUseRhiImpl(QRhi::Metal, referenceBackend)) {
                QRhiMetalInitParams params;
                m_rhi.reset(QRhi::create(QRhi::Metal, &params));
            }
#endif

#if defined(Q_OS_WIN)
            if (!m_rhi && canUseRhiImpl(QRhi::D3D11, referenceBackend)) {
                QRhiD3D11InitParams params;
                m_rhi.reset(QRhi::create(QRhi::D3D11, &params));
            }
#endif

#if QT_CONFIG(opengl)
            if (!m_rhi && canUseRhiImpl(QRhi::OpenGLES2, referenceBackend)) {
                if (openGLCapsSupported(*qpa)) {

                    m_fallbackSurface.reset(QRhiGles2InitParams::newFallbackSurface());
                    QRhiGles2InitParams params;
                    params.fallbackSurface = m_fallbackSurface.get();
                    if (referenceBackend == QRhi::OpenGLES2)
                        params.shareContext = static_cast<const QRhiGles2NativeHandles *>(
                                                      referenceRhi->nativeHandles())
                                                      ->context;
                    m_rhi.reset(QRhi::create(QRhi::OpenGLES2, &params));

#  if defined(Q_OS_ANDROID)
                    // reset RHI state on application suspension, as this will be invalid after
                    // resuming
                    if (!m_appStateChangedConnection) {
                        if (!m_eventsReceiver)
                            m_eventsReceiver = std::make_unique<QObject>();

                        auto onStateChanged = [this](auto state) {
                            if (state == Qt::ApplicationSuspended)
                                resetRhi();
                        };

                        m_appStateChangedConnection =
                                QObject::connect(qApp, &QGuiApplication::applicationStateChanged,
                                                 m_eventsReceiver.get(), onStateChanged);
                    }
#  endif
                }
            }
#endif
        }

        if (!m_rhi) {
            m_cpuOnly = true;
            qWarning() << Q_FUNC_INFO << ": No RHI backend. Using CPU conversion.";
        }

        return m_rhi.get();
    }

    void resetRhi()
    {
        m_rhi.reset();
#if QT_CONFIG(opengl)
        m_fallbackSurface.reset();
#endif
        m_cpuOnly = false;
    }

    bool canUseRhiImpl(const QRhi::Implementation implementation,
                       const QRhi::Implementation reference)
    {
        // First priority goes to reference backend
        if (reference != QRhi::Null)
            return implementation == reference;

        // If no reference, but preference exists, compare to that
        if (s_preferredBackend != QRhi::Null)
            return implementation == s_preferredBackend;

        // Can use (assuming platform and configuration allow)
        return true;
    }

private:
    std::unique_ptr<QRhi> m_rhi;
#if QT_CONFIG(opengl)
    std::unique_ptr<QOffscreenSurface> m_fallbackSurface;
#endif
    bool m_cpuOnly = false;
#if defined(Q_OS_ANDROID)
    std::unique_ptr<QObject> m_eventsReceiver;
    // we keep and check QMetaObject::Connection because the sender, qApp,
    // can be recreated and the connection invalidated.
    QMetaObject::Connection m_appStateChangedConnection;
#endif
};

Q_CONSTINIT thread_local std::optional<ThreadLocalRhiHolder> g_threadLocalRhiHolder;

ThreadLocalRhiHolder::ThreadLocalRhiHolder()
{
    if (QThread::isMainThread()) {
        // ensure cleanup in qApp dtor
        qAddPostRoutine([] {
            g_threadLocalRhiHolder.reset();
        });
    }
}

} // namespace

QRhi *qEnsureThreadLocalRhi(QRhi *referenceRhi)
{
    if (!g_threadLocalRhiHolder)
        g_threadLocalRhiHolder.emplace();

    return g_threadLocalRhiHolder->ensureRhi(referenceRhi);
}

void qSetPreferredThreadLocalRhiBackend(QRhi::Implementation backend)
{
    s_preferredBackend = backend;
    if (g_threadLocalRhiHolder)
        g_threadLocalRhiHolder->resetRhi();
}

QT_END_NAMESPACE