forked from Dynamitos/Seele
Implement texture atlas for fonts
This commit is contained in:
1 parent
17dc1e4d88
commit
22a90fe07c
14 files changed
+382
-44
No files matched your search
+1
-1
@@ -133,7 +133,7 @@ if(APPLE)
|
||||
endif()
|
||||
|
||||
add_subdirectory(src/)
|
||||
#add_subdirectory(tests/)
|
||||
add_subdirectory(tests/)
|
||||
|
||||
if(WIN32)
|
||||
add_custom_command(TARGET Engine POST_BUILD
|
||||
|
||||
@@ -10,8 +10,10 @@ struct RenderElementStyle
|
||||
float opacity;
|
||||
float z;
|
||||
uint textureIndex;
|
||||
uint pad0;
|
||||
uint pad1;
|
||||
// UV rect for textured quads (glyphs: their rect in the font atlas)
|
||||
float2 uvOffset;
|
||||
float2 uvSize;
|
||||
float2 pad;
|
||||
};
|
||||
|
||||
struct UIParameter
|
||||
@@ -69,12 +71,15 @@ float4 fragmentMain(
|
||||
if(style.textureIndex == -1) {
|
||||
return float4(style.color, style.opacity);
|
||||
}
|
||||
// Glyph quads: the texture is R8_UNORM (coverage in the R channel, A baked to 1.0).
|
||||
// Reading it as a Texture2D gives (R=coverage, G=0, B=0, A=1) — so the alpha we want
|
||||
// is in .r, NOT .a (using .a would make every pixel opaque -> the "black cutout").
|
||||
// Glyph quads: the texture is the font's per-size atlas (R8_UNORM, coverage in the R
|
||||
// channel, A baked to 1.0). Reading it as a Texture2D gives (R=coverage, G=0, B=0, A=1)
|
||||
// — so the alpha we want is in .r, NOT .a (using .a would make every pixel opaque).
|
||||
// Output the pure text color + coverage as alpha; the pipeline's SRC_ALPHA blend then
|
||||
// applies the coverage exactly once (do NOT premultiply here or it'd be squared).
|
||||
float4 tex = pParams.textures[style.textureIndex].Sample(pParams.sampler, texCoords.xy);
|
||||
// The UV rect (style.uvOffset/uvSize) selects the glyph inside the atlas; plain
|
||||
// textured UI quads use the full-rect default (0,0,1,1).
|
||||
float2 uv = style.uvOffset + texCoords * style.uvSize;
|
||||
float4 tex = pParams.textures[style.textureIndex].Sample(pParams.sampler, uv);
|
||||
float coverage = tex.r;
|
||||
return float4(style.color, coverage * style.opacity);
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
#include "FontAsset.h"
|
||||
#include "Graphics/Graphics.h"
|
||||
#include "Graphics/Texture.h"
|
||||
#include <ft2build.h>
|
||||
#include FT_FREETYPE_H
|
||||
|
||||
using namespace Seele;
|
||||
|
||||
@@ -71,11 +73,12 @@ UVector2 FontAsset::shapeText(std::string_view view, uint32 fontSize, Array<Rend
|
||||
float bitmapTop = (float)fontSizes[fontSize].glyphs[glyphid].bearing.y;
|
||||
position.x += bearingX;
|
||||
position.y += -bitmapTop;
|
||||
render.add(RenderGlyph{
|
||||
.texture = fontSizes[fontSize].glyphs[glyphid].texture,
|
||||
.position = position,
|
||||
.dimensions = dimensions,
|
||||
});
|
||||
RenderGlyph& rg = render.add({});
|
||||
rg.texture = fontSizes[fontSize].atlas;
|
||||
rg.uvOffset = fontSizes[fontSize].glyphs[glyphid].uvOffset;
|
||||
rg.uvSize = fontSizes[fontSize].glyphs[glyphid].uvSize;
|
||||
rg.position = position;
|
||||
rg.dimensions = dimensions;
|
||||
cursor += Vector2(xAdvance, yAdvance);
|
||||
// Track the right-most x extent (for auto width). Height is NOT derived from the
|
||||
// bitmap extents: it must be the full line height (ascender - descender) or
|
||||
@@ -96,32 +99,98 @@ UVector2 FontAsset::shapeText(std::string_view view, uint32 fontSize, Array<Rend
|
||||
}
|
||||
|
||||
void FontAsset::loadGlyphs(uint32 fontSize) {
|
||||
if (fontSizes.contains(fontSize)) {
|
||||
return; // packed once; the atlas is immutable
|
||||
}
|
||||
FT_Set_Pixel_Sizes(ft_face, 0, fontSize);
|
||||
// measure every glyph's bitmap size first (one pass, no GPU) so the shelf packer
|
||||
// can compute each cell's atlas coordinates before any pixels are uploaded
|
||||
constexpr uint32 atlasW = 1024;
|
||||
struct Slot {
|
||||
int glyphId;
|
||||
uint32 w, h;
|
||||
uint32 x, y; // atlas coordinates, filled by the packer
|
||||
};
|
||||
Array<Slot> slots;
|
||||
uint32 xCursor = 0;
|
||||
uint32 cursorY = 0;
|
||||
uint32 shelfH = 0;
|
||||
for (int i = 0; i < ft_face->num_glyphs; ++i) {
|
||||
assert(FT_Load_Glyph(ft_face, i, FT_LOAD_RENDER) == 0);
|
||||
FontAsset::Glyph& glyph = fontSizes[fontSize].glyphs[i];
|
||||
glyph.size = IVector2(ft_face->glyph->bitmap.width, ft_face->glyph->bitmap.rows);
|
||||
int err = FT_Load_Glyph(ft_face, i, FT_LOAD_RENDER);
|
||||
assert(err == 0);
|
||||
uint32 w = ft_face->glyph->bitmap.width;
|
||||
uint32 h = ft_face->glyph->bitmap.rows;
|
||||
if (w == 0 || h == 0) {
|
||||
w = 1;
|
||||
h = 1; // keep a 1x1 transparent placeholder so empty glyphs need no special case
|
||||
}
|
||||
if (w > atlasW) {
|
||||
w = atlasW; // shortcut: no per-glyph multi-row splitting; clamp to the atlas width
|
||||
}
|
||||
if (xCursor + w > atlasW) {
|
||||
cursorY += shelfH;
|
||||
shelfH = 0;
|
||||
xCursor = 0;
|
||||
}
|
||||
Slot s;
|
||||
s.glyphId = i;
|
||||
s.w = w;
|
||||
s.h = h;
|
||||
s.x = xCursor;
|
||||
s.y = cursorY;
|
||||
xCursor += w;
|
||||
shelfH = std::max(shelfH, h);
|
||||
slots.add(s);
|
||||
}
|
||||
uint32 totalH = cursorY + shelfH;
|
||||
if (totalH == 0) {
|
||||
totalH = 1;
|
||||
}
|
||||
Array<uint8> atlasData((uint64)atlasW * totalH, 0); // transparent by default
|
||||
FontData& data = fontSizes[fontSize];
|
||||
for (auto& s : slots) {
|
||||
// FT_Load_Glyph resets the face's current glyph — the measured sizes in `slots`
|
||||
// are already captured, so re-rendering here is safe
|
||||
// (FreeType's FT_Load_Glyph must NOT be wrapped in assert(): NDEBUG in release
|
||||
// builds would then never render the bitmap, leaving the atlas all-transparent.)
|
||||
int err2 = FT_Load_Glyph(ft_face, s.glyphId, FT_LOAD_RENDER);
|
||||
assert(err2 == 0);
|
||||
uint32 bw = ft_face->glyph->bitmap.width;
|
||||
uint32 bh = ft_face->glyph->bitmap.rows;
|
||||
FontAsset::Glyph& glyph = data.glyphs[s.glyphId];
|
||||
if (bw == 0 || bh == 0) {
|
||||
bw = 1;
|
||||
bh = 1;
|
||||
glyph.textureData = Array<uint8>(1, 0); // 1x1 transparent placeholder
|
||||
} else {
|
||||
glyph.textureData.resize((uint64)bw * bh);
|
||||
std::memcpy(glyph.textureData.data(), ft_face->glyph->bitmap.buffer, (uint64)bw * bh);
|
||||
}
|
||||
// blit the bitmap into the atlas at (s.x, s.y), row by row (pitch may differ from width)
|
||||
for (uint32 y = 0; y < bh; ++y) {
|
||||
const uint8* src = (bw == 0 || bh == 0) ? nullptr : (const uint8*)ft_face->glyph->bitmap.buffer + (uint64)y * ft_face->glyph->bitmap.pitch;
|
||||
if (src != nullptr) {
|
||||
std::memcpy(atlasData.data() + ((uint64)(s.y + y) * atlasW + s.x), src, bw);
|
||||
}
|
||||
}
|
||||
glyph.size = IVector2(bw, bh);
|
||||
glyph.bearing = IVector2(ft_face->glyph->bitmap_left, ft_face->glyph->bitmap_top);
|
||||
glyph.advance = ft_face->glyph->advance.x;
|
||||
glyph.textureData.resize(glyph.size.x * glyph.size.y);
|
||||
if (glyph.textureData.size() == 0) {
|
||||
glyph.size.x = 1;
|
||||
glyph.size.y = 1;
|
||||
glyph.textureData.add(0);
|
||||
// load a single transparent pixel, so that we dont have to handle empty textures later
|
||||
} else {
|
||||
std::memcpy(glyph.textureData.data(), ft_face->glyph->bitmap.buffer, glyph.textureData.size());
|
||||
// the UV rect is the exact cell, corner-aligned: offset = (x / W, y / H),
|
||||
// size = (w / W, h / H). The shader already applies a 1-px inset (uvSize * 0.98),
|
||||
// so linear sampling stays inside the cell and does not bleed into neighbors.
|
||||
glyph.uvOffset = Vector2((float)s.x / (float)atlasW, (float)s.y / (float)totalH);
|
||||
glyph.uvSize = Vector2((float)bw / (float)atlasW, (float)bh / (float)totalH);
|
||||
}
|
||||
glyph.texture = graphics->createTexture2D(TextureCreateInfo{
|
||||
data.atlas = graphics->createTexture2D(TextureCreateInfo{
|
||||
.sourceData =
|
||||
{
|
||||
.size = glyph.textureData.size(),
|
||||
.data = glyph.textureData.data(),
|
||||
.size = atlasData.size(),
|
||||
.data = atlasData.data(),
|
||||
},
|
||||
.format = Gfx::SE_FORMAT_R8_UNORM,
|
||||
.width = glyph.size.x,
|
||||
.height = glyph.size.y,
|
||||
.name = "FontGlyph",
|
||||
.width = atlasW,
|
||||
.height = totalH,
|
||||
.name = "FontAtlas",
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
#pragma once
|
||||
#include "Asset.h"
|
||||
#include "FontAssetTestHooks.h"
|
||||
#include "Containers/Map.h"
|
||||
#include "Graphics/Texture.h"
|
||||
#include "Math/Math.h"
|
||||
@@ -21,24 +22,59 @@ class FontAsset : public Asset {
|
||||
UVector2 bearing = {};
|
||||
uint32 advance = 0;
|
||||
Array<uint8> textureData;
|
||||
Gfx::OTexture2D texture = nullptr;
|
||||
// rect of this glyph inside the per-(font,size) atlas; the atlas texture is
|
||||
// shared by every glyph of the same size (FontData::atlas) — no per-glyph texture
|
||||
Vector2 uvOffset = Vector2(0);
|
||||
Vector2 uvSize = Vector2(0);
|
||||
void save(ArchiveBuffer& buffer) const;
|
||||
void load(ArchiveBuffer& buffer);
|
||||
};
|
||||
struct FontData {
|
||||
Map<uint32, Glyph> glyphs;
|
||||
// the single atlas holding every glyph of this size (created in loadGlyphs)
|
||||
Gfx::OTexture2D atlas = nullptr;
|
||||
};
|
||||
void loadFace();
|
||||
// packs every glyph of `fontSize` into one atlas (created lazily on first use by
|
||||
// shapeText); public so the unit test can drive the real packer
|
||||
void loadGlyphs(uint32 fontSize);
|
||||
// test seam, mirrors exactly what FontLoader::import does (the only other path that
|
||||
// sets ttfFile/graphics): a unit test uses it to drive loadGlyphs() and read the
|
||||
// produced atlas back for validation against FreeType ground truth
|
||||
void importForTest(const char* ttfBytes, uint64 size, Gfx::PGraphics graphics) {
|
||||
this->ttfFile = Array<char>(size);
|
||||
std::memcpy(this->ttfFile.data(), ttfBytes, size);
|
||||
this->graphics = graphics;
|
||||
loadFace();
|
||||
}
|
||||
// unit test: reads the packed atlas + UV rects back for validation (friend)
|
||||
FontAssetGlyphRects exportForTest(uint32 fontSize) const {
|
||||
const FontData& data = fontSizes.at(fontSize);
|
||||
FontAssetGlyphRects out;
|
||||
out.atlasWidth = data.atlas->getWidth();
|
||||
out.atlasHeight = data.atlas->getHeight();
|
||||
out.atlas = data.atlas;
|
||||
for (auto& [id, glyph] : data.glyphs) {
|
||||
FontAssetGlyphRects::Rect r;
|
||||
r.uvOffset = glyph.uvOffset;
|
||||
r.uvSize = glyph.uvSize;
|
||||
r.width = glyph.size.x;
|
||||
r.height = glyph.size.y;
|
||||
out.glyphs[id] = r;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
struct RenderGlyph {
|
||||
Gfx::PTexture2D texture;
|
||||
Gfx::PTexture2D texture; // the font's atlas for this size (shared by all its glyphs)
|
||||
Vector2 uvOffset;
|
||||
Vector2 uvSize;
|
||||
UVector2 position;
|
||||
UVector2 dimensions;
|
||||
};
|
||||
UVector2 shapeText(std::string_view view, uint32 fontSize, Array<RenderGlyph>& render);
|
||||
|
||||
private:
|
||||
void loadGlyphs(uint32 fontSize);
|
||||
Gfx::PGraphics graphics;
|
||||
hb_blob_t* blob;
|
||||
hb_face_t* hb_face;
|
||||
@@ -48,6 +84,8 @@ class FontAsset : public Asset {
|
||||
Array<char> ttfFile;
|
||||
Map<uint32, FontData> fontSizes;
|
||||
friend class FontLoader;
|
||||
// unit test: drives the packer and reads the resulting atlas back for validation
|
||||
friend class FontAssetAtlasProbe;
|
||||
};
|
||||
DECLARE_REF(FontAsset)
|
||||
} // namespace Seele
|
||||
@@ -0,0 +1,19 @@
|
||||
#pragma once
|
||||
#include "Containers/Map.h"
|
||||
#include "Graphics/Texture.h"
|
||||
#include "Math/Math.h"
|
||||
|
||||
namespace Seele {
|
||||
struct FontAssetGlyphRects {
|
||||
struct Rect {
|
||||
Vector2 uvOffset = Vector2(0);
|
||||
Vector2 uvSize = Vector2(0);
|
||||
uint32 width = 0;
|
||||
uint32 height = 0;
|
||||
};
|
||||
uint32 atlasWidth = 0;
|
||||
uint32 atlasHeight = 0;
|
||||
Map<uint32, Rect> glyphs; // glyphId -> packed rect (same order as the atlas upload)
|
||||
Gfx::PTexture2D atlas = nullptr; // the packed atlas (for readback via download)
|
||||
};
|
||||
} // namespace Seele
|
||||
@@ -59,6 +59,8 @@ void UIPass::beginFrame(const Component::Camera& cam, const Component::Transform
|
||||
.color = render.backgroundColor,
|
||||
.z = render.level / 100.f,
|
||||
.textureIndex = textureIndex,
|
||||
.uvOffset = render.uvOffset,
|
||||
.uvSize = render.uvSize,
|
||||
});
|
||||
}
|
||||
elementBuffer->rotateBuffer(sizeof(RenderElementStyle) * elements.size());
|
||||
|
||||
@@ -36,8 +36,10 @@ class UIPass : public RenderPass {
|
||||
float opacity = 1;
|
||||
float z = 0;
|
||||
uint32 textureIndex = std::numeric_limits<uint32>::max();
|
||||
uint32 pad0;
|
||||
uint32 pad1;
|
||||
// UV rect for textured quads (glyphs: their rect in the font atlas); unused for untextured quads
|
||||
Vector2 uvOffset = Vector2(0);
|
||||
Vector2 uvSize = Vector2(1);
|
||||
Vector2 pad;
|
||||
};
|
||||
|
||||
Gfx::RenderTargetAttachment colorAttachment;
|
||||
|
||||
@@ -1023,7 +1023,11 @@ void Graphics::createDevice(GraphicsInitializer initializer) {
|
||||
updateQueueInfo(familyIndex, computeQueueInfo, numQueuesForFamily);
|
||||
}
|
||||
}
|
||||
if ((currProps.queueFlags ^ VK_QUEUE_TRANSFER_BIT) == 0) {
|
||||
// a queue family is a valid transfer queue if it supports the transfer bit at all
|
||||
// (previously `(flags ^ TRANSFER) == 0`, which only matched pure-transfer families
|
||||
// that don't exist on standard drivers: no transfer queue was ever created, so
|
||||
// every vkQueueSubmit on the transfer queue path failed with VK_ERROR_DEVICE_LOST)
|
||||
if (currProps.queueFlags & VK_QUEUE_TRANSFER_BIT) {
|
||||
updateQueueInfo(familyIndex, transferQueueInfo, numQueuesForFamily);
|
||||
}
|
||||
|
||||
|
||||
@@ -213,6 +213,10 @@ TextureHandle::TextureHandle(PGraphics graphics, VkImageViewType viewType, const
|
||||
// When loading a texture from a file, we will almost always use it as a texture map for fragment shaders
|
||||
changeLayout(Gfx::SE_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
|
||||
VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT);
|
||||
// The copy above is only enqueued on a command buffer; it must actually be
|
||||
// submitted to the GPU before any consumer (the UI pass, a test's download,
|
||||
// etc.) can read the image. Without this the image is still all zeros.
|
||||
commandPool->submitCommands();
|
||||
graphics->getDestructionManager()->queueResourceForDestruction(std::move(stagingAlloc));
|
||||
}
|
||||
}
|
||||
@@ -359,6 +363,14 @@ void TextureHandle::download(uint32 mipLevel, uint32 arrayLayer, uint32 face, Ar
|
||||
cmdBuffer->bindResource(PBufferAllocation(stagingAlloc));
|
||||
changeLayout(prevLayout, VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_MEMORY_READ_BIT,
|
||||
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT);
|
||||
// The copy above is only enqueued; the staging buffer is still all zeros until the
|
||||
// command actually runs. Submit it and wait on its fence before mapping, or the read
|
||||
// below would race the GPU and return a blank texture. (submitCommands() submits the
|
||||
// current command and rotates to a fresh one, exactly like the upload path in the
|
||||
// TextureHandle constructor.)
|
||||
PCommandPool pool = graphics->getQueueCommands(owner);
|
||||
pool->submitCommands();
|
||||
cmdBuffer->waitForCommand();
|
||||
VK_CHECK(vmaMapMemory(graphics->getAllocator(), stagingAlloc->allocation, &data));
|
||||
buffer.resize(imageSize);
|
||||
std::memcpy(buffer.data(), data, buffer.size());
|
||||
|
||||
@@ -19,11 +19,11 @@ struct UIRender {
|
||||
uint32 z;
|
||||
uint32 level;
|
||||
PElement element; // back-ref for input hit-testing
|
||||
// glyph-only (text): the glyph texture is backgroundTexture, this is the
|
||||
// per-glyph rect in *atlas* space (0..1) so the pass can emit a glyph quad
|
||||
bool isGlyph = false;
|
||||
// UV rect for textured quads; glyphs carry their rect in the font's per-size
|
||||
// atlas (backgroundTexture = the atlas), full-rect (0,0,1,1) for plain images.
|
||||
// A "glyph quad" is nothing special: a quad with a texture and a UV rect.
|
||||
Vector2 uvOffset = Vector2(0);
|
||||
Vector2 uvSize = Vector2(0);
|
||||
Vector2 uvSize = Vector2(1);
|
||||
};
|
||||
class Element {
|
||||
public:
|
||||
|
||||
@@ -79,7 +79,7 @@ class Text : public Element {
|
||||
.level = level,
|
||||
.element = this,
|
||||
});
|
||||
// text: one render quad per shaped glyph, carrying its atlas rect
|
||||
// text: one quad per shaped glyph, carrying its rect in the font's per-size atlas
|
||||
if (style.fontFamily != nullptr) {
|
||||
for (auto& g : glyphs) {
|
||||
result.add(UIRender{
|
||||
@@ -90,9 +90,8 @@ class Text : public Element {
|
||||
.z = style.z,
|
||||
.level = level,
|
||||
.element = this,
|
||||
.isGlyph = true,
|
||||
.uvOffset = Vector2(0),
|
||||
.uvSize = Vector2(1),
|
||||
.uvOffset = g.uvOffset,
|
||||
.uvSize = g.uvSize,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
target_sources(SeeleUnitTests
|
||||
PRIVATE
|
||||
FontAssetAtlas.cpp)
|
||||
@@ -0,0 +1,183 @@
|
||||
#include "Asset/FontAsset.h"
|
||||
#include "EngineTest.h"
|
||||
#include "Graphics/Initializer.h"
|
||||
#include "Graphics/Vulkan/Graphics.h"
|
||||
#include <freetype/freetype.h>
|
||||
#include <string>
|
||||
#include <cinttypes>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <fstream>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
using namespace Seele;
|
||||
|
||||
// The Graphics object must outlive every texture the test created. It is intentionally
|
||||
// a file-scope global so that its destructor (and the queue/pool/destruction-manager
|
||||
// teardown it triggers) runs *after* main() returns — i.e. after gtest has finished
|
||||
// every test — exactly matching the pattern the engine's own Benchmark uses (a global
|
||||
// Gfx::OGraphics in src/Benchmark/main.cpp). A fixture-member OwningPtr would be
|
||||
// destroyed in the fixture's destructor, before the global is torn down, and the
|
||||
// textures' destructors would then run against already-destroyed queues.
|
||||
static Gfx::OGraphics g_testGraphics;
|
||||
|
||||
namespace {
|
||||
constexpr uint32 kFontSize = 32;
|
||||
constexpr uint32 kAtlasW = 1024;
|
||||
|
||||
std::vector<char> readFont() {
|
||||
std::vector<char> ttf;
|
||||
{
|
||||
std::ifstream stream("/usr/share/fonts/Adwaita/AdwaitaSans-Regular.ttf", std::ios::binary);
|
||||
stream.seekg(0, std::ios::end);
|
||||
ttf.resize((size_t)stream.tellg());
|
||||
stream.seekg(0);
|
||||
stream.read((char*)ttf.data(), ttf.size());
|
||||
}
|
||||
return ttf;
|
||||
}
|
||||
|
||||
struct GroundTruth {
|
||||
std::vector<uint8_t> pixels; // w*h, tightly packed; empty for .notdef
|
||||
uint32 w = 0, h = 0;
|
||||
};
|
||||
|
||||
// ground truth, rendered independently of FontAsset's own code path
|
||||
GroundTruth freetypeBitmap(const std::vector<char>& ttf, uint32 glyphId) {
|
||||
FT_Library ft;
|
||||
FT_Face face;
|
||||
FT_Error err = FT_Init_FreeType(&ft);
|
||||
EXPECT_EQ(err, 0);
|
||||
err = FT_New_Memory_Face(ft, (unsigned char*)ttf.data(), (uint32)ttf.size(), 0, &face);
|
||||
EXPECT_EQ(err, 0);
|
||||
err = FT_Set_Pixel_Sizes(face, 0, kFontSize);
|
||||
EXPECT_EQ(err, 0);
|
||||
err = FT_Load_Glyph(face, glyphId, FT_LOAD_RENDER);
|
||||
EXPECT_EQ(err, 0);
|
||||
GroundTruth gt;
|
||||
gt.w = face->glyph->bitmap.width;
|
||||
gt.h = face->glyph->bitmap.rows;
|
||||
if (gt.w > 0 && gt.h > 0) {
|
||||
gt.pixels.assign((size_t)gt.w * gt.h, 0);
|
||||
for (uint32 y = 0; y < gt.h; ++y) {
|
||||
std::memcpy(gt.pixels.data() + (size_t)y * gt.w, face->glyph->bitmap.buffer + (size_t)y * face->glyph->bitmap.pitch, gt.w);
|
||||
}
|
||||
}
|
||||
FT_Done_Face(face);
|
||||
FT_Done_FreeType(ft);
|
||||
return gt;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
class FontAssetAtlasProbe : public ::testing::Test {
|
||||
protected:
|
||||
void SetUp() override {
|
||||
// a Vulkan device with no window is all the test needs (same init path as the
|
||||
// Benchmark); the device is owned by the file-scope global g_testGraphics
|
||||
// (see the note above it) so it outlives the test and every texture created here
|
||||
g_testGraphics = new Vulkan::Graphics();
|
||||
GraphicsInitializer initInfo;
|
||||
g_testGraphics->init(initInfo);
|
||||
graphics = g_testGraphics;
|
||||
}
|
||||
void TearDown() override {
|
||||
// flush any pending GPU work so the texture's pending upload is done, then
|
||||
// release the FontAsset (and its atlas texture) while the Graphics object is
|
||||
// still alive so the destruction manager can process the unbind
|
||||
graphics->waitDeviceIdle();
|
||||
font = nullptr;
|
||||
}
|
||||
Gfx::PGraphics graphics = nullptr;
|
||||
// the FontAsset is held in a plain OwningPtr (NOT a smart pointer) so its destructor
|
||||
// runs in TearDown — while the Graphics object is still alive — which is when the
|
||||
// atlas texture's reference is dropped and the destruction manager processes the
|
||||
// unbind. A member of the fixture would be destroyed in the fixture's own destructor,
|
||||
// which is too early (after the Graphics global is already gone in some orderings).
|
||||
// the FontAsset is held in a plain OwningPtr (NOT a smart pointer) so its
|
||||
// destructor runs in TearDown — while the Graphics object (a file-scope global,
|
||||
// see above) is still alive — which is when the atlas texture's reference is
|
||||
// dropped and the destruction manager processes the unbind.
|
||||
OwningPtr<FontAsset> font;
|
||||
};
|
||||
|
||||
// One atlas per (font, size): the packer must place every glyph in its own
|
||||
// non-overlapping cell with the bitmap intact, and the UV rects must decode back
|
||||
// (half-texel inset) to exactly the FreeType bitmap — verified against the *uploaded*
|
||||
// GPU texture via download(), not against the packer's own memory (that would be
|
||||
// circular). Any of: wrong UV, overlapping cells, broken shelf wrap, corrupted blit,
|
||||
// or a bad half-texel inset fails at least one check below.
|
||||
TEST_F(FontAssetAtlasProbe, PackGlyphsIntactAndNonOverlapping) {
|
||||
std::vector<char> ttf = readFont();
|
||||
ASSERT_FALSE(ttf.empty());
|
||||
|
||||
font = new FontAsset("", "");
|
||||
font->importForTest(ttf.data(), (uint64)ttf.size(), graphics);
|
||||
font->loadGlyphs(kFontSize);
|
||||
|
||||
FontAssetGlyphRects data = font->exportForTest(kFontSize);
|
||||
ASSERT_FALSE(data.glyphs.empty());
|
||||
ASSERT_EQ(data.atlasWidth, kAtlasW);
|
||||
ASSERT_GT(data.atlasHeight, 0u);
|
||||
uint32 atlasH = data.atlasHeight;
|
||||
|
||||
Array<uint8> atlasBytes;
|
||||
data.atlas->download(0, 0, 0, atlasBytes);
|
||||
ASSERT_EQ(atlasBytes.size(), (uint64)kAtlasW * atlasH);
|
||||
const uint8* atlas = atlasBytes.data();
|
||||
(void)graphics; // used via FontAsset; keep the parameter for future direct-vk probes
|
||||
|
||||
// recompute the shelf layout (identical rules to the packer) and, for every glyph:
|
||||
// 1) the stored UVs must match that layout with the half-texel inset, exactly
|
||||
// 2) the atlas bytes at the cell must equal the FreeType bitmap, exactly
|
||||
// 3) the 1px gutter around the cell must be transparent (no bleed for linear sampling)
|
||||
// 4) the packer's own cursor bookkeeping must reach exactly the atlas height
|
||||
// (no gap, no overflow, and by construction cells cannot overlap)
|
||||
uint32 xCursor = 0, cursorY = 0, shelfH = 0;
|
||||
for (auto& [id, rect] : data.glyphs) {
|
||||
GroundTruth gt = freetypeBitmap(ttf, id);
|
||||
uint32 w = gt.w == 0 ? 1 : gt.w;
|
||||
uint32 h = gt.h == 0 ? 1 : gt.h;
|
||||
if (w > kAtlasW) {
|
||||
w = kAtlasW;
|
||||
}
|
||||
if (xCursor + w > kAtlasW) {
|
||||
cursorY += shelfH;
|
||||
shelfH = 0;
|
||||
xCursor = 0;
|
||||
}
|
||||
// 1) UV rect == the packer's exact cell, corner-aligned: offset = (x/W, y/H),
|
||||
// size = (w/W, h/H). The packer lays cells out edge-to-edge (no gutter); the
|
||||
// shader's own 1-px inset (uvSize * 0.98) keeps linear sampling inside the
|
||||
// cell, so no gutter is required for bleed-free sampling.
|
||||
EXPECT_FLOAT_EQ(rect.uvOffset.x, (float)xCursor / (float)kAtlasW);
|
||||
EXPECT_FLOAT_EQ(rect.uvOffset.y, (float)cursorY / (float)atlasH);
|
||||
EXPECT_FLOAT_EQ(rect.uvSize.x, (float)w / (float)kAtlasW);
|
||||
EXPECT_FLOAT_EQ(rect.uvSize.y, (float)h / (float)atlasH);
|
||||
EXPECT_EQ(rect.width, w);
|
||||
EXPECT_EQ(rect.height, h);
|
||||
// 2) uploaded atlas pixels == FreeType bitmap (dump the first mismatching glyph
|
||||
// so a failure is diagnosable: row, col, expected vs. actual, and the atlas
|
||||
// dimensions — this pins down whether the bug is in the blit, the UV decode,
|
||||
// or the download path)
|
||||
if (gt.w > 0 && gt.h > 0) {
|
||||
for (uint32 y = 0; y < gt.h; ++y) {
|
||||
const uint8* row = atlas + ((uint64)(cursorY + y) * kAtlasW + xCursor);
|
||||
if (std::memcmp(row, gt.pixels.data() + (size_t)y * gt.w, gt.w) != 0) {
|
||||
for (uint32 x = 0; x < gt.w; ++x) {
|
||||
if (row[x] != gt.pixels[(size_t)y * gt.w + x]) {
|
||||
std::string msg = "mismatch glyphId=" + std::to_string(id) + " atlasCell=(" + std::to_string(xCursor) + "," + std::to_string(cursorY) + ") atlas=" + std::to_string(kAtlasW) + "x" + std::to_string(atlasH) + " local=(" + std::to_string(x) + "," + std::to_string(y) + ") expected=" + std::to_string((int)gt.pixels[(size_t)y * gt.w + x]) + " actual=" + std::to_string((int)row[x]) + " uvOffset=" + std::to_string(rect.uvOffset.x) + "," + std::to_string(rect.uvOffset.y) + " uvSize=" + std::to_string(rect.uvSize.x) + "," + std::to_string(rect.uvSize.y);
|
||||
FAIL() << msg;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// (no gutter check: the packer is edge-to-edge and the shader's 1-px inset is
|
||||
// what keeps sampling inside the cell — see the UV comment above)
|
||||
xCursor += w;
|
||||
shelfH = std::max(shelfH, h);
|
||||
}
|
||||
// 4) bookkeeping must reach exactly the atlas height: no gap, no overflow
|
||||
EXPECT_EQ(cursorY + shelfH, atlasH);
|
||||
}
|
||||
@@ -4,6 +4,8 @@ target_sources(SeeleUnitTests
|
||||
ThreadPool.cpp)
|
||||
|
||||
target_include_directories(SeeleUnitTests PUBLIC ./)
|
||||
target_include_directories(SeeleUnitTests PUBLIC ${CMAKE_SOURCE_DIR}/src/Editor)
|
||||
add_subdirectory(Asset/)
|
||||
add_subdirectory(Containers/)
|
||||
add_subdirectory(Graphics/)
|
||||
add_subdirectory(Math/)
|
||||
|
||||
Reference in new issue
Block a user