/** 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/domains/graphics/surface/sgxsurface.cpp

*/

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

CSGXSurface::CSGXSurface(const CImageData &image, const CSGXSurface::tReason reason/*=CSGXSurface::tReason::eDefault*/)
{
	m_iWidth = image.getWidth();
	m_iHeight = image.getHeight();
	m_iFormat = image.getFormat();
	m_iReason = reason;
	m_BlendMode = eBlendDecal;

	// Make a complete copy of the data, so that we own it
	tMEM_SIZE size = m_iWidth*m_iHeight*CImageData::bpp(m_iFormat);
	m_pBitmap = new tBYTE[size];
	sgxMemcpy(m_pBitmap, image.getBitmap(), size);


	if (m_iFormat == CImageData::eRGBA) {
		m_BlendMode = eBlendReplace;
	}

}

CSGXSurface::CSGXSurface(const tUINT32 width, const tUINT32 height, const CImageData::tFormat format, void *bitmap, const CSGXSurface::tReason reason)
{
	m_iWidth = width;
	m_iHeight = height;
	m_iReason = reason;
	m_iFormat = format;
	m_BlendMode = eBlendDecal;

	if (m_iFormat == CImageData::eRGBA) {
		m_BlendMode = eBlendReplace;
	}

	if (reason == eReasonDynamic || bitmap) {
		m_pBitmap = bitmap;
	} else {
		m_pBitmap = NULL;
	}
}

void 
CSGXSurface::set() const
{
//	SGX_ENGINE_STATS("surface_texture_set");
}

void 
CSGXSurface::setRegion(const tUINT32 region)
{
   	SGX_UNUSED(region);
//	SGX_ENGINE_STATS("surface_region_set");
}

void 
CSGXSurface::setRegion(const sgxUV &uv)
{
   	SGX_UNUSED(uv);
//	SGX_ENGINE_STATS("surface_region_set");
}

// TODO: Base class to contain, activate/isactive/IncStats
void	
CSGXSurface::setWrapped(const tWrapped wrapped)
{
	m_Wrapped = wrapped;
}

tUINT32 
CSGXSurface::getWidth() const
{
	return m_iWidth;
}

tUINT32 
CSGXSurface::getHeight() const
{
	return m_iHeight;
}

void *
CSGXSurface::getDynamicBitmap()
{
	return m_pBitmap;
}

tBOOL
CSGXSurface::getDynamicImageData(CImageData &data) const
{
	if (!m_pBitmap) {
		return FALSE;
	}

	CImageData local(m_iWidth, m_iHeight, m_iFormat, m_iWidth*CImageData::bpp(m_iFormat), (tBYTE *)m_pBitmap);

	data = local;

	return TRUE;
}

void
CSGXSurface::rebuild(void *)
{
	
}

void
CSGXSurface::setBlendMode(const tBlendMode mode)
{
	m_BlendMode = mode;
}

tBOOL
CSGXSurface::lock(CImageData &img)
{
	m_Lock.inc();

	// If there is already suitable memory allocated by the ImageData then
	// don't waste time trying to destroy & re-allocate it.
	if (img.IsValid() && 
		img.getWidth() == m_iWidth && img.getHeight() == m_iHeight && img.getFormat() != m_iFormat) {
			return TRUE;
	}
	img.release();
	img.create(m_iWidth, m_iHeight, m_iFormat);

	return TRUE;
}

tBOOL
CSGXSurface::unlock()
{
	sgxAssertRts(m_Lock.getCount(), FALSE);
	if (m_Lock.dec()) {
		return TRUE;
	}

	return FALSE;
}

