]> git.lizzy.rs Git - dragonblocks_alpha.git/blob - src/client/texture.c
Rename wetness to humidity
[dragonblocks_alpha.git] / src / client / texture.c
1 #define STB_IMAGE_IMPLEMENTATION
2 #include <stb/stb_image.h>
3 #include <stdbool.h>
4 #include "client/texture.h"
5 #include "list.h"
6 #include "util.h"
7
8 static List textures;
9
10 __attribute((constructor(101))) static void textures_init()
11 {
12         stbi_set_flip_vertically_on_load(true);
13
14         textures = list_create(&list_compare_string);
15 }
16
17 static void list_delete_texture(unused void *key, void *value, unused void *arg)
18 {
19         texture_delete(value);
20 }
21
22 __attribute((destructor)) static void textures_deinit()
23 {
24         list_clear_func(&textures, &list_delete_texture, NULL);
25 }
26
27 Texture *texture_create(unsigned char *data, int width, int height, GLenum format)
28 {
29         Texture *texture = malloc(sizeof(Texture));
30         texture->width = width;
31         texture->height = height;
32
33         glGenTextures(1, &texture->id);
34
35         glBindTexture(GL_TEXTURE_2D, texture->id);
36
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);
41
42         glTexImage2D(GL_TEXTURE_2D, 0, format, texture->width, texture->height, 0, format, GL_UNSIGNED_BYTE, data);
43         glGenerateMipmap(GL_TEXTURE_2D);
44
45         glBindTexture(GL_TEXTURE_2D, 0);
46
47         return texture;
48 }
49
50 void texture_delete(Texture *texture)
51 {
52         glDeleteTextures(1, &texture->id);
53         free(texture);
54 }
55
56 static void *create_image_texture(void *key)
57 {
58         int width, height, channels;
59
60         unsigned char *data = stbi_load(key, &width, &height, &channels, 0);
61         if (! data) {
62                 printf("Failed to load texture %s\n", (char *) key);
63                 return 0;
64         }
65
66         Texture *texture = texture_create(data, width, height, GL_RGBA);
67
68         stbi_image_free(data);
69
70         return texture;
71 }
72
73 Texture *texture_get(char *path)
74 {
75         return list_get_cached(&textures, path, &create_image_texture);
76 }