//
// AVIPlugin.cpp
//
// AVI Plugin
//
// Copyright (c) 2000 memon/moppi productions
//

//#define WIN32_LEAN_AND_MEAN		// Exclude rarely-used stuff from Windows headers
#include <windows.h>
#include <gl\gl.h>
#include <gl\glu.h>

// Demopaja headers
#include "DemopajaVersion.h"
#include "PajaTypes.h"
#include "ClassDescC.h"
#include "ImportableI.h"
#include "OpenGLDeviceC.h"
#include "OpenGLViewportC.h"
#include "AVIPlugin.h"
#include "FileIO.h"
#include "AutoGizmoC.h"
#include "ImportableImageI.h"
#include "ImageResampleC.h"

#include "AVIPlayerC.h"

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

using namespace AVIPlugin;


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 );
}




inline
uint32
lowest_bit_mask( uint32 v )
{
	return (v & -v);
}

static
uint32
ceil_power2( uint32 ui32Num )
{
	uint32	i = lowest_bit_mask( ui32Num );
	while( i < ui32Num )
		i <<= 1;
	return i;
}

static
int32
nearest_power2( int32 i32Num )
{
	int32	i = ceil_power2( i32Num );	// bigger
	int32	j = i / 2;					// smaller

	int32	i32DiffI = i - i32Num;
	int32	i32DiffJ = i32Num - j;

	// diff J has to be twice as little as diffI to be chosen.
	i32DiffI /= 2;

	if( i32DiffJ < i32DiffI )
		return j;

	return i;
}


//////////////////////////////////////////////////////////////////////////
//
//  AVI importer class descriptor.
//

AVIImportDescC::AVIImportDescC()
{
	// empty
}

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

void*
AVIImportDescC::create()
{
	return AVIImportC::create_new();
}

int32
AVIImportDescC::get_classtype() const
{
	return CLASS_TYPE_FILEIMPORT;
}

SuperClassIdC
AVIImportDescC::get_super_class_id() const
{
	return SUPERCLASS_IMAGE;//SUPERCLASS_VIDEO;
}

ClassIdC
AVIImportDescC::get_class_id() const
{
	return CLASS_AVI_IMPORT;
}

const char*
AVIImportDescC::get_name() const
{
	return "AVI Animation";
}

const char*
AVIImportDescC::get_desc() const
{
	return "Importer for AVI animations";
}

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

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

const char*
AVIImportDescC::get_url() const
{
	return "http://moppi.inside.org/demopaja/";
}

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

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

const ClassIdC&
AVIImportDescC::get_required_device_driver( uint32 ui32Idx )
{
	return PajaSystem::CLASS_OPENGL_DEVICEDRIVER;
}

uint32
AVIImportDescC::get_ext_count() const
{
	return 1;
}

const char*
AVIImportDescC::get_ext( uint32 ui32Index ) const
{
	if( ui32Index == 0 )
		return "AVI";
	return 0;
}


//////////////////////////////////////////////////////////////////////////
//
//  AVI player effect class descriptor.
//

AVIPlayerDescC::AVIPlayerDescC()
{
	// empty
}

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

void*
AVIPlayerDescC::create()
{
	return (void*)AVIPlayerEffectC::create_new();
}

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

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

ClassIdC
AVIPlayerDescC::get_class_id() const
{
	return CLASS_AVIPLAYER_EFFECT;
};

const char*
AVIPlayerDescC::get_name() const
{
	return "Video Player";
}

const char*
AVIPlayerDescC::get_desc() const
{
	return "Video Player Effect";
}

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

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

const char*
AVIPlayerDescC::get_url() const
{
	return "http://moppi.inside.org/demopaja/";
}

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

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

const ClassIdC&
AVIPlayerDescC::get_required_device_driver( uint32 ui32Idx )
{
	return PajaSystem::CLASS_OPENGL_DEVICEDRIVER;
}


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

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


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

AVIImportDescC	g_rAVIImportDesc;
AVIPlayerDescC	g_rAVIPlayerDesc;

