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()),
51 for (QSet<glyph_t>::const_iterator it = glyphs.constBegin(); it != glyphs.constEnd() ; ++it) {
52 glyph_t glyphIndex = *it;
55 QRectF boundingRect = glyphData(glyphIndex).boundingRect;
56 int glyphWidth = qCeil(boundingRect.width() + distanceFieldRadius() * 2);
57 int glyphHeight = qCeil(boundingRect.height() + distanceFieldRadius() * 2);
58 QSize glyphSize(glyphWidth + padding * 2, glyphHeight + padding * 2);
59 QRect alloc = m_areaAllocator->allocate(glyphSize);
63 while (alloc.isNull() && !m_unusedGlyphs.isEmpty()) {
64 glyph_t unusedGlyph = *m_unusedGlyphs.constBegin();
66 TexCoord unusedCoord = glyphTexCoord(unusedGlyph);
67 if (!unusedCoord.isNull()) {
68 QRectF unusedGlyphBoundingRect = glyphData(unusedGlyph).boundingRect;
69 int unusedGlyphWidth = qCeil(unusedGlyphBoundingRect.width() + distanceFieldRadius() * 2);
70 int unusedGlyphHeight = qCeil(unusedGlyphBoundingRect.height() + distanceFieldRadius() * 2);
71 m_areaAllocator->deallocate(QRect(unusedCoord.x - padding,
72 unusedCoord.y - padding,
73 padding * 2 + unusedGlyphWidth,
74 padding * 2 + unusedGlyphHeight));
77 m_unusedGlyphs.remove(unusedGlyph);
78 m_glyphsTexture.remove(unusedGlyph);
79 removeGlyph(unusedGlyph);
81 alloc = m_areaAllocator->allocate(glyphSize);
89 const int textureIndex = alloc.y() / maxTextureSize();
90 TextureInfo *tex = textureInfo(textureIndex);
91 alloc = QRect(alloc.x(), alloc.y() % maxTextureSize(), alloc.width(), alloc.height());
92 Q_ASSERT(alloc.bottom() < maxTextureSize());
94 tex->allocatedArea |= alloc;
95 Q_ASSERT(tex->padding == padding || tex->padding < 0);
96 tex->padding = padding;
100 p.position = alloc.topLeft() + QPoint(padding, padding);
102 glyphPositions.append(p);
103 glyphsToRender.append(glyphIndex);
104 m_glyphsTexture.insert(glyphIndex, textureIndex);
107 setGlyphsPosition(glyphPositions);
108 markGlyphsToRender(glyphsToRender);
111bool QSGRhiDistanceFieldGlyphCache::isActive()
const
113 return !m_referencedGlyphs.empty();
116void QSGRhiDistanceFieldGlyphCache::storeGlyphs(
const QList<QDistanceField> &glyphs)
119 QList<QList<glyph_t> > glyphTextures(m_textures.size());
121 for (
int i = 0; i < glyphs.size(); ++i) {
122 QDistanceField glyph = glyphs.at(i);
123 glyph_t glyphIndex = glyph.glyph();
124 TexCoord c = glyphTexCoord(glyphIndex);
125 const int textureIndex = m_glyphsTexture.value(glyphIndex, -1);
126 Q_ASSERT(textureIndex >= 0 && textureIndex < m_textures.size());
127 TextureInfo *texInfo = textureInfo(textureIndex);
129 resizeTexture(texInfo, texInfo->allocatedArea.width(), texInfo->allocatedArea.height());
131 if (!texInfo->texture)
134 glyphTextures[textureIndex].append(glyphIndex);
136 int padding = texInfo->padding;
137 int expectedWidth = qCeil(c.width + c.xMargin * 2);
138 glyph = glyph.copy(-padding, -padding,
139 expectedWidth + padding * 2, glyph.height() + padding * 2);
141 if (useTextureResizeWorkaround()) {
142 uchar *inBits = glyph.scanLine(0);
143 uchar *outBits = texInfo->image.scanLine(
int(c.y) - padding) +
int(c.x) - padding;
144 for (
int y = 0; y < glyph.height(); ++y) {
145 memcpy(outBits, inBits, glyph.width());
146 inBits += glyph.width();
147 outBits += texInfo->image.width();
151 QRhiTextureSubresourceUploadDescription subresDesc(glyph.constBits(), glyph.width() * glyph.height());
152 subresDesc.setSourceSize(QSize(glyph.width(), glyph.height()));
153 subresDesc.setDestinationTopLeft(QPoint(c.x - padding, c.y - padding));
154 texInfo->uploads.append(QRhiTextureUploadEntry(0, 0, subresDesc));
157 QRhiResourceUpdateBatch *resourceUpdates = m_rc->glyphCacheResourceUpdates();
158 for (
int i = 0; i < glyphs.size(); ++i) {
159 const int textureIndex = m_glyphsTexture.value(glyphs.at(i).glyph(), -1);
160 Q_ASSERT(textureIndex >= 0 && textureIndex < m_textures.size());
161 TextureInfo *texInfo = textureInfo(textureIndex);
162 if (!texInfo->uploads.isEmpty() && texInfo->texture) {
163 QRhiTextureUploadDescription desc;
164 desc.setEntries(texInfo->uploads.cbegin(), texInfo->uploads.cend());
165 resourceUpdates->uploadTexture(texInfo->texture, desc);
166 texInfo->uploads.clear();
170 for (
int i = 0; i < glyphTextures.size(); ++i) {
171 const QList<glyph_t> &textureGlyphs = glyphTextures.at(i);
172 if (textureGlyphs.isEmpty())
175 const TextureInfo *texInfo = textureInfo(i);
177 t.texture = texInfo->texture;
178 t.size = texInfo->size;
179 setGlyphsTexture(textureGlyphs, t);
183void QSGRhiDistanceFieldGlyphCache::referenceGlyphs(
const QSet<glyph_t> &glyphs)
185 m_referencedGlyphs += glyphs;
186 m_unusedGlyphs -= glyphs;
189void QSGRhiDistanceFieldGlyphCache::releaseGlyphs(
const QSet<glyph_t> &glyphs)
191 m_referencedGlyphs -= glyphs;
192 m_unusedGlyphs += glyphs;
195void QSGRhiDistanceFieldGlyphCache::createTexture(TextureInfo *texInfo,
199 QByteArray zeroBuf(width * height, 0);
200 createTexture(texInfo, width, height, zeroBuf.constData());
203void QSGRhiDistanceFieldGlyphCache::createTexture(TextureInfo *texInfo,
208 QRhiTexture *newTexture = m_rhi->newTexture(QRhiTexture::RED_OR_ALPHA8, QSize(width, height), 1, QRhiTexture::UsedAsTransferSource);
209 if (!newTexture->create()) {
210 qWarning(
"Failed to create distance field glyph cache");
212 texInfo->texture =
nullptr;
213 texInfo->size = QSize();
214 texInfo->image = QDistanceField();
218 if (useTextureResizeWorkaround() && texInfo->image.isNull()) {
219 texInfo->image = QDistanceField(width, height);
220 if (texInfo->image.isNull()) {
221 qWarning(
"Failed to create distance field glyph cache");
223 texInfo->texture =
nullptr;
224 texInfo->size = QSize();
225 texInfo->image = QDistanceField();
228 memcpy(texInfo->image.bits(), pixels, width * height);
232 texInfo->texture = newTexture;
233 texInfo->size = QSize(width, height);
235 QRhiResourceUpdateBatch *resourceUpdates = m_rc->glyphCacheResourceUpdates();
236 QRhiTextureSubresourceUploadDescription subresDesc(pixels, width * height);
237 subresDesc.setSourceSize(QSize(width, height));
238 resourceUpdates->uploadTexture(texInfo->texture, QRhiTextureUploadEntry(0, 0, subresDesc));
241void QSGRhiDistanceFieldGlyphCache::resizeTexture(TextureInfo *texInfo,
int width,
int height)
243 int oldWidth = texInfo->size.width();
244 int oldHeight = texInfo->size.height();
245 if (width == oldWidth && height == oldHeight)
248 QRhiTexture *oldTexture = texInfo->texture;
249 createTexture(texInfo, width, height);
251 if (!texInfo->texture) {
253 updateRhiTexture(oldTexture,
nullptr, QSize());
254 m_rc->deferredReleaseGlyphCacheTexture(oldTexture);
262 updateRhiTexture(oldTexture, texInfo->texture, texInfo->size);
264 QRhiResourceUpdateBatch *resourceUpdates = m_rc->glyphCacheResourceUpdates();
265 if (useTextureResizeWorkaround()) {
266 QRhiTextureSubresourceUploadDescription subresDesc(texInfo->image.constBits(),
267 oldWidth * oldHeight);
268 subresDesc.setSourceSize(QSize(oldWidth, oldHeight));
269 resourceUpdates->uploadTexture(texInfo->texture, QRhiTextureUploadEntry(0, 0, subresDesc));
270 texInfo->image = texInfo->image.copy(0, 0, width, height);
272 resourceUpdates->copyTexture(texInfo->texture, oldTexture);
275 m_rc->deferredReleaseGlyphCacheTexture(oldTexture);
278bool QSGRhiDistanceFieldGlyphCache::useTextureResizeWorkaround()
const
280 static bool set =
false;
281 static bool useWorkaround =
false;
283 useWorkaround = m_rhi->backend() == QRhi::OpenGLES2 || qmlUseGlyphCacheWorkaround();
286 return useWorkaround;
289bool QSGRhiDistanceFieldGlyphCache::createFullSizeTextures()
const
291 return qsgPreferFullSizeGlyphCacheTextures() && glyphCount() > QT_DISTANCEFIELD_HIGHGLYPHCOUNT();
294int QSGRhiDistanceFieldGlyphCache::maxTextureSize()
const
296 if (!m_maxTextureSize) {
297 m_maxTextureSize = m_rhi->resourceLimit(QRhi::TextureSizeMax);
301 const int overriddenMaxTextureSize =
302 qEnvironmentVariableIntValue(
"QSG_DISTANCEFIELD_MAX_TEXTURE_SIZE");
303 if (overriddenMaxTextureSize > 0)
304 m_maxTextureSize = overriddenMaxTextureSize;
306 return m_maxTextureSize;
316 GlyphRecordSize = 46,
317 TextureRecordSize = 17
340 boundingRectWidth = 36,
341 boundingRectHeight = 40,
348 allocatedHeight = 12,
353 template <
typename T>
354 static inline T fetch(
const char *data, Offset offset)
356 return qFromBigEndian<T>(data +
int(offset));
361bool QSGRhiDistanceFieldGlyphCache::loadPregeneratedCache(
const QRawFont &font)
365 if (m_areaAllocator !=
nullptr) {
366 qWarning(
"Font cache must be loaded before cache is used");
370 static QElapsedTimer timer;
372 bool profile = QSG_LOG_TIME_GLYPH().isDebugEnabled();
376 QByteArray qtdfTable = font.fontTable(
"qtdf");
377 if (qtdfTable.isEmpty())
380 if (uint(qtdfTable.size()) < Qtdf::HeaderSize) {
381 qWarning(
"Invalid qtdf table in font '%s'",
382 qPrintable(font.familyName()));
386 const char *qtdfTableStart = qtdfTable.constData();
387 const char *qtdfTableEnd = qtdfTableStart + qtdfTable.size();
390 int textureCount = 0;
392 quint8 majorVersion = Qtdf::fetch<quint8>(qtdfTableStart, Qtdf::majorVersion);
393 quint8 minorVersion = Qtdf::fetch<quint8>(qtdfTableStart, Qtdf::minorVersion);
394 if (majorVersion != 5 || minorVersion != 12) {
395 qWarning(
"Invalid version of qtdf table %d.%d in font '%s'",
398 qPrintable(font.familyName()));
402 qreal pixelSize = qreal(Qtdf::fetch<quint16>(qtdfTableStart, Qtdf::pixelSize));
403 m_maxTextureSize = Qtdf::fetch<quint32>(qtdfTableStart, Qtdf::textureSize);
404 m_doubleGlyphResolution = Qtdf::fetch<quint8>(qtdfTableStart, Qtdf::flags) == 1;
405 padding = Qtdf::fetch<quint8>(qtdfTableStart, Qtdf::headerPadding);
407 if (pixelSize <= 0.0) {
408 qWarning(
"Invalid pixel size in '%s'", qPrintable(font.familyName()));
412 if (m_maxTextureSize <= 0) {
413 qWarning(
"Invalid texture size in '%s'", qPrintable(font.familyName()));
417 int systemMaxTextureSize = m_rhi->resourceLimit(QRhi::TextureSizeMax);
419 if (m_maxTextureSize > systemMaxTextureSize) {
420 qWarning(
"System maximum texture size is %d. This is lower than the value in '%s', which is %d",
421 systemMaxTextureSize,
422 qPrintable(font.familyName()),
427 qWarning(
"Padding mismatch in '%s'. Font requires %d, but Qt is compiled with %d.",
428 qPrintable(font.familyName()),
433 m_referenceFont.setPixelSize(pixelSize);
435 quint32 glyphCount = Qtdf::fetch<quint32>(qtdfTableStart, Qtdf::numGlyphs);
436 m_unusedGlyphs.reserve(glyphCount);
438 const char *allocatorData = qtdfTableStart + Qtdf::HeaderSize;
440 m_areaAllocator =
new QSGAreaAllocator(QSize(0, 0), m_maxTextureSize);
441 allocatorData = m_areaAllocator->deserialize(allocatorData, qtdfTableEnd - allocatorData);
442 if (allocatorData ==
nullptr)
446 if (m_areaAllocator->size().height() % m_maxTextureSize != 0) {
447 qWarning(
"Area allocator size mismatch in '%s'", qPrintable(font.familyName()));
451 textureCount = m_areaAllocator->size().height() / m_maxTextureSize;
452 m_maxTextureCount = qMax(m_maxTextureCount, textureCount);
455 QList<QList<glyph_t> > glyphTextures(textureCount);
457 const char *textureRecord = allocatorData;
458 for (
int i = 0; i < textureCount; ++i, textureRecord += Qtdf::TextureRecordSize) {
459 if (qtdfTableEnd - textureRecord < Qtdf::TextureRecordSize) {
460 qWarning(
"qtdf table too small in font '%s'.",
461 qPrintable(font.familyName()));
465 TextureInfo *tex = textureInfo(i);
467 const quint32 allocX = Qtdf::fetch<quint32>(textureRecord, Qtdf::allocatedX);
468 const quint32 allocY = Qtdf::fetch<quint32>(textureRecord, Qtdf::allocatedY);
469 const quint32 allocWidth = Qtdf::fetch<quint32>(textureRecord, Qtdf::allocatedWidth);
470 const quint32 allocHeight = Qtdf::fetch<quint32>(textureRecord, Qtdf::allocatedHeight);
471 const quint32 maxSize = quint32(m_maxTextureSize);
476 const quint32 maxTexHeight = maxSize * 2 - 1;
477 if (allocX > maxSize || allocY > maxSize
478 || allocWidth > maxSize || allocHeight > maxTexHeight) {
479 qWarning(
"Invalid texture geometry in qtdf table in font '%s'",
480 qPrintable(font.familyName()));
484 tex->allocatedArea.setX(
int(allocX));
485 tex->allocatedArea.setY(
int(allocY));
486 tex->allocatedArea.setWidth(
int(allocWidth));
487 tex->allocatedArea.setHeight(
int(allocHeight));
488 tex->padding = Qtdf::fetch<quint8>(textureRecord, Qtdf::texturePadding);
491 const char *glyphRecord = textureRecord;
492 for (quint32 i = 0; i < glyphCount; ++i, glyphRecord += Qtdf::GlyphRecordSize) {
493 if (qtdfTableEnd - glyphRecord < Qtdf:: GlyphRecordSize) {
494 qWarning(
"qtdf table too small in font '%s'.",
495 qPrintable(font.familyName()));
499 glyph_t glyph = Qtdf::fetch<quint32>(glyphRecord, Qtdf::glyphIndex);
500 m_unusedGlyphs.insert(glyph);
502 GlyphData &glyphData = emptyData(glyph);
504#define FROM_FIXED_POINT(value) \
505(((qreal)value)/(qreal)65536)
507 glyphData.texCoord.x =
FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::textureOffsetX));
508 glyphData.texCoord.y =
FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::textureOffsetY));
509 glyphData.texCoord.width =
FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::textureWidth));
510 glyphData.texCoord.height =
FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::textureHeight));
511 glyphData.texCoord.xMargin =
FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::xMargin));
512 glyphData.texCoord.yMargin =
FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::yMargin));
513 glyphData.boundingRect.setX(
FROM_FIXED_POINT(Qtdf::fetch<qint32>(glyphRecord, Qtdf::boundingRectX)));
514 glyphData.boundingRect.setY(
FROM_FIXED_POINT(Qtdf::fetch<qint32>(glyphRecord, Qtdf::boundingRectY)));
515 glyphData.boundingRect.setWidth(
FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::boundingRectWidth)));
516 glyphData.boundingRect.setHeight(
FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::boundingRectHeight)));
518#undef FROM_FIXED_POINT
520 int textureIndex = Qtdf::fetch<quint16>(glyphRecord, Qtdf::textureIndex);
521 if (textureIndex < 0 || textureIndex >= textureCount) {
522 qWarning(
"Invalid texture index %d (texture count == %d) in '%s'",
525 qPrintable(font.familyName()));
530 m_glyphsTexture.insert(glyph, textureIndex);
532 glyphTextures[textureIndex].append(glyph);
535 const uchar *textureData =
reinterpret_cast<
const uchar *>(glyphRecord);
536 for (
int i = 0; i < textureCount; ++i) {
538 TextureInfo *texInfo = textureInfo(i);
540 int width = texInfo->allocatedArea.width();
541 int height = texInfo->allocatedArea.height();
542 if (width <= 0 || height <= 0) {
543 qWarning(
"Invalid texture size in qtdf table in font '%s'",
544 qPrintable(font.familyName()));
547 qint64 size = qint64(width) * height;
548 if (qtdfTableEnd -
reinterpret_cast<
const char *>(textureData) < size) {
549 qWarning(
"qtdf table too small in font '%s'.",
550 qPrintable(font.familyName()));
554 createTexture(texInfo, width, height, textureData);
557 if (!texInfo->texture)
560 const QList<glyph_t> &glyphs = glyphTextures.at(i);
563 t.texture = texInfo->texture;
564 t.size = texInfo->size;
566 setGlyphsTexture(glyphs, t);
571 quint64 now = timer.elapsed();
572 qCDebug(QSG_LOG_TIME_GLYPH,
573 "distancefield: %d pre-generated glyphs loaded in %dms",
574 int(m_unusedGlyphs.size()),
581void QSGRhiDistanceFieldGlyphCache::commitResourceUpdates(QRhiResourceUpdateBatch *mergeInto)
583 if (QRhiResourceUpdateBatch *resourceUpdates = m_rc->maybeGlyphCacheResourceUpdates()) {
584 mergeInto->merge(resourceUpdates);
585 m_rc->resetGlyphCacheResources();
589bool QSGRhiDistanceFieldGlyphCache::eightBitFormatIsAlphaSwizzled()
const
593 return !m_rhi->isFeatureSupported(QRhi::RedOrAlpha8IsRed);
596bool QSGRhiDistanceFieldGlyphCache::screenSpaceDerivativesSupported()
const
598 return m_rhi->isFeatureSupported(QRhi::ScreenSpaceDerivatives);
601#if defined(QSG_DISTANCEFIELD_CACHE_DEBUG)
602void QSGRhiDistanceFieldGlyphCache::saveTexture(QRhiTexture *texture,
const QString &nameBase)
const
604 quint64 textureId = texture->nativeTexture().object;
605 QString fileName = nameBase + QLatin1Char(
'_') + QString::number(textureId, 16);
606 fileName.replace(QLatin1Char(
'/'), QLatin1Char(
'_'));
607 fileName.replace(QLatin1Char(
' '), QLatin1Char(
'_'));
608 fileName.append(QLatin1String(
".png"));
610 QRhiReadbackResult *rbResult =
new QRhiReadbackResult;
611 rbResult->completed = [rbResult, fileName] {
612 const QSize size = rbResult->pixelSize;
613 const qint64 numPixels = qint64(size.width()) * size.height();
614 if (numPixels == rbResult->data.size()) {
616 QImage image(size, QImage::Format_Grayscale8);
617 const char *p = rbResult->data.constData();
618 for (
int i = 0; i < size.height(); i++)
619 memcpy(image.scanLine(i), p + (i * size.width()), size.width());
620 image.save(fileName);
621 }
else if (4 * numPixels == rbResult->data.size()) {
623 const uchar *p =
reinterpret_cast<
const uchar *>(rbResult->data.constData());
624 QImage image(p, size.width(), size.height(), QImage::Format_RGBA8888);
625 image.save(fileName);
627 qWarning(
"Unhandled data format in glyph texture");
632 QRhiReadbackDescription rb(texture);
633 QRhiResourceUpdateBatch *resourceUpdates = m_rc->glyphCacheResourceUpdates();
634 resourceUpdates->readBackTexture(rb, rbResult);
Combined button and popup list for selecting options.
#define QSG_RHI_DISTANCEFIELD_GLYPH_CACHE_PADDING
#define FROM_FIXED_POINT(value)