#include "bmpFont.h"

// PUBLIC

bmpFont::bmpFont(int rgfResourceId, int charWidth, int charHeight, int xPadding)
{
	CharWidth = charWidth;
	CharHeight = charHeight;
	XPadding = xPadding;

	// create texture
	GLint icomps;
	GLenum eFormat;
	GLbyte *pixels = gltLoadRGF(rgfResourceId, &_texWidth, &_texHeight, &icomps, &eFormat );
	glGenTextures(1,&_texturemap);
	glBindTexture(GL_TEXTURE_2D,_texturemap);
	glTexImage2D(GL_TEXTURE_2D, 0, icomps, _texWidth, _texHeight, 0, eFormat, GL_UNSIGNED_BYTE, pixels );
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); // Linear Filtering
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); // Linear Filtering
	//glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);
	msys_mallocFree(pixels);

	ProcessFont();
}

// PRIVATE

void bmpFont::ProcessFont()
{
	float pixelSizeX = 1.0f / (float)_texWidth;
	float pixelSizeY = 1.0f / (float)_texHeight;

	float txOff = 0.0f;
	float tyOff = 0.0f;

	float charWidthF = CharWidth * pixelSizeX;
	float charHeightF = CharHeight * pixelSizeY;
	float charPaddingX = XPadding * pixelSizeX;

	int charsPerLine = (_texWidth / (CharWidth+XPadding));

	Aspect = (float)((float)CharHeight / (float)CharWidth);

	for(int i=0; i<256; i++)
	{
		if (i==48)
		{
			int asdas =1;
		}
		bmpFontChar* ch = &Chars[i];
		ch->charVal = i;

		ch->texCoords.tx1 = txOff;
		ch->texCoords.tx2 = txOff+charWidthF;
		ch->texCoords.ty1 = tyOff+charHeightF;
		ch->texCoords.ty2 = tyOff;

		//float x1 = ch->texCoords.ty1 * _texHeight;
		//float x2 = ch->texCoords.ty2 * _texHeight;

		txOff+=charWidthF + charPaddingX;
		

		if (i> 0 && (i+1)%charsPerLine == 0) // next line
		{
			tyOff+=charHeightF;
			txOff = 0;
		}
	}
}

void bmpFont::BindTexture()
{
	glBindTexture(GL_TEXTURE_2D,_texturemap);
}

bmpFont::~bmpFont(void)
{
}
