#include "texture.h" #include "log.h" int text_texture_init(text_texture* text_texture, SDL_Renderer* renderer, int font_size) { text_texture->texture = NULL; text_texture->renderer = renderer; text_texture->font = TTF_OpenFont("FiraCode-Regular.ttf", font_size); if (!text_texture->font) { log_message(LOG_ERROR, "Failed to load font! TTF_Error: %s", TTF_GetError()); return 0; } text_texture->width = 0; text_texture->height = 0; return 1; } int text_texture_load(text_texture* text_texture, char* string) { if (text_texture->texture) { SDL_DestroyTexture(text_texture->texture); text_texture->texture = NULL; } SDL_Color text_color = { 255, 255, 255 }; if (strlen(string) == 0) string = " "; SDL_Surface* text_surface = TTF_RenderText_Solid(text_texture->font, string, text_color); if (!text_surface) { log_message(LOG_ERROR, "Unable to render text surface! TTF_Error: %s", TTF_GetError()); return 0; } SDL_Texture* texture = SDL_CreateTextureFromSurface(text_texture->renderer, text_surface); if (!texture) { log_message(LOG_ERROR, "Unable to create texture from rendered text! SDL_Error: %s", SDL_GetError()); return 0; } text_texture->texture = texture; text_texture->width = text_surface->w; text_texture->height = text_surface->h; SDL_FreeSurface(text_surface); return 1; } int text_texture_render(text_texture* text_texture, int x, int y) { if (!text_texture) { log_message(LOG_ERROR, "text_texture uninitialized"); return 0; } if (!text_texture->texture) { log_message(LOG_ERROR, "text_texture->texture uninitialized"); return 0; } int quad_width = text_texture->width; int quad_height = text_texture->height; SDL_Rect render_quad = { x, y, quad_width, quad_height }; SDL_RenderCopy(text_texture->renderer, text_texture->texture, NULL, &render_quad); return 1; } void text_texture_destroy(text_texture* text_texture) { if (!text_texture->texture) { return; } SDL_DestroyTexture(text_texture->texture); TTF_CloseFont(text_texture->font); } int text_texture_frame_init(text_texture_frame* text_texture_frame, int len, SDL_Renderer* renderer, int font_size) { text_texture_frame->textures = malloc(len*sizeof(text_texture)); for (int i = 0; i < len; i++) { text_texture_init(&text_texture_frame->textures[i], renderer, font_size); text_texture_load(&text_texture_frame->textures[i], ""); } text_texture_frame->len = len; return 1; } int text_texture_frame_render(text_texture_frame* text_texture_frame, int x, int y) { int text_y_offset_step = TTF_FontHeight(text_texture_frame->textures[0].font); int text_y_offset = y; for (int i = 0; i < text_texture_frame->len; i++) { text_texture_render(&text_texture_frame->textures[i], x, text_y_offset); text_y_offset += text_y_offset_step; } return 1; } void text_texture_frame_destroy(text_texture_frame* text_texture_frame) { for (int i = 0; i < text_texture_frame->len; i++) { text_texture_destroy(&text_texture_frame->textures[i]); } free(text_texture_frame->textures); text_texture_frame->textures = NULL; }