From d71f3c26c26c22ac6782944f5732274abe64f8f8 Mon Sep 17 00:00:00 2001 From: Riley Beckett Date: Sun, 12 Oct 2025 16:55:23 -0400 Subject: Create atlas for font rendering --- font.c | 64 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) (limited to 'font.c') diff --git a/font.c b/font.c index 9198b3a..2a082b3 100644 --- a/font.c +++ b/font.c @@ -59,6 +59,70 @@ bool init_freetype(client_state* state, const char* file) { fprintf(stderr, "Failed to set font size\n"); return false; } + return true; +} + +bool init_atlas(client_state* state) { + FT_Int32 load_flags = FT_LOAD_RENDER | FT_LOAD_TARGET_(FT_RENDER_MODE_SDF); + for (int i = 32; i < 128; i++) { + if (FT_Load_Char(state->ft_face, i, load_flags)) { + fprintf(stderr, "Failed to render character %c\n", (char)i); + } + printf("%c: %u, %u\n", (char)i, state->ft_face->glyph->bitmap.width, state->ft_face->glyph->bitmap.rows); + state->atlas.width += state->ft_face->glyph->bitmap.width; + state->atlas.height = MAX(state->atlas.height, state->ft_face->glyph->bitmap.rows); + } + + glActiveTexture(GL_TEXTURE0); + glGenTextures(1, &state->atlas.texture); + glBindTexture(GL_TEXTURE_2D, state->atlas.texture); + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + glTexImage2D( + GL_TEXTURE_2D, + 0, + GL_RED, + (GLsizei) state->atlas.width, + (GLsizei) state->atlas.height, + 0, + GL_RED, + GL_UNSIGNED_BYTE, + NULL); + + uint32_t x = 0; + for (int i = 32; i < 128; i++) { + if (FT_Load_Char(state->ft_face, i, load_flags)) { + fprintf(stderr, "Failed to render character %c\n", (char)i); + } + + if (FT_Render_Glyph(state->ft_face->glyph, FT_RENDER_MODE_NORMAL)) { + fprintf(stderr, "ERROR: could not render glyph of a character with code %d\n", i); + } + + state->atlas.metrics[i].advance_x = (float)state->ft_face->glyph->advance.x / 64; + state->atlas.metrics[i].advance_y = (float)state->ft_face->glyph->advance.y / 64; + state->atlas.metrics[i].bitmap_width = state->ft_face->glyph->bitmap.width; + state->atlas.metrics[i].bitmap_height = state->ft_face->glyph->bitmap.rows; + state->atlas.metrics[i].texture_offset = x; + + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + glTexSubImage2D( + GL_TEXTURE_2D, + 0, + x, + 0, + state->ft_face->glyph->bitmap.width, + state->ft_face->glyph->bitmap.rows, + GL_RED, + GL_UNSIGNED_BYTE, + state->ft_face->glyph->bitmap.buffer); + x += state->ft_face->glyph->bitmap.width; + } return true; } -- cgit v1.2.3