8#include <QtGui/private/qdistancefield_p.h>
9#include <QtCore/qelapsedtimer.h>
10#include <QtQml/private/qqmlglobal_p.h>
16DEFINE_BOOL_CONFIG_OPTION(qmlUseGlyphCacheWorkaround, QML_USE_GLYPHCACHE_WORKAROUND)
17DEFINE_BOOL_CONFIG_OPTION(qsgPreferFullSizeGlyphCacheTextures, QSG_PREFER_FULLSIZE_GLYPHCACHE_TEXTURES)
19#if !defined(QSG_RHI_DISTANCEFIELD_GLYPH_CACHE_PADDING)
20# define QSG_RHI_DISTANCEFIELD_GLYPH_CACHE_PADDING 2
23QSGRhiDistanceFieldGlyphCache::QSGRhiDistanceFieldGlyphCache(QSGDefaultRenderContext *rc,
25 int renderTypeQuality)
26 : QSGDistanceFieldGlyphCache(font, renderTypeQuality)
31 loadPregeneratedCache(font);
34QSGRhiDistanceFieldGlyphCache::~QSGRhiDistanceFieldGlyphCache()
36 for (
const TextureInfo &t : std::as_const(m_textures))
37 m_rc->deferredReleaseGlyphCacheTexture(t.texture);
39 delete m_areaAllocator;
42void QSGRhiDistanceFieldGlyphCache::requestGlyphs(
const QSet<glyph_t> &glyphs)
44 QList<GlyphPosition> glyphPositions;
45 QList<glyph_t> glyphsToRender;
47 if (m_areaAllocator ==
nullptr)
48 m_areaAllocator =
new QSGAreaAllocator(QSize(maxTextureSize(), m_maxTextureCount * maxTextureSize()));
50 for (QSet<glyph_t>::const_iterator it = glyphs.constBegin(); it != glyphs.constEnd() ; ++it) {
51 glyph_t glyphIndex = *it;
54 QRectF boundingRect = glyphData(glyphIndex).boundingRect;
55 int glyphWidth = qCeil(boundingRect.width() + distanceFieldRadius() * 2);
56 int glyphHeight = qCeil(boundingRect.height() + distanceFieldRadius() * 2);
57 QSize glyphSize(glyphWidth + padding * 2, glyphHeight + padding * 2);
58 QRect alloc = m_areaAllocator->allocate(glyphSize);
62 while (alloc.isNull() && !m_unusedGlyphs.isEmpty()) {
63 glyph_t unusedGlyph = *m_unusedGlyphs.constBegin();
65 TexCoord unusedCoord = glyphTexCoord(unusedGlyph);
66 if (!unusedCoord.isNull()) {
67 QRectF unusedGlyphBoundingRect = glyphData(unusedGlyph).boundingRect;
68 int unusedGlyphWidth = qCeil(unusedGlyphBoundingRect.width() + distanceFieldRadius() * 2);
69 int unusedGlyphHeight = qCeil(unusedGlyphBoundingRect.height() + distanceFieldRadius() * 2);
70 m_areaAllocator->deallocate(QRect(unusedCoord.x - padding,
71 unusedCoord.y - padding,
72 padding * 2 + unusedGlyphWidth,
73 padding * 2 + unusedGlyphHeight));
76 m_unusedGlyphs.remove(unusedGlyph);
77 m_glyphsTexture.remove(unusedGlyph);
78 removeGlyph(unusedGlyph);
80 alloc = m_areaAllocator->allocate(glyphSize);
88 TextureInfo *tex = textureInfo(alloc.y() / maxTextureSize());
89 alloc = QRect(alloc.x(), alloc.y() % maxTextureSize(), alloc.width(), alloc.height());
91 tex->allocatedArea |= alloc;
92 Q_ASSERT(tex->padding == padding || tex->padding < 0);
93 tex->padding = padding;
97 p.position = alloc.topLeft() + QPoint(padding, padding);
99 glyphPositions.append(p);
100 glyphsToRender.append(glyphIndex);
101 m_glyphsTexture.insert(glyphIndex, tex);
104 setGlyphsPosition(glyphPositions);
105 markGlyphsToRender(glyphsToRender);
108bool QSGRhiDistanceFieldGlyphCache::isActive()
const
110 return !m_referencedGlyphs.empty();
113void QSGRhiDistanceFieldGlyphCache::storeGlyphs(
const QList<QDistanceField> &glyphs)
115 typedef QHash<TextureInfo *, QList<glyph_t> > GlyphTextureHash;
116 typedef GlyphTextureHash::const_iterator GlyphTextureHashConstIt;
118 GlyphTextureHash glyphTextures;
120 for (
int i = 0; i < glyphs.size(); ++i) {
121 QDistanceField glyph = glyphs.at(i);
122 glyph_t glyphIndex = glyph.glyph();
123 TexCoord c = glyphTexCoord(glyphIndex);
124 TextureInfo *texInfo = m_glyphsTexture.value(glyphIndex);
126 resizeTexture(texInfo, texInfo->allocatedArea.width(), texInfo->allocatedArea.height());
128 if (!texInfo->texture)
131 glyphTextures[texInfo].append(glyphIndex);
133 int padding = texInfo->padding;
134 int expectedWidth = qCeil(c.width + c.xMargin * 2);
135 glyph = glyph.copy(-padding, -padding,
136 expectedWidth + padding * 2, glyph.height() + padding * 2);
138 if (useTextureResizeWorkaround()) {
139 uchar *inBits = glyph.scanLine(0);
140 uchar *outBits = texInfo->image.scanLine(
int(c.y) - padding) +
int(c.x) - padding;
141 for (
int y = 0; y < glyph.height(); ++y) {
142 memcpy(outBits, inBits, glyph.width());
143 inBits += glyph.width();
144 outBits += texInfo->image.width();
148 QRhiTextureSubresourceUploadDescription subresDesc(glyph.constBits(), glyph.width() * glyph.height());
149 subresDesc.setSourceSize(QSize(glyph.width(), glyph.height()));
150 subresDesc.setDestinationTopLeft(QPoint(c.x - padding, c.y - padding));
151 texInfo->uploads.append(QRhiTextureUploadEntry(0, 0, subresDesc));
154 QRhiResourceUpdateBatch *resourceUpdates = m_rc->glyphCacheResourceUpdates();
155 for (
int i = 0; i < glyphs.size(); ++i) {
156 TextureInfo *texInfo = m_glyphsTexture.value(glyphs.at(i).glyph());
157 if (!texInfo->uploads.isEmpty() && texInfo->texture) {
158 QRhiTextureUploadDescription desc;
159 desc.setEntries(texInfo->uploads.cbegin(), texInfo->uploads.cend());
160 resourceUpdates->uploadTexture(texInfo->texture, desc);
161 texInfo->uploads.clear();
165 for (GlyphTextureHashConstIt i = glyphTextures.constBegin(), cend = glyphTextures.constEnd(); i != cend; ++i) {
167 t.texture = i.key()->texture;
168 t.size = i.key()->size;
169 setGlyphsTexture(i.value(), t);
173void QSGRhiDistanceFieldGlyphCache::referenceGlyphs(
const QSet<glyph_t> &glyphs)
175 m_referencedGlyphs += glyphs;
176 m_unusedGlyphs -= glyphs;
179void QSGRhiDistanceFieldGlyphCache::releaseGlyphs(
const QSet<glyph_t> &glyphs)
181 m_referencedGlyphs -= glyphs;
182 m_unusedGlyphs += glyphs;
185void QSGRhiDistanceFieldGlyphCache::createTexture(TextureInfo *texInfo,
189 QByteArray zeroBuf(width * height, 0);
190 createTexture(texInfo, width, height, zeroBuf.constData());
193void QSGRhiDistanceFieldGlyphCache::createTexture(TextureInfo *texInfo,
198 QRhiTexture *newTexture = m_rhi->newTexture(QRhiTexture::RED_OR_ALPHA8, QSize(width, height), 1, QRhiTexture::UsedAsTransferSource);
199 if (!newTexture->create()) {
200 qWarning(
"Failed to create distance field glyph cache");
202 texInfo->texture =
nullptr;
203 texInfo->size = QSize();
204 texInfo->image = QDistanceField();
208 if (useTextureResizeWorkaround() && texInfo->image.isNull()) {
209 texInfo->image = QDistanceField(width, height);
210 memcpy(texInfo->image.bits(), pixels, width * height);
213 texInfo->texture = newTexture;
214 texInfo->size = QSize(width, height);
216 QRhiResourceUpdateBatch *resourceUpdates = m_rc->glyphCacheResourceUpdates();
217 QRhiTextureSubresourceUploadDescription subresDesc(pixels, width * height);
218 subresDesc.setSourceSize(QSize(width, height));
219 resourceUpdates->uploadTexture(texInfo->texture, QRhiTextureUploadEntry(0, 0, subresDesc));
222void QSGRhiDistanceFieldGlyphCache::resizeTexture(TextureInfo *texInfo,
int width,
int height)
224 int oldWidth = texInfo->size.width();
225 int oldHeight = texInfo->size.height();
226 if (width == oldWidth && height == oldHeight)
229 QRhiTexture *oldTexture = texInfo->texture;
230 createTexture(texInfo, width, height);
232 if (!texInfo->texture) {
234 m_rc->deferredReleaseGlyphCacheTexture(oldTexture);
241 updateRhiTexture(oldTexture, texInfo->texture, texInfo->size);
243 QRhiResourceUpdateBatch *resourceUpdates = m_rc->glyphCacheResourceUpdates();
244 if (useTextureResizeWorkaround()) {
245 QRhiTextureSubresourceUploadDescription subresDesc(texInfo->image.constBits(),
246 oldWidth * oldHeight);
247 subresDesc.setSourceSize(QSize(oldWidth, oldHeight));
248 resourceUpdates->uploadTexture(texInfo->texture, QRhiTextureUploadEntry(0, 0, subresDesc));
249 texInfo->image = texInfo->image.copy(0, 0, width, height);
251 resourceUpdates->copyTexture(texInfo->texture, oldTexture);
254 m_rc->deferredReleaseGlyphCacheTexture(oldTexture);
257bool QSGRhiDistanceFieldGlyphCache::useTextureResizeWorkaround()
const
259 static bool set =
false;
260 static bool useWorkaround =
false;
262 useWorkaround = m_rhi->backend() == QRhi::OpenGLES2 || qmlUseGlyphCacheWorkaround();
265 return useWorkaround;
268bool QSGRhiDistanceFieldGlyphCache::createFullSizeTextures()
const
270 return qsgPreferFullSizeGlyphCacheTextures() && glyphCount() > QT_DISTANCEFIELD_HIGHGLYPHCOUNT();
273int QSGRhiDistanceFieldGlyphCache::maxTextureSize()
const
275 if (!m_maxTextureSize)
276 m_maxTextureSize = m_rhi->resourceLimit(QRhi::TextureSizeMax);
277 return m_maxTextureSize;
287 GlyphRecordSize = 46,
288 TextureRecordSize = 17
311 boundingRectWidth = 36,
312 boundingRectHeight = 40,
319 allocatedHeight = 12,
324 template <
typename T>
325 static inline T fetch(
const char *data, Offset offset)
327 return qFromBigEndian<T>(data +
int(offset));
332bool QSGRhiDistanceFieldGlyphCache::loadPregeneratedCache(
const QRawFont &font)
336 if (m_areaAllocator !=
nullptr) {
337 qWarning(
"Font cache must be loaded before cache is used");
341 static QElapsedTimer timer;
343 bool profile = QSG_LOG_TIME_GLYPH().isDebugEnabled();
347 QByteArray qtdfTable = font.fontTable(
"qtdf");
348 if (qtdfTable.isEmpty())
351 typedef QHash<TextureInfo *, QList<glyph_t> > GlyphTextureHash;
353 GlyphTextureHash glyphTextures;
355 if (uint(qtdfTable.size()) < Qtdf::HeaderSize) {
356 qWarning(
"Invalid qtdf table in font '%s'",
357 qPrintable(font.familyName()));
361 const char *qtdfTableStart = qtdfTable.constData();
362 const char *qtdfTableEnd = qtdfTableStart + qtdfTable.size();
365 int textureCount = 0;
367 quint8 majorVersion = Qtdf::fetch<quint8>(qtdfTableStart, Qtdf::majorVersion);
368 quint8 minorVersion = Qtdf::fetch<quint8>(qtdfTableStart, Qtdf::minorVersion);
369 if (majorVersion != 5 || minorVersion != 12) {
370 qWarning(
"Invalid version of qtdf table %d.%d in font '%s'",
373 qPrintable(font.familyName()));
377 qreal pixelSize = qreal(Qtdf::fetch<quint16>(qtdfTableStart, Qtdf::pixelSize));
378 m_maxTextureSize = Qtdf::fetch<quint32>(qtdfTableStart, Qtdf::textureSize);
379 m_doubleGlyphResolution = Qtdf::fetch<quint8>(qtdfTableStart, Qtdf::flags) == 1;
380 padding = Qtdf::fetch<quint8>(qtdfTableStart, Qtdf::headerPadding);
382 if (pixelSize <= 0.0) {
383 qWarning(
"Invalid pixel size in '%s'", qPrintable(font.familyName()));
387 if (m_maxTextureSize <= 0) {
388 qWarning(
"Invalid texture size in '%s'", qPrintable(font.familyName()));
392 int systemMaxTextureSize = m_rhi->resourceLimit(QRhi::TextureSizeMax);
394 if (m_maxTextureSize > systemMaxTextureSize) {
395 qWarning(
"System maximum texture size is %d. This is lower than the value in '%s', which is %d",
396 systemMaxTextureSize,
397 qPrintable(font.familyName()),
402 qWarning(
"Padding mismatch in '%s'. Font requires %d, but Qt is compiled with %d.",
403 qPrintable(font.familyName()),
408 m_referenceFont.setPixelSize(pixelSize);
410 quint32 glyphCount = Qtdf::fetch<quint32>(qtdfTableStart, Qtdf::numGlyphs);
411 m_unusedGlyphs.reserve(glyphCount);
413 const char *allocatorData = qtdfTableStart + Qtdf::HeaderSize;
415 m_areaAllocator =
new QSGAreaAllocator(QSize(0, 0));
416 allocatorData = m_areaAllocator->deserialize(allocatorData, qtdfTableEnd - allocatorData);
417 if (allocatorData ==
nullptr)
421 if (m_areaAllocator->size().height() % m_maxTextureSize != 0) {
422 qWarning(
"Area allocator size mismatch in '%s'", qPrintable(font.familyName()));
426 textureCount = m_areaAllocator->size().height() / m_maxTextureSize;
427 m_maxTextureCount = qMax(m_maxTextureCount, textureCount);
429 const char *textureRecord = allocatorData;
430 for (
int i = 0; i < textureCount; ++i, textureRecord += Qtdf::TextureRecordSize) {
431 if (qtdfTableEnd - textureRecord < Qtdf::TextureRecordSize) {
432 qWarning(
"qtdf table too small in font '%s'.",
433 qPrintable(font.familyName()));
437 TextureInfo *tex = textureInfo(i);
438 tex->allocatedArea.setX(Qtdf::fetch<quint32>(textureRecord, Qtdf::allocatedX));
439 tex->allocatedArea.setY(Qtdf::fetch<quint32>(textureRecord, Qtdf::allocatedY));
440 tex->allocatedArea.setWidth(Qtdf::fetch<quint32>(textureRecord, Qtdf::allocatedWidth));
441 tex->allocatedArea.setHeight(Qtdf::fetch<quint32>(textureRecord, Qtdf::allocatedHeight));
442 tex->padding = Qtdf::fetch<quint8>(textureRecord, Qtdf::texturePadding);
445 const char *glyphRecord = textureRecord;
446 for (quint32 i = 0; i < glyphCount; ++i, glyphRecord += Qtdf::GlyphRecordSize) {
447 if (qtdfTableEnd - glyphRecord < Qtdf:: GlyphRecordSize) {
448 qWarning(
"qtdf table too small in font '%s'.",
449 qPrintable(font.familyName()));
453 glyph_t glyph = Qtdf::fetch<quint32>(glyphRecord, Qtdf::glyphIndex);
454 m_unusedGlyphs.insert(glyph);
456 GlyphData &glyphData = emptyData(glyph);
458#define FROM_FIXED_POINT(value) \
459(((qreal)value)/(qreal)65536)
461 glyphData.texCoord.x =
FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::textureOffsetX));
462 glyphData.texCoord.y =
FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::textureOffsetY));
463 glyphData.texCoord.width =
FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::textureWidth));
464 glyphData.texCoord.height =
FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::textureHeight));
465 glyphData.texCoord.xMargin =
FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::xMargin));
466 glyphData.texCoord.yMargin =
FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::yMargin));
467 glyphData.boundingRect.setX(
FROM_FIXED_POINT(Qtdf::fetch<qint32>(glyphRecord, Qtdf::boundingRectX)));
468 glyphData.boundingRect.setY(
FROM_FIXED_POINT(Qtdf::fetch<qint32>(glyphRecord, Qtdf::boundingRectY)));
469 glyphData.boundingRect.setWidth(
FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::boundingRectWidth)));
470 glyphData.boundingRect.setHeight(
FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::boundingRectHeight)));
472#undef FROM_FIXED_POINT
474 int textureIndex = Qtdf::fetch<quint16>(glyphRecord, Qtdf::textureIndex);
475 if (textureIndex < 0 || textureIndex >= textureCount) {
476 qWarning(
"Invalid texture index %d (texture count == %d) in '%s'",
479 qPrintable(font.familyName()));
484 TextureInfo *texInfo = textureInfo(textureIndex);
485 m_glyphsTexture.insert(glyph, texInfo);
487 glyphTextures[texInfo].append(glyph);
490 const uchar *textureData =
reinterpret_cast<
const uchar *>(glyphRecord);
491 for (
int i = 0; i < textureCount; ++i) {
493 TextureInfo *texInfo = textureInfo(i);
495 int width = texInfo->allocatedArea.width();
496 int height = texInfo->allocatedArea.height();
497 qint64 size = qint64(width) * height;
498 if (qtdfTableEnd -
reinterpret_cast<
const char *>(textureData) < size) {
499 qWarning(
"qtdf table too small in font '%s'.",
500 qPrintable(font.familyName()));
504 createTexture(texInfo, width, height, textureData);
507 if (!texInfo->texture)
510 QList<glyph_t> glyphs = glyphTextures.value(texInfo);
513 t.texture = texInfo->texture;
514 t.size = texInfo->size;
516 setGlyphsTexture(glyphs, t);
521 quint64 now = timer.elapsed();
522 qCDebug(QSG_LOG_TIME_GLYPH,
523 "distancefield: %d pre-generated glyphs loaded in %dms",
524 int(m_unusedGlyphs.size()),
531void QSGRhiDistanceFieldGlyphCache::commitResourceUpdates(QRhiResourceUpdateBatch *mergeInto)
533 if (QRhiResourceUpdateBatch *resourceUpdates = m_rc->maybeGlyphCacheResourceUpdates()) {
534 mergeInto->merge(resourceUpdates);
535 m_rc->resetGlyphCacheResources();
539bool QSGRhiDistanceFieldGlyphCache::eightBitFormatIsAlphaSwizzled()
const
543 return !m_rhi->isFeatureSupported(QRhi::RedOrAlpha8IsRed);
546bool QSGRhiDistanceFieldGlyphCache::screenSpaceDerivativesSupported()
const
548 return m_rhi->isFeatureSupported(QRhi::ScreenSpaceDerivatives);
551#if defined(QSG_DISTANCEFIELD_CACHE_DEBUG)
552void QSGRhiDistanceFieldGlyphCache::saveTexture(QRhiTexture *texture,
const QString &nameBase)
const
554 quint64 textureId = texture->nativeTexture().object;
555 QString fileName = nameBase + QLatin1Char(
'_') + QString::number(textureId, 16);
556 fileName.replace(QLatin1Char(
'/'), QLatin1Char(
'_'));
557 fileName.replace(QLatin1Char(
' '), QLatin1Char(
'_'));
558 fileName.append(QLatin1String(
".png"));
560 QRhiReadbackResult *rbResult =
new QRhiReadbackResult;
561 rbResult->completed = [rbResult, fileName] {
562 const QSize size = rbResult->pixelSize;
563 const qint64 numPixels = qint64(size.width()) * size.height();
564 if (numPixels == rbResult->data.size()) {
566 QImage image(size, QImage::Format_Grayscale8);
567 const char *p = rbResult->data.constData();
568 for (
int i = 0; i < size.height(); i++)
569 memcpy(image.scanLine(i), p + (i * size.width()), size.width());
570 image.save(fileName);
571 }
else if (4 * numPixels == rbResult->data.size()) {
573 const uchar *p =
reinterpret_cast<
const uchar *>(rbResult->data.constData());
574 QImage image(p, size.width(), size.height(), QImage::Format_RGBA8888);
575 image.save(fileName);
577 qWarning(
"Unhandled data format in glyph texture");
582 QRhiReadbackDescription rb(texture);
583 QRhiResourceUpdateBatch *resourceUpdates = m_rc->glyphCacheResourceUpdates();
584 resourceUpdates->readBackTexture(rb, rbResult);
Combined button and popup list for selecting options.
#define QSG_RHI_DISTANCEFIELD_GLYPH_CACHE_PADDING
#define FROM_FIXED_POINT(value)