2024-10-13 22:43:33 +08:00
|
|
|
#include "texture.h"
|
2024-10-15 01:36:02 +08:00
|
|
|
#include "log.h"
|
2024-10-13 22:43:33 +08:00
|
|
|
|
|
|
|
int text_texture_init(text_texture* text_texture, SDL_Renderer* renderer)
|
|
|
|
{
|
|
|
|
text_texture->texture = NULL;
|
|
|
|
text_texture->renderer = renderer;
|
|
|
|
text_texture->font = TTF_OpenFont("FiraCode-Regular.ttf", 24);
|
|
|
|
if (!text_texture->font) {
|
2024-10-15 01:36:02 +08:00
|
|
|
log_message(LOG_ERROR, "Failed to load font! TTF_Error: %s", TTF_GetError());
|
2024-10-13 22:43:33 +08:00
|
|
|
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 };
|
|
|
|
SDL_Surface* text_surface = TTF_RenderText_Solid(text_texture->font, string, text_color);
|
|
|
|
if (!text_surface) {
|
2024-10-15 01:36:02 +08:00
|
|
|
log_message(LOG_ERROR, "Unable to render text surface! TTF_Error: %s", TTF_GetError());
|
2024-10-13 22:43:33 +08:00
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
SDL_Texture* texture = SDL_CreateTextureFromSurface(text_texture->renderer, text_surface);
|
|
|
|
if (!texture) {
|
2024-10-15 01:36:02 +08:00
|
|
|
log_message(LOG_ERROR, "Unable to create texture from rendered text! SDL_Error: %s", SDL_GetError());
|
2024-10-13 22:43:33 +08:00
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
text_texture->texture = SDL_CreateTextureFromSurface(text_texture->renderer, text_surface);
|
|
|
|
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) {
|
2024-10-15 01:36:02 +08:00
|
|
|
log_message(LOG_ERROR, "text_texture uninitialized");
|
2024-10-13 22:43:33 +08:00
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
if (!text_texture->texture) {
|
2024-10-15 01:36:02 +08:00
|
|
|
log_message(LOG_ERROR, "text_texture->texture uninitialized");
|
2024-10-13 22:43:33 +08:00
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
|
|
|
int text_texture_free(text_texture* text_texture)
|
|
|
|
{
|
|
|
|
if (!text_texture->texture) {
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
SDL_DestroyTexture(text_texture->texture);
|
|
|
|
return 1;
|
|
|
|
}
|