#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 2;
}


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

__declspec( dllexport )
ClassDescC*
get_classdesc( int32 i )
{
	if( i == 0 )
		return &g_rAVIImportDesc;
	if( i == 1 )
		return &g_rAVIPlayerDesc;
	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 "AVIPlugin.dll - AVI Animation Plugin (c)2000 memon/moppi productions";
}

#endif



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

AVIPlayerEffectC::AVIPlayerEffectC() :
	m_i32FilterMode( 0 ),
	m_i32RenderMode( 0 )
{
	//
	// 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 );

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

	// Render mode
	ParamIntC*	pRenderMode = ParamIntC::create_new( m_pAttGizmo, "Render mode", 0, ID_ATTRIBUTE_RENDERMODE, PARAM_STYLE_COMBOBOX, PARAM_ANIMATABLE, 0, 2 );
	pRenderMode->add_label( 0, "Normal" );
	pRenderMode->add_label( 1, "Add" );
	pRenderMode->add_label( 2, "Mult" );
	m_pAttGizmo->add_parameter( pRenderMode );

	// Filter mode
	ParamIntC*	pFilterMode = ParamIntC::create_new( m_pAttGizmo, "Filter mode", 0, ID_ATTRIBUTE_FILTERMODE, PARAM_STYLE_COMBOBOX, PARAM_ANIMATABLE, 0, 1 );
	pFilterMode->add_label( 0, "Bilinear" );
	pFilterMode->add_label( 1, "Nearest" );
	m_pAttGizmo->add_parameter( pFilterMode );

	// File
//	m_pAttGizmo->add_parameter(	ParamFileC::create_new( m_pAttGizmo, "Video", SUPERCLASS_VIDEO, NULL_CLASSID, ID_ATTRIBUTE_FILE ) );
	m_pAttGizmo->add_parameter(	ParamFileC::create_new( m_pAttGizmo, "Video", SUPERCLASS_IMAGE, NULL_CLASSID, ID_ATTRIBUTE_FILE, PARAM_STYLE_FILE, PARAM_ANIMATABLE ) );


	//
	// Create Time gizmo.
	//
	m_pTimeGizmo = AutoGizmoC::create_new( this, "Timing", ID_GIZMO_TIME );
	
//	m_pTimeGizmo->add_parameter( ParamFloatC::create_new( m_pTimeGizmo, "FPS", 0, ID_TIME_FPS,
//						PARAM_STYLE_EDITBOX, PARAM_NOT_ANIMATABLE, 0, 1000.0f, 1.0f ) );

	m_pTimeGizmo->add_parameter( ParamFloatC::create_new( m_pTimeGizmo, "Frame", 0, ID_TIME_FRAME,
						PARAM_STYLE_EDITBOX, PARAM_ANIMATABLE, 0, 0, 1.0f ) );

}

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

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

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

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

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

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

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

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

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

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

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

GizmoI*
AVIPlayerEffectC::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;
	case ID_GIZMO_TIME:
		return m_pTimeGizmo;
	}

	return 0;
}

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

const char*
AVIPlayerEffectC::get_class_name()
{
	// Return the class name. Should be same as in the class descriptor.
	return "Video Player";
}

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

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

	// 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*
