1 #define STB_IMAGE_IMPLEMENTATION
2 #include <stb/stb_image.h>
4 #include "client/texture.h"
10 __attribute((constructor(101))) static void textures_init()
12 stbi_set_flip_vertically_on_load(true);
14 textures = list_create(&list_compare_string);
17 static void list_delete_texture(unused void *key, void *value, unused void *arg)
19 texture_delete(value);
22 __attribute((destructor)) static void textures_deinit()
24 list_clear_func(&textures, &list_delete_texture, NULL);
27 Texture *texture_create(unsigned char *data, int width, int height, GLenum format)
29 Texture *texture = malloc(sizeof(Texture));
30 texture->width = width;
31 texture->height = height;
33 glGenTextures(1, &texture->id);
35 glBindTexture(GL_TEXTURE_2D, texture->id);
37 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST);
38 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
39 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
40 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
42 glTexImage2D(GL_TEXTURE_2D, 0, format, texture->width, texture->height, 0, format, GL_UNSIGNED_BYTE, data);
43 glGenerateMipmap(GL_TEXTURE_2D);
45 glBindTexture(GL_TEXTURE_2D, 0);
50 void texture_delete(Texture *texture)
52 glDeleteTextures(1, &texture->id);
56 static void *create_image_texture(void *key)
58 int width, height, channels;
60 unsigned char *data = stbi_load(key, &width, &height, &channels, 0);
62 printf("Failed to load texture %s\n", (char *) key);
66 Texture *texture = texture_create(data, width, height, GL_RGBA);
68 stbi_image_free(data);
73 Texture *texture_get(char *path)
75 return list_get_cached(&textures, path, &create_image_texture);