/** 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/drivers/common/opengl/ogltexturemanager.cpp

*/

#include "sgx/core/core.hpp"
#include "sgx/graphics/graphics.hpp"
#include "sgx/filesystem/filesystem.hpp"
#include "drivers/common/opengl/opengl.hpp"

GLuint CSGXOpenGLTextureManager::ms_CurrentTextureID = 1;

CSGXTextureManager *CSGXOpenGLTextureManager::create()
{
	if (m_pSingleton == NULL) {
		m_pSingleton = new CSGXOpenGLTextureManager();
		if (m_pSingleton) {
			m_pSingleton->initialize();
		}
	}
	return reinterpret_cast<CSGXTextureManager *>(m_pSingleton);
}

GLuint CSGXOpenGLTextureManager::getNextTextureID()
{
	return ms_CurrentTextureID++;
}

CSGXSurface *
CSGXOpenGLTextureManager::createSurface(const CImageData &img, const CSGXSurface::tReason reason/*=CSGXSurface::tReason::eDefault*/)
{
	return (CSGXSurface *)new CSGXOpenGLSurface(img.getWidth(), img.getHeight(), img.getFormat(), img.getBitmap(), reason);
}

CSGXTexture *
CSGXOpenGLTextureManager::loadTexture(const sgxString &filename, const sgxColorRGB &maskColor)
{
	return CSGXTextureManager::loadTexture(filename+".tga", maskColor);
}

CSGXTexture *
CSGXOpenGLTextureManager::loadTexture(const sgxString &filename, const CImageData::Mask &mask)
{
	CSGXTexture *pTexture = new CSGXTexture();

	CImageData *img = new CImageData();
	if (CImageLoader::get()->loadImageData(*img, filename+".tga") == NULL) {
		return NULL;
	}

	CSGXSurface *pSurface = createSurface(*img);
	pTexture->m_pSurface = pSurface;

	pTexture->m_Transparent = mask.isValid();
	pTexture->m_Translucent = mask.isValid();


	CSGXFile datFile(filename+".dat", "r");
	if (datFile.open()) {
		tUINT16 regions;
		datFile.seek(4, CSGXDeviceBlockState::eSeekFromBegin);	// skip w & h
		datFile >> regions;

#if 1
		for(tUINT16 r=0;r<regions;++r) {
			tUINT32 u1,v1, u2,v2;
			datFile >> u1 >> v1 >> u2 >> v2;
			pTexture->addPixelRegion(u1,v1, u2,v2);
		}
#else
		for(tUINT16 r=0;r<regions;++r) {
			tREAL32 u1,v1, u2,v2;
			datFile >> u1 >> v1 >> u2 >> v2;
			pTexture->addRegion(sgxUV(u1,v1, u2,v2));
		}
#endif
		if (regions == 0) {
			pTexture->addStandardRegions(1,1);
		}
		datFile.close();
	} else {
		pTexture->addRegion(sgxUV());
	}

	if (mask.isValid()) {
		img->applyMask(mask);
	}


	SurfaceCacheID id;
	m_SurfaceCache.getCacheID(id, filename);
	m_SurfaceCache.addSurface(id, pSurface);

	return pTexture;
}
  
