/*****************************************************************************
 * $Id: eng_tex.cc,v 1.21 2006/08/10 03:18:58 devel Exp $
 * @file
 * @author	Jim E. Brooks  http://www.jimbrooks.org
 * @brief	Texture code.
 *//*
 * LEGAL:	COPYRIGHT (C) 2004 JIM E. BROOKS
 *          THIS SOURCE CODE IS RELEASED UNDER THE TERMS
 *          OF THE GNU GENERAL PUBLIC LICENSE (GPL).
 *****************************************************************************/

#define ENG_TEX_CC 1
#include "eng.hh"
#include "eng_tex.hh"

// Shared objects used by TexBiquad and TexQuad.
namespace gfx {
template<> SharedValFactory<Texcoord8>* SharedValFactory<Texcoord8>::mInstance = NULL;
}

////////////////////////////////////////////////////////////////////////////////
///////////////////////////////  TexBiquad  ////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

/*****************************************************************************
 * Constructor.  Set() really does it.
 *****************************************************************************/
TexBiquad::TexBiquad( void )
{
	Init();
}
void
TexBiquad::Init( void )
{
	mWorldVertexs = NULL;
	mTexture	  = NULL;
	mTexcoords    = NULL;
}
TexBiquad::~TexBiquad()
{
	DELETE_ARR_NULL( mWorldVertexs );
	mTexture = NULL;	// don't delete Texture object
	UnshareVal<Texcoord8>( mTexcoords ); mTexcoords = NULL;
}

/*****************************************************************************
 * Variant to calculate world vertexs from a given position,width,height.
 *****************************************************************************/
void
TexBiquad::Set( const Position& center,
                const fp width,
                const fp height,
                TexturePtrc texture,
                const Texcoord8& texcoords,
                const RGBA rgba )
{
	Set( texture, texcoords, rgba );

	// Calculate world vertexs from position,width,height.

	DELETE_ARR_NULL( mWorldVertexs );
	mWorldVertexs = new WorldVertex[8];

	const fp widthHalf = width * 0.5;
	fp y = center.y - height * 0.5;
	for ( uint i = 0; i < 8; i +=4 )
	{
		mWorldVertexs[i+0].x = center.x;
		mWorldVertexs[i+0].y = y;
		mWorldVertexs[i+0].z = center.z + widthHalf;

		mWorldVertexs[i+1].x = center.x - widthHalf;
		mWorldVertexs[i+1].y = y;
		mWorldVertexs[i+1].z = center.z;

		mWorldVertexs[i+2].x = center.x;
		mWorldVertexs[i+2].y = y;
		mWorldVertexs[i+2].z = center.z - widthHalf;

		mWorldVertexs[i+3].x = center.x + widthHalf;
		mWorldVertexs[i+3].y = y;
		mWorldVertexs[i+3].z = center.z;

		y += height; // loop again once
	}
}

/*****************************************************************************
 * Variant for when WorldVertex array will be given to Draw().
 *****************************************************************************/
void
TexBiquad::Set( TexturePtrc texture,
                const Texcoord8& texcoords,
                const RGBA rgba )
{
	mTexture = texture;									// just assign it

	UnshareVal<Texcoord8>( mTexcoords );       			// unshare outgoing
	mTexcoords = ShareVal<Texcoord8>( &texcoords );    	// share incoming
ASSERT( *mTexcoords == texcoords );

	mRgba = rgba;
}

/*****************************************************************************
 * Draw a textured biquad.
 *****************************************************************************/
void
TexBiquad::Draw( void )
{
	Draw( mWorldVertexs );
}
void
TexBiquad::Draw( const WorldVertex wv[8] )
{
	// world --> eye
	static EyeVertex ev[8];
	TRANSFORM_VERTEX( ev[0], wv[0] );
	TRANSFORM_VERTEX( ev[1], wv[1] );
	TRANSFORM_VERTEX( ev[2], wv[2] );
	TRANSFORM_VERTEX( ev[3], wv[3] );
	TRANSFORM_VERTEX( ev[4], wv[4] );
	TRANSFORM_VERTEX( ev[5], wv[5] );
	TRANSFORM_VERTEX( ev[6], wv[6] );
	TRANSFORM_VERTEX( ev[7], wv[7] );

	// Draw both intersecting quads using the same texture.
	#define DRAW_TEXBIQUAD( VI1, VI2, VI3, VI4 )									\
	GFX_MAP_TEXTURE_2D( (*mTexcoords)[0], (*mTexcoords)[1] ); GFX_VERTEXV( &ev[VI1] );	\
	GFX_MAP_TEXTURE_2D( (*mTexcoords)[2], (*mTexcoords)[3] ); GFX_VERTEXV( &ev[VI2] );	\
	GFX_MAP_TEXTURE_2D( (*mTexcoords)[4], (*mTexcoords)[5] ); GFX_VERTEXV( &ev[VI3] );	\
	GFX_MAP_TEXTURE_2D( (*mTexcoords)[6], (*mTexcoords)[7] ); GFX_VERTEXV( &ev[VI4] );

	GFX_RGBA( mRgba );
//	GFX_BEGIN_ALPHA_BLEND( GP_SRC_ALPHA, GP_SRC_COLOR );
	GFX_BEGIN_ALPHA_BLEND();
		GFX_BEGIN( GP_QUADS, GET_PTR(mTexture) );
			DRAW_TEXBIQUAD( 5, 1, 3, 7 );
			DRAW_TEXBIQUAD( 6, 2, 0, 4 );
		GFX_END( GET_PTR(mTexture) );
	GFX_END_ALPHA_BLEND();
}

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////  TexQuad  /////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

