1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
|
#include "texture.h"
vector<Texture *>Texture::textures;
Texture::Texture(string in_filename, string in_name)
{
imageData = NULL;
loadTGA(in_filename);
name = in_name;
textures.push_back(this);
}
Texture::~Texture()
{
for ( vector<Texture *>::iterator it = textures.begin(); it != textures.end(); it++)
{
if ( (*it) == this )
{
textures.erase(it);
}
}
if (imageData)
{
delete imageData;
}
}
bool Texture::loadTGA(string filename)
{
TGA_Header TGAheader;
ifstream file( filename.data(), std::ios_base::binary );
if ( file.is_open() )
{
return false;
}
if (!file.read( (char * )&TGAheader, sizeof(TGAheader)))
{
return false;
}
if ( TGAheader.ImageType != 2)
{
return false;
}
width = TGAheader.imageWidth;
height = TGAheader.imageHeight;
bpp = TGAheader.pixelDepth;
if ( width <=0 || height <=0 || (bpp != 24 && bpp != 32) )
{
return false;
}
GLuint type = GL_RGBA;
if ( bpp == 24 )
{
type = GL_RGB;
}
GLuint bytesPerPixel = bpp / 8;
GLuint imageSize = width * height * bytesPerPixel;
imageData = new GLubyte[imageSize];
if ( imageData == NULL)
{
return false;
}
if (!file.read( ( char*)imageData, imageSize))
{
delete imageData;
return false;
}
//Concerts BGR--> TO RGB;
for ( GLuint i = 0; i < (int)imageSize; i+=bytesPerPixel)
{
GLuint temp = imageData[i];
imageData[i] = imageData[i+2];
imageData[i+2] = temp;
}
createTexture(imageData, width, height, type);
//No problems
return true;
}
bool Texture::createTexture ( unsigned char *imageData, int width, int height, int type)
{
glGenTextures(1, &texID);
glBindTexture(GL_TEXTURE_2D, texID);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D,0,type, width, height, 0 , type, GL_UNSIGNED_BYTE, imageData);
return true;
}
|