//
// DX9BoidsPlugin.cpp
//
// DX9Boids Plugin
//
// Copyright (c) 2000-2004 memon/moppi productions
//

#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <d3d9.h>
#include <d3dx9math.h>

// Demopaja headers
#include "DemopajaVersion.h"
#include "PajaTypes.h"
#include "ClassDescC.h"
#include "ImportableI.h"
#include "DX9DeviceC.h"
#include "Dx9ViewportC.h"
#include "FileIO.h"
#include "AutoGizmoC.h"
#include "Vector2C.h"
#include "BBox2C.h"
#include "EffectMaskI.h"

#include "DX9BoidsPlugin.h"

using namespace PajaTypes;
using namespace PluginClass;
using namespace PajaSystem;
using namespace Edit;
using namespace Composition;
using namespace Import;
using namespace FileIO;

using namespace DX9BoidsPlugin;

#define FVF_XYZCOLORUV_VERTEX			(D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1)
#define FVF_XYZCOLOR_VERTEX			(D3DFVF_XYZ | D3DFVF_DIFFUSE)

struct XYZCOLORUV_VERTEX
{
	float	x, y, z;
	DWORD	color;
	float	u, v;
};

struct XYZCOLOR_VERTEX
{
	float	x, y, z;
	DWORD	color;
};


static
void
TRACE( const char* szFormat, ...  )
{
	char	szMsg[256];
	va_list	rList;
	va_start( rList, szFormat );
	_vsnprintf( szMsg, 255, szFormat, rList );
	va_end( rList );
	OutputDebugString( szMsg );
}

//////////////////////////////////////////////////////////////////////////
//
//  DX9Boids effect class descriptor.
//

DX9BoidsDescC::DX9BoidsDescC()
{
	// empty
}

DX9BoidsDescC::~DX9BoidsDescC()
{
	// empty
}

void*
DX9BoidsDescC::create()
{
	return (void*)DX9BoidsEffectC::create_new();
}

int32
DX9BoidsDescC::get_classtype() const
{
	return CLASS_TYPE_EFFECT;
}

SuperClassIdC
DX9BoidsDescC::get_super_class_id() const
{
	return SUPERCLASS_EFFECT;
}

ClassIdC
DX9BoidsDescC::get_class_id() const
{
	return CLASS_DX9BOIDS_EFFECT;
};

const char*
DX9BoidsDescC::get_name() const
{
	return CLASS_DX9BOIDS_EFFECT_NAME;
}

const char*
DX9BoidsDescC::get_desc() const
{
	return "Boids Effect (DX9)";
}

const char*
DX9BoidsDescC::get_author_name() const
{
	return "Mikko \"memon\" Mononen";
}

const char*
DX9BoidsDescC::get_copyright_message() const
{
	return "Copyright (c) 2000-2004 Moppi Productions";
}

const char*
DX9BoidsDescC::get_url() const
{
	return "http://www.demopaja.org/";
}

const char*
DX9BoidsDescC::get_help_filename() const
{
	return "res://BoidsHelp.html";
}

uint32
DX9BoidsDescC::get_required_device_driver_count() const
{
	return 1;
}

const ClassIdC&
DX9BoidsDescC::get_required_device_driver( uint32 ui32Idx )
{
	return PajaSystem::CLASS_DX9_DEVICEDRIVER;
}


uint32
DX9BoidsDescC::get_ext_count() const
{
	return 0;
}

const char*
DX9BoidsDescC::get_ext( uint32 ui32Index ) const
{
	return 0;
}


//////////////////////////////////////////////////////////////////////////
//
// Global descriptors, which will be returned to the Demopaja.
//

DX9BoidsDescC			g_rDX9BoidsDesc;

#ifndef DEMOPAJAPLAYER

//////////////////////////////////////////////////////////////////////////
//
// The DLL
//