AVIPlayerEffectC::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
AVIPlayerEffectC::update_notify( EditableI* pCaller )
{
	return PARAM_NOTIFY_NONE;
}

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

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

	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 fiel or use the defautls if no file.
	ImportableImageI*	pImp = 0;
	FileHandleC*		pHandle;
	int32				i32FileTime;
	((ParamFileC*)m_pAttGizmo->get_parameter( ID_ATTRIBUTE_FILE ))->get_file( i32Time, pHandle, i32FileTime );

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

	if( pImp ) {

		// If "Frame" parameter is animated, use it instead of FPS setting.
		ParamFloatC*	pParamFrame = (ParamFloatC*)m_pTimeGizmo->get_parameter_by_id( ID_TIME_FRAME );
		ControllerC*	pCont = pParamFrame->get_controller();
		if( pCont && pCont->get_key_count() ) {
			float32	f32Frame;
			pParamFrame->get_val( i32Time, f32Frame );

			float32	f32StartFrame = pImp->get_start_label();
			float32	f32EndFrame = pImp->get_end_label();

			if( (f32EndFrame - f32StartFrame) >= 0 ) {
				i32FileTime = (int32)(((f32Frame - f32StartFrame) / (f32EndFrame - f32StartFrame)) * pImp->get_duration());
			}
//			else {
//				m_i32FileTime = i32FileTime;
//			}
		}
//		else {
//			m_i32FileTime = i32FileTime;
//		}

		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;

	// Get fill color.
	((ParamColorC*)m_pAttGizmo->get_parameter( ID_ATTRIBUTE_COLOR ))->get_val( i32Time, m_rFillColor );

	// Get rendermode
	((ParamIntC*)m_pAttGizmo->get_parameter( ID_ATTRIBUTE_RENDERMODE ))->get_val( i32Time, m_i32RenderMode );

	// Get filtermode
	((ParamIntC*)m_pAttGizmo->get_parameter( ID_ATTRIBUTE_FILTERMODE ))->get_val( i32Time, m_i32FilterMode );

/*	if( pImp ) {

		ParamFloatC*	pFrame = (ParamFloatC*)m_pTimeGizmo->get_parameter( ID_TIME_FRAME );
		ControllerC*	pCont = pFrame->get_controller();

		// If "Frame" parameter is animated, use it instead of FPS setting.
		if( pCont && pCont->get_key_count() ) {
			float32	f32Frame;
			pFrame->get_val( i32Time, f32Frame );
			m_i32Frame = (int32)f32Frame;
		}
		else {
			float32	f32Fps;
			((ParamFloatC*)m_pTimeGizmo->get_parameter( ID_TIME_FPS ))->get_val( i32Time, f32Fps );
			m_i32Frame = (int32)pTimeContext->convert_time_to_fps( i32Time, f32Fps );
			m_i32Frame += pImp->get_first_frame();
		}
	}
	else
		m_i32Frame = 0;*/



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

	// Get the OpenGL viewport.
	OpenGLViewportC*	pViewport = (OpenGLViewportC*)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] );

	if( pImp ) {
		// If there is image set it as current texture.
		int32	i32Flags = IMAGE_CLAMP;
		if( m_i32FilterMode == FILTERMODE_LINEAR )
			i32Flags |= IMAGE_LINEAR;
		else
			i32Flags |= IMAGE_NEAREST;

		pImp->bind_texture( pDevice, 0, i32Flags );
		glEnable( GL_TEXTURE_2D );
	}
	else
		glDisable( GL_TEXTURE_2D );

	glDisable( GL_DEPTH_TEST );
	glDepthMask( GL_FALSE );
	glEnable( GL_BLEND );

	if( m_i32RenderMode == RENDERMODE_NORMAL ) {
		// Normal
		glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
	}
	else if( m_i32RenderMode == RENDERMODE_ADD ) {
		// Add
		glBlendFunc( GL_SRC_ALPHA, GL_ONE );
	}
	else {
		// Mult
		glBlendFunc( GL_DST_COLOR, GL_ONE_MINUS_SRC_ALPHA );
	}
	

	if( m_i32RenderMode == RENDERMODE_MULT ) // mult
		glColor4f( m_rFillColor[0] * m_rFillColor[3], m_rFillColor[1] * m_rFillColor[3], m_rFillColor[2] * m_rFillColor[3], m_rFillColor[3] );
	else
		glColor4fv( m_rFillColor );

	// Draw rectangle.
	glBegin( GL_QUADS );

	glTexCoord2f( 0, 0 );
	glVertex2f( m_rVertices[0][0], m_rVertices[0][1] );
	
	glTexCoord2f( 1, 0 );
	glVertex2f( m_rVertices[1][0], m_rVertices[1][1] );
	
	glTexCoord2f( 1, 1 );
	glVertex2f( m_rVertices[2][0], m_rVertices[2][1] );

	glTexCoord2f( 0, 1 );
	glVertex2f( m_rVertices[3][0], m_rVertices[3][1] );

	glEnd();

	glDepthMask( GL_TRUE );
}

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

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

