7#include <QtGui/private/qdistancefield_p.h>
8#include <QtCore/qelapsedtimer.h>
9#include <QtQml/private/qqmlglobal_p.h>
15DEFINE_BOOL_CONFIG_OPTION(qmlUseGlyphCacheWorkaround, QML_USE_GLYPHCACHE_WORKAROUND)
16DEFINE_BOOL_CONFIG_OPTION(qsgPreferFullSizeGlyphCacheTextures, QSG_PREFER_FULLSIZE_GLYPHCACHE_TEXTURES)
18#if !defined(QSG_RHI_DISTANCEFIELD_GLYPH_CACHE_PADDING)
19# define QSG_RHI_DISTANCEFIELD_GLYPH_CACHE_PADDING 2
22QSGRhiDistanceFieldGlyphCache::QSGRhiDistanceFieldGlyphCache(QSGDefaultRenderContext *rc,
24 int renderTypeQuality)
25 : QSGDistanceFieldGlyphCache(font, renderTypeQuality)
30 loadPregeneratedCache(font);
33QSGRhiDistanceFieldGlyphCache::~QSGRhiDistanceFieldGlyphCache()
35 for (
const TextureInfo &t : std::as_const(m_textures))
36 m_rc->deferredReleaseGlyphCacheTexture(t.texture);
38 delete m_areaAllocator;
41void QSGRhiDistanceFieldGlyphCache::requestGlyphs(
const QSet<glyph_t> &glyphs)
43 QList<GlyphPosition> glyphPositions;
44 QVector<glyph_t> glyphsToRender;
46 if (m_areaAllocator ==
nullptr)
47 m_areaAllocator =
new QSGAreaAllocator(QSize(maxTextureSize(), m_maxTextureCount * maxTextureSize()));
49 for (QSet<glyph_t>::const_iterator it = glyphs.constBegin(); it != glyphs.constEnd() ; ++it) {
50 glyph_t glyphIndex = *it;
53 QRectF boundingRect = glyphData(glyphIndex).boundingRect;
54 int glyphWidth = qCeil(boundingRect.width() + distanceFieldRadius() * 2);
55 int glyphHeight = qCeil(boundingRect.height() + distanceFieldRadius() * 2);
56 QSize glyphSize(glyphWidth + padding * 2, glyphHeight + padding * 2);
57 QRect alloc = m_areaAllocator->allocate(glyphSize);
61 while (alloc.isNull() && !m_unusedGlyphs.isEmpty()) {
62 glyph_t unusedGlyph = *m_unusedGlyphs.constBegin();
64 TexCoord unusedCoord = glyphTexCoord(unusedGlyph);
65 if (!unusedCoord.isNull()) {
66 QRectF unusedGlyphBoundingRect = glyphData(unusedGlyph).boundingRect;
67 int unusedGlyphWidth = qCeil(unusedGlyphBoundingRect.width() + distanceFieldRadius() * 2);
68 int unusedGlyphHeight = qCeil(unusedGlyphBoundingRect.height() + distanceFieldRadius() * 2);
69 m_areaAllocator->deallocate(QRect(unusedCoord.x - padding,
70 unusedCoord.y - padding,
71 padding * 2 + unusedGlyphWidth,
72 padding * 2 + unusedGlyphHeight));
75 m_unusedGlyphs.remove(unusedGlyph);
76 m_glyphsTexture.remove(unusedGlyph);
77 removeGlyph(unusedGlyph);
79 alloc = m_areaAllocator->allocate(glyphSize);
87 TextureInfo *tex = textureInfo(alloc.y() / maxTextureSize());
88 alloc = QRect(alloc.x(), alloc.y() % maxTextureSize(), alloc.width(), alloc.height());
90 tex->allocatedArea |= alloc;
91 Q_ASSERT(tex->padding == padding || tex->padding < 0);
92 tex->padding = padding;
96 p.position = alloc.topLeft() + QPoint(padding, padding);
98 glyphPositions.append(p);
99 glyphsToRender.append(glyphIndex);
100 m_glyphsTexture.insert(glyphIndex, tex);
103 setGlyphsPosition(glyphPositions);
104 markGlyphsToRender(glyphsToRender);
107bool QSGRhiDistanceFieldGlyphCache::isActive()
const
109 return !m_referencedGlyphs.empty();
112void QSGRhiDistanceFieldGlyphCache::storeGlyphs(
const QList<QDistanceField> &glyphs)
114 typedef QHash<TextureInfo *, QVector<glyph_t> > GlyphTextureHash;
115 typedef GlyphTextureHash::const_iterator GlyphTextureHashConstIt;
117 GlyphTextureHash glyphTextures;
119 QVarLengthArray<QRhiTextureUploadEntry, 32> uploads;
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 glyphTextures[texInfo].append(glyphIndex);
130 int padding = texInfo->padding;
131 int expectedWidth = qCeil(c.width + c.xMargin * 2);
132 glyph = glyph.copy(-padding, -padding,
133 expectedWidth + padding * 2, glyph.height() + padding * 2);
135 if (useTextureResizeWorkaround()) {
136 uchar *inBits = glyph.scanLine(0);
137 uchar *outBits = texInfo->image.scanLine(
int(c.y) - padding) +
int(c.x) - padding;
138 for (
int y = 0; y < glyph.height(); ++y) {
139 memcpy(outBits, inBits, glyph.width());
140 inBits += glyph.width();
141 outBits += texInfo->image.width();
145 QRhiTextureSubresourceUploadDescription subresDesc(glyph.constBits(), glyph.width() * glyph.height());
146 subresDesc.setSourceSize(QSize(glyph.width(), glyph.height()));
147 subresDesc.setDestinationTopLeft(QPoint(c.x - padding, c.y - padding));
148 texInfo->uploads.append(QRhiTextureUploadEntry(0, 0, subresDesc));
151 QRhiResourceUpdateBatch *resourceUpdates = m_rc->glyphCacheResourceUpdates();
152 for (
int i = 0; i < glyphs.size(); ++i) {
153 TextureInfo *texInfo = m_glyphsTexture.value(glyphs.at(i).glyph());
154 if (!texInfo->uploads.isEmpty()) {
155 QRhiTextureUploadDescription desc;
156 desc.setEntries(texInfo->uploads.cbegin(), texInfo->uploads.cend());
157 resourceUpdates->uploadTexture(texInfo->texture, desc);
158 texInfo->uploads.clear();
162 for (GlyphTextureHashConstIt i = glyphTextures.constBegin(), cend = glyphTextures.constEnd(); i != cend; ++i) {
164 t.texture = i.key()->texture;
165 t.size = i.key()->size;
166 setGlyphsTexture(i.value(), t);
170void QSGRhiDistanceFieldGlyphCache::referenceGlyphs(
const QSet<glyph_t> &glyphs)
172 m_referencedGlyphs += glyphs;
173 m_unusedGlyphs -= glyphs;
176void QSGRhiDistanceFieldGlyphCache::releaseGlyphs(
const QSet<glyph_t> &glyphs)
178 m_referencedGlyphs -= glyphs;
179 m_unusedGlyphs += glyphs;
182void QSGRhiDistanceFieldGlyphCache::createTexture(TextureInfo *texInfo,
186 QByteArray zeroBuf(width * height, 0);
187 createTexture(texInfo, width, height, zeroBuf.constData());
190void QSGRhiDistanceFieldGlyphCache::createTexture(TextureInfo *texInfo,
195 if (useTextureResizeWorkaround() && texInfo->image.isNull()) {
196 texInfo->image = QDistanceField(width, height);
197 memcpy(texInfo->image.bits(), pixels, width * height);
200 texInfo->texture = m_rhi->newTexture(QRhiTexture::RED_OR_ALPHA8, QSize(width, height), 1, QRhiTexture::UsedAsTransferSource);
201 if (texInfo->texture->create()) {
202 QRhiResourceUpdateBatch *resourceUpdates = m_rc->glyphCacheResourceUpdates();
203 QRhiTextureSubresourceUploadDescription subresDesc(pixels, width * height);
204 subresDesc.setSourceSize(QSize(width, height));
205 resourceUpdates->uploadTexture(texInfo->texture, QRhiTextureUploadEntry(0, 0, subresDesc));
207 qWarning(
"Failed to create distance field glyph cache");
210 texInfo->size = QSize(width, height);
213void QSGRhiDistanceFieldGlyphCache::resizeTexture(TextureInfo *texInfo,
int width,
int height)
215 int oldWidth = texInfo->size.width();
216 int oldHeight = texInfo->size.height();
217 if (width == oldWidth && height == oldHeight)
220 QRhiTexture *oldTexture = texInfo->texture;
221 createTexture(texInfo, width, height);
226 updateRhiTexture(oldTexture, texInfo->texture, texInfo->size);
228 QRhiResourceUpdateBatch *resourceUpdates = m_rc->glyphCacheResourceUpdates();
229 if (useTextureResizeWorkaround()) {
230 QRhiTextureSubresourceUploadDescription subresDesc(texInfo->image.constBits(),
231 oldWidth * oldHeight);
232 subresDesc.setSourceSize(QSize(oldWidth, oldHeight));
233 resourceUpdates->uploadTexture(texInfo->texture, QRhiTextureUploadEntry(0, 0, subresDesc));
234 texInfo->image = texInfo->image.copy(0, 0, width, height);
236 resourceUpdates->copyTexture(texInfo->texture, oldTexture);
239 m_rc->deferredReleaseGlyphCacheTexture(oldTexture);
242bool QSGRhiDistanceFieldGlyphCache::useTextureResizeWorkaround()
const
244 static bool set =
false;
245 static bool useWorkaround =
false;
247 useWorkaround = m_rhi->backend() == QRhi::OpenGLES2 || qmlUseGlyphCacheWorkaround();
250 return useWorkaround;
253bool QSGRhiDistanceFieldGlyphCache::createFullSizeTextures()
const
255 return qsgPreferFullSizeGlyphCacheTextures() && glyphCount() > QT_DISTANCEFIELD_HIGHGLYPHCOUNT();
258int QSGRhiDistanceFieldGlyphCache::maxTextureSize()
const
260 if (!m_maxTextureSize)
261 m_maxTextureSize = m_rhi->resourceLimit(QRhi::TextureSizeMax);
262 return m_maxTextureSize;
272 GlyphRecordSize = 46,
273 TextureRecordSize = 17
296 boundingRectWidth = 36,
297 boundingRectHeight = 40,
304 allocatedHeight = 12,
309 template <
typename T>
310 static inline T fetch(
const char *data, Offset offset)
312 return qFromBigEndian<T>(data +
int(offset));
317bool QSGRhiDistanceFieldGlyphCache::loadPregeneratedCache(
const QRawFont &font)
321 if (m_areaAllocator !=
nullptr) {
322 qWarning(
"Font cache must be loaded before cache is used");
326 static QElapsedTimer timer;
328 bool profile = QSG_LOG_TIME_GLYPH().isDebugEnabled();
332 QByteArray qtdfTable = font.fontTable(
"qtdf");
333 if (qtdfTable.isEmpty())
336 typedef QHash<TextureInfo *, QVector<glyph_t> > GlyphTextureHash;
338 GlyphTextureHash glyphTextures;
340 if (uint(qtdfTable.size()) < Qtdf::HeaderSize) {
341 qWarning(
"Invalid qtdf table in font '%s'",
342 qPrintable(font.familyName()));
346 const char *qtdfTableStart = qtdfTable.constData();
347 const char *qtdfTableEnd = qtdfTableStart + qtdfTable.size();
350 int textureCount = 0;
352 quint8 majorVersion = Qtdf::fetch<quint8>(qtdfTableStart, Qtdf::majorVersion);
353 quint8 minorVersion = Qtdf::fetch<quint8>(qtdfTableStart, Qtdf::minorVersion);
354 if (majorVersion != 5 || minorVersion != 12) {
355 qWarning(
"Invalid version of qtdf table %d.%d in font '%s'",
358 qPrintable(font.familyName()));
362 qreal pixelSize = qreal(Qtdf::fetch<quint16>(qtdfTableStart, Qtdf::pixelSize));
363 m_maxTextureSize = Qtdf::fetch<quint32>(qtdfTableStart, Qtdf::textureSize);
364 m_doubleGlyphResolution = Qtdf::fetch<quint8>(qtdfTableStart, Qtdf::flags) == 1;
365 padding = Qtdf::fetch<quint8>(qtdfTableStart, Qtdf::headerPadding);
367 if (pixelSize <= 0.0) {
368 qWarning(
"Invalid pixel size in '%s'", qPrintable(font.familyName()));
372 if (m_maxTextureSize <= 0) {
373 qWarning(
"Invalid texture size in '%s'", qPrintable(font.familyName()));
377 int systemMaxTextureSize = m_rhi->resourceLimit(QRhi::TextureSizeMax);
379 if (m_maxTextureSize > systemMaxTextureSize) {
380 qWarning(
"System maximum texture size is %d. This is lower than the value in '%s', which is %d",
381 systemMaxTextureSize,
382 qPrintable(font.familyName()),
387 qWarning(
"Padding mismatch in '%s'. Font requires %d, but Qt is compiled with %d.",
388 qPrintable(font.familyName()),
393 m_referenceFont.setPixelSize(pixelSize);
395 quint32 glyphCount = Qtdf::fetch<quint32>(qtdfTableStart, Qtdf::numGlyphs);
396 m_unusedGlyphs.reserve(glyphCount);
398 const char *allocatorData = qtdfTableStart + Qtdf::HeaderSize;
400 m_areaAllocator =
new QSGAreaAllocator(QSize(0, 0));
401 allocatorData = m_areaAllocator->deserialize(allocatorData, qtdfTableEnd - allocatorData);
402 if (allocatorData ==
nullptr)
406 if (m_areaAllocator->size().height() % m_maxTextureSize != 0) {
407 qWarning(
"Area allocator size mismatch in '%s'", qPrintable(font.familyName()));
411 textureCount = m_areaAllocator->size().height() / m_maxTextureSize;
412 m_maxTextureCount = qMax(m_maxTextureCount, textureCount);
414 const char *textureRecord = allocatorData;
415 for (
int i = 0; i < textureCount; ++i, textureRecord += Qtdf::TextureRecordSize) {
416 if (qtdfTableEnd - textureRecord < Qtdf::TextureRecordSize) {
417 qWarning(
"qtdf table too small in font '%s'.",
418 qPrintable(font.familyName()));
422 TextureInfo *tex = textureInfo(i);
423 tex->allocatedArea.setX(Qtdf::fetch<quint32>(textureRecord, Qtdf::allocatedX));
424 tex->allocatedArea.setY(Qtdf::fetch<quint32>(textureRecord, Qtdf::allocatedY));
425 tex->allocatedArea.setWidth(Qtdf::fetch<quint32>(textureRecord, Qtdf::allocatedWidth));
426 tex->allocatedArea.setHeight(Qtdf::fetch<quint32>(textureRecord, Qtdf::allocatedHeight));
427 tex->padding = Qtdf::fetch<quint8>(textureRecord, Qtdf::texturePadding);
430 const char *glyphRecord = textureRecord;
431 for (quint32 i = 0; i < glyphCount; ++i, glyphRecord += Qtdf::GlyphRecordSize) {
432 if (qtdfTableEnd - glyphRecord < Qtdf:: GlyphRecordSize) {
433 qWarning(
"qtdf table too small in font '%s'.",
434 qPrintable(font.familyName()));
438 glyph_t glyph = Qtdf::fetch<quint32>(glyphRecord, Qtdf::glyphIndex);
439 m_unusedGlyphs.insert(glyph);
441 GlyphData &glyphData = emptyData(glyph);
443#define FROM_FIXED_POINT(value) \
444(((qreal)value)/(qreal)65536)
446 glyphData.texCoord.x =
FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::textureOffsetX));
447 glyphData.texCoord.y =
FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::textureOffsetY));
448 glyphData.texCoord.width =
FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::textureWidth));
449 glyphData.texCoord.height =
FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::textureHeight));
450 glyphData.texCoord.xMargin =
FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::xMargin));
451 glyphData.texCoord.yMargin =
FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::yMargin));
452 glyphData.boundingRect.setX(
FROM_FIXED_POINT(Qtdf::fetch<qint32>(glyphRecord, Qtdf::boundingRectX)));
453 glyphData.boundingRect.setY(
FROM_FIXED_POINT(Qtdf::fetch<qint32>(glyphRecord, Qtdf::boundingRectY)));
454 glyphData.boundingRect.setWidth(
FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::boundingRectWidth)));
455 glyphData.boundingRect.setHeight(
FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::boundingRectHeight)));
457#undef FROM_FIXED_POINT
459 int textureIndex = Qtdf::fetch<quint16>(glyphRecord, Qtdf::textureIndex);
460 if (textureIndex < 0 || textureIndex >= textureCount) {
461 qWarning(
"Invalid texture index %d (texture count == %d) in '%s'",
464 qPrintable(font.familyName()));
469 TextureInfo *texInfo = textureInfo(textureIndex);
470 m_glyphsTexture.insert(glyph, texInfo);
472 glyphTextures[texInfo].append(glyph);
475 const uchar *textureData =
reinterpret_cast<
const uchar *>(glyphRecord);
476 for (
int i = 0; i < textureCount; ++i) {
478 TextureInfo *texInfo = textureInfo(i);
480 int width = texInfo->allocatedArea.width();
481 int height = texInfo->allocatedArea.height();
482 qint64 size = qint64(width) * height;
483 if (qtdfTableEnd -
reinterpret_cast<
const char *>(textureData) < size) {
484 qWarning(
"qtdf table too small in font '%s'.",
485 qPrintable(font.familyName()));
489 createTexture(texInfo, width, height, textureData);
491 QVector<glyph_t> glyphs = glyphTextures.value(texInfo);
494 t.texture = texInfo->texture;
495 t.size = texInfo->size;
497 setGlyphsTexture(glyphs, t);
504 quint64 now = timer.elapsed();
505 qCDebug(QSG_LOG_TIME_GLYPH,
506 "distancefield: %d pre-generated glyphs loaded in %dms",
507 int(m_unusedGlyphs.size()),
514void QSGRhiDistanceFieldGlyphCache::commitResourceUpdates(QRhiResourceUpdateBatch *mergeInto)
516 if (QRhiResourceUpdateBatch *resourceUpdates = m_rc->maybeGlyphCacheResourceUpdates()) {
517 mergeInto->merge(resourceUpdates);
518 m_rc->resetGlyphCacheResources();
522bool QSGRhiDistanceFieldGlyphCache::eightBitFormatIsAlphaSwizzled()
const
526 return !m_rhi->isFeatureSupported(QRhi::RedOrAlpha8IsRed);
529bool QSGRhiDistanceFieldGlyphCache::screenSpaceDerivativesSupported()
const
531 return m_rhi->isFeatureSupported(QRhi::ScreenSpaceDerivatives);
534#if defined(QSG_DISTANCEFIELD_CACHE_DEBUG)
535void QSGRhiDistanceFieldGlyphCache::saveTexture(QRhiTexture *texture,
const QString &nameBase)
const
537 quint64 textureId = texture->nativeTexture().object;
538 QString fileName = nameBase + QLatin1Char(
'_') + QString::number(textureId, 16);
539 fileName.replace(QLatin1Char(
'/'), QLatin1Char(
'_'));
540 fileName.replace(QLatin1Char(
' '), QLatin1Char(
'_'));
541 fileName.append(QLatin1String(
".png"));
543 QRhiReadbackResult *rbResult =
new QRhiReadbackResult;
544 rbResult->completed = [rbResult, fileName] {
545 const QSize size = rbResult->pixelSize;
546 const qint64 numPixels = qint64(size.width()) * size.height();
547 if (numPixels == rbResult->data.size()) {
549 QImage image(size, QImage::Format_Grayscale8);
550 const char *p = rbResult->data.constData();
551 for (
int i = 0; i < size.height(); i++)
552 memcpy(image.scanLine(i), p + (i * size.width()), size.width());
553 image.save(fileName);
554 }
else if (4 * numPixels == rbResult->data.size()) {
556 const uchar *p =
reinterpret_cast<
const uchar *>(rbResult->data.constData());
557 QImage image(p, size.width(), size.height(), QImage::Format_RGBA8888);
558 image.save(fileName);
560 qWarning(
"Unhandled data format in glyph texture");
565 QRhiReadbackDescription rb(texture);
566 QRhiResourceUpdateBatch *resourceUpdates = m_rc->glyphCacheResourceUpdates();
567 resourceUpdates->readBackTexture(rb, rbResult);
#define QSG_RHI_DISTANCEFIELD_GLYPH_CACHE_PADDING
#define FROM_FIXED_POINT(value)