BOOL APIENTRY
DllMain( HANDLE hModule, DWORD ulReasonForCall, LPVOID lpReserved )
{
    switch( ulReasonForCall )
	{
		case DLL_PROCESS_ATTACH:
		case DLL_THREAD_ATTACH:
		case DLL_THREAD_DETACH:
		case DLL_PROCESS_DETACH:
			break;
    }
    return TRUE;
}


//
// Returns number of classes inside this plugin DLL.
//

__declspec( dllexport )
int32
get_classdesc_count()
{
	return 1;
}


//
// Returns class descriptors of the plugin classes.
//

__declspec( dllexport )
ClassDescC*
get_classdesc( int32 i )
{
	if( i == 0 )
		return &g_rDX9BoidsDesc;
	return 0;
}


//
// Returns the API version this DLL was made with.
//

__declspec( dllexport )
int32
get_api_version()
{
	return DEMOPAJA_VERSION;
}

//
// Returns the DLL name.
//

__declspec( dllexport )
char*
get_dll_name()
{
	return "DX9BoidsPlugin.dll - Image Plugin (c)2000-2004 memon/moppi productions";
}

#endif



//////////////////////////////////////////////////////////////////////////
//
// The effect
//

DX9BoidsEffectC::DX9BoidsEffectC()
{
	//
	// Create Transform gizmo.
	//
	m_pTraGizmo = AutoGizmoC::create_new( this, "Transform", ID_GIZMO_TRANS );

	m_pTraGizmo->add_parameter(	ParamVector2C::create_new( m_pTraGizmo, "Position", Vector2C(), ID_TRANSFORM_POS,
						PARAM_STYLE_EDITBOX | PARAM_STYLE_ABS_POSITION, PARAM_ANIMATABLE ) );
	
	m_pTraGizmo->add_parameter(	ParamVector2C::create_new( m_pTraGizmo, "Pivot", Vector2C(), ID_TRANSFORM_PIVOT,
						PARAM_STYLE_EDITBOX | PARAM_STYLE_REL_POSITION | PARAM_STYLE_WORLD_SPACE, PARAM_ANIMATABLE ) );
	
	m_pTraGizmo->add_parameter(	ParamFloatC::create_new( m_pTraGizmo, "Rotation", 0, ID_TRANSFORM_ROT,
						PARAM_STYLE_EDITBOX | PARAM_STYLE_ANGLE, PARAM_ANIMATABLE, 0, 0, 1.0f ) );

	m_pTraGizmo->add_parameter(	ParamVector2C::create_new( m_pTraGizmo, "Scale", Vector2C( 1, 1 ), ID_TRANSFORM_SCALE,
						PARAM_STYLE_EDITBOX | PARAM_STYLE_PERCENT, PARAM_ANIMATABLE, Vector2C(), Vector2C(), 0.01f ) );


	//
	// Create Attributes gizmo.
	//

	m_pAttGizmo = AutoGizmoC::create_new( this, "Attributes", ID_GIZMO_ATTRIB );

	// Image
	m_pAttGizmo->add_parameter(	ParamFileC::create_new( m_pAttGizmo, "Image", SUPERCLASS_IMAGE, NULL_CLASSID, ID_ATTRIBUTE_IMAGE, PARAM_STYLE_FILE, PARAM_ANIMATABLE ) );

	// Scale
	m_pAttGizmo->add_parameter(	ParamVector2C::create_new( m_pAttGizmo, "Scale", Vector2C( 1, 1 ), ID_ATTRIBUTE_SCALE,
						PARAM_STYLE_EDITBOX | PARAM_STYLE_PERCENT, PARAM_ANIMATABLE, Vector2C(), Vector2C(), 0.01f ) );

	// Offset
	m_pAttGizmo->add_parameter(	ParamVector2C::create_new( m_pAttGizmo, "Offset", Vector2C(), ID_ATTRIBUTE_OFFSET,
						PARAM_STYLE_EDITBOX | PARAM_STYLE_REL_POSITION | PARAM_STYLE_OBJECT_SPACE, PARAM_ANIMATABLE ) );

	// Wrap
	ParamIntC*	pWrapMode = ParamIntC::create_new( m_pAttGizmo, "Wrap", 0, ID_ATTRIBUTE_WRAP, PARAM_STYLE_COMBOBOX, PARAM_ANIMATABLE, 0, 1 );
	pWrapMode->add_label( 0, "Clamp" );
	pWrapMode->add_label( 1, "Repeat" );
	m_pAttGizmo->add_parameter( pWrapMode );

	// Resample
	ParamIntC*	pResampleMode = ParamIntC::create_new( m_pAttGizmo, "Resample", 0, ID_ATTRIBUTE_RESAMPLE, PARAM_STYLE_COMBOBOX, PARAM_ANIMATABLE, 0, 1 );
	pResampleMode->add_label( 0, "Bilinear" );
	pResampleMode->add_label( 1, "Nearest" );
	m_pAttGizmo->add_parameter( pResampleMode );

	// Color
	m_pAttGizmo->add_parameter(	ParamColorC::create_new( m_pAttGizmo, "Color", ColorC( 1, 1, 1, 1 ), ID_ATTRIBUTE_COLOR,
							PARAM_STYLE_COLORPICKER_RGB, PARAM_ANIMATABLE ) );

	// Opacity
	m_pAttGizmo->add_parameter(	ParamFloatC::create_new( m_pAttGizmo, "Opacity", 1.0f, ID_ATTRIBUTE_OPACITY,
						PARAM_STYLE_EDITBOX | PARAM_STYLE_PERCENT, PARAM_ANIMATABLE, 0, 1.0f, 0.01f ) );

	// Blend
	ParamIntC*	pBlendMode = ParamIntC::create_new( m_pAttGizmo, "Blend", 0, ID_ATTRIBUTE_BLEND, PARAM_STYLE_COMBOBOX, PARAM_ANIMATABLE, 0, 6 );
	pBlendMode->add_label( 0, "Normal" );
	pBlendMode->add_label( 1, "Replace" );
	pBlendMode->add_label( 2, "Add" );
	pBlendMode->add_label( 3, "Mult" );
	pBlendMode->add_label( 4, "Sub" );
	pBlendMode->add_label( 5, "Lighten" );
	pBlendMode->add_label( 6, "Darken" );
	m_pAttGizmo->add_parameter( pBlendMode );

	// Mask
	m_pAttGizmo->add_parameter(	ParamLinkC::create_new( m_pAttGizmo, "Mask", SUPERCLASS_EFFECT_MASK, NULL_CLASSID,
						ID_ATTRIBUTE_MASK, PARAM_STYLE_SINGLE_LINK ) );
}