bool
AVIPlayerEffectC::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 AVIPlayerEffectChunksE {
	CHUNK_AVIPLAYER_BASE =			0x1000,
	CHUNK_AVIPLAYER_TRANSGIZMO =	0x2000,
	CHUNK_AVIPLAYER_ATTRIBGIZMO =	0x3000,
	CHUNK_AVIPLAYER_TIMEGIZMO =	0x4000,
};

const uint32	AVIPLAYER_VERSION = 1;

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

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

	// Transform
	pSave->begin_chunk( CHUNK_AVIPLAYER_TRANSGIZMO, AVIPLAYER_VERSION );
		ui32Error = m_pTraGizmo->save( pSave );
	pSave->end_chunk();

	// Attribute
	pSave->begin_chunk( CHUNK_AVIPLAYER_ATTRIBGIZMO, AVIPLAYER_VERSION );
		ui32Error = m_pAttGizmo->save( pSave );
	pSave->end_chunk();

	// Time
	pSave->begin_chunk( CHUNK_AVIPLAYER_TIMEGIZMO, AVIPLAYER_VERSION );
		ui32Error = m_pTimeGizmo->save( pSave );
	pSave->end_chunk();

	return ui32Error;
}

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

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

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

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

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

		case CHUNK_AVIPLAYER_TIMEGIZMO:
			// Attribute
			if( pLoad->get_chunk_version() == AVIPLAYER_VERSION )
				ui32Error = m_pTimeGizmo->load( pLoad );
			break;

		default:
			assert( 0 );
		}

		pLoad->close_chunk();

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

	return ui32Error;
}


//////////////////////////////////////////////////////////////////////////
//
// AVI Importer class implementation.
//

AVIImportC::AVIImportC() :
	m_ui32TextureId( 0 ),
	m_pRawData( 0 ),
	m_ui32RawSize( 0 ),
	m_pPlayer( 0 ),
	m_i32LastFrame( -1 ),
	m_pResampleData( 0 ),
	m_ui32ResampleWidth( 0 ),
	m_ui32ResampleHeight( 0 ),
	m_i32CurrentFrame( 0 ),
	m_bNeedUpdate( false )
{
	m_rTexBounds[0] = Vector2C( 0, 0 );
	m_rTexBounds[1] = Vector2C( 1, 1 );
}

AVIImportC::AVIImportC( EditableI* pOriginal ) :
//	ImportableVideoI( pOriginal ),
	ImportableImageI( pOriginal ),
	m_ui32TextureId( 0 ),
	m_pRawData( 0 ),
	m_ui32RawSize( 0 ),
	m_pPlayer( 0 ),
	m_i32LastFrame( -1 ),
	m_pResampleData( 0 ),
	m_ui32ResampleWidth( 0 ),
	m_ui32ResampleHeight( 0 ),
	m_i32CurrentFrame( 0 ),
	m_bNeedUpdate( false )
{
	m_rTexBounds[0] = Vector2C( 0, 0 );
	m_rTexBounds[1] = Vector2C( 1, 1 );
}

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

	// Delete creted texture.
	if( m_ui32TextureId )
		glDeleteTextures( 1, &m_ui32TextureId );

	delete [] m_pRawData;
	delete m_pPlayer;

	delete [] m_pResampleData;
}

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

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

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

void
AVIImportC::copy( EditableI* pEditable )
{
	// Importables which loads the data from a file does
	// not have to implement this method, since they will
	// not be duplicated.
}

