6 #include "sprite_font.h"
8 #include "system/error.h"
10 #define FONT_ROW_SIZE 18
21 sprite_font_t *create_sprite_font_from_file(const char *bmp_file_path,
22 SDL_Renderer *renderer)
24 assert(bmp_file_path);
26 lt_t *lt = create_lt();
31 sprite_font_t *sprite_font = PUSH_LT(lt, malloc(sizeof(sprite_font_t)), free);
32 if (sprite_font == NULL) {
33 throw_error(ERROR_TYPE_LIBC);
37 sprite_font->surface = PUSH_LT(lt, SDL_LoadBMP(bmp_file_path), SDL_FreeSurface);
38 if (sprite_font->surface == NULL) {
39 throw_error(ERROR_TYPE_SDL2);
43 sprite_font->texture = PUSH_LT(
45 SDL_CreateTextureFromSurface(renderer, sprite_font->surface),
47 if (sprite_font->texture == NULL) {
48 throw_error(ERROR_TYPE_SDL2);
57 void destroy_sprite_font(sprite_font_t *sprite_font)
60 RETURN_LT0(sprite_font->lt);
63 static SDL_Rect sprite_font_char_rect(const sprite_font_t *sprite_font, char x)
67 if (32 <= x && x <= 126) {
68 const SDL_Rect rect = {
69 .x = ((x - 32) % FONT_ROW_SIZE) * CHAR_WIDTH,
70 .y = ((x - 32) / FONT_ROW_SIZE) * CHAR_HEIGHT,
76 return sprite_font_char_rect(sprite_font, '?');
80 int sprite_font_render_text(const sprite_font_t *sprite_font,
81 SDL_Renderer *renderer,
90 const size_t text_size = strlen(text);
91 const int px = (int) roundf(position.x);
92 const int py = (int) roundf(position.y);
93 for (size_t i = 0; i < text_size; ++i) {
94 const SDL_Rect char_rect = sprite_font_char_rect(sprite_font, text[i]);
95 const SDL_Rect dest_rect = {
96 .x = px + CHAR_WIDTH * (int) i * size,
98 .w = char_rect.w * size,
99 .h = char_rect.h * size
101 if (SDL_RenderCopy(renderer, sprite_font->texture, &char_rect, &dest_rect) < 0) {
108 int sprite_font_debug_render_whole_texture(const sprite_font_t *sprite_font,
109 SDL_Renderer *renderer,
115 if (SDL_QueryTexture(sprite_font->texture, NULL, NULL, &texW, &texH) < 0) {
116 throw_error(ERROR_TYPE_SDL2);
120 const SDL_Rect dstrect = { (int) position.x, (int) position.y, texW, texH };
122 if (SDL_RenderCopy(renderer, sprite_font->texture, NULL, &dstrect) < 0) {
123 throw_error(ERROR_TYPE_SDL2);