DX9BoidsEffectC::DX9BoidsEffectC( EditableI* pOriginal ) :
	EffectI( pOriginal ),
	m_pTraGizmo( 0 ),
	m_pAttGizmo( 0 )
{
	// Empty. The parameters are not created in the clone constructor.
}

DX9BoidsEffectC::~DX9BoidsEffectC()
{
	// Return if this is a clone.
	if( get_original() )
		return;

	// Release gizmos.
	m_pTraGizmo->release();
	m_pAttGizmo->release();
}

DX9BoidsEffectC*
DX9BoidsEffectC::create_new()
{
	return new DX9BoidsEffectC;
}

DataBlockI*
DX9BoidsEffectC::create()
{
	return new DX9BoidsEffectC;
}

DataBlockI*
DX9BoidsEffectC::create( EditableI* pOriginal )
{
	return new DX9BoidsEffectC( pOriginal );
}

void
DX9BoidsEffectC::copy( EditableI* pEditable )
{
	EffectI::copy( pEditable );

	// Make deep copy.
	DX9BoidsEffectC*	pEffect = (DX9BoidsEffectC*)pEditable;
	m_pTraGizmo->copy( pEffect->m_pTraGizmo );
	m_pAttGizmo->copy( pEffect->m_pAttGizmo );
}

void
DX9BoidsEffectC::restore( EditableI* pEditable )
{
	EffectI::restore( pEditable );

	// Make shallow copy.
	DX9BoidsEffectC*	pEffect = (DX9BoidsEffectC*)pEditable;
	m_pTraGizmo = pEffect->m_pTraGizmo;
	m_pAttGizmo = pEffect->m_pAttGizmo;
}