/*****************************************************************************
 * Constructor/destructor.
 *****************************************************************************/
TexQuad::TexQuad( void )
{
	mTexture	= NULL;
	mTexcoords	= NULL;
}
TexQuad::~TexQuad()
{
	mTexture = NULL;	// don't delete Texture objects
	UnshareVal<Texcoord8>( mTexcoords ); mTexcoords = NULL;
}

/*****************************************************************************
 * Set() assigns all members except the public mWorldVertexs[]
 * which user can do directly for speed.
 *****************************************************************************/
void
TexQuad::Set( TexturePtrc texture,
              const Texcoord8& texcoords,
              const RGBA rgba )
{
	// same as TexBiquad::Set()

	mTexture = texture;									// just assign it

	UnshareVal<Texcoord8>( mTexcoords );       			// unshare outgoing
	mTexcoords = ShareVal<Texcoord8>( &texcoords );		// share incoming
ASSERT( *mTexcoords == texcoords );

	mRgba = rgba;
}

/*****************************************************************************
 * Draw a single textured quad.
 *****************************************************************************/
void
TexQuad::Draw( eGpAlpha alpha1, eGpAlpha alpha2 )
{
	// world --> eye
	static EyeVertex ev[4];
	TRANSFORM_VERTEX( ev[0], mWorldVertexs[0] );
	TRANSFORM_VERTEX( ev[1], mWorldVertexs[1] );
	TRANSFORM_VERTEX( ev[2], mWorldVertexs[2] );
	TRANSFORM_VERTEX( ev[3], mWorldVertexs[3] );

	GFX_RGBA( mRgba );

	// Subtle: The outer-level alpha-blending overrides the inner-level Texture.
	GFX_BEGIN_ALPHA_BLEND( alpha1, alpha2 );
		GFX_BEGIN( GP_QUADS, GET_PTR(mTexture) );
			GFX_MAP_TEXTURE_2D( (*mTexcoords)[0], (*mTexcoords)[1] ); GFX_VERTEXV( &ev[0] );
			GFX_MAP_TEXTURE_2D( (*mTexcoords)[2], (*mTexcoords)[3] ); GFX_VERTEXV( &ev[1] );
			GFX_MAP_TEXTURE_2D( (*mTexcoords)[4], (*mTexcoords)[5] ); GFX_VERTEXV( &ev[2] );
			GFX_MAP_TEXTURE_2D( (*mTexcoords)[6], (*mTexcoords)[7] ); GFX_VERTEXV( &ev[3] );
		GFX_END( GET_PTR(mTexture) );
	GFX_END_ALPHA_BLEND();
}

////////////////////////////////////////////////////////////////////////////////
//////////////////////////  Misc texture code  /////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

/*****************************************************************************
 * Initialize texture objects (even if disabled by cmd-line).
 *****************************************************************************/
void
Engine::InitTextures( bool gfxsysReady )
{
	InitTexturesTgaFiles( gfxsysReady );
}
// Targa files.
void
Engine::InitTexturesTgaFiles( bool gfxsysReady )
{
	// The engine doesn't know where the texture directories are, so it asks.
	gEngineEvent.mNeedTextureDirVec.Call();
	if ( mTextureDirVec.empty() ) return;	// nobody responded

	// Find all .tga files and load them into STL map.
	vector<string>::const_iterator itrDirs;
	for ( itrDirs = mTextureDirVec.begin();
          itrDirs != mTextureDirVec.end();
          ++itrDirs )
	{
		const string& dirName = *itrDirs;
		vector<string> files;
		if ( FilesInDir( dirName, files ) )
		{
			vector<string>::iterator itrFiles;
			for ( itrFiles = files.begin(); itrFiles != files.end(); ++itrFiles )
			{
				if ( (*itrFiles).find( ".tga", 0 ) != string::npos )
				{
					string fileBuf;
					const string pathname = dirName + *itrFiles;
#if GFX_ZLIB
					string textureName = *itrFiles; RemoveSuffix( textureName, ".gz" );
					bool textureFileRead = ReadFileGzip( pathname, fileBuf );
#else // zlib isn't available and the user had to gunzip *.tga.gz
					if ( pathname.find( ".gz", 0 ) != string::npos )
					{
						*gStreamError << "ERROR: can't read compressed texture files" << endl;
						*gStreamError << "ERROR: compile with zlib or use gunzip *.tga.gz" << endl;
						Exit(1);
					}
					string textureName = *itrFiles;
					bool textureFileRead = ReadFile( pathname, fileBuf );
#endif
					if ( textureFileRead )
					{
						// Create Texture object.
						Targa targa( (uchar*)fileBuf.c_str(), fileBuf.size() );
						ASSERT( targa.IfValid() );
						Texture* texture = new StaticTexture( targa );

						// Enable mipmapping.
						texture->SetMipmap();
						texture->SetMinFilter( GP_TEXTURE_MIN_FILTER_LINEAR_MIPMAP_NEAREST );
						texture->SetMagFilter( GP_TEXTURE_MAG_FILTER_LINEAR );

						// Insert Texture object into map that gives names to textures.
						mTextureMap.insert( pair<string,Texture*>( textureName, texture ) );
					}
					else
					{
						*gStreamError << "ERROR: can't read texture files" << endl;
						Exit(1);
					}
				}
			}
		}
		else
		{
			*gStreamError << "ERROR: can't read texture files" << endl;
			Exit(1);
		}
	}
}