void
AVIImportC::restore( EditableI* pEditable )
{
	AVIImportC*	pFile = (AVIImportC*)pEditable;

	m_ui32TextureId = pFile->m_ui32TextureId;
	m_sFileName = pFile->m_sFileName;

	m_pRawData = pFile->m_pRawData;
	m_ui32RawSize = pFile->m_ui32RawSize;
	m_pPlayer = pFile->m_pPlayer;
	m_i32LastFrame = pFile->m_i32LastFrame;
	m_pResampleData = pFile->m_pResampleData;
	m_ui32ResampleWidth = pFile->m_ui32ResampleWidth;
	m_ui32ResampleHeight = pFile->m_ui32ResampleHeight;
}

const char*
AVIImportC::get_filename()
{
	return m_sFileName.c_str();
}

void
AVIImportC::set_filename( const char* szName )
{
	m_sFileName = szName;
}

bool
AVIImportC::load_file( const char* szName, PajaSystem::DemoInterfaceC* pInterface )
{
	uint32	ui32Header[3];
	FILE*	pStream;

	// Store interface pointer.
	m_pDemoInterface = pInterface;

	// Open file stream.
	if( (pStream = fopen( pInterface->get_absolute_path( szName ), "rb" )) == 0 ) {
		return false;
	}

	// Check if the file type is correct
	fread( ui32Header, sizeof( ui32Header ), 1, pStream );

	if( ui32Header[0] != RIFF_TAG || ui32Header[2] != AVI_TAG ) {
		fclose( pStream );
		return false;
	}

	// Find file size
	fseek( pStream, 0, SEEK_END );
	m_ui32RawSize = ftell( pStream );
	fseek( pStream, 0, SEEK_SET );

	// Allocate data for whole file
	m_pRawData = new uint8[m_ui32RawSize];

	// Read the whole file in.
	fread( m_pRawData, 1, m_ui32RawSize, pStream );

	// Close file stream.
	fclose( pStream );

	// Store file name.
	m_sFileName = szName;

	// Parse file.
	delete m_pPlayer;

	m_pPlayer = new AVIPlayerC;
	m_pPlayer->parse_file( m_pRawData, m_ui32RawSize );

	m_i32LastFrame = -1;

	return true;
}

void
AVIImportC::initialize( uint32 ui32Reason, DemoInterfaceC* pInterface )
{
	ImportableI::initialize( ui32Reason, pInterface );

	DeviceContextC* pContext = pInterface->get_device_context();
	TimeContextC* pTimeContext = pInterface->get_time_context();

	if( ui32Reason == INIT_DEVICE_CHANGED ) {

		OpenGLDeviceC*	pDevice = (OpenGLDeviceC*)pContext->query_interface( CLASS_OPENGL_DEVICEDRIVER );
		if( !pDevice )
			return;

		if( pDevice->get_state() == DEVICE_STATE_SHUTTINGDOWN ) {
			// Delete textures
			glDeleteTextures( 1, &m_ui32TextureId );
			m_ui32TextureId = 0;
			m_bNeedUpdate = true;
		}

	}
	else if( ui32Reason == INIT_INITIAL_UPDATE ) {

		OpenGLDeviceC*	pDevice = (OpenGLDeviceC*)pContext->query_interface( CLASS_OPENGL_DEVICEDRIVER );
		if( !pDevice )
			return;

		// Check if the video needs to be rescaled.
		if( m_pPlayer ) {
			uint32	ui32WidthPow2 = nearest_power2( m_pPlayer->get_width() );
			uint32	ui32HeightPow2 = nearest_power2( m_pPlayer->get_height() );

//			TRACE( "%d x %d --> %d x %d\n", m_pPlayer->get_width(), m_pPlayer->get_height(), ui32WidthPow2, ui32HeightPow2 );

			if( m_pPlayer->get_width() != ui32WidthPow2 || m_pPlayer->get_height() != ui32HeightPow2 ) {
				m_pResampleData = new uint8[ui32WidthPow2 * ui32HeightPow2 * (m_pPlayer->get_bpp() / 8)];
				m_ui32ResampleWidth = ui32WidthPow2;
				m_ui32ResampleHeight = ui32HeightPow2;
			}
		}
		m_bNeedUpdate = true;
	}
}