int32
DX9BoidsEffectC::get_gizmo_count()
{
	// Return number of gizmos inside this effect.
	return GIZMO_COUNT;
}

GizmoI*
DX9BoidsEffectC::get_gizmo( PajaTypes::int32 i32Index )
{
	// Returns specified gizmo.
	// Since the ID's are zero based, we can use them as indices.
	switch( i32Index ) {
	case ID_GIZMO_TRANS:
		return m_pTraGizmo;
	case ID_GIZMO_ATTRIB:
		return m_pAttGizmo;
	}

	return 0;
}

ClassIdC
DX9BoidsEffectC::get_class_id()
{
	// Return the class ID. Should be same as in the class descriptor.
	return CLASS_DX9BOIDS_EFFECT;
}

const char*
DX9BoidsEffectC::get_class_name()
{
	// Return the class name. Should be same as in the class descriptor.
	return CLASS_DX9BOIDS_EFFECT_NAME;
}

void
DX9BoidsEffectC::set_default_file( int32 i32Time, FileHandleC* pHandle )
{
	// Sets the default file.

	// Get the file parameter.
	ParamFileC*	pParam = (ParamFileC*)m_pAttGizmo->get_parameter( ID_ATTRIBUTE_IMAGE );

	// Begin Undo block.
	UndoC*	pOldUndo = pParam->begin_editing( get_undo() );
		// Set the file.
		pParam->set_file( i32Time, pHandle );
	// End undo block.
	pParam->end_editing( pOldUndo );
}

ParamI*
DX9BoidsEffectC::get_default_param( int32 i32Param )
{
	// Return specified default parameter.
	if( i32Param == DEFAULT_PARAM_POSITION )
		return m_pTraGizmo->get_parameter( ID_TRANSFORM_POS );
	else if( i32Param == DEFAULT_PARAM_ROTATION )
		return m_pTraGizmo->get_parameter( ID_TRANSFORM_ROT );
	else if( i32Param == DEFAULT_PARAM_SCALE )
		return m_pTraGizmo->get_parameter( ID_TRANSFORM_SCALE );
	else if( i32Param == DEFAULT_PARAM_PIVOT )
		return m_pTraGizmo->get_parameter( ID_TRANSFORM_PIVOT );
	return 0;
}

uint32
DX9BoidsEffectC::update_notify( EditableI* pCaller )
{
	return PARAM_NOTIFY_NONE;
}

void
DX9BoidsEffectC::initialize( uint32 ui32Reason, PajaSystem::DemoInterfaceC* pInterface )
{
	EffectI::initialize( ui32Reason, pInterface );
}


