我一直在通過加載TGA文件的基本OpenGl教程,將其用作3D對象上的紋理。我已經能夠從TGA頭部加載數據,但是當我嘗試加載實際的圖像數據時,它失敗了。我不確定它出錯的地方。這裏是我的紋理加載類:C++ OpenGL TGA加載失敗
頭文件
struct TGA_Header
{
GLbyte ID_Length;
GLbyte ColorMapType;
GLbyte ImageType;
// Color map specifications
GLbyte firstEntryIndex[2];
GLbyte colorMapLength[2];
GLbyte colorMapEntrySize;
//image specification
GLshort xOrigin;
GLshort yOrigin;
GLshort ImageWidth;
GLshort ImageHeight;
GLbyte PixelDepth;
GLbyte ImageDescriptor;
};
class Texture
{
public:
Texture(string in_filename, string in_name = "");
~Texture();
public:
unsigned short width;
unsigned short height;
unsigned int length;
unsigned char type;
unsigned char *imageData;
unsigned int bpp;
unsigned int texID;
string name;
static vector<Texture *> textures;
private:
bool loadTGA(string filename);
bool createTexture(unsigned char *imageData, int width, int height, int type);
void swap(unsigned char * ori, unsigned char * dest, GLint size);
void flipImage(unsigned char * image, bool flipHorizontal, bool flipVertical, GLushort width, GLushort height, GLbyte bpp);
};
這裏是在CPP負載TGA功能:
bool Texture::loadTGA(string filename)
{
TGA_Header TGAheader;
ifstream file(filename.data(), std::ios::in, std::ios::binary);
//make sure the file was opened properly
if (!file.is_open())
return false;
if(!file.read((char *)&TGAheader, sizeof(TGAheader)))
return false;
//make sure the image is of a type we can handle
if(TGAheader.ImageType != 2)
return false;
width = TGAheader.ImageWidth;
height = TGAheader.ImageHeight;
bpp = TGAheader.PixelDepth;
if(width < 0 || // if the width or height is less than 0, than
height <= 0 || // the image is corrupt
(bpp != 24 && bpp != 32)) // make sure we are of the correct bit depth
{
return false;
}
//check for an alpha channel
GLuint type = GL_RGBA;
if (bpp == 24)
type = GL_RGB;
GLuint bytesPerPixel = bpp/8;
//allocate memory for the TGA so we can read it
GLuint imageSize = width * height * bytesPerPixel;
imageData = new GLubyte[imageSize];
if (imageData == NULL)
return false;
//make sure we are in the correct position to load the image data
file.seekg(-imageSize, std::ios::end);
// if something when wrong, make sure we free up the memory
//NOTE: It never gets past this point. The conditional always fails.
if (!file.read((char *)imageData, imageSize))
{
delete imageData;
return false;
}
//more code is down here, but it doesnt matter because it does not pass the above function
}
這似乎加載一些數據,但它一直返回該它失敗了。任何幫助爲什麼將不勝感激。如果它有點羅嗦,但我不確定什麼是或不重要。
更新: 所以,我只是重寫了函數。我使用的ifste似乎是問題的原因。具體來說,它會嘗試加載比我輸入的更多的字節數據。我不知道行爲的原因,但我已在下面列出了我的功能代碼。感謝大家的幫助。
你是怎麼從調試學到了什麼? – 2012-01-13 06:00:05
不幸的是,並不多。 imageData指針肯定會加載某種類型的數據,但它無論如何都會失敗。 – Donutfiend84 2012-01-13 06:34:34
請注意,您應該使用'delete [] imageData',雖然 – rotoglup 2012-01-13 07:00:09