#include "fonts.h"

GLuint		gl_fonts[2];

static void		PrintChar(float x, float y, float size, char c)
{
	float		sx;
	float		sy;

	sx = (c & 15) / 16.0;
	sy = 1 - (c >> 4) / 16.0 - 0.0625f;

	glBegin(GL_QUADS);
		glTexCoord2f(sx + 0.0625f, sy + 0.0625f);	glVertex2i(x + size, y + size);
		glTexCoord2f(sx + 0.0625f, sy);				glVertex2i(x + size, y);
		glTexCoord2f(sx, sy); 						glVertex2i(x, y);
		glTexCoord2f(sx, sy + 0.0625f); 			glVertex2i(x, y + size);
	glEnd();
};

int				PrintString(float x, float y, float size, float gap, int numfont, char *format, ...)
{
	char		buffer[1024];
	int			i;
	int			idx;
	float		decal;
	va_list	list;

	va_start(list, format);
	for (idx = 0; *format; ++format)
		if (*format == '%')
		{
			if (*(++format))
			{
				if (*format == 'c')
					idx += sprintf(buffer + idx, "%c", va_arg(list, int));
				else if (*format == 'd')
					idx += sprintf(buffer + idx, "%d", va_arg(list, int));
				else if (*format == 's')
					idx += sprintf(buffer + idx, "%s", va_arg(list, char *));
				else
					idx += sprintf(buffer + idx, "%%%c", *format);
			}
		}
		else
			buffer[idx++] = *format;
	va_end(list);

	VTX_ScrDimention(VTX_DIMENTION_2D);

	glEnable(GL_BLEND);
	glEnable(GL_TEXTURE_2D);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	glBindTexture(GL_TEXTURE_2D, gl_fonts[numfont]);
	glPushMatrix();
	for (i = 0, decal = 0; i < idx; ++i)
	{
		PrintChar(x + decal, y, size, buffer[i]);
		decal += gap;
	}
	glPopMatrix();

	glDisable(GL_TEXTURE_2D);
	glDisable(GL_BLEND);
	return 0;
}

int	font_init(void)
{
	struct s_surface	surface;
	
	surface_alpha_define(&surface, 255, 255, 255, 0);

	if (surface_load(&surface, "data/font_texture_00.bmp", &gl_fonts[E_FONT_ARIAL]))
		return 1;

	surface_alpha_reset(&surface, 255);
	return 0;
}
