diff --git a/include/image.h b/include/image.h new file mode 100644 index 0000000..1250776 --- /dev/null +++ b/include/image.h @@ -0,0 +1,24 @@ +#ifndef IMAGE_H +#define IMAGE_H + +#include "SDL_render.h" +#include "aliases/aliases.h" +#include "window.h" +#include +#include + +typedef struct { + char path[PATH_MAX]; + u64 length; +} path_t; + +typedef struct { + i64 width; + i64 height; + SDL_Texture *texture; + path_t filepath; +} image_t; + +bool load_image(const window_t *wnd, image_t *img, const char *path); + +#endif // !IMAGE_H diff --git a/src/image.c b/src/image.c new file mode 100644 index 0000000..5be2a8e --- /dev/null +++ b/src/image.c @@ -0,0 +1,93 @@ +#include "image.h" +#include "aliases/aliases.h" +#include "window.h" +#include +#include + +#define STREQ(S1, S2) (strcmp(S1, S2) == 0) + +enum file_formats { + EXT_PNG, + EXT_PNG_CAPS, + EXT_JPG, + EXT_JPG_CAPS, + EXT_JPEG, + EXT_JPEG_CAPS, + EXT_TIF, + EXT_TIF_CAPS, + EXT_TIFF, + EXT_TIFF_CAPS, + + COUNT_EXT, +}; + +INTERNAL const char *extensions[COUNT_EXT] = { + // clang-format off + [EXT_PNG] = ".png", + [EXT_PNG_CAPS] = ".PNG", + [EXT_JPG] = ".jpg", + [EXT_JPG_CAPS] = ".JPG", + [EXT_JPEG] = ".jpeg", + [EXT_JPEG_CAPS] = ".JPEG", + [EXT_TIF] = ".tif", + [EXT_TIF_CAPS] = ".TIF", + [EXT_TIFF] = ".tiff", + [EXT_TIFF_CAPS] = ".TIFF", + // clang-format on +}; + +bool valid_image(const char *path) { + for (u64 i = 0; i < COUNT_EXT; ++i) { + char *ext = strrchr(path, '.'); + if (!ext) { + return false; + } + + if (STREQ(ext, extensions[i])) { + return true; + } + } + + return false; +} + +bool load_image(const window_t *wnd, image_t *img, const char *path) { + if (!img || !path) { + return false; + } + + img->filepath.length = strlen(path); + if (img->filepath.length == 0) { + return false; + } + + if (!valid_image(path)) { + return false; + } + + u64 length = strlen(img->filepath.path); + if (length > 0) { + memset(img->filepath.path, 0, length); + } + + strncpy(img->filepath.path, path, img->filepath.length); + + if (img->texture) { + unload_texture(img->texture); + img->texture = NULL; + } + + img->texture = load_texture(wnd, path); + if (!(img->texture)) { + return false; + } + + i32 w; + i32 h; + get_texture_size(img->texture, &w, &h); + + img->width = w; + img->height = h; + + return true; +}