//
// BrightnessContrastPlugin.cpp
//
// BrightnessContrast 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>
#include <stdio.h>
#include "glext.h"
#include "extgl.h"

#include "ColorMatrix.h"

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

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

using namespace HueSaturationPlugin;


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







//////////////////////////////////////////////////////////////////////////
//
//  HueSaturation effect class descriptor.
//

HueSaturationDescC::HueSaturationDescC()
{
	// empty
}

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

void*
HueSaturationDescC::create()
{
	return (void*)HueSaturationEffectC::create_new();
}

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

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

ClassIdC
HueSaturationDescC::get_class_id() const
{
	return CLASS_HUESATURATION_EFFECT;
};

const char*
HueSaturationDescC::get_name() const
{
	return "Hue/Saturation";
}

const char*
HueSaturationDescC::get_desc() const
{
	return "Hue/Saturation/Lightness Adjustment Effect";
}

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

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

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

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

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

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


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

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



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

HueSaturationDescC		g_rHueSaturationDesc;


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

HueSaturationEffectC::HueSaturationEffectC()
{
	//
	// 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(	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 );

	// Hue Amount
	m_pAttGizmo->add_parameter(	ParamFloatC::create_new( m_pAttGizmo, "Hue", 0.0f, ID_ATTRIBUTE_HUE,
						PARAM_STYLE_EDITBOX | PARAM_STYLE_ANGLE, PARAM_ANIMATABLE, 0.0f, 360.0f, 1.0f ) );

	// Saturation Amount
	m_pAttGizmo->add_parameter(	ParamFloatC::create_new( m_pAttGizmo, "Saturation", 0.0f, ID_ATTRIBUTE_SATURATION,
						PARAM_STYLE_EDITBOX | PARAM_STYLE_PERCENT, PARAM_ANIMATABLE, -1.0f, 1.0f, 0.01f ) );

	// Lightness Amount
	m_pAttGizmo->add_parameter(	ParamFloatC::create_new( m_pAttGizmo, "Lightness", 0.0f, ID_ATTRIBUTE_LIGHTNESS,
						PARAM_STYLE_EDITBOX | PARAM_STYLE_PERCENT, PARAM_ANIMATABLE, -1.0f, 1.0f, 0.01f ) );

}

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

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

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

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

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

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

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

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

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

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

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

GizmoI*
HueSaturationEffectC::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
HueSaturationEffectC::get_class_id()
{
	// Return the class ID. Should be same as in the class descriptor.
	return CLASS_HUESATURATION_EFFECT;
}

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

void
HueSaturationEffectC::set_default_file( int32 i32Time, FileHandleC* pHandle )
{
	// empty
}

ParamI*
HueSaturationEffectC::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_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;
}

void
HueSaturationEffectC::initialize( uint32 ui32Reason, DeviceContextC* pContext, TimeContextC* pTimeContext )
{
	if( ui32Reason == INIT_INITIAL_UPDATE ) {
		init_gl_extension();
	}
}


void
HueSaturationEffectC::eval_state( int32 i32Time, DeviceContextC* pContext, TimeContextC* pTimeContext )
{
	uint32		i;
	Matrix2C	rPosMat, rRotMat, rScaleMat, rPivotMat;

	Vector2C	rScale;
	Vector2C	rPos;
	Vector2C	rPivot;

	// 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 );
	((ParamVector2C*)m_pTraGizmo->get_parameter( ID_TRANSFORM_SCALE ))->get_val( i32Time, rScale );

	// Calculate transformation matrix.
	rPivotMat.set_trans( rPivot );
	rPosMat.set_trans( rPos );
	rScaleMat.set_scale( rScale ) ;
	m_rTM = rPivotMat * rScaleMat * rPosMat;

	//
	// calc bounding box
	//
	float32		f32Width = 25;
	float32		f32Height = 25;
	Vector2C	rMin, rMax;
	Vector2C	rVec;

	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;

	for( 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];
		}
	}

	// set
	m_rBBox[0] = rMin;
	m_rBBox[1] = rMax;


	float32	f32Hue = 0.0f;
	float32	f32Saturation = 0.0f;
	float32	f32Lightness = 0.0f;

	// Get hue
	((ParamFloatC*)m_pAttGizmo->get_parameter_by_id( ID_ATTRIBUTE_HUE ))->get_val( i32Time, f32Hue );

	// Get saturation
	((ParamFloatC*)m_pAttGizmo->get_parameter_by_id( ID_ATTRIBUTE_SATURATION ))->get_val( i32Time, f32Saturation );

	// Get lightness
	((ParamFloatC*)m_pAttGizmo->get_parameter_by_id( ID_ATTRIBUTE_LIGHTNESS ))->get_val( i32Time, f32Lightness );



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

	OpenGLViewportC*	pViewport = (OpenGLViewportC*)pDevice->query_interface( GRAPHICSDEVICE_VIEWPORT_INTERFACE );
	if( !pViewport )
		return;

	pViewport->set_ortho_pixel( m_rBBox );


