summaryrefslogtreecommitdiff
path: root/in_practice/breakout/texture.c
diff options
context:
space:
mode:
Diffstat (limited to 'in_practice/breakout/texture.c')
-rw-r--r--in_practice/breakout/texture.c70
1 files changed, 70 insertions, 0 deletions
diff --git a/in_practice/breakout/texture.c b/in_practice/breakout/texture.c
new file mode 100644
index 0000000..ac672f3
--- /dev/null
+++ b/in_practice/breakout/texture.c
@@ -0,0 +1,70 @@
+#include "texture.h"
+#include "sys.h"
+#include <string.h>
+#define STB_IMAGE_IMPLEMENTATION
+#include "stb_image.h"
+
+gl_texture_t textures[MAX_TEXTURES] = {0};
+
+void generate_texture(gl_texture_t *texture, u32 width, u32 height, void *data)
+{
+ texture->width = width;
+ texture->height = height;
+ glGenTextures(1, &texture->id);
+ glBindTexture(GL_TEXTURE_2D, texture->id);
+ glTexImage2D(GL_TEXTURE_2D, 0, texture->internal_format, width, height, 0, texture->image_format, GL_UNSIGNED_BYTE, data);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, texture->wrap_s);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, texture->wrap_t);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, texture->min_filter);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, texture->mag_filter);
+ glBindTexture(GL_TEXTURE_2D, 0);
+}
+
+gl_texture_t load_texture(const char *dir, const char *filename, const char *name, i32 alpha)
+{
+ gl_texture_t texture = {0};
+ if (get_texture_id(name)) {
+ info("texture with name \"%s\" already exist", name);
+ return texture;
+ }
+ texture = (gl_texture_t)DEFAULT_TEXTURE;
+ texture.name = name;
+ if (alpha) {
+ texture.internal_format = GL_RGBA;
+ texture.image_format = GL_RGBA;
+ }
+ char path[512] = {0};
+ snprintf(path, 512, "%s/%s", (dir ? dir : "."), filename);
+ i32 width, height;
+ u8 *data = stbi_load(path, &width, &height, 0, 0);
+ if (!data) {
+ info("failed to load \"%s\"", path);
+ return texture;
+ }
+ generate_texture(&texture, width, height, data);
+ stbi_image_free(data);
+ for (u32 i = 0; i < MAX_TEXTURES; i++) {
+ if (!textures[i].name) {
+ textures[i] = texture;
+ info("texture \"%s\" loaded successfully", path);
+ return textures[i];
+ }
+ }
+ return texture;
+}
+
+u32 get_texture_id(const char *name)
+{
+ for (i32 i = 0; i < MAX_TEXTURES; i++)
+ if (textures[i].name && strstr(textures[i].name, name))
+ return textures[i].id;
+ return 0;
+}
+
+v2 get_texture_size(const char *name)
+{
+ for (i32 i = 0; i < MAX_TEXTURES; i++)
+ if (textures[i].name && strstr(textures[i].name, name))
+ return (v2){textures[i].width, textures[i].height};
+ return (v2){0.0f, 0.0f};
+}