void
DX9BoidsEffectC::eval_state( int32 i32Time )
{
	if( !m_pDemoInterface )
		return;

	// Requires multitexturing and bledn equation.
	DeviceContextC* pContext = m_pDemoInterface->get_device_context();
	TimeContextC* pTimeContext = m_pDemoInterface->get_time_context();


	Matrix2C	rPosMat, rRotMat, rScaleMat, rPivotMat;

	Vector2C	rScale;
	Vector2C	rPos;
	Vector2C	rPivot;
	float32		f32Rot;

	// Get parameters which affect the transformation.
	((ParamVector2C*)m_pTraGizmo->get_parameter( ID_TRANSFORM_POS ))->get_val( i32Time, rPos );
	((ParamVector2C*)m_pTraGizmo->get_parameter( ID_TRANSFORM_PIVOT ))->get_val( i32Time, rPivot );
	((ParamFloatC*)m_pTraGizmo->get_parameter( ID_TRANSFORM_ROT ))->get_val( i32Time, f32Rot );
	((ParamVector2C*)m_pTraGizmo->get_parameter( ID_TRANSFORM_SCALE ))->get_val( i32Time, rScale );

	// Calculate transformation matrix.
	rPivotMat.set_trans( rPivot );
	rPosMat.set_trans( rPos );
	rRotMat.set_rot( f32Rot / 180.0f * (float32)M_PI );
	rScaleMat.set_scale( rScale ) ;
	m_rTM = rPivotMat * rRotMat * rScaleMat * rPosMat;

	float32		f32Width = 25;
	float32		f32Height = 25;
	Vector2C	rMin, rMax;
	Vector2C	rVec;


	// Get the size from the file or use the defaults if no file.
	ImportableImageI*	pImp = 0;
	FileHandleC*		pHandle;
	int32				i32FileTime;
	((ParamFileC*)m_pAttGizmo->get_parameter( ID_ATTRIBUTE_IMAGE ))->get_file( i32Time, pHandle, i32FileTime );

	if( pHandle )
		pImp = (ImportableImageI*)pHandle->get_importable();

	if( pImp )
	{
		pImp->eval_state( i32FileTime );
		f32Width = (float32)pImp->get_width() * 0.5f;
		f32Height = (float32)pImp->get_height() * 0.5f;
	}


	// Calcualte vertices of the rectangle.
	m_rVertices[0][0] = -f32Width;		// top-left
	m_rVertices[0][1] =  f32Height;

	m_rVertices[1][0] =  f32Width;		// top-right
	m_rVertices[1][1] =  f32Height;

	m_rVertices[2][0] =  f32Width;		// bottom-right
	m_rVertices[2][1] = -f32Height;

	m_rVertices[3][0] = -f32Width;		// bottom-left
	m_rVertices[3][1] = -f32Height;

	// Calculate bounding box
	for( uint32 i = 0; i < 4; i++ ) {
		rVec = m_rTM * m_rVertices[i];
		m_rVertices[i] = rVec;

		if( !i )
			rMin = rMax = rVec;
		else {
			if( rVec[0] < rMin[0] ) rMin[0] = rVec[0];
			if( rVec[1] < rMin[1] ) rMin[1] = rVec[1];
			if( rVec[0] > rMax[0] ) rMax[0] = rVec[0];
			if( rVec[1] > rMax[1] ) rMax[1] = rVec[1];
		}
	}

	// Store bounding box.
	m_rBBox[0] = rMin;
	m_rBBox[1] = rMax;

	Vector2C	rImageScale( 1, 1 );
	Vector2C	rImageOffset( 0, 0 );
	int32			i32Wrap = WRAPMODE_CLAMP;
	int32			i32Resample = RESAMPLEMODE_BILINEAR;
	int32			i32Blend = BLENDMODE_NORMAL;
	ColorC		rColor( 1, 1, 1 );
	float32		f32Opacity = 1.0f;


	// Get image scale.
	((ParamVector2C*)m_pAttGizmo->get_parameter( ID_ATTRIBUTE_SCALE ))->get_val( i32Time, rImageScale );
	// Get image offset.
	((ParamVector2C*)m_pAttGizmo->get_parameter( ID_ATTRIBUTE_OFFSET ))->get_val( i32Time, rImageOffset );
	// Get Wrap
	((ParamIntC*)m_pAttGizmo->get_parameter( ID_ATTRIBUTE_WRAP ))->get_val( i32Time, i32Wrap );
	// Get Resample
	((ParamIntC*)m_pAttGizmo->get_parameter( ID_ATTRIBUTE_RESAMPLE ))->get_val( i32Time, i32Resample );
	// Get Color.
	((ParamColorC*)m_pAttGizmo->get_parameter( ID_ATTRIBUTE_COLOR ))->get_val( i32Time, rColor );
	// Get Opacity.
	((ParamFloatC*)m_pAttGizmo->get_parameter( ID_ATTRIBUTE_OPACITY ))->get_val( i32Time, f32Opacity );
	// Get Blend mode.
	((ParamIntC*)m_pAttGizmo->get_parameter( ID_ATTRIBUTE_BLEND ))->get_val( i32Time, i32Blend );


	// Mask
	ParamLinkC*				pMaskParam = (ParamLinkC*)m_pAttGizmo->get_parameter( ID_ATTRIBUTE_MASK );
	EffectMaskI*			pMaskEffect = (EffectMaskI*)pMaskParam->get_link( 0 );
	ImportableImageI*	pMaskImp = 0;
	int32							i32MaskImageFlags = 0;
	Matrix2C					rMaskMat;
	if( pMaskEffect )
	{
		pMaskImp = pMaskEffect->get_mask_image();
		i32MaskImageFlags = pMaskEffect->get_mask_image_flags();
		rMaskMat = pMaskEffect->get_mask_matrix();
	}


	// Get the OpenGL device.
	DX9DeviceC*	pDevice = (DX9DeviceC*)pContext->query_interface( CLASS_DX9_DEVICEDRIVER );
	if( !pDevice )
		return;

	LPDIRECT3DDEVICE9	pD3DDevice = pDevice->get_d3ddevice();

	// Get the OpenGL viewport.
	DX9ViewportC*	pViewport = (DX9ViewportC*)pDevice->query_interface( GRAPHICSDEVICE_VIEWPORT_INTERFACE );
	if( !pViewport )
		return;

	// Set orthographic projection.
	pViewport->set_ortho( m_rBBox, m_rBBox[0][0], m_rBBox[1][0], m_rBBox[1][1], m_rBBox[0][1] );


	int	i32TextureUnit = 0;

	// If there is image set it as current texture.
	int32	i32TextureFlags = 0;

	if( i32Wrap == WRAPMODE_CLAMP )
		i32TextureFlags |= IMAGE_CLAMP;
	else
		i32TextureFlags |= IMAGE_WRAP;

	if( i32Resample == RESAMPLEMODE_BILINEAR )
		i32TextureFlags |= IMAGE_LINEAR;
	else
		i32TextureFlags |= IMAGE_NEAREST;

	pD3DDevice->SetRenderState( D3DRS_LIGHTING, FALSE );
  pD3DDevice->SetRenderState( D3DRS_ALPHATESTENABLE, FALSE );
  pD3DDevice->SetRenderState( D3DRS_FILLMODE, D3DFILL_SOLID );
  pD3DDevice->SetRenderState( D3DRS_STENCILENABLE, FALSE );
  pD3DDevice->SetRenderState( D3DRS_CLIPPING, TRUE );
  pD3DDevice->SetRenderState( D3DRS_CLIPPLANEENABLE, FALSE );
  pD3DDevice->SetRenderState( D3DRS_VERTEXBLEND, D3DVBF_DISABLE );
  pD3DDevice->SetRenderState( D3DRS_INDEXEDVERTEXBLENDENABLE, FALSE );
  pD3DDevice->SetRenderState( D3DRS_FOGENABLE, FALSE );
  pD3DDevice->SetRenderState( D3DRS_COLORWRITEENABLE,
      D3DCOLORWRITEENABLE_RED  | D3DCOLORWRITEENABLE_GREEN |
      D3DCOLORWRITEENABLE_BLUE | D3DCOLORWRITEENABLE_ALPHA );

	pD3DDevice->SetRenderState( D3DRS_ZENABLE, FALSE );
	pD3DDevice->SetRenderState( D3DRS_ZWRITEENABLE, FALSE );
	pD3DDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE );
	
	pD3DDevice->SetRenderState( D3DRS_BLENDOP, D3DBLENDOP_ADD );
	pD3DDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA );
	pD3DDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA );

	BBox2C	TexBounds;
	
	if( pImp )
	{
		TexBounds = pImp->get_tex_coord_bounds();
		pImp->bind_texture( pDevice, 0, i32TextureFlags );

    pD3DDevice->SetTextureStageState( 0, D3DTSS_COLOROP,   D3DTOP_MODULATE );
    pD3DDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
    pD3DDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
    pD3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP,   D3DTOP_MODULATE );
    pD3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE );
    pD3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE );
    pD3DDevice->SetTextureStageState( 0, D3DTSS_TEXCOORDINDEX, 0 );
    pD3DDevice->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE );
	}
	else
	{
		pD3DDevice->SetTextureStageState( 0, D3DTSS_COLOROP,   D3DTOP_SELECTARG2 );
    pD3DDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
    pD3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP,   D3DTOP_SELECTARG2 );
    pD3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE );
	}

	Vector2C	rTexCoords[4];

	rTexCoords[0][0] = TexBounds[0][0];
	rTexCoords[0][1] = TexBounds[0][1];

	rTexCoords[1][0] = TexBounds[1][0];
	rTexCoords[1][1] = TexBounds[0][1];

	rTexCoords[2][0] = TexBounds[1][0];
	rTexCoords[2][1] = TexBounds[1][1];

	rTexCoords[3][0] = TexBounds[0][0];
	rTexCoords[3][1] = TexBounds[1][1];

	rImageOffset[0] *= (1.0f / (f32Width * 2.0f)) * TexBounds.width();
	rImageOffset[1] *= (1.0f / (f32Height * 2.0f)) * TexBounds.height();

	Vector2C	rCenter( TexBounds.width() * 0.5f, TexBounds.height() * 0.5f );

	// Transform texture coords
	for( i = 0; i < 4; i++ )
		rTexCoords[i] = (rTexCoords[i] - rCenter - rImageOffset) * rImageScale + rCenter;


	if( pImp )
	{
		DWORD	dwCol = D3DCOLOR_ARGB( (int32)(f32Opacity * 255), (int32)(rColor[0] * 255), (int32)(rColor[1] * 255), (int32)(rColor[2] * 255) );

		XYZCOLORUV_VERTEX	rQuad[4];
		rQuad[0].x = m_rVertices[0][0];
		rQuad[0].y = m_rVertices[0][1];
		rQuad[0].z = 0;
		rQuad[0].color = dwCol;
		rQuad[0].u = rTexCoords[0][0];
		rQuad[0].v = rTexCoords[0][1];

		rQuad[1].x = m_rVertices[1][0];
		rQuad[1].y = m_rVertices[1][1];
		rQuad[1].z = 0;
		rQuad[1].color = dwCol;
		rQuad[1].u = rTexCoords[1][0];
		rQuad[1].v = rTexCoords[1][1];

		rQuad[2].x = m_rVertices[2][0];
		rQuad[2].y = m_rVertices[2][1];
		rQuad[2].z = 0;
		rQuad[2].color = dwCol;
		rQuad[2].u = rTexCoords[2][0];
		rQuad[2].v = rTexCoords[2][1];

		rQuad[3].x = m_rVertices[3][0];
		rQuad[3].y = m_rVertices[3][1];
		rQuad[3].z = 0;
		rQuad[3].color = dwCol;
		rQuad[3].u = rTexCoords[3][0];
		rQuad[3].v = rTexCoords[3][1];

		pD3DDevice->SetFVF( FVF_XYZCOLORUV_VERTEX );
		pD3DDevice->SetPixelShader( NULL );
		pD3DDevice->DrawPrimitiveUP( D3DPT_TRIANGLEFAN, 2, rQuad, sizeof( XYZCOLORUV_VERTEX ) );
	}
	else
	{
		DWORD	dwCol = D3DCOLOR_ARGB( (int32)(f32Opacity * 255), (int32)(rColor[0] * 255), (int32)(rColor[1] * 255), (int32)(rColor[2] * 255) );

		XYZCOLOR_VERTEX	rQuad[4];
		rQuad[0].x = m_rVertices[0][0];
		rQuad[0].y = m_rVertices[0][1];
		rQuad[0].z = 0;
		rQuad[0].color = dwCol;

		rQuad[1].x = m_rVertices[1][0];
		rQuad[1].y = m_rVertices[1][1];
		rQuad[1].z = 0;
		rQuad[1].color = dwCol;

		rQuad[2].x = m_rVertices[2][0];
		rQuad[2].y = m_rVertices[2][1];
		rQuad[2].z = 0;
		rQuad[2].color = dwCol;

		rQuad[3].x = m_rVertices[3][0];
		rQuad[3].y = m_rVertices[3][1];
		rQuad[3].z = 0;
		rQuad[3].color = dwCol;

		pD3DDevice->SetFVF( FVF_XYZCOLOR_VERTEX );
		pD3DDevice->SetPixelShader( NULL );
		pD3DDevice->DrawPrimitiveUP( D3DPT_TRIANGLEFAN, 2, rQuad, sizeof( XYZCOLOR_VERTEX ) );
	}

	pD3DDevice->SetRenderState( D3DRS_ZENABLE, TRUE );
	pD3DDevice->SetRenderState( D3DRS_ZWRITEENABLE, TRUE );
}

