mElite  1.0
An Elite clone based on TextElite by Jan-Philipp Kappmeier and Melanie Schmidt.
 All Classes Files Functions Variables Typedefs Enumerations Enumerator Friends Macros
TextureLoaderTGA.cpp
Go to the documentation of this file.
1 
6 #include "TextureLoaderTGA.h"
7 #include <fstream>
8 
9 using namespace std;
10 
15 
20 
22 
29 bool TextureLoaderTGA::load( const string& filename ) {
30  ifstream file( filename.c_str(), ios::binary );
31  if(!file)
32  return 0;
33 
34  // read the header and check if the file is uncompressed
35  BYTE tgaHeader[12];
36  BYTE unCompressHeader[12] = {0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0};
37  file.read( (char *)tgaHeader, sizeof(tgaHeader) );
38  if(!file)
39  return 0;
40  if( memcmp( unCompressHeader, tgaHeader, sizeof(unCompressHeader) ) != 0 )
41  return false;
42 
43  // read and save image info, return if the bits are more than 8 bpp
44  BYTE header[6];
45  file.read( (char *)header, sizeof(header) );
46  if( !file )
47  return false;
48  if( header[4] != 24 )
49  return false;
50 
51  setWidth( header[1] * 256 + header[0] );
52  setHeight( header[3] * 256 + header[2] );
53  setBPP( header[4] / 8 );
54 
55 
56  // allocate data for the image and load it
57  BYTE *image = new BYTE[sizeof(BYTE) * getWidth() * getHeight() * getBPP()];
58 
59  file.read( (char *)image, sizeof(BYTE)*getWidth() * getHeight() * getBPP());
60  if( !file ) {
61  delete image;
62  return false;
63  }
64 
65  setImage( image );
66 #ifdef GL_BGR_EXT
67  if( useBGR() )
68  setFormat( GL_BGR_EXT );
69  else {
70  bgr2rgb( 3 );
71  setFormat( GL_RGB );
72  }
73 #else
74  bgr2rgb( 3 );
75  setFormat( GL_RGB );
76 #endif
77 
78  return true;
79 }
80 
82 
88 bool TextureLoaderTGA::write( const std::string& filename ) {
89  // open file for output
90  FILE *file = 0;
91  fopen_s( &file, filename.c_str(), "wb" );
92  if(!file) {
93  fclose(file);
94  return false;
95  }
96 
97  // save width and height into the header
98  unsigned char unCompressHeader[12] = {0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // uncompressed Targa file
99  unsigned char header[6]; // header, used to fill with width, height and bpp
100  header[0] = getWidth() % 256;
101  header[1] = getWidth() / 256;
102  header[2] = getHeight() % 256;
103  header[3] = getHeight() / 256;
104  header[4] = 8 * getBPP();
105  header[5] = 0;
106  fwrite( unCompressHeader, sizeof(unCompressHeader), 1, file );
107  fwrite( header, sizeof(header), 1, file );
108 
109  // transform into BGR format and write image
110 #ifdef GL_BGR_EXT
111  if( getFormat() == GL_RGB ) {
112  bgr2rgb( getBPP() );
113  setFormat( GL_BGR_EXT );
114  }
115 #else
116  bgr2rgb( getBPP() );
117  setFormat( GL_RGB );
118 #endif
119  fwrite( getImage(), getWidth() * getHeight() * getBPP(), 1, file );
120  fclose(file);
121  return true;
122 }