LoadTGA example

Emp empty at nomail.com
Thu Aug 3 17:59:48 PDT 2006


I've written some code to load tga files for openGl use and wanted to donate 
it (somewhere?)

Could you people check whether it is not totally faulty (not to my knowledge 
though).
I've written it so that it will even take a textfile as long as it is big 
enough and the first 18 or so bytes are correct :)

Any comments/improvements are more than welcome.
Also if anyone knows how to do good openGL error handling...

struct Texture
{
 GLuint width;
 GLuint height;
 GLuint id;
}

bool LoadTGA(inout Texture tex, char[] filename)
{
 GLubyte[] TGAfile;
 GLubyte  temp;
 GLuint  mode=GL_RGBA;
 GLuint  bpp;
 int   imageSize;
 const GLubyte[]  TGAheader= [0,0,2,0,0,0,0,0,0,0,0,0];

 try{
  TGAfile=cast(GLubyte[])read(filename);
    }
    catch{
  return false;
    }

 if (TGAfile[].length<18) return false;
 if (TGAfile[0..12] != TGAheader) return false;

 tex.width  = TGAfile[12+1] * 256 + TGAfile[12+0];
 tex.height = TGAfile[12+3] * 256 + TGAfile[12+2];

  if( tex.width <=0 || tex.width&(tex.width-1)  !=0 ||tex.width >512||
  tex.height<=0 || tex.height&(tex.height-1)!=0 ||tex.height>512||
  (TGAfile[12+4]!=24 && TGAfile[12+4]!=32)){
  return false;
 }

 bpp = TGAfile[12+4]/8;
 if (bpp==3) mode=GL_RGB;

 imageSize = tex.width * tex.height * bpp;

 if (TGAfile[].length<(18+imageSize)) return false;

 for(int i=0; i<imageSize; i+=bpp){
  temp=TGAfile[(12+6)+i];
  TGAfile[(12+6)+i] = TGAfile[(12+6)+i+2];
  TGAfile[(12+6)+i+2] = temp;
 }

 //error handling!
 glGenTextures(1, &tex.id);
 //error handling!
 glBindTexture(GL_TEXTURE_2D, tex.id);
 //error handling!
 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
 //error handling!
 glTexImage2D(GL_TEXTURE_2D, 0, mode, tex.width, tex.height, 0, mode, 
GL_UNSIGNED_BYTE, TGAfile[(12+6)..(imageSize+12+6)]);

 return true;
} 





More information about the Digitalmars-d-learn mailing list