cubemapper

view src/texture.cc @ 0:8fc9e1d3aad2

initial commit
author John Tsiombikas <nuclear@member.fsf.org>
date Thu, 27 Jul 2017 20:36:12 +0300
parents
children d7a29cb7ac8d
line source
1 #include <stdio.h>
2 #include <imago2.h>
3 #include "texture.h"
4 #include "opengl.h"
6 Texture::Texture()
7 {
8 width = height = tex_width = tex_height = 0;
9 tex = 0;
10 }
12 Texture::~Texture()
13 {
14 if(tex) {
15 glDeleteTextures(1, &tex);
16 }
17 }
19 static unsigned int next_pow2(unsigned int x)
20 {
21 --x;
22 x |= x >> 1;
23 x |= x >> 2;
24 x |= x >> 4;
25 x |= x >> 8;
26 x |= x >> 16;
27 return x + 1;
28 }
30 bool Texture::load(const char *fname)
31 {
32 img_pixmap img;
33 img_init(&img);
34 if(img_load(&img, fname) == -1) {
35 fprintf(stderr, "failed to load texture: %s\n", fname);
36 img_destroy(&img);
37 return false;
38 }
40 unsigned int intfmt = img_glintfmt(&img);
41 unsigned int pixfmt = img_glfmt(&img);
42 unsigned int pixtype = img_gltype(&img);
44 // if we have the sRGB extension, change the internal formats to sRGB
45 if(GLEW_EXT_texture_sRGB) {
46 switch(intfmt) {
47 case 3:
48 case GL_RGB:
49 intfmt = GL_SRGB_EXT;
50 break;
51 case 4:
52 case GL_RGBA:
53 intfmt = GL_SRGB_ALPHA;
54 break;
55 case 1:
56 case GL_LUMINANCE:
57 intfmt = GL_SLUMINANCE;
58 break;
59 default:
60 break;
61 }
62 }
64 width = img.width;
65 height = img.height;
66 tex_width = next_pow2(width);
67 tex_height = next_pow2(height);
69 if(!tex) {
70 glGenTextures(1, &tex);
71 }
72 glBindTexture(GL_TEXTURE_2D, tex);
74 if(GLEW_SGIS_generate_mipmap) {
75 glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS, GL_TRUE);
76 } else {
77 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
78 }
80 glTexImage2D(GL_TEXTURE_2D, 0, intfmt, tex_width, tex_height, 0, pixfmt, pixtype, 0);
81 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, pixfmt, pixtype, img.pixels);
83 tmat.scaling((float)width / (float)tex_width, (float)height / (float)tex_height, 1);
84 return true;
85 }
87 const Mat4 &Texture::texture_matrix() const
88 {
89 return tmat;
90 }
92 void Texture::bind(bool loadmat) const
93 {
94 if(!tex) return;
96 if(loadmat) {
97 glMatrixMode(GL_TEXTURE);
98 glLoadMatrixf(tmat[0]);
99 glMatrixMode(GL_MODELVIEW);
100 }
102 glBindTexture(GL_TEXTURE_2D, tex);
103 }