From 51d85c011b718af9fb465e650a94a866769443a2 Mon Sep 17 00:00:00 2001 From: cat Date: Sun, 25 May 2025 14:40:05 +1000 Subject: [PATCH] image display test bring your own test.png --- dat.h | 11 ++++++++++ slutpet.c | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+) diff --git a/dat.h b/dat.h index 09895e0..0a724de 100644 --- a/dat.h +++ b/dat.h @@ -1,5 +1,16 @@ +typedef struct Image Image; +struct Image { + int w; + int h; + int bpp; + unsigned char *data; + SDL_Texture *tex; +}; + typedef struct State State; struct State { SDL_Window *win; SDL_Renderer *ren; + + Image *test; }; diff --git a/slutpet.c b/slutpet.c index 01b4d33..3e4f934 100644 --- a/slutpet.c +++ b/slutpet.c @@ -9,6 +9,26 @@ void SDL_AppQuit(void *as, SDL_AppResult res) { + State *st; + + st = as; + if (st) { + if (st->test) { + if (st->test->tex) { + SDL_Log("free test texture..."); + SDL_DestroyTexture(st->test->tex); + } + if (st->test->data) { + SDL_Log("free test img data..."); + SDL_free(st->test->data); + } + SDL_Log("free test img..."); + SDL_free(st->test); + } + SDL_Log("free state..."); + SDL_free(st); + } + SDL_Log("bye!"); return; } @@ -29,6 +49,13 @@ SDL_AppEvent(void *as, SDL_Event *ev) SDL_AppResult SDL_AppIterate(void *as) { + State *st = as; + + SDL_SetRenderDrawColor(st->ren, 0, 0, 0, SDL_ALPHA_TRANSPARENT); + SDL_RenderClear(st->ren); + + SDL_RenderTexture(st->ren, st->test->tex, NULL, NULL); + SDL_RenderPresent(st->ren); return SDL_APP_CONTINUE; } @@ -36,6 +63,7 @@ SDL_AppResult SDL_AppInit(void **as, int argc, char **argv) { State *st; + SDL_Surface *sur; SDL_Log("init sdl..."); if (!SDL_Init(SDL_INIT_VIDEO)) { @@ -62,6 +90,39 @@ SDL_AppInit(void **as, int argc, char **argv) return SDL_APP_FAILURE; } + SDL_Log("create test image..."); + st->test = SDL_calloc(1, sizeof(Image)); + if (!st->test) { + SDL_LogCritical(SDL_LOG_CATEGORY_APPLICATION, + "mem alloc fail: %s", SDL_GetError()); + return SDL_APP_FAILURE; + } + + st->test->data = stbi_load("test.png", &st->test->w, &st->test->h, + &st->test->bpp, 4); + if (!st->test->data) { + SDL_LogCritical(SDL_LOG_CATEGORY_APPLICATION, + "mem alloc fail: %s", SDL_GetError()); + return SDL_APP_FAILURE; + } + + sur = SDL_CreateSurfaceFrom(st->test->w, st->test->h, + SDL_PIXELFORMAT_RGBA32, st->test->data, + st->test->w * 4); + if (!sur) { + SDL_LogCritical(SDL_LOG_CATEGORY_APPLICATION, + "surface creation fail: %s", SDL_GetError()); + return SDL_APP_FAILURE; + } + + st->test->tex = SDL_CreateTextureFromSurface(st->ren, sur); + if (!st->test->tex) { + SDL_LogCritical(SDL_LOG_CATEGORY_APPLICATION, + "surface creation fail: %s", SDL_GetError()); + SDL_DestroySurface(sur); + return SDL_APP_FAILURE; + } + SDL_Log("it work"); return SDL_APP_CONTINUE; }