
// BlinkGame - Hunt for the Lost Pixels
// an SDL game in honor of the BlinkenArea crew
//
// (C) 2005-06 Rene Schickbauer
//
// See License.txt for licensing information
//
#ifdef NOP_CODE
/*--------------------------------------------------------------------
					CVS AUTO-GENERATED INFO
$Author: cavac $
$Date: 2006/03/02 13:06:43 $
$Name: rel-0-3-patches $
$Revision: 1.5 $
$State: Exp $

$Log: fonthandler.cpp,v $
Revision 1.5  2006/03/02 13:06:43  cavac
Changed (*tmp).format to tmp->format

Revision 1.4  2006/03/02 13:03:42  cavac
Re-formatted all .cpp and .h files a bit to get rid of the TAB/SPACE mess
that makes troubles with XCode's "re-format" feature

Revision 1.3  2006/02/27 16:37:21  dauti
Generalized renderFontHandlerText(), so that one can specify the color of the text.

Revision 1.2  2006/02/26 14:35:55  cavac
Added docs for scripting

Revision 1.1  2006/02/26 14:06:05  cavac
Added menu support

--------------------------------------------------------------------*/
#endif //NOP_CODE

#include "globals.h"
#include "errorhandler.h"
#include "fonthandler.h"
#include "SDL_ttf.h"

TTF_Font* menufont = 0;

void initFontHandler() {
	TTF_Init();

	menufont = TTF_OpenFont(RESPATH "Ghostmeat.ttf", 50);
	if(!menufont) {
		DIE(ERROR_FONTLOAD, "Ghostmeat.ttf");
	}
}

void deInitFontHandler() {
	TTF_Quit();
}

void renderFontHandlerText(Sint32 x, Sint32 y, char* text, SDL_Color fontcolor, bool hcentered, bool vcentered) {
	SDL_Color fcol = { 0xff, 0xff, 0xff, 0 };

	SDL_Surface* tmp2 = TTF_RenderText_Solid(menufont, text, fcol);
		SDL_Surface* tmp = SDL_ConvertSurface(tmp2, gScreen->format, SDL_SWSURFACE);
		SDL_FreeSurface(tmp2);

	
	// Center text on screen if needed
	if(hcentered) {
		x = (SCR_WIDTH - tmp->w) / 2;
	}
	if(vcentered) {
		y = (SCR_HEIGHT - tmp->h) / 2;
	}

	// Calculate offset in tiles-pixmap
	Uint32 xorigoffs = 0;
	Uint32 yorigoffs = 0;
	if(x < 0) {
		xorigoffs = -x;
	}
	if(y < 0) {
		yorigoffs = -y;
	}
	
	// Calculate HEIGHT/WIDTH of text to copy
	Uint32 width = tmp->w;
	Uint32 height = tmp->h;
	if(x > (SCR_WIDTH - tmp->w)) {
		width = SCR_WIDTH - x;
	}
	if(y > (SCR_HEIGHT - tmp->h)) {
		height = SCR_HEIGHT - y;
	}
	
	// -- Let's get blitting!!!
	if (SDL_MUSTLOCK(tmp))
		if (SDL_LockSurface(tmp) < 0)
			return;	

	Uint32 scrpitch = gScreen->pitch / 4;
	Uint32 tilpitch = tmp->pitch / 4;
	
	Uint32 color;
	for(Uint32 ybg = yorigoffs; ybg < height; ybg++) { 
		for(Uint32 xbg = xorigoffs; xbg < width; xbg++) {
			color = ((Uint32*)tmp->pixels)[xbg + ybg * tilpitch];
			
			if(color != 0x00000000) {
			  ((Uint32*)gScreen->pixels)[xbg + x + (y + ybg) * scrpitch] = SDL_MapRGB(tmp->format, fontcolor.r, fontcolor.g, fontcolor.b);
			}
			
		}
	}
	
	// Unlock if needed
	if (SDL_MUSTLOCK(tmp))
		SDL_UnlockSurface(tmp);


	
	SDL_FreeSurface(tmp);
}
