I'm working on a TGA writer for a ray-tracer, but I can't get it to work. Can anyone see what is wrong with it?
Code:
#include <fstream.h>
#include <iostream.h>
typedef unsigned char UCHAR;
typedef signed char SCHAR;
typedef unsigned short int USINT;
class TARGA
{
public:
TARGA();
UCHAR idfield_no; // no. of chars in id field.
UCHAR colormap_type; // 1 = map 0 = no map
UCHAR image_type; // 1 = color mapped, 2 = rgb, 3 = b&w. All uncompressed
USINT colormap_origin; // index of first entry (lo-hi)
USINT colormap_length; // no. of color map entries (lo-hi)
UCHAR colormap_bit; // 16 for 16bit, 24 for 24bit...
USINT x_origin; // lower left corner (lo-hi)
USINT y_origin; // lower left corner (lo-hi)
USINT width; // width of image (lo-hi)
USINT height; // height of image (lo-hi)
UCHAR pixel_bit; // 16 for 16bit, 24 for 24bit...
UCHAR img_descriptor; // Wierd bit-thingy (ignore?)
//UCHAR* idfield; // Usually omitted (idfield_no=0)
//UCHAR* colormap; // Omitted if truecolor
UCHAR* image_data; // data stored differently depending on bitrate and colormap etc.
// The footer is ignored
};
TARGA::TARGA()
{
idfield_no = 0;
colormap_type = 0;
image_type = 2; // truecolor
colormap_origin = 0;
colormap_length = 0;
colormap_bit = 24; // 24 bit
x_origin = 0;
y_origin = 0;
width = 2; // width
height = 2; // height
pixel_bit = 24; // 24 bit
img_descriptor = 0;
//idfield; omitted!
//colormap; omitted!
image_data = new UCHAR[width*height*3];
for (int n=0; n<width*height*3; n++)
{
image_data[n]= 128; // should make all pixels gray
}
}
main(int argc, char* argv)
{
fstream file;
TARGA targa;
char outfile[] = "outfile.tga";
file.open(outfile, ios::out); // should it be "ios::binary"?
if (!file)
{
cout << "Error in opening " << outfile << " for writing" << endl;
return 1;
}
file.write((UCHAR *)&targa,sizeof(targa));
file.close();
file.open(outfile, ios::in);
if (!file)
{
cout << "Error in opening " << outfile << " for reading" << endl;
return 1;
}
char c;
int n=0;
while (true)
{
file.get(c);
cout << n << ": " << int(c) << endl;
if (file.eof()) { break; }
n++;
}
//file.read((UCHAR *)&targa,sizeof(targa));
file.close();
return 0;
}
The written file is wierd, as one can see from the output. Why, for example, are there values in the written file that were not in the object targa?
Some bytes of the file seems to be correct while others are not. For example the forth byte, is "-52" (or something) when it should be "0' (colormap origin). Or is that because it is a USINT?
Any suggestions?