aboutsummaryrefslogtreecommitdiff
path: root/sources/TZR_DirectResourceLoad.c
diff options
context:
space:
mode:
Diffstat (limited to 'sources/TZR_DirectResourceLoad.c')
-rw-r--r--sources/TZR_DirectResourceLoad.c53
1 files changed, 53 insertions, 0 deletions
diff --git a/sources/TZR_DirectResourceLoad.c b/sources/TZR_DirectResourceLoad.c
index 9c7153d..6bbbc5c 100644
--- a/sources/TZR_DirectResourceLoad.c
+++ b/sources/TZR_DirectResourceLoad.c
@@ -6,6 +6,53 @@
#include <SDL2/SDL_rwops.h>
#include <string.h>
+#ifdef TZR_STB_IMAGE
+#define STB_IMAGE_IMPLEMENTATION
+#include "stb_image.h"
+
+SDL_Surface *
+stbi_load_surface(void *src, int size)
+{
+ int width, height, chans;
+ void *const data = stbi_load_from_memory(src, size, &width, &height,
+ &chans, 4);
+ const int pitch = (width * 4 + 3) & ~3;
+
+ if (data == NULL) {
+ fprintf(stderr, "stbi: %s\n", stbi_failure_reason());
+ return NULL;
+ }
+
+ if (chans != 4) {
+ fprintf(stderr, "TZR only supports RGBA images\n");
+ free(data);
+ return NULL;
+ }
+
+#if SDL_BYTEORDER == SDL_LIL_ENDIAN
+ const int rmask = 0x000000ff;
+ const int gmask = 0x0000ff00;
+ const int bmask = 0x00ff0000;
+ const int amask = 0xff000000 * (chans == 4);
+#else
+ const int s = 8 * (chans != 4);
+ const int rmask = 0xff000000 >> s;
+ const int gmask = 0x00ff0000 >> s;
+ const int bmask = 0x0000ff00 >> s;
+ const int amask = 0x000000ff >> s;
+#endif
+
+ SDL_Surface *const surf = SDL_CreateRGBSurfaceFrom(data, width, height, chans * 8, pitch, rmask, gmask, bmask, amask);
+ if (surf == NULL) {
+ sdl_error(0);
+ free(data);
+ return NULL;
+ }
+
+ return surf;
+}
+#endif
+
int
TZR_DirectResourceLoad(TZR_Resource *res, const void *data, int size)
{
@@ -20,12 +67,18 @@ TZR_DirectResourceLoad(TZR_Resource *res, const void *data, int size)
memcpy(res->raw.data, data, size);
break;
case TZR_RES_IMAGE: {
+#ifdef TZR_STB_IMAGE
+ SDL_Surface *const surf = stbi_load_surface((void*)data, size);
+ if (surf == NULL)
+ return -1;
+#else
SDL_RWops *const rw = SDL_RWFromConstMem(data, size);
if (rw == NULL)
return sdl_error(-1);
SDL_Surface *const surf = SDL_LoadBMP_RW(rw, 1);
if (surf == NULL)
return sdl_error(-1);
+#endif
SDL_Texture *const tex =
SDL_CreateTextureFromSurface(___tzr_renderer, surf);
SDL_FreeSurface(surf);