157d0bb771e5dd51298cb17876193fef4fa4348f
[demo] / src / opengl / texture-gl.cc
1 #include <GL/glew.h>
2 #include <stdlib.h>
3
4 #include "texture.h"
5 #include "opengl/texture-gl.h"
6
7 TextureGL::TextureGL()
8 {
9         tex = 0;
10         target = GL_TEXTURE_2D;
11 }
12
13 TextureGL::~TextureGL()
14 {
15         glDeleteTextures(1, &tex);
16 }
17
18 void TextureGL::update()
19 {
20         if(images.empty())
21                 return;
22
23         if(!tex) {
24                 target = is_cubemap() ? GL_TEXTURE_CUBE_MAP : GL_TEXTURE_2D;
25
26                 glGenTextures(1, &tex);
27                 glBindTexture(target, tex);
28                 glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
29                 glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
30         }
31         else {
32                 glBindTexture(target, tex);
33         }
34
35         static const unsigned int faces[] = {
36                 GL_TEXTURE_CUBE_MAP_POSITIVE_X, GL_TEXTURE_CUBE_MAP_POSITIVE_Y, GL_TEXTURE_CUBE_MAP_POSITIVE_Z,
37                 GL_TEXTURE_CUBE_MAP_NEGATIVE_X, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z
38         };
39
40         for(size_t i=0; i<images.size(); i++) {
41                 int w = images[i].w;
42                 int h = images[i].h;
43
44                 /* target */
45                 unsigned int t = is_cubemap() ? faces[i] : GL_TEXTURE_2D;
46
47                 /* internal format */
48                 unsigned int ifmt = images[i].is_float ? GL_RGBA16F : GL_SRGB_ALPHA;
49
50                 /* data type of pixel data */
51                 unsigned int type = images[i].is_float ? GL_FLOAT : GL_UNSIGNED_BYTE;
52
53                 glTexImage2D(t, 0, ifmt, w, h, 0, GL_RGBA, type, images[i].pixels);
54         }
55
56         glGenerateMipmap(target);
57 }
58
59 void TextureGL::bind()
60 {
61         unsigned int target = is_cubemap() ? GL_TEXTURE_CUBE_MAP : GL_TEXTURE_2D;
62         glBindTexture(target, tex);
63 }
64
65 void TextureGL::unbind()
66 {
67         unsigned int target = is_cubemap() ? GL_TEXTURE_CUBE_MAP : GL_TEXTURE_2D;
68         glBindTexture(target, 0);
69 }