BBox2C
DX9BoidsEffectC::get_bbox()
{
	// Return the bounding box.
	return m_rBBox;
}

const Matrix2C&
DX9BoidsEffectC::get_transform_matrix() const
{
	// Return the trnasformation matrix.
	return m_rTM;
}

bool
DX9BoidsEffectC::hit_test( const Vector2C& rPoint )
{
	// Point in polygon test.
	// from c.g.a FAQ
	int		i, j;
	bool	bInside = false;

	for( i = 0, j = 4 - 1; i < 4; j = i++ ) {
		if( ( ((m_rVertices[i][1] <= rPoint[1]) && (rPoint[1] < m_rVertices[j][1])) ||
			((m_rVertices[j][1] <= rPoint[1]) && (rPoint[1] < m_rVertices[i][1])) ) &&
			(rPoint[0] < (m_rVertices[j][0] - m_rVertices[i][0]) * (rPoint[1] - m_rVertices[i][1]) / (m_rVertices[j][1] - m_rVertices[i][1]) + m_rVertices[i][0]) )

			bInside = !bInside;
	}

	return bInside;
}


enum DX9BoidsEffectChunksE {
	CHUNK_IMAGE_BASE =				0x10,
	CHUNK_IMAGE_TRANSGIZMO =	0x20,
	CHUNK_IMAGE_ATTRIBGIZMO =	0x30,
};

