Font:getWidth;

This commit is contained in:
bjorn 2022-06-30 17:25:47 -07:00
parent 4125b1dc7e
commit 9e7bd34ab1
3 changed files with 53 additions and 0 deletions

View File

@ -118,6 +118,16 @@ static int l_lovrFontGetLines(lua_State* L) {
return 1;
}
static int l_lovrFontGetWidth(lua_State* L) {
Font* font = luax_checktype(L, 1, Font);
uint32_t count;
ColoredString stack;
ColoredString* strings = luax_checkcoloredstrings(L, 2, &count, &stack);
float width = lovrFontGetWidth(font, strings, count);
lua_pushnumber(L, width);
return 1;
}
const luaL_Reg lovrFont[] = {
{ "getRasterizer", l_lovrFontGetRasterizer },
{ "getPixelDensity", l_lovrFontGetPixelDensity },
@ -128,6 +138,7 @@ const luaL_Reg lovrFont[] = {
{ "getDescent", l_lovrFontGetDescent },
{ "getHeight", l_lovrFontGetHeight },
{ "getKerning", l_lovrFontGetKerning },
{ "getWidth", l_lovrFontGetWidth },
{ "getLines", l_lovrFontGetLines },
{ NULL, NULL }
};

View File

@ -1992,6 +1992,47 @@ float lovrFontGetKerning(Font* font, uint32_t left, uint32_t right) {
return kerning.f32;
}
float lovrFontGetWidth(Font* font, ColoredString* strings, uint32_t count) {
float x = 0.f;
float maxWidth = 0.f;
float space = lovrFontGetGlyph(font, ' ', NULL)->advance;
for (uint32_t i = 0; i < count; i++) {
size_t bytes;
uint32_t codepoint;
uint32_t previous = '\0';
const char* str = strings[i].string;
const char* end = strings[i].string + strings[i].length;
while ((bytes = utf8_decode(str, end, &codepoint)) > 0) {
if (codepoint == ' ' || codepoint == '\t') {
x += codepoint == '\t' ? space * 4.f : space;
previous = '\0';
str += bytes;
continue;
} else if (codepoint == '\n') {
maxWidth = MAX(maxWidth, x);
x = 0.f;
previous = '\0';
str += bytes;
continue;
} else if (codepoint == '\r') {
str += bytes;
continue;
}
Glyph* glyph = lovrFontGetGlyph(font, codepoint, NULL);
if (previous) x += lovrFontGetKerning(font, previous, codepoint);
previous = codepoint;
x += glyph->advance;
str += bytes;
}
}
return MAX(maxWidth, x) / font->pixelDensity;
}
void lovrFontGetLines(Font* font, ColoredString* strings, uint32_t count, float wrap, void (*callback)(void* context, const char* string, size_t length), void* context) {
size_t totalLength = 0;
for (uint32_t i = 0; i < count; i++) {

View File

@ -354,6 +354,7 @@ void lovrFontSetPixelDensity(Font* font, float pixelDensity);
float lovrFontGetLineSpacing(Font* font);
void lovrFontSetLineSpacing(Font* font, float spacing);
float lovrFontGetKerning(Font* font, uint32_t left, uint32_t right);
float lovrFontGetWidth(Font* font, ColoredString* strings, uint32_t count);
void lovrFontGetLines(Font* font, ColoredString* strings, uint32_t count, float wrap, void (*callback)(void* context, const char* string, size_t length), void* context);
// Pass