/*	Renegade Scripts.dll
	Normal Map Shader Class
	Copyright 2007 Mark Sararu, Jonathan Wilson

	This file is part of the Renegade scripts.dll
	The Renegade scripts.dll is free software; you can redistribute it and/or modify it under
	the terms of the GNU General Public License as published by the Free
	Software Foundation; either version 2, or (at your option) any later
	version. See the file COPYING for more details.
	In addition, an exemption is given to allow Run Time Dynamic Linking of this code with any closed source module that does not contain code covered by this licence.
	Only the source code to the module(s) containing the licenced code has to be released.
*/
#include "scripts.h"
#include "shadereng.h"
#include "resourcemanager.h"
#include "shaderstatemanager.h"
#include "effect.h"
#include "shader.h"
#include "normalmapshader.h"

NormalMapShaderClass::NormalMapShaderClass() : ProgrammableShaderClass()
{
	PixelShaderVersion = 2.0f;
	VertexShaderVersion = 2.0f;
	LightColor = Vector4(1.0f, 1.0f, 1.0f, 1.0f);
	AmbientColor = Vector4(0.4f, 0.4f, 0.4f, 1.0f);
	SurfaceColor = Vector4(1.0f, 1.0f, 1.0f, 1.0f);
	SpecularEnabled = false;
	SpecularColor = Vector4(0.4f, 0.4f, 0.4f, 1.0f);
	SpecularPower = 30.0f;
	NormalMapFilename = 0;
#ifndef SDBEDIT
	ResetMapVariables = true;
	EnableFillHandles = true;
#endif
}
NormalMapShaderClass::~NormalMapShaderClass()
{
	delete[] NormalMapFilename;
	ProgrammableShaderClass::~ProgrammableShaderClass();
}
void NormalMapShaderClass::Load(ChunkLoadClass &cload)
{
	while (cload.Open_Micro_Chunk())
	{
		switch(cload.Cur_Micro_Chunk_ID())
		{
			case MC_NORMALMAP_MATERIALNAME:
				Name = new char[cload.Cur_Micro_Chunk_Length()];
				cload.Read(Name,cload.Cur_Micro_Chunk_Length());
				CRC32 = CRC_Memory((unsigned char *)_strlwr(Name),strlen(Name),0);
				break;
			case MC_NORMALMAP_FXFILENAME:
				Filename = new char[cload.Cur_Micro_Chunk_Length()];
				cload.Read(Filename,cload.Cur_Micro_Chunk_Length());
				#ifndef SDBEDIT
				Effect = new EffectClass(Filename);
				#endif
				break;
			case MC_NORMALMAP_NORMALMAPFILENAME:
				NormalMapFilename = new char[cload.Cur_Micro_Chunk_Length()];
				cload.Read(NormalMapFilename,cload.Cur_Micro_Chunk_Length());
				break;
			case MC_NORMALMAP_LIGHTCOLOR:
				cload.Read(&LightColor,sizeof(Vector4));
				break;
			case MC_NORMALMAP_AMBIENTCOLOR:
				cload.Read(&AmbientColor,sizeof(Vector4));
				break;
			case MC_NORMALMAP_SURFACECOLOR:
				cload.Read(&SurfaceColor,sizeof(Vector4));
				break;
			case MC_NORMALMAP_SPECULARENABLED:
				cload.Read(&SpecularEnabled,sizeof(bool));
				break;
			case MC_NORMALMAP_SPECULARCOLOR:
				cload.Read(&SpecularColor,sizeof(Vector4));
				break;
			case MC_NORMALMAP_SPECULARPOWER:
				cload.Read(&SpecularPower,sizeof(float));
				break;
		}
		cload.Close_Micro_Chunk();
	}

}
void NormalMapShaderClass::Save(ChunkSaveClass &csave)
{
	csave.Begin_Chunk(SHADER_NORMALMAP);
	csave.Begin_Micro_Chunk(MC_NORMALMAP_MATERIALNAME);
	csave.Write(Name,strlen(Name) + 1);
	csave.End_Micro_Chunk();
	csave.Begin_Micro_Chunk(MC_NORMALMAP_FXFILENAME);
	csave.Write(Filename,strlen(Filename) + 1);
	csave.End_Micro_Chunk();
	csave.Begin_Micro_Chunk(MC_NORMALMAP_NORMALMAPFILENAME);
	csave.Write(NormalMapFilename,strlen(NormalMapFilename) + 1);
	csave.End_Micro_Chunk();
	csave.Begin_Micro_Chunk(MC_NORMALMAP_LIGHTCOLOR);
	csave.Write(&LightColor,sizeof(Vector4));
	csave.End_Micro_Chunk();
	csave.Begin_Micro_Chunk(MC_NORMALMAP_AMBIENTCOLOR);
	csave.Write(&AmbientColor,sizeof(Vector4));
	csave.End_Micro_Chunk();
	csave.Begin_Micro_Chunk(MC_NORMALMAP_SURFACECOLOR);
	csave.Write(&SurfaceColor,sizeof(Vector4));
	csave.End_Micro_Chunk();
	csave.Begin_Micro_Chunk(MC_NORMALMAP_SPECULARENABLED);
	csave.Write(&SpecularEnabled,sizeof(bool));
	csave.End_Micro_Chunk();
	csave.Begin_Micro_Chunk(MC_NORMALMAP_SPECULARCOLOR);
	csave.Write(&SpecularColor,sizeof(Vector4));
	csave.End_Micro_Chunk();
	csave.Begin_Micro_Chunk(MC_NORMALMAP_SPECULARPOWER);
	csave.Write(&SpecularPower,sizeof(float));
	csave.End_Micro_Chunk();
	csave.End_Chunk();
}
#ifndef SDBEDIT
void NormalMapShaderClass::Reset_Cache()
{
	ResetMapVariables = true;
				  
}
void NormalMapShaderClass::Reload_Resources() 
{
	if ((PixelShaderVersion > ShaderCaps::PixelShaderVersion) || (VertexShaderVersion > ShaderCaps::VertexShaderVersion))
	{
		return;
	}
	if (Loaded)
	{
		return;
	}
	if (Effect->Initialized != true)
	{
		Effect->Init();
	}
	else 
	{
		Effect->OnDeviceReset();
	}
	texture_NormalMap = Load_Texture(NormalMapFilename,MIP_LEVELS_ALL,WW3D_FORMAT_UNKNOWN,true);
	Loaded = true;
}
void NormalMapShaderClass::Release_Resources()
{
	if (!Loaded)
	{
		return;
	}
	Free_Texture(texture_NormalMap);
	Effect->OnDeviceLost();
	Loaded = false;
}
void NormalMapShaderClass::FillHandles()
{
	ColorTextureHandle =							Effect->GetParameterBySemantic(NULL,"TextureColor");
	NormalTextureHandle =							Effect->GetParameterBySemantic(NULL,"TextureNormal");
	AmbientLightColorHandle	=						Effect->GetParameterBySemantic(NULL,"AmbientColor");
	SurfaceColorHandle =							Effect->GetParameterBySemantic(NULL,"SurfaceColor");
	Light1DirectionHandle =							Effect->GetParameterBySemantic(NULL,"Light1Direction");
	Light1DiffuseColorHandle =						Effect->GetParameterBySemantic(NULL,"Light1Diffuse");
	Light1SpecularColorHandle =						Effect->GetParameterBySemantic(NULL,"Light1Specular");
	Light1SpecularPowerHandle =						Effect->GetParameterBySemantic(NULL,"Light1SpecularPower");
	WorldMatrixHandle =								Effect->GetParameterBySemantic(NULL,"World");
	WorldInverseTransposeMatrixHandle =				Effect->GetParameterBySemantic(NULL,"WorldInverseTranspose");
	ViewInverseMatrixHandle =						Effect->GetParameterBySemantic(NULL,"ViewInverse");
	WorldViewProjectionMatrixHandle =				Effect->GetParameterBySemantic(NULL,"WorldViewProjection");
	NormalMapTechniqueHandle =						Effect->GetTechniqueByName("NormalMapping");
	NormalMapSpecularTechniqueHandle =				Effect->GetTechniqueByName("NormalMapping_Spec");
	NormalMapTerrainTechniqueHandle =				Effect->GetTechniqueByName("NormalMapping_Terrain");
	NormalMapTerrainSpecularTechniqueHandle =		Effect->GetTechniqueByName("NormalMapping_Spec_Terrain");
	FogModeHandle =									Effect->GetParameterBySemantic(NULL,"FogMode");
	FogStartHandle =								Effect->GetParameterBySemantic(NULL,"FogStart");
	FogEndHandle =									Effect->GetParameterBySemantic(NULL,"FogEnd");
	FogDensityHandle =								Effect->GetParameterBySemantic(NULL,"FogDensity");
	FogColorHandle =								Effect->GetParameterBySemantic(NULL,"FogColor");
	EnableFillHandles = false;
}	
void NormalMapShaderClass::Render(unsigned int primitive_type, unsigned short start_index, unsigned short polygon_count, unsigned short min_vertex_index, unsigned short vertex_count)
{
	if (ResetMapVariables)
	{
		if (EnableFillHandles)
		{
			Effect->ForceReset();
			FillHandles();
		}
		ResetMapVariables = false;
		LightDirectionCache = Vector4(UnitLightVector->X,UnitLightVector->Y,UnitLightVector->Z,1);
		if (*IsNighttime)
		{
			Vector4 lightVectorInverse = Vector4(-1,-1,-1,-1);
			LightDirectionCache *= lightVectorInverse;	
		}
	}
	DebugEventStart(DEBUG_COLOR1,L"NormalMapShaderClass<%S>::Render",this->Name);
	unsigned int cPasses;
	ApplyRenderState();
	ShaderStateSaver saver = ShaderStateSaver(D3DRS_FOGENABLE);
	StateManager->SetRenderState(D3DRS_FOGENABLE,false);
	Effect->Begin(&cPasses,0);
	for (unsigned int iPass = 0; iPass < cPasses; iPass++)
	{
		Effect->BeginPass(iPass);
		Effect->CommitChanges();
		Draw(primitive_type,start_index,polygon_count,min_vertex_index,vertex_count);
		Effect->EndPass();
	}
	Effect->End();
	DebugEventEnd();
}
void NormalMapShaderClass::ApplyRenderState()
{
	if (SpecularEnabled)
	{
		if (((DeclarationVertexBufferClass *)(render_state->vertex_buffer))->HasDiffuse) 
		{
			Effect->SetTechnique(NormalMapTerrainSpecularTechniqueHandle);
		}
		else
		{
			Effect->SetTechnique(NormalMapSpecularTechniqueHandle);
		}
	}
	else
	{
		if (((DeclarationVertexBufferClass *)(render_state->vertex_buffer))->HasDiffuse) 
		{
			Effect->SetTechnique(NormalMapTerrainTechniqueHandle);
		}
		else
		{
			Effect->SetTechnique(NormalMapTechniqueHandle);
		}
	}
	Effect->SetVector(Light1DirectionHandle,&LightDirectionCache);
	Effect->SetVector(Light1DiffuseColorHandle,&LightColor);
	Effect->SetVector(Light1SpecularColorHandle,&SpecularColor);
	Effect->SetFloat(Light1SpecularPowerHandle,SpecularPower);
	Effect->SetVector(AmbientLightColorHandle,&AmbientColor);
	Effect->SetVector(SurfaceColorHandle,&SurfaceColor);
	TextureClass *texture_DiffuseMap = render_state->Textures[0];
	if (texture_DiffuseMap)
	{
		if (texture_DiffuseMap->Initialized != true)
		{
			texture_DiffuseMap->Init();
		}
		texture_DiffuseMap->LastAccessed = *SyncTime;
		Effect->SetTexture(ColorTextureHandle,texture_DiffuseMap->D3DTexture->texture9);
	}
	else 
	{
		Effect->SetTexture(ColorTextureHandle,NULL);
	}
	if (texture_NormalMap->Initialized != true) texture_NormalMap->Init();
	texture_NormalMap->LastAccessed = *SyncTime;
	Effect->SetTexture(NormalTextureHandle,texture_NormalMap->D3DTexture->texture9);
	ApplyTransform();
	if (*render_state_changed & VERTEX_BUFFER_CHANGED)
	{
		ApplyVertexBuffer();
		*render_state_changed &= ~VERTEX_BUFFER_CHANGED;
	}
	if (*render_state_changed & INDEX_BUFFER_CHANGED)
	{
		ApplyIndexBuffer();
		*render_state_changed &= ~INDEX_BUFFER_CHANGED;
	}
	ShaderClass *s = &(render_state->shader);
	s->Apply();
	*render_state_changed &= ~SHADER_CHANGED;

	DWORD FogEnable = StateManager->GetRenderState(D3DRS_FOGENABLE);
	DWORD FogVertexMode = StateManager->GetRenderState(D3DRS_FOGVERTEXMODE);
	DWORD FogStart = StateManager->GetRenderState(D3DRS_FOGSTART);
	DWORD FogEnd = StateManager->GetRenderState(D3DRS_FOGEND);
	DWORD FogDensity = StateManager->GetRenderState(D3DRS_FOGDENSITY);
	Vector4 FogColor = GetColorVector4(StateManager->GetRenderState(D3DRS_FOGCOLOR));
	Effect->SetInt(FogModeHandle,FogEnable ? FogVertexMode : 0);
	Effect->SetFloat(FogStartHandle,*((float*) (&FogStart)));
	Effect->SetFloat(FogEndHandle,*((float*) (&FogEnd)));
	Effect->SetFloat(FogDensityHandle,*((float*) (&FogDensity)));
	Effect->SetVector(FogColorHandle,&FogColor);
}
void NormalMapShaderClass::ApplyTransform()
{
	Matrix4 projection = Matrix4();
	Get_Projection_Matrix(&projection);
	Matrix4 world = render_state->world;
	Matrix4 view = render_state->view;
	Matrix4 worldViewProjection = world * view * projection;
	Matrix4 worldInverse = world.Inverse();
	Matrix4 viewInverse = view.Inverse();
	Effect->SetMatrix(WorldMatrixHandle,&world);
	Effect->SetMatrixTranspose(WorldInverseTransposeMatrixHandle,&worldInverse);
	Effect->SetMatrix(ViewInverseMatrixHandle,&viewInverse);
	Effect->SetMatrix(WorldViewProjectionMatrixHandle,&worldViewProjection);
}
void NormalMapShaderClass::ApplyVertexBuffer()
{
	if (render_state->vertex_buffer)
	{
		if ((!render_state->vertex_buffer_type) || (render_state->vertex_buffer_type == 2))
		{
			if (render_state->vertex_buffer->fvf_info)
			{
				Direct3DDevice->SetStreamSource(0,((DX8VertexBufferClass *)render_state->vertex_buffer)->Get_DX8_Vertex_Buffer(),0,render_state->vertex_buffer->FVF_Info().Get_FVF_Size());
				Direct3DDevice->SetFVF(render_state->vertex_buffer->FVF_Info().Get_FVF());
			}
			else
			{
				Direct3DDevice->SetStreamSource(0,((DX8VertexBufferClass *)render_state->vertex_buffer)->Get_DX8_Vertex_Buffer(),0,((DeclarationVertexBufferClass *)render_state->vertex_buffer)->DeclarationSize);
				Direct3DDevice->SetVertexDeclaration(((DeclarationVertexBufferClass *)render_state->vertex_buffer)->VertexDecl);
			}
		}
	}
	else
	{
		Direct3DDevice->SetStreamSource(0,0,0,0);
	}
}
void NormalMapShaderClass::ApplyIndexBuffer()
{
	if (render_state->index_buffer)
	{
		if ((!render_state->index_buffer_type) || (render_state->index_buffer_type == 2))
		{
			Direct3DDevice->SetIndices(((DX8IndexBufferClass *)render_state->index_buffer)->Get_DX8_Index_Buffer());
		}
	}
	else
	{
		Direct3DDevice->SetIndices(0);
	}
}
bool NormalMapShaderClass::Can_Render(unsigned int primitive_type, unsigned short start_index, unsigned short polygon_count, unsigned short min_vertex_index, unsigned short vertex_count)
{
	if (render_state->vertex_buffer)
	{
		if ((!render_state->vertex_buffer_type) || (render_state->vertex_buffer_type == 2))
		{
			if (!render_state->vertex_buffer->fvf_info)
			{
				if (((DeclarationVertexBufferClass *)(render_state->vertex_buffer))->HasTangents)
				{
 					return ProgrammableShaderClass::Can_Render(primitive_type,start_index,polygon_count,min_vertex_index,vertex_count);
				}
			}
		}
	}
	return false;
}
ShaderRegistrant<NormalMapShaderClass> NormalMapShaderRegistrant(SHADER_NORMALMAP);
#endif