const uint32	IMAGE_VERSION = 1;

uint32
DX9BoidsEffectC::save( SaveC* pSave )
{
	uint32	ui32Error = IO_OK;

	// EffectI base class
	pSave->begin_chunk( CHUNK_IMAGE_BASE, IMAGE_VERSION );
		ui32Error = EffectI::save( pSave );
	pSave->end_chunk();

	// Transform
	pSave->begin_chunk( CHUNK_IMAGE_TRANSGIZMO, IMAGE_VERSION );
		ui32Error = m_pTraGizmo->save( pSave );
	pSave->end_chunk();

	// Attribute
	pSave->begin_chunk( CHUNK_IMAGE_ATTRIBGIZMO, IMAGE_VERSION );
		ui32Error = m_pAttGizmo->save( pSave );
	pSave->end_chunk();

	return ui32Error;
}

uint32
DX9BoidsEffectC::load( LoadC* pLoad )
{
	uint32	ui32Error = IO_OK;

	while( (ui32Error = pLoad->open_chunk()) == IO_OK ) {

		switch( pLoad->get_chunk_id() ) {
		case CHUNK_IMAGE_BASE:
			// EffectI base class
			if( pLoad->get_chunk_version() == IMAGE_VERSION )
				ui32Error = EffectI::load( pLoad );
			break;

		case CHUNK_IMAGE_TRANSGIZMO:
			// Transform
			if( pLoad->get_chunk_version() == IMAGE_VERSION )
				ui32Error = m_pTraGizmo->load( pLoad );
			break;

		case CHUNK_IMAGE_ATTRIBGIZMO:
			// Attribute
			if( pLoad->get_chunk_version() == IMAGE_VERSION )
				ui32Error = m_pAttGizmo->load( pLoad );
			break;

		default:
			assert( 0 );
		}

		pLoad->close_chunk();

		if( ui32Error != IO_OK && ui32Error != IO_END )
			return ui32Error;
	}

	return ui32Error;
}
