8#include <QtGui/private/qa8image_p.h>
9#include <QtGui/private/qdistancefield_p.h>
10#include <QtCore/qelapsedtimer.h>
11#include <QtQml/private/qqmlglobal_p.h>
17DEFINE_BOOL_CONFIG_OPTION(qmlUseGlyphCacheWorkaround, QML_USE_GLYPHCACHE_WORKAROUND)
18DEFINE_BOOL_CONFIG_OPTION(qsgPreferFullSizeGlyphCacheTextures, QSG_PREFER_FULLSIZE_GLYPHCACHE_TEXTURES)
20#if !defined(QSG_RHI_DISTANCEFIELD_GLYPH_CACHE_PADDING)
21# define QSG_RHI_DISTANCEFIELD_GLYPH_CACHE_PADDING 2
24QSGRhiDistanceFieldGlyphCache::QSGRhiDistanceFieldGlyphCache(QSGDefaultRenderContext *rc,
26 int renderTypeQuality)
27 : QSGDistanceFieldGlyphCache(font, renderTypeQuality)
32 loadPregeneratedCache(font);
35QSGRhiDistanceFieldGlyphCache::~QSGRhiDistanceFieldGlyphCache()
37 for (
const TextureInfo &t : std::as_const(m_textures))
38 m_rc->deferredReleaseGlyphCacheTexture(t.texture);
40 delete m_areaAllocator;
43void QSGRhiDistanceFieldGlyphCache::requestGlyphs(
const QSet<glyph_t> &glyphs)
45 QList<GlyphPosition> glyphPositions;
46 QList<glyph_t> glyphsToRender;
48 if (m_areaAllocator ==
nullptr)
49 m_areaAllocator =
new QSGAreaAllocator(QSize(maxTextureSize(), m_maxTextureCount * maxTextureSize()),
52 for (QSet<glyph_t>::const_iterator it = glyphs.constBegin(); it != glyphs.constEnd() ; ++it) {
53 glyph_t glyphIndex = *it;
56 QRectF boundingRect = glyphData(glyphIndex).boundingRect;
57 int glyphWidth = qCeil(boundingRect.width() + distanceFieldRadius() * 2);
58 int glyphHeight = qCeil(boundingRect.height() + distanceFieldRadius() * 2);
59 QSize glyphSize(glyphWidth + padding * 2, glyphHeight + padding * 2);
60 QRect alloc = m_areaAllocator->allocate(glyphSize);
64 while (alloc.isNull() && !m_unusedGlyphs.isEmpty()) {
65 glyph_t unusedGlyph = *m_unusedGlyphs.constBegin();
67 TexCoord unusedCoord = glyphTexCoord(unusedGlyph);
68 if (!unusedCoord.isNull()) {
69 QRectF unusedGlyphBoundingRect = glyphData(unusedGlyph).boundingRect;
70 int unusedGlyphWidth = qCeil(unusedGlyphBoundingRect.width() + distanceFieldRadius() * 2);
71 int unusedGlyphHeight = qCeil(unusedGlyphBoundingRect.height() + distanceFieldRadius() * 2);
72 m_areaAllocator->deallocate(QRect(unusedCoord.x - padding,
73 unusedCoord.y - padding,
74 padding * 2 + unusedGlyphWidth,
75 padding * 2 + unusedGlyphHeight));
78 m_unusedGlyphs.remove(unusedGlyph);
79 m_glyphsTexture.remove(unusedGlyph);
80 removeGlyph(unusedGlyph);
82 alloc = m_areaAllocator->allocate(glyphSize);
90 const int textureIndex = alloc.y() / maxTextureSize();
91 TextureInfo *tex = textureInfo(textureIndex);
92 alloc = QRect(alloc.x(), alloc.y() % maxTextureSize(), alloc.width(), alloc.height());
93 Q_ASSERT(alloc.bottom() < maxTextureSize());
95 tex->allocatedArea |= alloc;
96 Q_ASSERT(tex->padding == padding || tex->padding < 0);
97 tex->padding = padding;
100 p.glyph = glyphIndex;
101 p.position = alloc.topLeft() + QPoint(padding, padding);
103 glyphPositions.append(p);
104 glyphsToRender.append(glyphIndex);
105 m_glyphsTexture.insert(glyphIndex, textureIndex);
108 setGlyphsPosition(glyphPositions);
109 markGlyphsToRender(glyphsToRender);
112bool QSGRhiDistanceFieldGlyphCache::isActive()
const
114 return !m_referencedGlyphs.empty();
117void QSGRhiDistanceFieldGlyphCache::storeGlyphs(
const QList<QDistanceField> &glyphs)
120 QList<QList<glyph_t> > glyphTextures(m_textures.size());
122 for (
int i = 0; i < glyphs.size(); ++i) {
123 QDistanceField glyph = glyphs.at(i);
124 glyph_t glyphIndex = glyph.glyph();
125 TexCoord c = glyphTexCoord(glyphIndex);
126 const int textureIndex = m_glyphsTexture.value(glyphIndex, -1);
127 Q_ASSERT(textureIndex >= 0 && textureIndex < m_textures.size());
128 TextureInfo *texInfo = textureInfo(textureIndex);
130 resizeTexture(texInfo, texInfo->allocatedArea.width(), texInfo->allocatedArea.height());
132 if (!texInfo->texture)
135 glyphTextures[textureIndex].append(glyphIndex);
137 int padding = texInfo->padding;
138 int expectedWidth = qCeil(c.width + c.xMargin * 2);
139 glyph = glyph.copy(-padding, -padding,
140 expectedWidth + padding * 2, glyph.height() + padding * 2);
142 if (useTextureResizeWorkaround()) {
143 uchar *inBits = glyph.scanLine(0);
144 uchar *outBits = texInfo->image.scanLine(
int(c.y) - padding) +
int(c.x) - padding;
145 for (
int y = 0; y < glyph.height(); ++y) {
146 memcpy(outBits, inBits, glyph.width());
147 inBits += glyph.width();
148 outBits += texInfo->image.width();
152 QRhiTextureSubresourceUploadDescription subresDesc(glyph.constBits(), glyph.width() * glyph.height());
153 subresDesc.setSourceSize(QSize(glyph.width(), glyph.height()));
154 subresDesc.setDestinationTopLeft(QPoint(c.x - padding, c.y - padding));
155 texInfo->uploads.append(QRhiTextureUploadEntry(0, 0, subresDesc));
158 QRhiResourceUpdateBatch *resourceUpdates = m_rc->glyphCacheResourceUpdates();
159 for (
int i = 0; i < glyphs.size(); ++i) {
160 const int textureIndex = m_glyphsTexture.value(glyphs.at(i).glyph(), -1);
161 Q_ASSERT(textureIndex >= 0 && textureIndex < m_textures.size());
162 TextureInfo *texInfo = textureInfo(textureIndex);
163 if (!texInfo->uploads.isEmpty() && texInfo->texture) {
164 QRhiTextureUploadDescription desc;
165 desc.setEntries(texInfo->uploads.cbegin(), texInfo->uploads.cend());
166 resourceUpdates->uploadTexture(texInfo->texture, desc);
167 texInfo->uploads.clear();
171 for (
int i = 0; i < glyphTextures.size(); ++i) {
172 const QList<glyph_t> &textureGlyphs = glyphTextures.at(i);
173 if (textureGlyphs.isEmpty())
176 const TextureInfo *texInfo = textureInfo(i);
178 t.texture = texInfo->texture;
179 t.size = texInfo->size;
180 setGlyphsTexture(textureGlyphs, t);
184void QSGRhiDistanceFieldGlyphCache::referenceGlyphs(
const QSet<glyph_t> &glyphs)
186 m_referencedGlyphs += glyphs;
187 m_unusedGlyphs -= glyphs;
190void QSGRhiDistanceFieldGlyphCache::releaseGlyphs(
const QSet<glyph_t> &glyphs)
192 m_referencedGlyphs -= glyphs;
193 m_unusedGlyphs += glyphs;
196void QSGRhiDistanceFieldGlyphCache::createTexture(TextureInfo *texInfo,
200 QByteArray zeroBuf(width * height, 0);
201 createTexture(texInfo, width, height, zeroBuf);
204void QSGRhiDistanceFieldGlyphCache::createTexture(TextureInfo *texInfo,
207 const QByteArray &pixels)
209 QRhiTexture *newTexture = m_rhi->newTexture(QRhiTexture::RED_OR_ALPHA8, QSize(width, height), 1, QRhiTexture::UsedAsTransferSource);
210 if (!newTexture->create()) {
211 qWarning(
"Failed to create distance field glyph cache");
213 texInfo->texture =
nullptr;
214 texInfo->size = QSize();
215 texInfo->image = QA8Image();
219 if (useTextureResizeWorkaround() && texInfo->image.isNull()) {
220 texInfo->image = QA8Image(width, height);
221 if (texInfo->image.isNull()) {
222 qWarning(
"Failed to create distance field glyph cache");
224 texInfo->texture =
nullptr;
225 texInfo->size = QSize();
226 texInfo->image = QA8Image();
229 memcpy(texInfo->image.bits(), pixels.constData(), width * height);
233 texInfo->texture = newTexture;
234 texInfo->size = QSize(width, height);
236 QRhiResourceUpdateBatch *resourceUpdates = m_rc->glyphCacheResourceUpdates();
237 QRhiTextureSubresourceUploadDescription subresDesc(pixels);
238 subresDesc.setSourceSize(QSize(width, height));
239 resourceUpdates->uploadTexture(texInfo->texture, QRhiTextureUploadEntry(0, 0, subresDesc));
242void QSGRhiDistanceFieldGlyphCache::resizeTexture(TextureInfo *texInfo,
int width,
int height)
244 int oldWidth = texInfo->size.width();
245 int oldHeight = texInfo->size.height();
246 if (width == oldWidth && height == oldHeight)
249 QRhiTexture *oldTexture = texInfo->texture;
250 createTexture(texInfo, width, height);
252 if (!texInfo->texture) {
254 updateRhiTexture(oldTexture,
nullptr, QSize());
255 m_rc->deferredReleaseGlyphCacheTexture(oldTexture);
263 updateRhiTexture(oldTexture, texInfo->texture, texInfo->size);
265 QRhiResourceUpdateBatch *resourceUpdates = m_rc->glyphCacheResourceUpdates();
266 if (useTextureResizeWorkaround()) {
267 QRhiTextureSubresourceUploadDescription subresDesc(texInfo->image.constBits(),
268 oldWidth * oldHeight);
269 subresDesc.setSourceSize(QSize(oldWidth, oldHeight));
270 resourceUpdates->uploadTexture(texInfo->texture, QRhiTextureUploadEntry(0, 0, subresDesc));
271 texInfo->image = texInfo->image.copy(0, 0, width, height);
273 resourceUpdates->copyTexture(texInfo->texture, oldTexture);
276 m_rc->deferredReleaseGlyphCacheTexture(oldTexture);
279bool QSGRhiDistanceFieldGlyphCache::useTextureResizeWorkaround()
const
281 static bool set =
false;
282 static bool useWorkaround =
false;
284 useWorkaround = m_rhi->backend() == QRhi::OpenGLES2 || qmlUseGlyphCacheWorkaround();
287 return useWorkaround;
290bool QSGRhiDistanceFieldGlyphCache::createFullSizeTextures()
const
292 return qsgPreferFullSizeGlyphCacheTextures() && glyphCount() > QT_DISTANCEFIELD_HIGHGLYPHCOUNT();
295int QSGRhiDistanceFieldGlyphCache::maxTextureSize()
const
297 if (!m_maxTextureSize) {
298 m_maxTextureSize = m_rhi->resourceLimit(QRhi::TextureSizeMax);
302 const int overriddenMaxTextureSize =
303 qEnvironmentVariableIntValue(
"QSG_DISTANCEFIELD_MAX_TEXTURE_SIZE");
304 if (overriddenMaxTextureSize > 0)
305 m_maxTextureSize = overriddenMaxTextureSize;
307 return m_maxTextureSize;
317 GlyphRecordSize = 46,
318 TextureRecordSize = 17
341 boundingRectWidth = 36,
342 boundingRectHeight = 40,
349 allocatedHeight = 12,
354 template <
typename T>
355 static inline T fetch(
const char *data, Offset offset)
357 return qFromBigEndian<T>(data +
int(offset));
362bool QSGRhiDistanceFieldGlyphCache::loadPregeneratedCache(
const QRawFont &font)
366 if (m_areaAllocator !=
nullptr) {
367 qWarning(
"Font cache must be loaded before cache is used");
371 static QElapsedTimer timer;
373 bool profile = QSG_LOG_TIME_GLYPH().isDebugEnabled();
377 QByteArray qtdfTable = font.fontTable(
"qtdf");
378 if (qtdfTable.isEmpty())
381 if (uint(qtdfTable.size()) < Qtdf::HeaderSize) {
382 qWarning(
"Invalid qtdf table in font '%s'",
383 qPrintable(font.familyName()));
387 const char *qtdfTableStart = qtdfTable.constData();
388 const char *qtdfTableEnd = qtdfTableStart + qtdfTable.size();
391 int textureCount = 0;
393 quint8 majorVersion = Qtdf::fetch<quint8>(qtdfTableStart, Qtdf::majorVersion);
394 quint8 minorVersion = Qtdf::fetch<quint8>(qtdfTableStart, Qtdf::minorVersion);
395 if (majorVersion != 5 || minorVersion != 12) {
396 qWarning(
"Invalid version of qtdf table %d.%d in font '%s'",
399 qPrintable(font.familyName()));
403 qreal pixelSize = qreal(Qtdf::fetch<quint16>(qtdfTableStart, Qtdf::pixelSize));
404 m_maxTextureSize = Qtdf::fetch<quint32>(qtdfTableStart, Qtdf::textureSize);
405 m_doubleGlyphResolution = Qtdf::fetch<quint8>(qtdfTableStart, Qtdf::flags) == 1;
406 padding = Qtdf::fetch<quint8>(qtdfTableStart, Qtdf::headerPadding);
408 if (pixelSize <= 0.0) {
409 qWarning(
"Invalid pixel size in '%s'", qPrintable(font.familyName()));
413 if (m_maxTextureSize <= 0) {
414 qWarning(
"Invalid texture size in '%s'", qPrintable(font.familyName()));
418 int systemMaxTextureSize = m_rhi->resourceLimit(QRhi::TextureSizeMax);
420 if (m_maxTextureSize > systemMaxTextureSize) {
421 qWarning(
"System maximum texture size is %d. This is lower than the value in '%s', which is %d",
422 systemMaxTextureSize,
423 qPrintable(font.familyName()),
428 qWarning(
"Padding mismatch in '%s'. Font requires %d, but Qt is compiled with %d.",
429 qPrintable(font.familyName()),
434 m_referenceFont.setPixelSize(pixelSize);
436 quint32 glyphCount = Qtdf::fetch<quint32>(qtdfTableStart, Qtdf::numGlyphs);
437 m_unusedGlyphs.reserve(glyphCount);
439 const char *allocatorData = qtdfTableStart + Qtdf::HeaderSize;
441 m_areaAllocator =
new QSGAreaAllocator(QSize(0, 0), m_maxTextureSize);
442 allocatorData = m_areaAllocator->deserialize(allocatorData, qtdfTableEnd - allocatorData);
443 if (allocatorData ==
nullptr)
447 if (m_areaAllocator->size().height() % m_maxTextureSize != 0) {
448 qWarning(
"Area allocator size mismatch in '%s'", qPrintable(font.familyName()));
452 textureCount = m_areaAllocator->size().height() / m_maxTextureSize;
453 m_maxTextureCount = qMax(m_maxTextureCount, textureCount);
456 QList<QList<glyph_t> > glyphTextures(textureCount);
458 const char *textureRecord = allocatorData;
459 for (
int i = 0; i < textureCount; ++i, textureRecord += Qtdf::TextureRecordSize) {
460 if (qtdfTableEnd - textureRecord < Qtdf::TextureRecordSize) {
461 qWarning(
"qtdf table too small in font '%s'.",
462 qPrintable(font.familyName()));
466 TextureInfo *tex = textureInfo(i);
468 const quint32 allocX = Qtdf::fetch<quint32>(textureRecord, Qtdf::allocatedX);
469 const quint32 allocY = Qtdf::fetch<quint32>(textureRecord, Qtdf::allocatedY);
470 const quint32 allocWidth = Qtdf::fetch<quint32>(textureRecord, Qtdf::allocatedWidth);
471 const quint32 allocHeight = Qtdf::fetch<quint32>(textureRecord, Qtdf::allocatedHeight);
472 const quint32 maxSize = quint32(m_maxTextureSize);
477 const quint32 maxTexHeight = maxSize * 2 - 1;
478 if (allocX > maxSize || allocY > maxSize
479 || allocWidth > maxSize || allocHeight > maxTexHeight) {
480 qWarning(
"Invalid texture geometry in qtdf table in font '%s'",
481 qPrintable(font.familyName()));
485 tex->allocatedArea.setX(
int(allocX));
486 tex->allocatedArea.setY(
int(allocY));
487 tex->allocatedArea.setWidth(
int(allocWidth));
488 tex->allocatedArea.setHeight(
int(allocHeight));
489 tex->padding = Qtdf::fetch<quint8>(textureRecord, Qtdf::texturePadding);
492 const char *glyphRecord = textureRecord;
493 for (quint32 i = 0; i < glyphCount; ++i, glyphRecord += Qtdf::GlyphRecordSize) {
494 if (qtdfTableEnd - glyphRecord < Qtdf:: GlyphRecordSize) {
495 qWarning(
"qtdf table too small in font '%s'.",
496 qPrintable(font.familyName()));
500 glyph_t glyph = Qtdf::fetch<quint32>(glyphRecord, Qtdf::glyphIndex);
501 m_unusedGlyphs.insert(glyph);
503 GlyphData &glyphData = emptyData(glyph);
505#define FROM_FIXED_POINT(value) \
506(((qreal)value)/(qreal)65536)
508 glyphData.texCoord.x =
FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::textureOffsetX));
509 glyphData.texCoord.y =
FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::textureOffsetY));
510 glyphData.texCoord.width =
FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::textureWidth));
511 glyphData.texCoord.height =
FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::textureHeight));
512 glyphData.texCoord.xMargin =
FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::xMargin));
513 glyphData.texCoord.yMargin =
FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::yMargin));
514 glyphData.boundingRect.setX(
FROM_FIXED_POINT(Qtdf::fetch<qint32>(glyphRecord, Qtdf::boundingRectX)));
515 glyphData.boundingRect.setY(
FROM_FIXED_POINT(Qtdf::fetch<qint32>(glyphRecord, Qtdf::boundingRectY)));
516 glyphData.boundingRect.setWidth(
FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::boundingRectWidth)));
517 glyphData.boundingRect.setHeight(
FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::boundingRectHeight)));
519#undef FROM_FIXED_POINT
521 int textureIndex = Qtdf::fetch<quint16>(glyphRecord, Qtdf::textureIndex);
522 if (textureIndex < 0 || textureIndex >= textureCount) {
523 qWarning(
"Invalid texture index %d (texture count == %d) in '%s'",
526 qPrintable(font.familyName()));
531 m_glyphsTexture.insert(glyph, textureIndex);
533 glyphTextures[textureIndex].append(glyph);
536 const uchar *textureData =
reinterpret_cast<
const uchar *>(glyphRecord);
537 for (
int i = 0; i < textureCount; ++i) {
539 TextureInfo *texInfo = textureInfo(i);
541 int width = texInfo->allocatedArea.width();
542 int height = texInfo->allocatedArea.height();
543 if (width <= 0 || height <= 0) {
544 qWarning(
"Invalid texture size in qtdf table in font '%s'",
545 qPrintable(font.familyName()));
548 qint64 size = qint64(width) * height;
549 if (qtdfTableEnd -
reinterpret_cast<
const char *>(textureData) < size) {
550 qWarning(
"qtdf table too small in font '%s'.",
551 qPrintable(font.familyName()));
555 createTexture(texInfo, width, height,
556 QByteArray(
reinterpret_cast<
const char *>(textureData), qsizetype(size)));
559 if (!texInfo->texture)
562 const QList<glyph_t> &glyphs = glyphTextures.at(i);
565 t.texture = texInfo->texture;
566 t.size = texInfo->size;
568 setGlyphsTexture(glyphs, t);
573 quint64 now = timer.elapsed();
574 qCDebug(QSG_LOG_TIME_GLYPH,
575 "distancefield: %d pre-generated glyphs loaded in %dms",
576 int(m_unusedGlyphs.size()),
583void QSGRhiDistanceFieldGlyphCache::commitResourceUpdates(QRhiResourceUpdateBatch *mergeInto)
585 if (QRhiResourceUpdateBatch *resourceUpdates = m_rc->maybeGlyphCacheResourceUpdates()) {
586 mergeInto->merge(resourceUpdates);
587 m_rc->resetGlyphCacheResources();
591bool QSGRhiDistanceFieldGlyphCache::eightBitFormatIsAlphaSwizzled()
const
595 return !m_rhi->isFeatureSupported(QRhi::RedOrAlpha8IsRed);
598bool QSGRhiDistanceFieldGlyphCache::screenSpaceDerivativesSupported()
const
600 return m_rhi->isFeatureSupported(QRhi::ScreenSpaceDerivatives);
603#if defined(QSG_DISTANCEFIELD_CACHE_DEBUG)
604void QSGRhiDistanceFieldGlyphCache::saveTexture(QRhiTexture *texture,
const QString &nameBase)
const
606 quint64 textureId = texture->nativeTexture().object;
607 QString fileName = nameBase + QLatin1Char(
'_') + QString::number(textureId, 16);
608 fileName.replace(QLatin1Char(
'/'), QLatin1Char(
'_'));
609 fileName.replace(QLatin1Char(
' '), QLatin1Char(
'_'));
610 fileName.append(QLatin1String(
".png"));
612 QRhiReadbackResult *rbResult =
new QRhiReadbackResult;
613 rbResult->completed = [rbResult, fileName] {
614 const QSize size = rbResult->pixelSize;
615 const qint64 numPixels = qint64(size.width()) * size.height();
616 if (numPixels == rbResult->data.size()) {
618 QImage image(size, QImage::Format_Grayscale8);
619 const char *p = rbResult->data.constData();
620 for (
int i = 0; i < size.height(); i++)
621 memcpy(image.scanLine(i), p + (i * size.width()), size.width());
622 image.save(fileName);
623 }
else if (4 * numPixels == rbResult->data.size()) {
625 const uchar *p =
reinterpret_cast<
const uchar *>(rbResult->data.constData());
626 QImage image(p, size.width(), size.height(), QImage::Format_RGBA8888);
627 image.save(fileName);
629 qWarning(
"Unhandled data format in glyph texture");
634 QRhiReadbackDescription rb(texture);
635 QRhiResourceUpdateBatch *resourceUpdates = m_rc->glyphCacheResourceUpdates();
636 resourceUpdates->readBackTexture(rb, rbResult);
Combined button and popup list for selecting options.
#define QSG_RHI_DISTANCEFIELD_GLYPH_CACHE_PADDING
#define FROM_FIXED_POINT(value)