conworlds

view src/texture.cc @ 20:782ff06817fb

merged ...
author John Tsiombikas <nuclear@member.fsf.org>
date Tue, 26 Aug 2014 18:42:53 +0300
parents bd8202d6d28d
children
line source
1 #include "texture.h"
2 #include "opengl.h"
4 Texture::Texture()
5 {
6 tex = 0;
7 type = GL_TEXTURE_2D;
8 }
10 Texture::~Texture()
11 {
12 destroy();
13 }
15 int Texture::get_width() const
16 {
17 return img.get_width();
18 }
20 int Texture::get_height() const
21 {
22 return img.get_height();
23 }
25 void Texture::create2d(int xsz, int ysz)
26 {
27 destroy();
29 type = GL_TEXTURE_2D;
30 img.create(xsz, ysz);
32 if(!tex) {
33 glGenTextures(1, &tex);
34 }
35 glBindTexture(type, tex);
36 glTexParameteri(type, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
37 glTexParameteri(type, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
38 glTexImage2D(type, 0, GL_RGBA, xsz, ysz, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
39 }
41 void Texture::destroy()
42 {
43 if(tex) {
44 glDeleteTextures(1, &tex);
45 }
46 }
48 void Texture::set_image(const Image &img)
49 {
50 this->img = img;
51 create2d(img.get_width(), img.get_height());
53 glTexSubImage2D(type, 0, 0, 0, img.get_width(), img.get_height(),
54 GL_RGBA, GL_UNSIGNED_BYTE, img.get_pixels());
55 }
57 Image &Texture::get_image()
58 {
59 return img;
60 }
62 const Image &Texture::get_image() const
63 {
64 return img;
65 }
67 unsigned int Texture::get_type() const
68 {
69 return type;
70 }
72 unsigned int Texture::get_texture_id() const
73 {
74 return tex;
75 }
77 bool Texture::load(const char *fname)
78 {
79 Image image;
80 if(!image.load(fname)) {
81 return false;
82 }
83 set_image(image);
84 return true;
85 }
87 void bind_texture(const Texture *tex, int tunit)
88 {
89 static unsigned int cur_tex_type[8] = {
90 GL_TEXTURE_2D, GL_TEXTURE_2D, GL_TEXTURE_2D, GL_TEXTURE_2D,
91 GL_TEXTURE_2D, GL_TEXTURE_2D, GL_TEXTURE_2D, GL_TEXTURE_2D
92 };
94 glActiveTextureARB(GL_TEXTURE0_ARB + tunit);
95 if(tex) {
96 glBindTexture(tex->get_type(), tex->get_texture_id());
97 glEnable(tex->get_type());
98 } else {
99 glDisable(cur_tex_type[tunit]);
100 }
101 glActiveTextureARB(GL_TEXTURE0_ARB);
103 cur_tex_type[tunit] = tex->get_type();
104 }
107 unsigned int next_pow2(unsigned int x)
108 {
109 x -= 1;
110 x |= x >> 1;
111 x |= x >> 2;
112 x |= x >> 4;
113 x |= x >> 8;
114 x |= x >> 16;
115 return x + 1;
116 }