As the title suggests, I've been having problems loading .tga files. I've been using this for reference and as far as I can tell (Apart from using c++ functions instead of c ones) I'm doing the same thing. I do get a texture but it's a garbled version of what it should be and I'm not really sure why. Please excuse all the mistakes, I'm just trying to get it working.
Header:
struct TGA
{
GLuint Load(const char* filename);
unsigned char header_[12];
unsigned char bpp_;
unsigned char id_;
unsigned short width_;
unsigned short height_;
unsigned char* data_;
};
Cpp:
GLuint TGA::Load(const char* filename)
{
width_ = 0; height_ = 0;
bpp_ = 32; id_ = 8;
data_ = 0;
std::ifstream file;
file.open(filename, std::ios::binary | std::ios::ate);
if(file.fail())
{
std::cout<<filename<<" could not be opened."<<std::endl;
return 0;
}
file.seekg(0, std::ios::beg);
file.read((char*)header_, sizeof(unsigned char)*12);
file.read((char*)&width_, sizeof(unsigned short));
file.read((char*)&height_, sizeof(unsigned short));
file.read((char*)&bpp_, sizeof(unsigned char));
file.read((char*)&id_, sizeof(unsigned char));
int imageSize = width_ * height_;
std::cout<<imageSize<<std::endl;
data_ = new unsigned char[imageSize * 3]; //3 means RGB
file.read((char*)data_, imageSize * 3);
file.close();
GLuint texture;
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width_, height_, 0, GL_BGRA, GL_UNSIGNED_BYTE, data_);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
gluBuild2DMipmaps(GL_TEXTURE_2D, 3, width_, height_, GL_RGBA, GL_UNSIGNED_BYTE, data_);
delete [] data_;
return texture;
}
When you read in the data, you assume the targa file has 24 bits per pixel (
file.read((char*)data_, imageSize * 3)
) without checking the value ofbpp_
. You then pass the image data to OpenGL, and say your data is in 32-bpp BGRA format.You should check what the value of
bpp_
is, allocate and read the data based on that value and also pass the correct data format to OpenGL (BGR or BGRA, depending on whether the alpha channel is included in the image or not).