All pastes #1287473 Raw Edit

Mine

public cpp v1 · immutable
#1287473 ·published 2008-12-17 06:57 UTC
rendered paste body
struct Texture		{			int width_;			int height_;			unsigned char* data_;			Texture()			{				width_ = 0;				height_ = 0;				data_ = 0;			};						~Texture()			{				if (data_)				{					free(data_);				}			}		};bool TextureLoader::LoadBMP(const char* fileName, Texture& texture)		{			FILE* fp = fopen(fileName, "rb");			if (fp)			{				unsigned short fileType = 0;				if (!fread(&fileType, sizeof(unsigned short), 1, fp))				{					fprintf(stderr, "Error reading file!\n");					return false;				}								if (0x4D42 != fileType)				{					fprintf(stderr, "Error: Not a valid BMP bitmap file!\n");					return false;				}								// locate image data				fseek(fp, 0x8, SEEK_CUR);				unsigned long imageBytesOffset = 0;				if (!fread(&imageBytesOffset, sizeof(unsigned long), 1, fp))				{					fprintf(stderr, "Error reading file!\n");					return false;				}								// get size of the image				fseek(fp, 0x4, SEEK_CUR);				if (!fread(&texture.width_, sizeof(int), 1, fp))				{					fprintf(stderr, "Error reading file!\n");					return false;				}								if (!fread(&texture.height_, sizeof(int), 1, fp))				{					fprintf(stderr, "Error reading file!\n");					return false;				}								fprintf(stderr, "DEBUG:\nImage Size %dx%d\n", texture.width_, texture.height_);								// get the number of color planes (this should always be 1)				short imageColorPlanes = 0;				if (!fread(&imageColorPlanes, sizeof(short), 1, fp))				{					fprintf(stderr, "Error reading file!\n");					return false;				}								if (0x1 != imageColorPlanes)				{					fprintf(stderr, "Error: Color planes must be equal to 0x1 not 0x%X!\n", imageColorPlanes);					return false;				}								// get the color depth				short imageColorDepth = 0;				if (!fread(&imageColorDepth, sizeof(short int), 1, fp))				{					fprintf(stderr, "Error reading file!\n");					return false;				}								// we only want 24-bit BMP files				if (0x18 != imageColorDepth)				{					fprintf(stderr, "Error: Color depth must be 24-bit! %d-bit is not supported!\n", imageColorDepth);					return false;				}								// calculate the size of the image data				unsigned long imageDataSize = 0x3 * (texture.width_ * texture.height_);								// allocate the image data				texture.data_ = reinterpret_cast<unsigned char*>(malloc(imageDataSize));								// jump to the image data				fseek(fp, imageBytesOffset, SEEK_SET);								// load the image data				if (!fread(&texture.data_, imageDataSize, 1, fp))				{					fprintf(stderr, "Error reading file!\n");					return false;				}								// convert loaded BGR to RGB				for (unsigned long index = 0; index < imageDataSize; index += 0x3)				{					unsigned char temp = texture.data_[index];					texture.data_[index] = texture.data_[index + 0x2];					texture.data_[index + 0x2] = temp;				}								fclose(fp);				return true;			}						fprintf(stderr, "Error opening file %s!\n", fileName);			return false;		}