]> git.lizzy.rs Git - dragonblocks3d.git/blob - src/dragonblocks/texture.cpp
Multithreading
[dragonblocks3d.git] / src / dragonblocks / texture.cpp
1 #include <stdexcept>
2 #define STB_IMAGE_IMPLEMENTATION
3 #include "stb_image.h"
4 #include "gldebug.hpp"
5 #include "log.hpp"
6 #include "texture.hpp"
7
8 using namespace std;
9 using namespace dragonblocks;
10
11 bool Texture::mipmap;
12 bool Texture::bilinear_filter;
13 GLenum Texture::min_filter, Texture::mag_filter;
14
15 void Texture::initArgs()
16 {
17         min_filter = mag_filter = bilinear_filter ? GL_LINEAR : GL_NEAREST;
18         if (mipmap) {
19                 if (min_filter == GL_NEAREST) {
20                         min_filter = GL_NEAREST_MIPMAP_NEAREST;
21                 } else {
22                         min_filter = GL_LINEAR_MIPMAP_NEAREST;
23                 }
24         }
25         stbi_set_flip_vertically_on_load(true);
26 }
27
28 void Texture::bind() const
29 {
30         glBindTexture(GL_TEXTURE_2D, id); CHECKERR
31 }
32
33 void Texture::load(const string &path)
34 {
35         int width, height, nrChannels;
36         unsigned char *data = stbi_load(path.c_str(), &width, &height, &nrChannels, 0);
37         if (! data)
38                 throw runtime_error("Failed to load texture " + path);
39         glGenTextures(1, &id); CHECKERR
40         bind();
41         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, Texture::min_filter); CHECKERR
42         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, Texture::mag_filter); CHECKERR
43         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); CHECKERR
44         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); CHECKERR
45         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); CHECKERR
46         if (Texture::mipmap)
47                 glGenerateMipmap(GL_TEXTURE_2D); CHECKERR
48         stbi_image_free(data);
49         glBindTexture(GL_TEXTURE_2D, 0); CHECKERR
50         log("Loaded texture " + path);
51 }
52