ClassIdC
AVIImportC::get_class_id()
{
	return CLASS_AVI_IMPORT;
}

const char*
AVIImportC::get_class_name()
{
	return "AVI Animation";
}

float32
AVIImportC::get_width()
{
	if( m_pPlayer )
		return (float32)m_pPlayer->get_width();
	return 0;
}

float32
AVIImportC::get_height()
{
	if( m_pPlayer )
		return (float32)m_pPlayer->get_height();
	return 0;
}

int32
AVIImportC::get_data_width()
{
	if( m_pPlayer ) {
		return m_pPlayer->get_width();
	}
	return 0;
}

int32
AVIImportC::get_data_height()
{
	if( m_pPlayer ) {
		return m_pPlayer->get_height();
	}
	return 0;
}

int32
AVIImportC::get_data_pitch()
{
	if( m_pPlayer ) {
		return m_pPlayer->get_width();
	}
	return 0;
}

BBox2C&
AVIImportC::get_tex_coord_bounds()
{
	return m_rTexBounds;
}

int32
AVIImportC::get_data_bpp()
{
	if( m_pPlayer )
		return m_pPlayer->get_bpp();
	return 0;
}

uint8*
AVIImportC::get_data()
{
	if( m_pPlayer ) {
		return m_pPlayer->get_data();
	}
	return 0;
}


int32
AVIImportC::get_first_frame()
{
	return 0;
}

int32
AVIImportC::get_last_frame()
{
	if( m_pPlayer )
		return m_pPlayer->get_frames();
	return 0;
}

float32
AVIImportC::get_fps()
{
	if( m_pPlayer )
		return m_pPlayer->get_fps();
	return 0;
}



void
AVIImportC::bind_texture( DeviceInterfaceI* pInterface, PajaTypes::uint32 ui32Stage, uint32 ui32Properties )
{
	if( !pInterface || pInterface->get_class_id() != CLASS_OPENGL_DEVICEDRIVER )
		return;

	if( !m_ui32TextureId )
		glGenTextures( 1, &m_ui32TextureId );


	glBindTexture( GL_TEXTURE_2D, m_ui32TextureId );
	glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );

	if( ui32Properties & IMAGE_LINEAR ) {
		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
	}
	else {
		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
	}

	if( ui32Properties & IMAGE_CLAMP ) {
		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP );
		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP );
	}
	else {
		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
	}

	if( !m_bNeedUpdate )
		return;

	m_bNeedUpdate = false;

//	if( m_i32LastFrame == m_i32CurrentFrame )
//		return;
//	m_i32LastFrame = m_i32CurrentFrame;

	int32	i32Width = m_pPlayer->get_width();
	int32	i32Height = m_pPlayer->get_height();
	int32	i32Bpp = m_pPlayer->get_bpp();
	uint8*	pFrameData = m_pPlayer->get_data(); //decompress_frame( m_i32CurrentFrame );

	if( !pFrameData )
		return;

	// resample
	if( m_ui32ResampleWidth && m_ui32ResampleHeight ) {
		uint8*	pData = pFrameData;
		ImageResampleC::resample_nearest( m_pPlayer->get_bpp(), pFrameData, m_pPlayer->get_width(), m_pPlayer->get_height(),
			m_pResampleData, m_ui32ResampleWidth, m_ui32ResampleHeight );

		i32Width = m_ui32ResampleWidth;
		i32Height = m_ui32ResampleHeight;
		pFrameData = m_pResampleData;
	}

	glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, i32Width, i32Height, 0, GL_BGR_EXT, GL_UNSIGNED_BYTE, pFrameData );

}

