textpsys

view src/image.cc @ 0:a4ffd9e6984c

initial commit
author John Tsiombikas <nuclear@member.fsf.org>
date Wed, 19 Aug 2015 09:13:48 +0300
parents
children
line source
1 #include <string.h>
2 #include <math.h>
3 #include "opengl.h"
4 #include "image.h"
6 static unsigned int next_pow2(unsigned int x);
8 Image::Image()
9 {
10 width = height = 0;
11 tex_width = tex_height = 0;
12 pixels = 0;
13 texture = 0;
14 own_pixels = 0;
15 }
17 Image::~Image()
18 {
19 destroy();
20 }
22 void Image::create(int xsz, int ysz, unsigned char *pix)
23 {
24 destroy();
26 pixels = own_pixels = new unsigned char[xsz * ysz * 3];
27 if(pix) {
28 memcpy(pixels, pix, xsz * ysz * 3);
29 } else {
30 memset(pixels, 0, xsz * ysz * 3);
31 }
32 width = xsz;
33 height = ysz;
34 }
36 void Image::destroy()
37 {
38 if(texture) {
39 glDeleteTextures(1, &texture);
40 texture = 0;
41 }
43 delete [] own_pixels;
44 own_pixels = pixels = 0;
46 width = height = tex_width = tex_height = 0;
47 }
49 unsigned int Image::gen_texture()
50 {
51 if(!pixels || !width || !height) {
52 return 0;
53 }
55 if(!texture) {
56 glGenTextures(1, &texture);
57 glBindTexture(GL_TEXTURE_2D, texture);
58 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
59 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
60 glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS, GL_TRUE);
61 } else {
62 glBindTexture(GL_TEXTURE_2D, texture);
63 }
65 tex_width = next_pow2(width);
66 tex_height = next_pow2(height);
68 if(tex_width == width && tex_height == height) {
69 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tex_width, tex_height, 0,
70 GL_RGB, GL_UNSIGNED_BYTE, pixels);
71 } else {
72 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tex_width, tex_height, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
73 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height,
74 GL_RGB, GL_UNSIGNED_BYTE, pixels);
75 }
77 return texture;
78 }
80 static unsigned int next_pow2(unsigned int x)
81 {
82 --x;
83 x |= x >> 1;
84 x |= x >> 2;
85 x |= x >> 4;
86 x |= x >> 8;
87 x |= x >> 16;
88 return x + 1;
89 }