Files
Seele/tests/Engine/Asset/FontAssetAtlas.cpp
T

183 lines
8.5 KiB
C++
Raw Normal View History

2026-10-21 21:21:49 +02:00
#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);
}