Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
22a90fe07c | ||
|
|
17dc1e4d88 |
No files matched your search
@@ -346,3 +346,5 @@ ASALocalRun/
|
||||
# BeatPulse healthcheck temp database
|
||||
healthchecksdb
|
||||
.DS_Store
|
||||
|
||||
**/generated/**
|
||||
+1
-4
@@ -133,16 +133,13 @@ if(APPLE)
|
||||
endif()
|
||||
|
||||
add_subdirectory(src/)
|
||||
#add_subdirectory(tests/)
|
||||
add_subdirectory(tests/)
|
||||
|
||||
if(WIN32)
|
||||
add_custom_command(TARGET Engine POST_BUILD
|
||||
COMMAND ${CMAKE_COMMAND} -E copy_if_different $<TARGET_RUNTIME_DLLS:Engine> $<TARGET_FILE_DIR:Editor>)
|
||||
endif()
|
||||
|
||||
add_custom_command(TARGET Engine POST_BUILD
|
||||
COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/res $<TARGET_FILE_DIR:Engine>)
|
||||
|
||||
install(
|
||||
TARGETS
|
||||
AssetViewer
|
||||
|
||||
@@ -64,6 +64,130 @@ class ListSyntheticProvider:
|
||||
def has_children(self):
|
||||
return True
|
||||
|
||||
def Tree_SummaryProvider(valobj, internal_dict):
|
||||
size = valobj.GetChildMemberWithName('_size').GetValueAsUnsigned(0)
|
||||
return f"Tree(size={size})"
|
||||
|
||||
class TreeSyntheticProvider:
|
||||
def __init__(self, valobj, internal_dict):
|
||||
self.valobj = valobj
|
||||
self.update()
|
||||
|
||||
def num_children(self):
|
||||
return self.size
|
||||
|
||||
def get_child_index(self, name):
|
||||
try:
|
||||
return int(name.lstrip('[').rstrip(']'))
|
||||
except:
|
||||
return -1
|
||||
|
||||
def get_child_at_index(self, index):
|
||||
if index < 0 or index >= self.size:
|
||||
return None
|
||||
# Collect all nodes via in-order traversal, then return the one at `index`
|
||||
nodes = []
|
||||
self._collect(self.root, nodes)
|
||||
if index >= len(nodes):
|
||||
return None
|
||||
return nodes[index].GetChildMemberWithName('data')
|
||||
|
||||
def _collect(self, node, out):
|
||||
if not node.IsValid():
|
||||
return
|
||||
self._collect(node.GetChildMemberWithName('leftChild'), out)
|
||||
out.append(node)
|
||||
self._collect(node.GetChildMemberWithName('rightChild'), out)
|
||||
|
||||
def update(self):
|
||||
self.root = self.valobj.GetChildMemberWithName('root')
|
||||
self.size = self.valobj.GetChildMemberWithName('_size').GetValueAsUnsigned(0)
|
||||
|
||||
def has_children(self):
|
||||
return True
|
||||
|
||||
def Set_SummaryProvider(valobj, internal_dict):
|
||||
size = valobj.GetChildMemberWithName('_size').GetValueAsUnsigned(0)
|
||||
return f"Set(size={size})"
|
||||
|
||||
class SetSyntheticProvider:
|
||||
def __init__(self, valobj, internal_dict):
|
||||
self.valobj = valobj
|
||||
self.update()
|
||||
|
||||
def num_children(self):
|
||||
return self.size
|
||||
|
||||
def get_child_index(self, name):
|
||||
try:
|
||||
return int(name.lstrip('[').rstrip(']'))
|
||||
except:
|
||||
return -1
|
||||
|
||||
def get_child_at_index(self, index):
|
||||
if index < 0 or index >= self.size:
|
||||
return None
|
||||
nodes = []
|
||||
self._collect(self.root, nodes)
|
||||
if index >= len(nodes):
|
||||
return None
|
||||
return nodes[index].GetChildMemberWithName('data')
|
||||
|
||||
def _collect(self, node, out):
|
||||
if not node.IsValid():
|
||||
return
|
||||
self._collect(node.GetChildMemberWithName('leftChild'), out)
|
||||
out.append(node)
|
||||
self._collect(node.GetChildMemberWithName('rightChild'), out)
|
||||
|
||||
def update(self):
|
||||
self.root = self.valobj.GetChildMemberWithName('root')
|
||||
self.size = self.valobj.GetChildMemberWithName('_size').GetValueAsUnsigned(0)
|
||||
|
||||
def has_children(self):
|
||||
return True
|
||||
|
||||
def Map_SummaryProvider(valobj, internal_dict):
|
||||
size = valobj.GetChildMemberWithName('_size').GetValueAsUnsigned(0)
|
||||
return f"Map(size={size})"
|
||||
|
||||
class MapSyntheticProvider:
|
||||
def __init__(self, valobj, internal_dict):
|
||||
self.valobj = valobj
|
||||
self.update()
|
||||
|
||||
def num_children(self):
|
||||
return self.size
|
||||
|
||||
def get_child_index(self, name):
|
||||
try:
|
||||
return int(name.lstrip('[').rstrip(']'))
|
||||
except:
|
||||
return -1
|
||||
|
||||
def get_child_at_index(self, index):
|
||||
if index < 0 or index >= self.size:
|
||||
return None
|
||||
nodes = []
|
||||
self._collect(self.root, nodes)
|
||||
if index >= len(nodes):
|
||||
return None
|
||||
return nodes[index].GetChildMemberWithName('data')
|
||||
|
||||
def _collect(self, node, out):
|
||||
if not node.IsValid():
|
||||
return
|
||||
self._collect(node.GetChildMemberWithName('leftChild'), out)
|
||||
out.append(node)
|
||||
self._collect(node.GetChildMemberWithName('rightChild'), out)
|
||||
|
||||
def update(self):
|
||||
self.root = self.valobj.GetChildMemberWithName('root')
|
||||
self.size = self.valobj.GetChildMemberWithName('_size').GetValueAsUnsigned(0)
|
||||
|
||||
def has_children(self):
|
||||
return True
|
||||
|
||||
def Vector_SummaryProvider(valobj, internal_dict):
|
||||
# Get the template parameters to determine vector length
|
||||
type_name = valobj.GetTypeName()
|
||||
@@ -93,6 +217,14 @@ def __lldb_init_module(debugger, internal_dict):
|
||||
debugger.HandleCommand('type summary add -F Seele_lldb.List_SummaryProvider -x "^Seele::List<.*>$"')
|
||||
debugger.HandleCommand('type synthetic add -l Seele_lldb.ListSyntheticProvider -x "^Seele::List<.*>$"')
|
||||
|
||||
# Register Set formatter
|
||||
debugger.HandleCommand('type summary add -F Seele_lldb.Set_SummaryProvider -x "^Seele::Set<.*>$"')
|
||||
debugger.HandleCommand('type synthetic add -l Seele_lldb.SetSyntheticProvider -x "^Seele::Set<.*>$"')
|
||||
|
||||
# Register Map formatter
|
||||
debugger.HandleCommand('type summary add -F Seele_lldb.Map_SummaryProvider -x "^Seele::Map<.*>$"')
|
||||
debugger.HandleCommand('type synthetic add -l Seele_lldb.MapSyntheticProvider -x "^Seele::Map<.*>$"')
|
||||
|
||||
# Register Vector formatter
|
||||
debugger.HandleCommand('type summary add -F Seele_lldb.Vector_SummaryProvider -x "^glm::(detail::)?t?vec[234]?<.*>$"')
|
||||
|
||||
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
fonts/
|
||||
@@ -1,65 +0,0 @@
|
||||
import Common;
|
||||
|
||||
struct VertexInput
|
||||
{
|
||||
uint vertexId : SV_VertexID;
|
||||
uint instanceId : SV_InstanceID;
|
||||
};
|
||||
|
||||
struct VertexOutput
|
||||
{
|
||||
float4 position : SV_Position;
|
||||
float2 texCoords : TEXCOORD;
|
||||
uint glyphIndex : GLYPHINDEX;
|
||||
};
|
||||
|
||||
struct GlyphInstanceData
|
||||
{
|
||||
float x;
|
||||
float y;
|
||||
float z;
|
||||
float width;
|
||||
float height;
|
||||
uint glyphIndex;
|
||||
};
|
||||
struct TextData
|
||||
{
|
||||
StructuredBuffer<GlyphInstanceData> glyphs;
|
||||
SamplerState glyphSampler;
|
||||
Texture2D<float> glyphTextures[];
|
||||
};
|
||||
ParameterBlock<TextData> pText;
|
||||
|
||||
|
||||
[shader("vertex")]
|
||||
VertexOutput vertexMain(VertexInput input)
|
||||
{
|
||||
float xpos = pText.glyphs[input.instanceId].x;
|
||||
float ypos = pText.glyphs[input.instanceId].y;
|
||||
|
||||
float w = pText.glyphs[input.instanceId].width;
|
||||
float h = pText.glyphs[input.instanceId].height;
|
||||
|
||||
const float4 coordinates[4] = {
|
||||
float4(xpos, ypos, 0, 0),
|
||||
float4(xpos, ypos + h, 0, 1),
|
||||
float4(xpos + w, ypos, 1, 0),
|
||||
float4(xpos + w, ypos + h, 1, 1),
|
||||
};
|
||||
float4 vertex = coordinates[input.vertexId];
|
||||
VertexOutput output;
|
||||
output.texCoords = vertex.zw;
|
||||
output.position = mul(pViewParams.projectionMatrix, float4(vertex.xy, pText.glyphs[input.instanceId].z-1, 1));
|
||||
output.glyphIndex = pText.glyphs[input.instanceId].glyphIndex;
|
||||
return output;
|
||||
}
|
||||
|
||||
[shader("fragment")]
|
||||
float4 fragmentMain(
|
||||
float4 position : SV_Position,
|
||||
float2 texCoords : TEXCOORD,
|
||||
uint glyphIndex : GLYPHINDEX
|
||||
) : SV_Target
|
||||
{
|
||||
return float4(0,0,0,pText.glyphTextures[glyphIndex].Sample(pText.glyphSampler, texCoords));
|
||||
}
|
||||
@@ -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
|
||||
@@ -44,7 +46,17 @@ VertexOutput vertexMain(uint vertexId : SV_VertexID, uint instanceId: SV_Instanc
|
||||
float4(xMax, yMax, 1, 1)
|
||||
};
|
||||
VertexOutput output;
|
||||
output.position = mul(pViewParams.projectionMatrix, float4(coordinates[vertexId].xy, style.z-1, 1));
|
||||
// The UI is a 2D overlay in *screen* pixel space (top-left origin, y down).
|
||||
// The 3D scene camera's projectionMatrix is meaningless for these coordinates,
|
||||
// so build a 2D ortho screen->NDC projection from the viewport size instead:
|
||||
// ndcX = (x / W) * 2 - 1
|
||||
// ndcY = 1 - (y / H) * 2 (flip y: screen is top-down, NDC is bottom-up)
|
||||
// The UI must NOT be transformed by pViewParams.projectionMatrix (the 3D camera).
|
||||
float2 ndc = float2(
|
||||
coordinates[vertexId].x * pViewParams.invScreenDimensions.x * 2.0 - 1.0,
|
||||
1.0 - coordinates[vertexId].y * pViewParams.invScreenDimensions.y * 2.0
|
||||
);
|
||||
output.position = float4(ndc, style.z, 1.0);
|
||||
output.texCoords = coordinates[vertexId].zw;
|
||||
output.style = style;
|
||||
return output;
|
||||
@@ -59,5 +71,15 @@ float4 fragmentMain(
|
||||
if(style.textureIndex == -1) {
|
||||
return float4(style.color, style.opacity);
|
||||
}
|
||||
return pParams.textures[style.textureIndex].Sample(pParams.sampler, texCoords.xy);
|
||||
}
|
||||
// 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).
|
||||
// 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);
|
||||
}
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
shaders/
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
textures/
|
||||
+127
-34
@@ -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;
|
||||
|
||||
@@ -45,11 +47,15 @@ UVector2 FontAsset::shapeText(std::string_view view, uint32 fontSize, Array<Rend
|
||||
uint32 num_glyphs;
|
||||
hb_glyph_info_t* glyphs = hb_buffer_get_glyph_infos(buf, &num_glyphs);
|
||||
hb_glyph_position_t* positions = hb_buffer_get_glyph_positions(buf, &num_glyphs);
|
||||
Vector2 min = Vector2(std::numeric_limits<float>::max());
|
||||
Vector2 max = Vector2(std::numeric_limits<float>::lowest());
|
||||
int32 xppem, yppem;
|
||||
hb_font_get_scale(hb_font, &xppem, &yppem);
|
||||
Vector2 cursor = Vector2(0);
|
||||
// Baseline (in pixels, relative to the text block's top-left) = the font's ascender.
|
||||
// FreeType gives it in 1/64-pixel units after FT_Set_Pixel_Sizes; convert to pixels.
|
||||
// Screen space is y-down; the baseline sits `ascender` px *below* the block's top edge.
|
||||
// (FT metrics ascender is positive-up, so the baseline screen y = +ascender in y-down.)
|
||||
float ascenderPx = (float)ft_face->size->metrics.ascender / 64.0f;
|
||||
Vector2 cursor = Vector2(0, ascenderPx);
|
||||
for (uint32 i = 0; i < num_glyphs; ++i) {
|
||||
hb_codepoint_t glyphid = glyphs[i].codepoint;
|
||||
float xOffset = (float)positions[i].x_offset * fontSize / xppem;
|
||||
@@ -58,46 +64,133 @@ UVector2 FontAsset::shapeText(std::string_view view, uint32 fontSize, Array<Rend
|
||||
float yAdvance = (float)positions[i].y_advance * fontSize / yppem;
|
||||
Vector2 position = cursor + Vector2(xOffset, yOffset);
|
||||
Vector2 dimensions = fontSizes[fontSize].glyphs[glyphid].size;
|
||||
render.add(RenderGlyph{
|
||||
.texture = fontSizes[fontSize].glyphs[glyphid].texture,
|
||||
.position = position,
|
||||
.dimensions = dimensions,
|
||||
});
|
||||
// FreeType bitmap_top = distance from the baseline to the TOP of the bitmap
|
||||
// (positive up). In y-down screen space the bitmap's top edge is therefore at
|
||||
// (baselineY - bitmap_top). bearing.x (bitmap_left) shifts the bitmap right of the
|
||||
// pen. This is what was missing: without it every glyph's top sat on the cursor y
|
||||
// (text top), giving top-aligned instead of baseline-aligned text.
|
||||
float bearingX = (float)fontSizes[fontSize].glyphs[glyphid].bearing.x;
|
||||
float bitmapTop = (float)fontSizes[fontSize].glyphs[glyphid].bearing.y;
|
||||
position.x += bearingX;
|
||||
position.y += -bitmapTop;
|
||||
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);
|
||||
min = Vector2(std::min(min.x, position.x), std::min(min.y, position.y));
|
||||
max = Vector2(std::max(max.x, position.x + dimensions.x), std::max(min.y, position.y + dimensions.y));
|
||||
// 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
|
||||
// auto-sized elements would clip descenders. See below.
|
||||
max.x = std::max(max.x, position.x + dimensions.x);
|
||||
}
|
||||
hb_buffer_destroy(buf);
|
||||
return UVector2(max - min);
|
||||
// Width = right-most x extent (glyphs start at x>=0, so max.x is the full width).
|
||||
// Height = line height from the font metrics: ascender (above baseline) plus the
|
||||
// descender depth (FT descender is negative-up => its magnitude is below baseline).
|
||||
// This is the correct auto-size: it fits the whole em, including descenders.
|
||||
float descenderPx = (float)ft_face->size->metrics.descender / 64.0f; // <= 0 (down is negative-up)
|
||||
float lineHeightPx = ascenderPx - descenderPx;
|
||||
if (max.x <= 0.0f) { // empty string
|
||||
return UVector2(0, 0);
|
||||
}
|
||||
return UVector2((uint32)std::ceil(max.x), (uint32)std::ceil(lineHeightPx));
|
||||
}
|
||||
|
||||
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());
|
||||
}
|
||||
glyph.texture = graphics->createTexture2D(TextureCreateInfo{
|
||||
.sourceData =
|
||||
{
|
||||
.size = glyph.textureData.size(),
|
||||
.data = glyph.textureData.data(),
|
||||
},
|
||||
.format = Gfx::SE_FORMAT_R8_UNORM,
|
||||
.width = glyph.size.x,
|
||||
.height = glyph.size.y,
|
||||
.name = "FontGlyph",
|
||||
});
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
data.atlas = graphics->createTexture2D(TextureCreateInfo{
|
||||
.sourceData =
|
||||
{
|
||||
.size = atlasData.size(),
|
||||
.data = atlasData.data(),
|
||||
},
|
||||
.format = Gfx::SE_FORMAT_R8_UNORM,
|
||||
.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
|
||||
@@ -9,26 +9,7 @@
|
||||
using namespace Seele;
|
||||
|
||||
UIPass::UIPass(Gfx::PGraphics graphics, UI::PSystem system) : RenderPass(graphics), system(system) {
|
||||
glyphInstanceBuffer = graphics->createShaderBuffer(ShaderBufferCreateInfo{.name = "GlyphInstanceBuffer"});
|
||||
elementBuffer = graphics->createShaderBuffer(ShaderBufferCreateInfo{.name = "RenderStyleElements"});
|
||||
textDescriptorLayout = graphics->createDescriptorLayout("pText");
|
||||
textDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = GLYPHINSTANCE_NAME,
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
textDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = GLYPHSAMPLER_NAME,
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLER,
|
||||
});
|
||||
textDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = TEXTURES_NAME,
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE,
|
||||
.descriptorCount = 1024,
|
||||
.access = Gfx::SE_DESCRIPTOR_ACCESS_SAMPLE_BIT,
|
||||
});
|
||||
textPipelineLayout = graphics->createPipelineLayout("TextPipeline");
|
||||
textPipelineLayout->addDescriptorLayout(viewParamsLayout);
|
||||
textPipelineLayout->addDescriptorLayout(textDescriptorLayout);
|
||||
|
||||
uiDescriptorLayout = graphics->createDescriptorLayout("pParams");
|
||||
uiDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
@@ -48,7 +29,6 @@ UIPass::UIPass(Gfx::PGraphics graphics, UI::PSystem system) : RenderPass(graphic
|
||||
uiPipelineLayout = graphics->createPipelineLayout("UIPipeline");
|
||||
uiPipelineLayout->addDescriptorLayout(viewParamsLayout);
|
||||
uiPipelineLayout->addDescriptorLayout(uiDescriptorLayout);
|
||||
// todo:
|
||||
}
|
||||
|
||||
UIPass::~UIPass() {}
|
||||
@@ -60,7 +40,6 @@ void UIPass::beginFrame(const Component::Camera& cam, const Component::Transform
|
||||
system->processInput();
|
||||
system->beginFrame(UVector2(viewport->getWidth(), viewport->getHeight()));
|
||||
renderElements = system->render();
|
||||
glyphs.clear();
|
||||
usedTextures.clear();
|
||||
elements.clear();
|
||||
for (auto& render : renderElements) {
|
||||
@@ -80,22 +59,10 @@ 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,
|
||||
});
|
||||
}
|
||||
glyphInstanceBuffer->rotateBuffer(sizeof(GlyphInstanceData) * glyphs.size());
|
||||
glyphInstanceBuffer->updateContents(0, sizeof(GlyphInstanceData) * glyphs.size(), glyphs.data());
|
||||
glyphInstanceBuffer->pipelineBarrier(Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT,
|
||||
Gfx::SE_ACCESS_SHADER_READ_BIT, Gfx::SE_PIPELINE_STAGE_VERTEX_SHADER_BIT);
|
||||
|
||||
textDescriptorLayout->reset();
|
||||
textDescriptorSet = textDescriptorLayout->allocateDescriptorSet();
|
||||
textDescriptorSet->updateBuffer(GLYPHINSTANCE_NAME, 0, glyphInstanceBuffer);
|
||||
textDescriptorSet->updateSampler(GLYPHSAMPLER_NAME, 0, glyphSampler);
|
||||
for (uint32 i = 0; i < usedTextures.size(); ++i) {
|
||||
textDescriptorSet->updateTexture(TEXTURES_NAME, i, usedTextures[i]->getDefaultView());
|
||||
}
|
||||
textDescriptorSet->writeChanges();
|
||||
|
||||
elementBuffer->rotateBuffer(sizeof(RenderElementStyle) * elements.size());
|
||||
elementBuffer->updateContents(0, sizeof(RenderElementStyle) * elements.size(), elements.data());
|
||||
elementBuffer->pipelineBarrier(Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT, Gfx::SE_ACCESS_SHADER_READ_BIT,
|
||||
@@ -103,7 +70,7 @@ void UIPass::beginFrame(const Component::Camera& cam, const Component::Transform
|
||||
uiDescriptorLayout->reset();
|
||||
uiDescriptorSet = uiDescriptorLayout->allocateDescriptorSet();
|
||||
uiDescriptorSet->updateBuffer(ELEMENT_NAME, 0, elementBuffer);
|
||||
uiDescriptorSet->updateSampler(GLYPHSAMPLER_NAME, 0, glyphSampler);
|
||||
uiDescriptorSet->updateSampler(GLYPHSAMPLER_NAME, 0, uiSampler);
|
||||
for (uint32 i = 0; i < usedTextures.size(); ++i) {
|
||||
uiDescriptorSet->updateTexture(TEXTURES_NAME, i, usedTextures[i]->getDefaultView());
|
||||
}
|
||||
@@ -113,7 +80,7 @@ void UIPass::beginFrame(const Component::Camera& cam, const Component::Transform
|
||||
void UIPass::render() {
|
||||
graphics->beginRenderPass(renderPass);
|
||||
Array<Gfx::ORenderCommand> commands;
|
||||
Gfx::ORenderCommand command = graphics->createRenderCommand("TextPassCommand");
|
||||
Gfx::ORenderCommand command = graphics->createRenderCommand("UIPassCommand");
|
||||
command->setViewport(viewport);
|
||||
command->bindPipeline(uiPipeline);
|
||||
command->bindDescriptor({viewParamsSet, uiDescriptorSet});
|
||||
@@ -175,52 +142,15 @@ void UIPass::createRenderPass() {
|
||||
Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
|
||||
},
|
||||
};
|
||||
renderPass = graphics->createRenderPass(std::move(layout), dependency, viewport->getRenderArea(), "TextPass");
|
||||
renderPass = graphics->createRenderPass(std::move(layout), dependency, viewport->getRenderArea(), "UIPass");
|
||||
|
||||
graphics->beginShaderCompilation(ShaderCompilationInfo{
|
||||
.name = "TextVertex",
|
||||
.modules = {"TextPass"},
|
||||
.entryPoints = {{"vertexMain", "TextPass"}, {"fragmentMain", "TextPass"}},
|
||||
.rootSignature = textPipelineLayout,
|
||||
});
|
||||
textPipelineLayout->create();
|
||||
textVertexShader = graphics->createVertexShader({0});
|
||||
textFragmentShader = graphics->createFragmentShader({1});
|
||||
|
||||
glyphSampler = graphics->createSampler({
|
||||
uiSampler = graphics->createSampler({
|
||||
.magFilter = Gfx::SE_FILTER_LINEAR,
|
||||
.minFilter = Gfx::SE_FILTER_LINEAR,
|
||||
.addressModeU = Gfx::SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
|
||||
.addressModeV = Gfx::SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
|
||||
});
|
||||
|
||||
textPipeline = graphics->createGraphicsPipeline(Gfx::LegacyPipelineCreateInfo{
|
||||
.topology = Gfx::SE_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP,
|
||||
.vertexShader = textVertexShader,
|
||||
.fragmentShader = textFragmentShader,
|
||||
.renderPass = renderPass,
|
||||
.pipelineLayout = textPipelineLayout,
|
||||
.rasterizationState =
|
||||
{
|
||||
.cullMode = Gfx::SE_CULL_MODE_NONE,
|
||||
},
|
||||
.colorBlend =
|
||||
{
|
||||
|
||||
.attachmentCount = 1,
|
||||
.blendAttachments = {{
|
||||
.blendEnable = true,
|
||||
.srcColorBlendFactor = Gfx::SE_BLEND_FACTOR_SRC_ALPHA,
|
||||
.dstColorBlendFactor = Gfx::SE_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
|
||||
.srcAlphaBlendFactor = Gfx::SE_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
|
||||
.dstAlphaBlendFactor = Gfx::SE_BLEND_FACTOR_ZERO,
|
||||
.alphaBlendOp = Gfx::SE_BLEND_OP_ADD,
|
||||
.colorWriteMask = Gfx::SE_COLOR_COMPONENT_R_BIT | Gfx::SE_COLOR_COMPONENT_G_BIT | Gfx::SE_COLOR_COMPONENT_B_BIT |
|
||||
Gfx::SE_COLOR_COMPONENT_A_BIT,
|
||||
}},
|
||||
},
|
||||
});
|
||||
|
||||
graphics->beginShaderCompilation(ShaderCompilationInfo{
|
||||
.name = "UIVertex",
|
||||
.modules = {"UIPass"},
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
#pragma once
|
||||
#include "Graphics/Shader.h"
|
||||
#include "RenderPass.h"
|
||||
#include "Asset/FontAsset.h"
|
||||
#include "UI/System.h"
|
||||
|
||||
namespace Seele {
|
||||
@@ -28,20 +27,6 @@ class UIPass : public RenderPass {
|
||||
void key(KeyCode code, InputAction action, KeyModifierFlags modifier, char text = 0) { system->key(code, action, (KeyModifier)modifier, text); }
|
||||
|
||||
private:
|
||||
struct GlyphData {
|
||||
Vector2 bearing;
|
||||
Vector2 size;
|
||||
uint32 advance;
|
||||
};
|
||||
struct GlyphInstanceData {
|
||||
float x;
|
||||
float y;
|
||||
float z;
|
||||
float width;
|
||||
float height;
|
||||
uint32 glyphIndex;
|
||||
};
|
||||
|
||||
struct RenderElementStyle {
|
||||
float x;
|
||||
float y;
|
||||
@@ -51,22 +36,16 @@ 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;
|
||||
Gfx::RenderTargetAttachment depthAttachment;
|
||||
Gfx::OTexture2D depthBuffer;
|
||||
|
||||
Gfx::ODescriptorLayout textDescriptorLayout;
|
||||
Gfx::ODescriptorSet textDescriptorSet;
|
||||
|
||||
Gfx::OVertexShader textVertexShader;
|
||||
Gfx::OFragmentShader textFragmentShader;
|
||||
Gfx::OPipelineLayout textPipelineLayout;
|
||||
Gfx::PGraphicsPipeline textPipeline;
|
||||
|
||||
Gfx::ODescriptorLayout uiDescriptorLayout;
|
||||
Gfx::ODescriptorSet uiDescriptorSet;
|
||||
|
||||
@@ -79,13 +58,10 @@ class UIPass : public RenderPass {
|
||||
|
||||
UI::PSystem system;
|
||||
Array<UI::UIRender> renderElements;
|
||||
Array<GlyphInstanceData> glyphs;
|
||||
Array<RenderElementStyle> elements;
|
||||
Gfx::OShaderBuffer glyphInstanceBuffer;
|
||||
constexpr static const char* GLYPHINSTANCE_NAME = "glyphData";
|
||||
Gfx::OShaderBuffer elementBuffer;
|
||||
constexpr static const char* ELEMENT_NAME = "elements";
|
||||
Gfx::OSampler glyphSampler;
|
||||
Gfx::OSampler uiSampler;
|
||||
constexpr static const char* GLYPHSAMPLER_NAME = "glyphSampler";
|
||||
Array<Gfx::PTexture2D> usedTextures;
|
||||
constexpr static const char* TEXTURES_NAME = "textures";
|
||||
|
||||
@@ -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