conworlds

view src/texture.cc @ 7:bd8202d6d28d

some progress...
author John Tsiombikas <nuclear@member.fsf.org>
date Fri, 22 Aug 2014 16:55:16 +0300
parents 3c36bc28c6c2
children 283cdfa7dda2
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_texture_id() const
68 {
69 return tex;
70 }
72 void Texture::bind(int tunit) const
73 {
74 glActiveTextureARB(GL_TEXTURE0_ARB + tunit);
75 glBindTexture(type, tex);
76 glActiveTextureARB(GL_TEXTURE0_ARB);
77 }
79 bool Texture::load(const char *fname)
80 {
81 Image image;
82 if(!image.load(fname)) {
83 return false;
84 }
85 set_image(image);
86 return true;
87 }
89 unsigned int next_pow2(unsigned int x)
90 {
91 x -= 1;
92 x |= x >> 1;
93 x |= x >> 2;
94 x |= x >> 4;
95 x |= x >> 8;
96 x |= x >> 16;
97 return x + 1;
98 }