/*
	Trig Wars.
	Copyright (c) 2008, Darragh Coy.
	All rights reserved.
	Original work(s), source code & author(s) details available at: http://www.darraghcoy.com

	Redistribution and use in source and binary forms, with or without modification, are permitted 
	provided that the following conditions are met:

		* 	Redistributions of source code must retain the above copyright notice, this list of 
			conditions and the following disclaimer.
		* 	Redistributions in binary form must reproduce the above copyright notice, this list of 
			conditions and the following disclaimer in the documentation.
		* 	Neither the name of the author nor the names of contributors may be used to endorse or 
			promote products derived from this software without specific prior written permission.
		* 	The use of any third party libraries, modules or data files provided with the source 
			form of the program must follow and respect the individual licensing terms of these 
			components. You do not have permission to modify or circumvent the licensing terms for 
			provided third party components unless the third party licenses specifically allow this. 
			If you do not agree to the terms of provided third party components then you do not have 
			permission to use them in your derived work(s).
		* 	The terms of this license do not apply to separate (but related) distributions if supplied 
			by the author(s), only to the contents of this source distribution, derived works, and the 
			binaries produced by either modified or unmodified versions of the source code. The terms 
			of this license do not also apply to any third party libraries or components provided with 
			the source distribution. Such third party elements are licensed under their own separate 
			agreements.

	THIS SOFTWARE IS PROVIDED BY DARRAGH COY ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, 
	BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
	ARE DISCLAIMED. IN NO EVENT SHALL DARRAGH COY BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
	EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 
	OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
	OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING 
	IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

//=====================================================================================================================
/// @brief		Represents the predator enemy. Predators actively hunt the player, even when they are not 
///				offscreen. 
//=====================================================================================================================

#include "Precompiled.h"
#include "GameObjects\EnemyPredator.h"
#include "GameObjects\PlayerShip.h"
#include "Graphics\PrimitivesRenderer.h"
#include "Graphics\Camera2D.h"
#include "Graphics\ParticleEmitter.h"
#include "Game\GameCore.h"
#include "Game\EnemyBulletManager.h"

using namespace Game;

//=====================================================================================================================
/// Constants
//=====================================================================================================================

/// Amount of linear acceleration the enemy factory has

const float EnemyPredator::LIN_ACCELERATION = 2400.0f;

/// Amount of angular acceleration the player ship has per second

const float EnemyPredator::ANG_ACCELERATION = 35.8f;

/// Time it takes for a factory to fade in

const float EnemyPredator::FADE_IN_TIME = 1.0f;

/// Size of the enemy factory

const Vec2f EnemyPredator::SIZE = Vec2f(20,20);

/// Time it takes to change from the hunt goal

const float EnemyPredator::GOAL_HUNTING_CHANGE_TIME = 0.5f;

/// Maximum amount of time the predator can be in the attack goal until a goal change

const float EnemyPredator::GOAL_ATTACK_CHANGE_TIME = 10.0f;

/// Distance the predator has to be within the enemy for the predator to disengage attack for a while

const float EnemyPredator::GOAL_ATTACK_BACKOFF_DISTANCE = 200.0f;

/// Distance the predator will try to move away from the player when disengaging attack

const float EnemyPredator::REST_FALLBACK_DISTANCE = 300.0f;

//'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
/// Time it takes to change from the attack rest goal: if the predator reaches its goal point 
/// before then however this time may be terminated. It is there simply to ensure the predator does
/// not spend too much time resting after attacking the player.
//'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

const float EnemyPredator::GOAL_ATTACK_REST_CHANGE_TIME = 1.5f;

/// Points that make up the shape of the ship;

const Vec3f EnemyPredator::SHAPE_POINTS[9] = 
{
	Vec3f( -SIZE.x * 0.5f	, +SIZE.y			),
	Vec3f( +SIZE.x			, +SIZE.y			),
	Vec3f( 0				, +SIZE.y * 0.5f	),
	Vec3f( +SIZE.x			, 0					),
	Vec3f( 0				, -SIZE.y * 0.5f	),
	Vec3f( +SIZE.x			, -SIZE.y			),
	Vec3f( -SIZE.x * 0.5f	, -SIZE.y			),
	Vec3f( -SIZE.x			, -SIZE.y * 0.5f	),
	Vec3f( -SIZE.x			, +SIZE.y * 0.5f	)
};

/// Color of this enemy

const Color EnemyPredator::SHAPE_COLOR = Color(1.0f , 0.55f , 0.15f );

//=====================================================================================================================
/// @brief		Constructor: creates a wasp at position 0,0. This object is designed to be pooled, hence the 
///				lack of a more definite constructor.
/// @param		m - AIManager this factory belongs to
//=====================================================================================================================

EnemyPredator::EnemyPredator( AIManager * m ) : AttackingEnemy(m,500)
{
	m_current_goal = GOAL_HUNTING;
	
	// Attacking enemy base class settings

	m_fire_interval_min		= 0.10f;
	m_fire_view_cone_angle	= Float::PI() * 0.25f;
	m_fire_inaccuracy_max	= Float::PI() * 0.05f;	
	m_fire_chance			= 0.25f;	
}

//=====================================================================================================================
/// @brief		Annouces the type name for this object.
/// @returns	Type name of this object
//=====================================================================================================================

const char * EnemyPredator::GetTypeName() const
{
	return "EnemyPredator";
}

//=====================================================================================================================
/// @brief		Resets the state of the predator, health, goal etc. Also randomly picks a direction for the predator.
/// @remarks	This is is something of a default constructor after an object has been grabbed from the pool
//=====================================================================================================================

void EnemyPredator::ResetState()
{
	Revive();																// Restore health
	SetAngle( GameCore::GetSingleton()->GetRandom().NextFloat(0,3.147f) );	// Pick a random angle for the enemy
	m_fade_in_time_left = FADE_IN_TIME;										// Fade in
	m_current_goal = GOAL_HUNTING;											// Hunt initially
	m_goal_change_time_left	= GOAL_HUNTING_CHANGE_TIME;						// Not onscreen yet
}

//=====================================================================================================================
/// @brief			Draws the ship
/// @param			c - camera we are viewing from
/// @pre			Given camera cannot be null
/// @pre			Game must exist
/// @pre			Primitives renderer used by the game must not be null
/// @deprecated		Calls to OnDraw() are no longer used. Instead the much faster BufferedDraw() is used which
///					is designed for batch rendering.
//=====================================================================================================================

#pragma warning(disable:4100)

void EnemyPredator::OnDraw( Camera2D * c )
{
	// Only buffered rendering is used now.. this does nothing
}

#pragma warning(default:4100)

//=====================================================================================================================
/// @brief		Does ai for this enemy
/// @param		time_delta - time since the last frame.
/// @pre		The game must exist
/// @pre		The game must exist
/// @pre		The game must have a particle emitter
/// @pre		The AI manager for this object must have a bullet manager
//=====================================================================================================================

void EnemyPredator::OnUpdate( float time_delta )
{	
	// Make sure ok:
	
	ENSURE( GameCore::GetSingleton()							, "The game must exist"											)
	ENSURE( GameCore::GetSingleton()->GetParticleEmitter()		, "The game must have a particle emitter"						)
	ENSURE( GetAIManager().GetBulletManager()					, "The AI manager for this object must have a bullet manager"	)

	// Reduce the time left to fade in by:
	
	m_fade_in_time_left -= time_delta;
	
	// Clamp to zero
	
	if ( m_fade_in_time_left < 0 ) m_fade_in_time_left = 0;
	
	// Update the goal of the factory
	
	UpdateGoal(time_delta);
	
	// Do the current goal
	
	switch ( m_current_goal )
	{
		case GOAL_HUNTING:				DoHunting(time_delta);			break;
		case GOAL_ATTACK:				DoAttack(time_delta);			break;
		case GOAL_MOVE_STRAIGHT:		DoMoveStraight(time_delta);		break;
		case GOAL_ATTACK_REST:			DoAttackRest(time_delta);		break;
	}
	
	// Do turning to avoid obstacles: this should override normal behaviour if urgent		
	
	AvoidObstacles
	(
		400						,	// Scan radius
		4000.0f					,	// Repulsion strength
		0.0005f					,	// Repulsion attenuation
		ANG_ACCELERATION * 2.0f	,	// Maximum amount of turning to do: allow for more than normal turning since this needs to override normal behavior
		time_delta					// time delta for frames
	);
	
	// Do collision with obstacles:
	
	if ( ObstacleManager * o_mgr = GetAIManager().GetObstacleManager() )
	{			
		// See if there was a collision:
	
		bool collision = ObstacleCollide( o_mgr , Float::Max( SIZE.x , SIZE.y ) );
		
		// Kill this ai if there was one:
		
		if ( collision ) 
		{
			// Kill us
		
			Kill();
		
			// Get the particle texture we will use to emit particles
			
			Texture & tex  = GetAIManager().GetBulletManager()->GetParticleTexture();
			
			// Only if valid:
			
			if ( tex.IsValid() )
			{
				// Make a particle burst:
				
				GameCore::GetSingleton()->GetParticleEmitter()->CreateBurst
				(
					512								,
					tex								,
					GetPosition()					,
					0.5f							,	// live time 1
					1.0f							,	// live time 2
					2.0f							,	// size 1
					10.0f							,	// size 2
					Color(1.0f,0.35f,0.25f,0.7f)	,	// color 1
					Color(1.0f,1.00f,0.25f,0.4f)	,	// color 2
					5.0f							,	// speed 1
					150.0f							,	// speed 2
					false								// alpha blend
				);			
			}
		}		
	}	
	
	// Do base class update:
	
	AttackingEnemy::OnUpdate(time_delta);
}

//=====================================================================================================================
/// @brief		Updates the current goal of the factory
/// @param		time_delta - amount of time in between this frame and the last
/// @pre		Game must exist
/// @pre		Game must have a valid camera
//=====================================================================================================================

void EnemyPredator::UpdateGoal( float time_delta )
{
	// Make sure ok:
	
	ENSURE( GameCore::GetSingleton()				, "Game must exist"					);
	ENSURE( GameCore::GetSingleton()->GetCamera()	, "Game must have a valid camera"	);
	
	// Determine if we are onscreen:
	
	bool onscreen = IsOnscreen( SIZE , GameCore::GetSingleton()->GetCamera() );
	
	// Get the player ship:
	
	PlayerShip * player = GetAIManager().GetPlayerShip();
	
	// NB: If the player is dead then just keep wandering the way we are

	if ( player == 0 ) 
	{
		// Move in our current direction:
	
		m_current_goal = GOAL_MOVE_STRAIGHT; return;
	}

	// See what our current goal is:
	
	switch ( m_current_goal )
	{
		//-------------------------------------------------------------------------------------------------------------
		// Hunting the player:
		//-------------------------------------------------------------------------------------------------------------
		
		case GOAL_HUNTING:
		{
			// See if we are onscreen:
			
			if ( onscreen )
			{
				// Onscreen: decrease time till goal change
				
				m_goal_change_time_left -= time_delta;
				
				// See if time to change behaviour:
				
				if ( m_goal_change_time_left <= 0 )
				{
					// Go into attack mode: now attacking the player
					
					m_current_goal			= GOAL_ATTACK;
					m_goal_change_time_left	= GOAL_ATTACK_CHANGE_TIME;
				}
			}
			else
			{
				// Not onscreen: reset the amount of time till we change goal
				
				m_goal_change_time_left = GOAL_HUNTING_CHANGE_TIME;
			}
			
		}	break;
		
		//-------------------------------------------------------------------------------------------------------------
		// Attacking:
		//-------------------------------------------------------------------------------------------------------------
		
		case GOAL_ATTACK:
		{
			// See if we are onscreen:
			
			if ( onscreen )
			{
				// Onscreen: decrement the amount of time till attack run ends
				
				m_goal_change_time_left -= time_delta;
				
				// See if time to change to rest mode:
				
				if ( m_goal_change_time_left <= 0 )
				{
					// Go into rest mode:
					
					m_current_goal			= GOAL_ATTACK_REST;
					m_goal_change_time_left	= GOAL_ATTACK_CHANGE_TIME;
					
					// Pick a rest point to move to:
					
					PickAttackRestGoalPoint();
				}
				else
				{
					// Not in rest mode: see if we are getting too close to the player
					
					if ( SqDistanceTo(player) < ( GOAL_ATTACK_BACKOFF_DISTANCE * GOAL_ATTACK_BACKOFF_DISTANCE ) )
					{
						// Getting too close: go into rest mode
						
						m_current_goal			= GOAL_ATTACK_REST;
						m_goal_change_time_left	= GOAL_ATTACK_REST_CHANGE_TIME;
						
						// Pick a rest point to move to:
						
						PickAttackRestGoalPoint();									
					}
				}
			}
			else
			{
				// Not onscreen: go back into hunt mode
				
				m_current_goal			= GOAL_HUNTING;
				m_goal_change_time_left	= GOAL_HUNTING_CHANGE_TIME;				
			}
		
		}	break;
		
		//-------------------------------------------------------------------------------------------------------------
		// Resting from attack for a little while:
		//-------------------------------------------------------------------------------------------------------------
		
		case GOAL_ATTACK_REST:
		{
			// See if onscreen:
			
			if ( onscreen )
			{
				// See if we are within distance of our goal point:
				
				if ( m_attack_rest_goal_pt.SqDistanceTo(GetPosition()) < 200.0f )
				{
					// We are within distance: switch back to attacking
					
					m_current_goal				= GOAL_ATTACK;
					m_goal_change_time_left		= GOAL_ATTACK_CHANGE_TIME;
				}
				else
				{
					// Not within distance of the goal point: decrement the time left till state change
					
					m_goal_change_time_left -= time_delta;
					
					// See if time to change goal:
					
					if ( m_goal_change_time_left <= 0 )
					{
						// Time to attack again: been resting for too long
						
						m_current_goal				= GOAL_ATTACK;
						m_goal_change_time_left		= GOAL_ATTACK_CHANGE_TIME;						
					}
				}
			}
			else
			{
				// Not onscreen: go back to hunting
				
				m_current_goal			= GOAL_HUNTING;
				m_goal_change_time_left = GOAL_HUNTING_CHANGE_TIME;
			}
		
		}	break;
	}
}

//=====================================================================================================================
/// @brief		Picks a point to move to when the enemy is taking a little break from attacking
/// @pre		The player must be in the game
/// @pre		The game must exist
//=====================================================================================================================

void EnemyPredator::PickAttackRestGoalPoint()
{
	// Make sure ok:
	
	ENSURE( GetAIManager().GetPlayerShip()  , "The player must be in the game"	)
	ENSURE( GameCore::GetSingleton()		, "The game must exist"				)
			
	// Get the random number generator from the game
	
	Random & random = GameCore::GetSingleton()->GetRandom();
	
	// Get the player ship:
	
	PlayerShip * player = GetAIManager().GetPlayerShip();
	
	// Get the direction to the player:
	
	Vec2f dir_to_player = GetPosition() - player->GetPosition(); 
	
	// Normalise: but save distance for safety
	
	float dist = dir_to_player.Normalize();
	
	// If distance is very small then pick a random direction to move away from the player
	
	if ( dist < 0.01f )
	{
		// Pick a random angle:
		
		float a = random.NextFloat(0,Float::PI());
		
		// Make this the direction to the player
		
		dir_to_player.x = Float::Cos(a);
		dir_to_player.y = Float::Sin(a);
	}
	
	// Move to a position in front of the player
	
	dir_to_player = -dir_to_player;	
	
	// Scale by distance we are to move away from the player:
	
	dir_to_player *= REST_FALLBACK_DISTANCE;
	
	// Move to that point: and make sure it is wrapped
	
	m_attack_rest_goal_pt = PositionalObject::WrapCoordinates( player->GetPosition() + dir_to_player );
}

//=====================================================================================================================
/// @brief		This is a more optimised version of the OnDraw() function which uses the buffered line 
///				rendererer from the game. It is used for batch rendering of these enemy types.
/// @param		s - stack that the lines for the factory should be placed on
/// @param		cam_pos - position of the camera
/// @param		z - z value that the object should be drawn at
/// @returns	The factory should return the number of lines it has placed on the stack for rendering
//=====================================================================================================================

unsigned EnemyPredator::BufferedDraw( Stack & s , const Vec2f & cam_pos , float z )
{
	// Get our position:

	Vec3f pos = Vec3f( UnwrapCoordinates(cam_pos,GetPosition()) , z );

	// Pick color:
	
	Color col = SHAPE_COLOR; col.a *= ( 1.0f - m_fade_in_time_left ) / FADE_IN_TIME;

	// Convert to unsigned:

	unsigned col_unsigned = col.ToDxUnsigned();

	// Make a rotation matrix to rotate all our points

	Matrix2f rot = Matrix2f::Rotation( GetAngle() );

	// Put all our lines onto the stack

	Vec3f t1 = rot.Transform( SHAPE_POINTS[0] ) + pos;
	Vec3f t2 = rot.Transform( SHAPE_POINTS[1] ) + pos;

	s.Push( t1 );
	s.Push( col_unsigned );
	s.Push( t2 );
	s.Push( col_unsigned );

	t1 = rot.Transform( SHAPE_POINTS[2] ) + pos;

	s.Push( t2 );
	s.Push( col_unsigned );
	s.Push( t1 );
	s.Push( col_unsigned );

	t2 = rot.Transform( SHAPE_POINTS[3] ) + pos;

	s.Push( t1 );
	s.Push( col_unsigned );
	s.Push( t2 );
	s.Push( col_unsigned );

	t1 = rot.Transform( SHAPE_POINTS[4] ) + pos;

	s.Push( t2 );
	s.Push( col_unsigned );
	s.Push( t1 );
	s.Push( col_unsigned );

	t2 = rot.Transform( SHAPE_POINTS[5] ) + pos;

	s.Push( t1 );
	s.Push( col_unsigned );
	s.Push( t2 );
	s.Push( col_unsigned );

	t1 = rot.Transform( SHAPE_POINTS[6] ) + pos;

	s.Push( t2 );
	s.Push( col_unsigned );
	s.Push( t1 );
	s.Push( col_unsigned );

	t2 = rot.Transform( SHAPE_POINTS[7] ) + pos;

	s.Push( t1 );
	s.Push( col_unsigned );
	s.Push( t2 );
	s.Push( col_unsigned );

	t1 = rot.Transform( SHAPE_POINTS[8] ) + pos;

	s.Push( t2 );
	s.Push( col_unsigned );
	s.Push( t1 );
	s.Push( col_unsigned );

	t2 = rot.Transform( SHAPE_POINTS[0] ) + pos;

	s.Push( t1 );
	s.Push( col_unsigned );
	s.Push( t2 );
	s.Push( col_unsigned );

	// Drawing 9 lines

	return 9;
}

//=====================================================================================================================
/// @brief		Does the move straight goal. Not exactly rocket science but it has to be done all the same.
/// @param		time_delta - time between this frame and the last one
//=====================================================================================================================

void EnemyPredator::DoMoveStraight( float time_delta )
{
	// Move in our current direction:
	
	Acclerate( GetDirection() * LIN_ACCELERATION , time_delta );	
}

//=====================================================================================================================
/// @brief		Does the hunt player goal. The predator will try to intercept the player's future position.
/// @param		time_delta - time between this frame and the last one
/// @pre		The player should exist before executing this goal
//=====================================================================================================================

void EnemyPredator::DoHunting( float time_delta )
{
	// Make sure ok:

	ENSURE( GetAIManager().GetPlayerShip() , "The player should exist before executing this goal" )
	
	// Get the player ship:
	
	PlayerShip * player = GetAIManager().GetPlayerShip();
	
	// Get the relative speed to the player:
	
	float rel_speed = ( player->GetLinearVelocity() - GetLinearVelocity() ).Length();
	
	// Get the distance to the player:
	
	float dist_to = DistanceTo(player);
	
	// Now calculate the future position of the player that we will chase:
	
	Vec2f future_pos = player->GetPosition();
	
	// Only do if the relative speed is over zero:
	
	if ( rel_speed > 0.00001f )
	{
		// Calculate the time required to close the gap:
		
		float t = dist_to / rel_speed;
		
		// Estimate where the player will be at this time:
		
		future_pos += player->GetLinearVelocity() * t;
	}
	
	// This position needs to be wrapped for the next function:
	
	future_pos = WrapCoordinates(future_pos);	
	
	// Calculate what way to turn towards this angle:
	
	float turning = CalculateTurningToPoint( future_pos , ANG_ACCELERATION , 0.0001f );
	
	// Clamp to range:
	
	turning = Float::Clamp( turning , -ANG_ACCELERATION , +ANG_ACCELERATION );
	
	// Turn:
	
	AngularAcclerate(turning,time_delta);
	
	// Move in our current direction:
	
	Acclerate( GetDirection() * LIN_ACCELERATION , time_delta );	
}

//=====================================================================================================================
/// @brief		Does the attack run for the predator
/// @param		time_delta - time between this frame and the last one
/// @pre		The player should exist before executing this goal
//=====================================================================================================================

void EnemyPredator::DoAttack( float time_delta )
{
	// Make sure ok:

	ENSURE( GetAIManager().GetPlayerShip() , "The player should exist before executing this goal" )

	// This is pretty much the exact same as the hunting goal:
	
	DoHunting(time_delta);
	
	// Do firing if we can:
	
	DoFiring();
}

//=====================================================================================================================
/// @brief		Does the attack rest goal for the predator
/// @param		time_delta - time between this frame and the last one
/// @pre		The player should exist before executing this goal
//=====================================================================================================================

void EnemyPredator::DoAttackRest( float time_delta )
{
	// Make sure ok:

	ENSURE( GetAIManager().GetPlayerShip() , "The player should exist before executing this goal" )
	
	// Calculate how much turning we should do to reach our goal point
	
	float turning = CalculateTurningToPoint(m_attack_rest_goal_pt,25.0f,0.0001f);
	
	// Make sure the turning amount is within our allowed angular acceleration:
	
	if ( turning < - ANG_ACCELERATION ) turning = -ANG_ACCELERATION; else if ( turning > ANG_ACCELERATION ) turning = ANG_ACCELERATION;
	
	// Do the turning:
	
	AngularAcclerate( turning , time_delta );

	// Move in our current direction:
	
	SetLinearVelocity( GetLinearVelocity() + GetDirection() * LIN_ACCELERATION * time_delta ); 
	
	// Fire if we can: don't let up on the player despite the fact that we are backing off
	
	DoFiring();
}