/** SGX

The   sss    gggg x   x   
     s      g      x x    Engine
      sss   g  gg   x
         s  g   g  x x          Copyright 1995-2009.
     ssss    gggg x   x         Steven Goodwin. All Rights Reserved.
    
This version has been released under the GNU Public License v2.0.

Please see the license files for details.

File: sgx/src/sgx/graphics/gfx_font_regioned_texture.cpp

*/

#include "sgx/core/core.hpp"
#include "sgx/graphics/graphics.hpp"


CSGXRegionedTextureFont::CSGXRegionedTextureFont(const sgxString &str) {
	m_pTexture = CSGXTextureManager::get()->loadTexture(str);

	sgxMemset(m_RegionMapping, '\0', sizeof(m_RegionMapping));

	tUINT32 numRegions = m_pTexture->getNumRegions();
	sgxAssert(numRegions < 255 && "You can't have more than 255 regions in a font, yet.");
	for(tUINT32 g=0;g<numRegions;++g) {
		m_RegionMapping[g+32] = (tBYTE)g;
	}
}

tUINT32
CSGXRegionedTextureFont::getHeight() const {
	if (m_pTexture) {
		return m_pTexture->getRegionHeight(0);
	}
	return 0;
}

tUINT32
CSGXRegionedTextureFont::getBaseline() const {
	if (m_pTexture) {
		return m_pTexture->getRegionHeight(0);
	}
	return 0;
}

tUINT32
CSGXRegionedTextureFont::getXHeight() const {
	if (m_pTexture) {
		return m_pTexture->getRegionHeight(0);
	}
	return 0;
}

tUINT32
CSGXRegionedTextureFont::getAscender() const {
	if (m_pTexture) {
		return m_pTexture->getRegionHeight(0);
	}
	return 0;
}

tUINT32
CSGXRegionedTextureFont::getCharacterWidth(const tCHAR c) const {
	if (m_pTexture) {
		return m_pTexture->getRegionWidth(m_RegionMapping[(unsigned char)c]);
	}
	return 0;
}


void 
CSGXRegionedTextureFont::draw(CSGXDrawSurface *pSurface, const tCHAR *pStr, const tPOINT x, const tPOINT y) const {
	tPOINT xpos = x;
	const tCHAR *p = pStr;
	tBYTE c;

	while((c = *p++) != 0) {
		draw(pSurface, c, xpos, y);
		xpos += getCharacterWidth(c);
		xpos += m_CharacterSpacing;
	}
}

void
CSGXRegionedTextureFont::draw(CSGXDrawSurface *pSurface, const tCHAR c, const tPOINT x, const tPOINT y) const {
	if (m_pTexture) {
		pSurface = CSGXDrawSurfaceManager::get()->getDisplaySurface();

		const CSGXTexture *pTexture = pSurface->getFillTexture();
		tUINT32 region = pSurface->getFillTextureRegion();

		pSurface->setFillTexture(m_pTexture, m_RegionMapping[(tBYTE)c]);
		pSurface->fillPoint(x, y, CSGXDrawSurface::eFromTopLeft);
		pSurface->setFillTexture(pTexture, region);
	}
}
