slutpet/img.c
2025-05-26 15:02:11 +10:00

88 lines
1.8 KiB
C

#define STB_IMAGE_IMPLEMENTATION
#define STBI_MALLOC(sz) SDL_malloc(sz)
#define STBI_REALLOC(p,newsz) SDL_realloc(p,newsz)
#define STBI_FREE(p) SDL_free(p)
#include <SDL3/SDL.h>
#include "stb_image.h"
#include "dat.h"
#include "fns.h"
void
free_image(Image *i)
{
if (i) {
if (i->tex) {
babble("free img %s texture...", i->name);
SDL_DestroyTexture(i->tex);
}
if (i->sur) {
babble("destroy image %s surface...", i->name);
SDL_DestroySurface(i->sur);
}
if (i->data) {
babble("free img %s data...", i->name);
stbi_image_free(i->data);
}
if (i->name) {
babble("free img %s name...", i->name);
SDL_free(i->name);
}
babble("free aforementioned img...");
SDL_free(i);
}
}
Image *
load_image(SDL_Renderer *ren, char *path)
{
Image *i;
babble("create image %s...", path);
babble("alloc image...", path);
i = SDL_calloc(1, sizeof(Image));
if (!i) {
shit("mem alloc fail: %s", SDL_GetError());
return NULL;
}
babble("alloc image %s name...", path);
i->name = SDL_strdup(path);
if (!i->name) {
shit("strdup fail: %s", SDL_GetError());
free_image(i);
return NULL;
}
babble("alloc image %s data...", i->name);
i->data = stbi_load(path, &i->w, &i->h,
&i->bpp, 4);
if (!i->data) {
shit("img load fail: %s", stbi_failure_reason());
free_image(i);
return NULL;
}
babble("alloc image %s surface...", i->name);
i->sur = SDL_CreateSurfaceFrom(i->w, i->h,
SDL_PIXELFORMAT_RGBA32, i->data,
i->w * 4);
if (!i->sur) {
shit("surface creation fail: %s", SDL_GetError());
free_image(i);
return NULL;
}
babble("alloc image %s texture...", i->name);
i->tex = SDL_CreateTextureFromSurface(ren, i->sur);
if (!i->tex) {
shit("surface creation fail: %s", SDL_GetError());
SDL_DestroySurface(i->sur);
free_image(i);
return NULL;
}
babble("image %s created", path);
return i;
}