aboutsummaryrefslogtreecommitdiffstats
path: root/src/quick/scenegraph/qsgdefaultrendercontext.cpp
blob: 3fee9d9faf8c99ac5048457dbffc418be1396479 (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
// Copyright (C) 2016 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 "qsgdefaultrendercontext_p.h"

#include <QtGui/QGuiApplication>

#include <QtQuick/private/qsgbatchrenderer_p.h>
#include <QtQuick/private/qsgrenderer_p.h>
#include <QtQuick/private/qsgrhiatlastexture_p.h>
#include <QtQuick/private/qsgrhidistancefieldglyphcache_p.h>
#include <QtQuick/private/qsgmaterialshader_p.h>

#include <QtQuick/private/qsgcompressedtexture_p.h>

#include <QtQuick/qsgrendererinterface.h>
#include <QtQuick/qquickgraphicsconfiguration.h>

QT_BEGIN_NAMESPACE

QSGDefaultRenderContext::QSGDefaultRenderContext(QSGContext *context)
    : QSGRenderContext(context)
    , m_rhi(nullptr)
    , m_maxTextureSize(0)
    , m_rhiAtlasManager(nullptr)
    , m_currentFrameCommandBuffer(nullptr)
    , m_currentFrameRenderPass(nullptr)
    , m_useDepthBufferFor2D(true)
    , m_glyphCacheResourceUpdates(nullptr)
{
}

/*!
    Initializes the scene graph render context with the GL context \a context. This also
    emits the ready() signal so that the QML graph can start building scene graph nodes.
 */
void QSGDefaultRenderContext::initialize(const QSGRenderContext::InitParams *params)
{
    if (!m_sg)
        return;

    const InitParams *initParams = static_cast<const InitParams *>(params);
    if (initParams->sType != INIT_PARAMS_MAGIC)
        qFatal("QSGDefaultRenderContext: Invalid parameters passed to initialize()");

    m_initParams = *initParams;

    m_rhi = m_initParams.rhi;
    m_maxTextureSize = m_rhi->resourceLimit(QRhi::TextureSizeMax);
    if (!m_rhiAtlasManager)
        m_rhiAtlasManager = new QSGRhiAtlasTexture::Manager(this, m_initParams.initialSurfacePixelSize, m_initParams.maybeSurface);

    m_glyphCacheResourceUpdates = nullptr;

    m_sg->renderContextInitialized(this);

    emit initialized();
}

void QSGDefaultRenderContext::invalidateGlyphCaches()
{
    auto it = m_glyphCaches.begin();
    while (it != m_glyphCaches.end()) {
        if (!(*it)->isActive()) {
            delete *it;
            it = m_glyphCaches.erase(it);
        } else {
            ++it;
        }
    }
}

void QSGDefaultRenderContext::invalidate()
{
    if (!m_rhi)
        return;

    qDeleteAll(m_texturesToDelete);
    m_texturesToDelete.clear();

    qDeleteAll(m_textures);
    m_textures.clear();

    /* The cleanup of the atlas textures is a bit intriguing.
       As part of the cleanup in the threaded render loop, we
       do:
       1. call this function
       2. call QCoreApp::sendPostedEvents() to immediately process
          any pending deferred deletes.
       3. delete the GL context.

       As textures need the atlas manager while cleaning up, the
       manager needs to be cleaned up after the textures, so
       we post a deleteLater here at the very bottom so it gets
       deferred deleted last.

       Another alternative would be to use a QPointer in
       QSGOpenGLAtlasTexture::Texture, but this seemed simpler.
     */
    if (m_rhiAtlasManager) {
        m_rhiAtlasManager->invalidate();
        m_rhiAtlasManager->deleteLater();
        m_rhiAtlasManager = nullptr;
    }

    // The following piece of code will read/write to the font engine's caches,
    // potentially from different threads. However, this is safe because this
    // code is only called from QQuickWindow's shutdown which is called
    // only when the GUI is blocked, and multiple threads will call it in
    // sequence. (see qsgdefaultglyphnode_p.cpp's init())
    for (QSet<QFontEngine *>::const_iterator it = m_fontEnginesToClean.constBegin(),
         end = m_fontEnginesToClean.constEnd(); it != end; ++it) {
        (*it)->clearGlyphCache(m_rhi);
        if (!(*it)->ref.deref())
            delete *it;
    }
    m_fontEnginesToClean.clear();

    qDeleteAll(m_glyphCaches);
    m_glyphCaches.clear();

    releaseGlyphCacheResourceUpdates();

    m_rhi = nullptr;

    if (m_sg)
        m_sg->renderContextInvalidated(this);

    emit invalidated();
}

void QSGDefaultRenderContext::prepareSync(qreal devicePixelRatio,
                                          QRhiCommandBuffer *cb,
                                          const QQuickGraphicsConfiguration &config)
{
    m_currentDevicePixelRatio = devicePixelRatio;
    m_useDepthBufferFor2D = config.isDepthBufferEnabledFor2D();

    // we store the command buffer already here, in case there is something in
    // an updatePaintNode() implementation that leads to needing it (for
    // example, an updateTexture() call on a QSGRhiLayer)
    m_currentFrameCommandBuffer = cb;
}

void QSGDefaultRenderContext::beginNextFrame(QSGRenderer *renderer, const QSGRenderTarget &renderTarget,
                                             RenderPassCallback mainPassRecordingStart,
                                             RenderPassCallback mainPassRecordingEnd,
                                             void *callbackUserData)
{
    renderer->setRenderTarget(renderTarget);
    renderer->setRenderPassRecordingCallbacks(mainPassRecordingStart, mainPassRecordingEnd, callbackUserData);

    m_currentFrameCommandBuffer = renderTarget.cb; // usually the same as what was passed to prepareSync() but cannot count on that having been called
    m_currentFrameRenderPass = renderTarget.rpDesc;
}

void QSGDefaultRenderContext::renderNextFrame(QSGRenderer *renderer)
{
    renderer->renderScene();
}

void QSGDefaultRenderContext::endNextFrame(QSGRenderer *renderer)
{
    Q_UNUSED(renderer);
    m_currentFrameCommandBuffer = nullptr;
    m_currentFrameRenderPass = nullptr;
}

QSGTexture *QSGDefaultRenderContext::createTexture(const QImage &image, uint flags) const
{
    bool atlas = flags & CreateTexture_Atlas;
    bool mipmap = flags & CreateTexture_Mipmap;
    bool alpha = flags & CreateTexture_Alpha;

    // The atlas implementation is only supported from the render thread and
    // does not support mipmaps.
    if (m_rhi) {
        if (!mipmap && atlas && QThread::currentThread() == m_rhi->thread()) {
            QSGTexture *t = m_rhiAtlasManager->create(image, alpha);
            if (t)
                return t;
        }
    }

    QSGPlainTexture *texture = new QSGPlainTexture;
    texture->setImage(image);
    if (texture->hasAlphaChannel() && !alpha)
        texture->setHasAlphaChannel(false);

    return texture;
}

QSGRenderer *QSGDefaultRenderContext::createRenderer(QSGRendererInterface::RenderMode renderMode)
{
    return new QSGBatchRenderer::Renderer(this, renderMode);
}

QSGTexture *QSGDefaultRenderContext::compressedTextureForFactory(const QSGCompressedTextureFactory *factory) const
{
    // This is only used for atlasing compressed textures. Returning null implies no atlas.

    if (m_rhi && QThread::currentThread() == m_rhi->thread())
        return m_rhiAtlasManager->create(factory);

    return nullptr;
}

QString QSGDefaultRenderContext::fontKey(const QRawFont &font, int renderTypeQuality)
{
    QFontEngine *fe = QRawFontPrivate::get(font)->fontEngine;
    if (!fe->faceId().filename.isEmpty()) {
        QByteArray keyName =
                fe->faceId().filename + ' ' + QByteArray::number(fe->faceId().index)
                + (font.style() != QFont::StyleNormal ? QByteArray(" I") : QByteArray())
                + (font.weight() != QFont::Normal ? ' ' + QByteArray::number(font.weight()) : QByteArray())
                + ' ' + QByteArray::number(renderTypeQuality)
                + QByteArray(" DF");
        return QString::fromUtf8(keyName);
    } else {
        return QString::fromLatin1("%1_%2_%3_%4_%5")
            .arg(font.familyName())
            .arg(font.styleName())
            .arg(font.weight())
            .arg(font.style())
            .arg(renderTypeQuality);
    }
}

void QSGDefaultRenderContext::initializeRhiShader(QSGMaterialShader *shader, QShader::Variant shaderVariant)
{
    QSGMaterialShaderPrivate::get(shader)->prepare(shaderVariant);
}

void QSGDefaultRenderContext::preprocess()
{
    for (auto it = m_glyphCaches.begin(); it != m_glyphCaches.end(); ++it) {
        it.value()->processPendingGlyphs();
        it.value()->update();
    }
}

QSGDistanceFieldGlyphCache *QSGDefaultRenderContext::distanceFieldGlyphCache(const QRawFont &font, int renderTypeQuality)
{
    QString key = fontKey(font, renderTypeQuality);
    QSGDistanceFieldGlyphCache *cache = m_glyphCaches.value(key, 0);
    if (!cache) {
        cache = new QSGRhiDistanceFieldGlyphCache(this, font, renderTypeQuality);
        m_glyphCaches.insert(key, cache);
    }

    return cache;
}

QRhiResourceUpdateBatch *QSGDefaultRenderContext::maybeGlyphCacheResourceUpdates()
{
    return m_glyphCacheResourceUpdates;
}

QRhiResourceUpdateBatch *QSGDefaultRenderContext::glyphCacheResourceUpdates()
{
    if (!m_glyphCacheResourceUpdates)
        m_glyphCacheResourceUpdates = m_rhi->nextResourceUpdateBatch();

    return m_glyphCacheResourceUpdates;
}

void QSGDefaultRenderContext::releaseGlyphCacheResourceUpdates()
{
    if (m_glyphCacheResourceUpdates) {
        m_glyphCacheResourceUpdates->release();
        m_glyphCacheResourceUpdates = nullptr;
    }
}

QT_END_NAMESPACE

#include "moc_qsgdefaultrendercontext_p.cpp"