1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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};
}
|