/*	if( g_bColorTableInitialised ) {
		uint8	ui8ColorTable[4 * 256];

		for( i = 0; i < 256; i++ ) {
			ui8ColorTable[i * 4 + 0] = i / 2;
			ui8ColorTable[i * 4 + 1] = i / 2;
			ui8ColorTable[i * 4 + 2] = i / 2;
			ui8ColorTable[i * 4 + 3] = i / 2;
		}

		glEnable( GL_COLOR_TABLE );
		glColorTable( GL_COLOR_TABLE, GL_RGBA, 256, GL_RGBA, GL_UNSIGNED_BYTE, ui8ColorTable );
	}
*/


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


	// get image from frame buffer
	int32	i32Width = pViewport->get_width();
	int32	i32Height = pViewport->get_height();

	// Trim the bounding box to the layout
	BBox2C	rTrimBBox = pViewport->get_layout().trim( m_rBBox );

	BBox2C	rCapture;
	rCapture[0] = pViewport->layout_to_client( rTrimBBox[0] );
	rCapture[1] = pViewport->layout_to_client( rTrimBBox[1] );

	int32	i32X, i32Y;

	i32X = (int32)floor( rCapture[0][0] );
	i32Y = (int32)floor( rCapture[0][1] );

	int32	i32CaptureWidth = (int32)ceil( rCapture.width() );
	int32	i32CaptureHeight = (int32)ceil( rCapture.height() );

	if( i32X >= i32Width )
		return;
	if( i32X < 0 ) {
		i32CaptureWidth += i32X;
		i32X = 0;
	}
	if( (i32X + i32CaptureWidth) >= i32Width )
		i32CaptureWidth -= (i32X + i32CaptureWidth) - i32Width;
	if( i32CaptureWidth <= 0 )
		return;

	if( i32Y >= i32Height )
		return;
	if( i32Y < 0 ) {
		i32CaptureHeight += i32Y;
		i32Y = 0;
	}
	if( (i32Y + i32CaptureHeight) >= i32Height )
		i32CaptureHeight -= (i32Y + i32CaptureHeight) - i32Height;
	if( i32CaptureHeight <= 0 )
		return;


	glMatrixMode( GL_COLOR );
	glLoadIdentity();

	float	fMat[16];
	identmat( fMat );

	// hue
	simplehuerotatemat( fMat, f32Hue );

	// saturation
	saturatemat( fMat, (float)pow( 1.0f + f32Saturation, 2 ) );
	
	// Lightness
	offsetmat( fMat, f32Lightness, f32Lightness, f32Lightness );

	
	glLoadMatrixf( fMat );


	glColor4f( 1, 1, 1, 1 );
	glRasterPos2i( i32X, i32Y );
	glCopyPixels( i32X, i32Y, i32CaptureWidth, i32CaptureHeight, GL_COLOR );


//	if( g_bColorTableInitialised )
//		glDisable( GL_COLOR_TABLE );

	glMatrixMode( GL_COLOR );
	glLoadIdentity();
	glMatrixMode( GL_MODELVIEW );


	glDepthMask( GL_TRUE );
}

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

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

bool
HueSaturationEffectC::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 HueSaturationEffectChunksE {
	CHUNK_HueSaturation_BASE =			0x1000,
	CHUNK_HueSaturation_TRANSGIZMO =		0x2000,
	CHUNK_HueSaturation_ATTRIBGIZMO =	0x3000,
};

const uint32	HueSaturation_VERSION = 1;

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

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

	// Transform
	pSave->begin_chunk( CHUNK_HueSaturation_TRANSGIZMO, HueSaturation_VERSION );
		ui32Error = m_pTraGizmo->save( pSave );
	pSave->end_chunk();

	// Attribute
	pSave->begin_chunk( CHUNK_HueSaturation_ATTRIBGIZMO, HueSaturation_VERSION );
		ui32Error = m_pAttGizmo->save( pSave );
	pSave->end_chunk();

	return ui32Error;
}

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

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

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

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

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

		default:
			assert( 0 );
		}

		pLoad->close_chunk();

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

	return ui32Error;
}
