From 9e97d9b80dbe0786fedfa46942bd9308a47bc9be Mon Sep 17 00:00:00 2001 From: cflip Date: Thu, 12 Jan 2023 14:14:17 -0700 Subject: Big improvements to font rendering The previous rasterizing code relied on each row in the font being 8 bits wide, which is not the case with any font wider than 8 pixels. These changes make it possible to properly load the 24px Terminus font, and somehow also fixes incorrect characters in the 12px font. --- font.c | 10 ++++++---- window.c | 4 ++-- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/font.c b/font.c index c1d1e7a..d0d3f72 100644 --- a/font.c +++ b/font.c @@ -9,8 +9,8 @@ SDL_Texture *font_create_texture(SDL_Renderer *renderer, PSFFont *font) { SDL_Texture *result; + const int bytes_per_row = (font->bytes_per_glyph / font->height); const int texture_width = font->num_glyphs * font->width; - const int bits_per_glyph = 8; SDL_Surface *surface = SDL_CreateRGBSurface(0, texture_width, font->height, 32, 0, 0, 0, 0); for (int glyph_idx = 0; glyph_idx < font->num_glyphs; glyph_idx++) { @@ -20,11 +20,12 @@ SDL_Texture *font_create_texture(SDL_Renderer *renderer, PSFFont *font) * TODO: Make it possible for the texture atlas to have more * than one row. */ - int xp = x + glyph_idx * bits_per_glyph; + int xp = x + glyph_idx * font->width; int yp = y; - int bit_idx = 8 - 1 - x; - char current_bit = font->glyph_data[glyph_idx * font->bytes_per_glyph + y] & (1 << bit_idx); + int bit_idx = 7 - (x % 8); + int row_byte_idx = (glyph_idx * font->bytes_per_glyph) + y * bytes_per_row + (x / 8); + char current_bit = font->glyph_data[row_byte_idx] & (1 << bit_idx); ((Uint32*)(surface->pixels))[xp + yp * surface->w] = current_bit ? 0xffffffff : 0; } } @@ -64,6 +65,7 @@ PSFFont font_load(const char *filename) size_t glyph_buffer_size = font.num_glyphs * font.bytes_per_glyph; font.glyph_data = malloc(glyph_buffer_size); + fseek(fp, font.header_size, SEEK_SET); fread(font.glyph_data, font.bytes_per_glyph, font.num_glyphs, fp); font.unicode_desc = NULL; diff --git a/window.c b/window.c index 1c300b7..3ffd748 100644 --- a/window.c +++ b/window.c @@ -19,7 +19,7 @@ void window_init(const char *title, int rows, int cols) if (SDL_Init(SDL_INIT_VIDEO) != 0) fatal_error("Failed to init SDL: %s\n", SDL_GetError()); - font = font_load("terminus/ter-u12n.psf"); + font = font_load("terminus/ter-u24n.psf"); int window_width = cols * font.width; int window_height = rows * font.height; @@ -82,7 +82,7 @@ static void draw_font_text(struct append_buffer *buffer) dstrect.w = font.width; dstrect.h = font.height; - srcrect.x = glyph_index * 8; + srcrect.x = glyph_index * font.width; srcrect.y = 0; srcrect.w = font.width; srcrect.h = font.height; -- cgit v1.2.3