7 #include "sdl/renderer.h"
8 #include "sprite_font.h"
9 #include "system/error.h"
10 #include "system/lt.h"
11 #include "system/nth_alloc.h"
13 #define FONT_ROW_SIZE 18
21 Sprite_font *create_sprite_font_from_file(const char *bmp_file_path,
22 SDL_Renderer *renderer)
24 assert(bmp_file_path);
27 Lt * const lt = create_lt();
32 Sprite_font * const sprite_font = PUSH_LT(lt, nth_alloc(sizeof(Sprite_font)), free);
33 if (sprite_font == NULL) {
34 throw_error(ERROR_TYPE_LIBC);
38 SDL_Surface * const surface = PUSH_LT(lt, SDL_LoadBMP(bmp_file_path), SDL_FreeSurface);
39 if (surface == NULL) {
40 throw_error(ERROR_TYPE_SDL2);
44 if (SDL_SetColorKey(surface,
46 SDL_MapRGB(surface->format,
48 throw_error(ERROR_TYPE_SDL2);
52 sprite_font->texture = PUSH_LT(
54 SDL_CreateTextureFromSurface(renderer, surface),
56 if (sprite_font->texture == NULL) {
57 throw_error(ERROR_TYPE_SDL2);
61 SDL_FreeSurface(RELEASE_LT(lt, surface));
68 void destroy_sprite_font(Sprite_font *sprite_font)
71 RETURN_LT0(sprite_font->lt);
74 static SDL_Rect sprite_font_char_rect(const Sprite_font *sprite_font, char x)
78 if (32 <= x && x <= 126) {
79 const SDL_Rect rect = {
80 .x = ((x - 32) % FONT_ROW_SIZE) * FONT_CHAR_WIDTH,
81 .y = ((x - 32) / FONT_ROW_SIZE) * FONT_CHAR_HEIGHT,
87 return sprite_font_char_rect(sprite_font, '?');
91 int sprite_font_render_text(const Sprite_font *sprite_font,
92 SDL_Renderer *renderer,
102 const SDL_Color sdl_color = color_for_sdl(color);
104 if (SDL_SetTextureColorMod(sprite_font->texture, sdl_color.r, sdl_color.g, sdl_color.b) < 0) {
105 throw_error(ERROR_TYPE_SDL2);
109 if (SDL_SetTextureAlphaMod(sprite_font->texture, sdl_color.a) < 0) {
110 throw_error(ERROR_TYPE_SDL2);
114 const size_t text_size = strlen(text);
115 for (size_t i = 0; i < text_size; ++i) {
116 const SDL_Rect char_rect = sprite_font_char_rect(sprite_font, text[i]);
117 const SDL_Rect dest_rect = rect_for_sdl(
119 position.x + (float) FONT_CHAR_WIDTH * (float) i * size.x,
121 (float) char_rect.w * size.x,
122 (float) char_rect.h * size.y));
123 if (SDL_RenderCopy(renderer, sprite_font->texture, &char_rect, &dest_rect) < 0) {
131 Rect sprite_font_boundary_box(const Sprite_font *sprite_font,
139 position.x, position.y,
140 size.x * FONT_CHAR_WIDTH * (float) strlen(text),
141 size.y * FONT_CHAR_HEIGHT);