const char*
AVIImportC::get_info()
{
	static char	szInfo[256];
	if( m_pPlayer ) {
		int32	i32Width = m_pPlayer->get_width();
		int32	i32Height = m_pPlayer->get_height();
		int32	i32Bpp = m_pPlayer->get_bpp();
		float32	f32Fps = m_pPlayer->get_fps();
		_snprintf( szInfo, 255, "%d x %d x %dBPP @ %.1f FPS", i32Width, i32Height, i32Bpp, f32Fps );
	}
	else {
		_snprintf( szInfo, 255, "No Player" );
	}
	return szInfo;
}

ClassIdC
AVIImportC::get_default_effect()
{
	return CLASS_AVIPLAYER_EFFECT;
}


int32
AVIImportC::get_duration()
{
	if( !m_pDemoInterface )
		return -1;
	TimeContextC* pTimeContext = m_pDemoInterface->get_time_context();

	if( m_pPlayer )
		return (int32)pTimeContext->convert_fps_to_time( m_pPlayer->get_frames(), m_pPlayer->get_fps() );
	return -1;
}

float32
AVIImportC::get_start_label()
{
	return 0;
}

float32
AVIImportC::get_end_label()
{
	if( m_pPlayer )
		return (float32)m_pPlayer->get_frames();
	return 0;
}

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

	DeviceContextC* pContext = m_pDemoInterface->get_device_context();
	TimeContextC* pTimeContext = m_pDemoInterface->get_time_context();

	m_i32CurrentFrame = (int32)pTimeContext->convert_time_to_fps( i32Time, m_pPlayer->get_fps() );

	if( m_i32LastFrame == m_i32CurrentFrame )
		return;

	m_i32LastFrame = m_i32CurrentFrame;

	m_pPlayer->decompress_frame( m_i32CurrentFrame );
	m_bNeedUpdate = true;
}


enum AVIImportChunksE {
	CHUNK_AVIIMPORT_BASE =		0x1000,
	CHUNK_AVIIMPORT_DATA =		0x2000,
};

const uint32	AVIIMPORT_VERSION = 1;


uint32
AVIImportC::save( SaveC* pSave )
{
	uint32		ui32Error = IO_OK;
	std::string	sStr;

	// file base
	pSave->begin_chunk( CHUNK_AVIIMPORT_BASE, AVIIMPORT_VERSION );
		sStr = m_sFileName;
		if( sStr.size() > 255 )
			sStr.resize( 255 );
		ui32Error = pSave->write_str( sStr.c_str() );
	pSave->end_chunk();

	// file data
	pSave->begin_chunk( CHUNK_AVIIMPORT_DATA, AVIIMPORT_VERSION );
		ui32Error = pSave->write( &m_ui32RawSize, sizeof( m_ui32RawSize ) );
		ui32Error = pSave->write( m_pRawData, m_ui32RawSize );
	pSave->end_chunk();

	return ui32Error;
}

uint32
AVIImportC::load( LoadC* pLoad )
{
	uint32	ui32Error = IO_OK;
	char	szStr[256];

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

		switch( pLoad->get_chunk_id() ) {
		case CHUNK_AVIIMPORT_BASE:
			{
				if( pLoad->get_chunk_version() == AVIIMPORT_VERSION ) {
					ui32Error = pLoad->read_str( szStr );
					m_sFileName = szStr;
				}
			}
			break;

		case CHUNK_AVIIMPORT_DATA:
			{
				if( pLoad->get_chunk_version() == AVIIMPORT_VERSION ) {
					// delete old data if any
					delete m_pRawData;
					// load new
					ui32Error = pLoad->read( &m_ui32RawSize, sizeof( m_ui32RawSize ) );
					m_pRawData = new uint8[m_ui32RawSize];
					ui32Error = pLoad->read( m_pRawData, m_ui32RawSize );

					// Parse file.
					delete m_pPlayer;

					m_pPlayer = new AVIPlayerC;
					m_pPlayer->parse_file( m_pRawData, m_ui32RawSize );
				}
			}
			break;

		default:
			assert( 0 );
		}

		pLoad->close_chunk();

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

	return ui32Error;
}


