话不多说,直接上函数
GLbyte *ReadTGABits(const char *szFileName, GLint *iWidth, GLint *iHeight, GLint *iComponents, GLenum *eFormat);
bool LoadTGATexture(const char *szFileName, GLenum minFilter, GLenum magFilter, GLenum wrapMode)
{
GLbyte *pBits;
int nWidth, nHeight, nComponents;
GLenum eFormat;
pBits = ReadTGABits(szFileName, &nWidth, &nHeight, &nComponents, &eFormat);
if(pBits == NULL)
return false;
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapMode);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapMode);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magFilter);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, nComponents, nWidth, nHeight, 0,
eFormat, GL_UNSIGNED_BYTE, pBits);
free(pBits);
if(minFilter == GL_LINEAR_MIPMAP_LINEAR ||
minFilter == GL_LINEAR_MIPMAP_NEAREST ||
minFilter == GL_NEAREST_MIPMAP_LINEAR ||
minFilter == GL_NEAREST_MIPMAP_NEAREST)
glGenerateMipmap(GL_TEXTURE_2D);
return true;
}
GLbyte *ReadTGABits(const char *szFileName, GLint *iWidth, GLint *iHeight, GLint *iComponents, GLenum *eFormat)
{
FILE *pFile;
typedef struct
{
GLubyte Header[12];
GLubyte header[6];
}TGAHEADER;
unsigned long lImageSize;
GLuint sDepth;
GLbyte *pBits=NULL;
TGAHEADER tgaHeader;
*iWidth=0;
*iHeight=0;
*eFormat=GL_RGB;
*iComponents=GL_RGB;
pFile=fopen(szFileName,"rb");
if(pFile==NULL)
return NULL;
fread(&tgaHeader,18,1,pFile);
*iWidth=tgaHeader.header[1]*256+tgaHeader.header[0];
*iHeight=tgaHeader.header[3]*256+tgaHeader.header[2];
sDepth=tgaHeader.header[4]/8;
// cout<<"1="<<*iWidth<<endl;
// cout<<"2="<<*iHeight<<endl;
// cout<<"3="<<sDepth;
if(tgaHeader.header[4]!=8&&tgaHeader.header[4]!=24&&tgaHeader.header[4]!=32)
return NULL;
lImageSize=(*iWidth)*(*iHeight)*sDepth;
pBits=(GLbyte*)malloc(lImageSize*sizeof(GLbyte));
if(pBits==NULL)
return NULL;
if(fread(pBits,lImageSize,1,pFile)!=1)
{
free(pBits);
return NULL;
}
switch(sDepth)
{
case 4:
*eFormat=GL_BGRA;
*iComponents=GL_RGBA;
break;
case 1:
*eFormat=GL_LUMINANCE;
*iComponents=GL_LUMINANCE;
break;
}
for(GLuint i=0;i<int(lImageSize);i+=sDepth)
{
GLubyte temp=pBits[i];
pBits[i]=pBits[i+2];
pBits[i+2]=temp;
}
fclose(pFile);
return pBits;
}