cubemapper

view src/texture.cc @ 2:e308561f9889

correct cubemap export and visualization
author John Tsiombikas <nuclear@member.fsf.org>
date Fri, 28 Jul 2017 13:24:34 +0300
parents d7a29cb7ac8d
children 2bfafdced01a
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 int Texture::get_width() const
31 {
32 return width;
33 }
35 int Texture::get_height() const
36 {
37 return height;
38 }
40 bool Texture::load(const char *fname)
41 {
42 img_pixmap img;
43 img_init(&img);
44 if(img_load(&img, fname) == -1) {
45 fprintf(stderr, "failed to load texture: %s\n", fname);
46 img_destroy(&img);
47 return false;
48 }
50 unsigned int intfmt = img_glintfmt(&img);
51 unsigned int pixfmt = img_glfmt(&img);
52 unsigned int pixtype = img_gltype(&img);
54 width = img.width;
55 height = img.height;
56 tex_width = next_pow2(width);
57 tex_height = next_pow2(height);
59 if(!tex) {
60 glGenTextures(1, &tex);
61 }
62 glBindTexture(GL_TEXTURE_2D, tex);
64 if(GLEW_SGIS_generate_mipmap) {
65 glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS, GL_TRUE);
66 } else {
67 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
68 }
70 glTexImage2D(GL_TEXTURE_2D, 0, intfmt, tex_width, tex_height, 0, pixfmt, pixtype, 0);
71 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, pixfmt, pixtype, img.pixels);
73 tmat.scaling((float)width / (float)tex_width, (float)height / (float)tex_height, 1);
74 return true;
75 }
77 const Mat4 &Texture::texture_matrix() const
78 {
79 return tmat;
80 }
82 void Texture::bind(bool loadmat) const
83 {
84 if(!tex) return;
86 if(loadmat) {
87 glMatrixMode(GL_TEXTURE);
88 glLoadMatrixf(tmat[0]);
89 glMatrixMode(GL_MODELVIEW);
90 }
92 glBindTexture(GL_TEXTURE_2D, tex);
93 }