/*
	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 one factory ship enemy. Factories wander at random until they encounter the player and
///				flock to avoid the player. They also spawn wasp interceptors.
//=====================================================================================================================

#include "Precompiled.h"
#include "GameObjects\EnemyFactory.h"
#include "GameObjects\EnemyFactoryManager.h"
#include "GameObjects\EnemyWasp.h"
#include "GameObjects\EnemyWaspManager.h"
#include "GameObjects\EnemyPredator.h"
#include "GameObjects\EnemyPredatorManager.h"
#include "Graphics\PrimitivesRenderer.h"
#include "Graphics\ParticleEmitter.h"
#include "Graphics\Camera2D.h"
#include "Game\GameCore.h"
#include "GameObjects\ObstacleManager.h"
#include "Game\EnemyBulletManager.h"

using namespace Game;

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

/// Amount of linear acceleration the enemy factory has

const float EnemyFactory::LIN_ACCELERATION = 1800.5f;

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

const float EnemyFactory::ANG_ACCELERATION = 30.8f;

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

const float EnemyFactory::FADE_IN_TIME = 1.0f;

/// Size of the enemy factory

const Vec2f EnemyFactory::SIZE = Vec2f(20,10);

/// Time it takes to change from the wandering goal to another

const float EnemyFactory::GOAL_WANDER_CHANGE_TIME = 0.25f;

/// Time it takes to change from the fleeing goal to another

const float EnemyFactory::GOAL_FLEEING_CHANGE_TIME = 3.0f;

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

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

/// Color of this enemy

const Color EnemyFactory::SHAPE_COLOR = Color( 0.55f , 0.95f , 1.0f );

/// Minimum time in between spawning wasp enemies for the factory

const float EnemyFactory::WASP_SPAWN_INTERVAL_MIN = 2.00f;

/// Maximum time in between spawning wasp enemies for the factory

const float EnemyFactory::WASP_SPAWN_INTERVAL_MAX = 5.0f;

/// Minimum time in between spawning predator enemies for the factory

const float EnemyFactory::PREDATOR_SPAWN_INTERVAL_MIN = 3.0f;

/// Maximum time in between spawning predator enemies for the factory

const float EnemyFactory::PREDATOR_SPAWN_INTERVAL_MAX = 10.0f;

/// Minimum radius to spawn away from the factory

const float EnemyFactory::SPAWN_RADIUS_MIN = 100.0f;

/// Maximum radius to spawn away from the factory

const float EnemyFactory::SPAWN_RADIUS_MAX = 200.0f;

//=====================================================================================================================
/// @brief		Constructor: creates a factory 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
//=====================================================================================================================

EnemyFactory::EnemyFactory( AIManager * m ) : AIControlled(m,400)
{
	// Set default goal

	m_current_goal = GOAL_WANDER;
}

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

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

//=====================================================================================================================
/// @brief		Resets the state of the factory, health, goal etc. Also randomly picks a direction for the factory.
/// @remarks	This is is something of a default constructor after an object has been grabbed from the pool
/// @pre		The game must exist
/// @post		The picked wander point must be wrapped
//=====================================================================================================================

void EnemyFactory::ResetState()
{
	// Make sure this is ok:

	ENSURE( GameCore::GetSingleton() , "The game must exist" )
	
	// Reset everything

	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_WANDER;				// Wander initially
	m_goal_change_time_left	= GOAL_WANDER_CHANGE_TIME;	// Not onscreen yet
	
	// Reset time till spawn
	
	m_time_till_spawn = GameCore::GetSingleton()->GetRandom().NextFloat( WASP_SPAWN_INTERVAL_MIN , WASP_SPAWN_INTERVAL_MAX );
	
	// Pick a random point to wander to: use the pick spawn point function because it keeps us away from the player
	
	m_wander_point = GetAIManager().PickPointAwayfrom( GetPosition() , 300 );
	
	// Make sure this is ok:
	
	ENSURE( PositionalObject::IsWrapped(m_wander_point) , "The picked wander point must be wrapped" );
}

//=====================================================================================================================
/// @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.
//=====================================================================================================================

void EnemyFactory::OnDraw( Camera2D * c )
{
	// Make sure ok:

	ENSURE( c							, "Given camera cannot be null"		);
	ENSURE( GameCore::GetSingleton()	, "Game must exist"					);
	
	// Get the primitives renderer from the game:
	
	PrimitivesRenderer * r = GameCore::GetSingleton()->GetPrimitivesRenderer();
	
	// Make sure ok:
	
	ENSURE( r , "Primitives renderer used by the game must not be null" );

	// Do not draw if we are offscreen:

	if ( IsOnscreen(SIZE,c) == false ) return;
	
	// Makeup the points of the factory:
	
	Vec3f points[10];
	
	// Set local positions:

	for ( int i = 0 ; i < 10 ; ++i ) points[i] = SHAPE_POINTS[i];
	
	// Translate and rotate:
	
	{
		// Rotation transform:
		
		Matrix4f r = Matrix4f::RotationZ( GetAngle() );
		
		// Translation transform:
		
		Matrix4f t = Matrix4f::Translation( UnwrapCoordinates( c->GetPosition() , GetPosition() ) );
		
		// Combined transform:
		
		Matrix4f c = r * t;
		
		// Rotate and translate all:
		
		for ( int i = 0 ; i < 10 ; ++i ) points[i] = c.Transform(points[i]);
	}

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

	// Convert color to unsigned integer:
	
	unsigned dxc = col.ToDxUnsigned();

	// Draw all lines bar the last:
	
	for ( int i = 0 ; i < 9 ; ++i )
	{
		// Draw this line:
	
		r->DrawLine( c , points[i].ToVec2() , points[i+1].ToVec2() , dxc );
	}
	
	// Draw the last line:
	
	r->DrawLine( c , points[9].ToVec2() , points[0].ToVec2() , dxc );
}

//=====================================================================================================================
/// @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 EnemyFactory::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[9] ) + pos;

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

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

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

	// Drawing 10 lines

	return 10;
}

//=====================================================================================================================
/// @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 exist
/// @pre		The game must have a particle emitter
/// @pre		The ai manager for this object must be an EnemyFactoryManager
//=====================================================================================================================

void EnemyFactory::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( dynamic_cast<EnemyFactoryManager*>(&GetAIManager())	, "The ai manager for this object must be an EnemyFactoryManager"	)
	
	// 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
	
	if ( m_current_goal == GOAL_WANDER )
	{
		DoWandering(time_delta);
	}
	else
	{
		DoFleeing(time_delta);
	}
	
	// Do turning to avoid obstacles: this should override normal behaviour if urgent		
	
	AvoidObstacles
	(
		300						,	// Scan radius
		500.0f					,	// Repulsion strength
		0.0001f					,	// 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 spawning if we can:
	
	DoSpawning(time_delta);
	
	// 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  = ((EnemyFactoryManager*)(&GetAIManager()))->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:
	
	AIControlled::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 EnemyFactory::UpdateGoal( float time_delta )
{
	// Make sure ok:
	
	ENSURE( GameCore::GetSingleton()				, "Game must exist"					);
	ENSURE( GameCore::GetSingleton()->GetCamera()	, "Game must have a valid camera"	);
	
	// NB: If the player is dead then just wander

	if ( GetAIManager().GetPlayerShip() == 0 )
	{
		// Wander the hills: 
	
		m_current_goal			= GOAL_WANDER;
		m_goal_change_time_left	= GOAL_WANDER_CHANGE_TIME;
		
		// Done:
		
		return;
	}	

	// See if the factory is on screen:
	
	if ( IsOnscreen( SIZE, GameCore::GetSingleton()->GetCamera() ) )
	{
		// We are on screen and therefore visible: see what our goal is
		
		if ( m_current_goal == GOAL_FLEEING )
		{
			//'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
			// We are fleeing: Reset the amount of time we have left to a state change.
			// We need to get more away from the player and get out of sight !!
			//'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
			
			m_goal_change_time_left = GOAL_FLEEING_CHANGE_TIME;
		}
		else
		{
			//'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
			// We are wandering onscreen: Decrement amount of time until we change state to fleeing. 
			//'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
			
			m_goal_change_time_left -= time_delta;
			
			// See if time for change:
			
			if ( m_goal_change_time_left <= 0 )
			{
				// Change state:
				
				m_current_goal = GOAL_FLEEING;
				m_goal_change_time_left = GOAL_FLEEING_CHANGE_TIME;
			}
		}
	}		
	else
	{
		// We are offscreen and not visible: see what our current goal is
		
		if ( m_current_goal == GOAL_FLEEING )
		{
			//'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
			// We are fleeing: decrease the amount of time till the next goal change. Eventually we will start
			// wandering again.
			//'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
			
			m_goal_change_time_left -= time_delta;
			
			// See if time to relax a little:
			
			if ( m_goal_change_time_left <= 0 )
			{
				// Relax and switch to wandering again
				
				m_current_goal = GOAL_WANDER;
				m_goal_change_time_left = GOAL_WANDER_CHANGE_TIME;
			}
		}
		else
		{
			//'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
			// We are wandering: reset the amount of time till the next state change. We want to keep wandering so
			// long as we are offscreen
			//'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
			
			m_goal_change_time_left = GOAL_WANDER_CHANGE_TIME;
		}
	}
}

//=====================================================================================================================
/// @brief		Does the wandering goal
/// @param		time_delta - amount of time in between this frame and the last
/// @post		If picking a wander point, the picked wander point must be wrapped.
//=====================================================================================================================

void EnemyFactory::DoWandering( float time_delta )
{
	// Calculate how much turning we should do to reach our goal point
	
	float turning = CalculateTurningToPoint(m_wander_point,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:
	
	Acclerate( GetDirection() * LIN_ACCELERATION , time_delta );
	
	// See if we are within distance of the wander point:
	
	if ( WithinDistance( PositionalObject::UnwrapCoordinates(GetPosition(),m_wander_point) , 100 ) )
	{
		// Pick a new point away from our wander point
	
		m_wander_point = GetAIManager().PickPointAwayfrom( m_wander_point , 300 );
		
		// Make sure this is ok:
		
		ENSURE( PositionalObject::IsWrapped(m_wander_point) , "If picking a wander point, the picked wander point must be wrapped." );
	}
}

//=====================================================================================================================
/// @brief		Does the fleeing goal
/// @param		time_delta - amount of time in between this frame and the last
/// @pre		The player must be in the game
//=====================================================================================================================

void EnemyFactory::DoFleeing( float time_delta )
{
	// Make sure the player is in the game

	ENSURE( GetAIManager().GetPlayerShip() , "The player must be in the game" )

	// Turn away from the player and flock to avoid it:
	
	FlockAction action = FlockToAvoid
	(
		GetAIManager().GetPlayerShip()->GetPosition()	,	// avoid this
		Float::PI() * 1.20f								,	// fov for alignment and cohesion
		Float::PI() * 1.80f								,	// fov for separation
		300												,	// flock radius
		10.0f											,	// turn force 
		1.00f											,	// cohesion weight	
		0.25f											,	// separation weight
		0.75f											,	// alignment weight
		150.0f											,	// separation distance
		0.001f											,	// separation attenuation
		LIN_ACCELERATION								,	// maximum acceleration that can be applied
		0.75f											,	// amount of acceleration the leader should apply
		0.55f												// Minimum acceleration that can be applied 
	);

	// Restrict the amount of turning:
	
	action.m_steering = Float::Clamp( action.m_steering , -ANG_ACCELERATION , ANG_ACCELERATION );

	// Do our turning:

	AngularAcclerate( action.m_steering , time_delta );

	// Move in our current direction:
	
	SetLinearVelocity( GetLinearVelocity() + GetDirection() * time_delta * action.m_acceleration ); 
}

//=====================================================================================================================
/// @brief		Does spawning for the enemy if it can spawn:
/// @param		time_delta - time between this frame and the last one
/// @pre		The game must exist
/// @pre		The manager of this type of object must be a factory manager
/// @pre		The wasp manager must never return null when allocating a wasp from the pool when it is not full
/// @pre		The wasp manager must return a wasp when spawning
/// @pre		The predator manager must never return null when allocating a predator from the pool when it is not full
/// @pre		The predator manager must return a wasp when spawning
//=====================================================================================================================

void EnemyFactory::DoSpawning( float time_delta )
{
	// Make sure ok:
	
	ENSURE( GameCore::GetSingleton()							, "The game must exist"												)
	ENSURE( dynamic_cast<EnemyFactoryManager*>(&GetAIManager())	, "The manager of this type of object must be a factory manager"	)
	
	// Only spawn when we are fleeing: i.e we are onscreen
	
	if ( m_current_goal != GOAL_FLEEING ) return;
	
	// Decrement time till the next spawn
	
	m_time_till_spawn -= time_delta;
	
	// See if time to spawn:
	
	if ( m_time_till_spawn <= 0 )
	{
		// Get the RNG:
		
		Random & random = GameCore::GetSingleton()->GetRandom();
		
		// This is the bounding circle radius for the enemy type we are spawning
		
		float enemy_circle_radius;		
		
		// Pick a time till the next spawn:
		
		if ( GetHealth() < GetMaxHealth() )
		{
			// Spawn predators: we have been damaged
		
			m_time_till_spawn = random.NextFloat( PREDATOR_SPAWN_INTERVAL_MIN , PREDATOR_SPAWN_INTERVAL_MAX );
			
			// Get the size of the predator
			
			enemy_circle_radius = Float::Max( EnemyPredator::SIZE.x , EnemyPredator::SIZE.y );
		}
		else
		{
			// Spawn wasps: not been damaged yet
			
			m_time_till_spawn = random.NextFloat( WASP_SPAWN_INTERVAL_MIN , WASP_SPAWN_INTERVAL_MAX );
			
			// Get the size of the predator
			
			enemy_circle_radius = Float::Max( EnemyWasp::SIZE.x , EnemyWasp::SIZE.y );			
		}
		
		// This is the point we will spawn the enemy at
		
		Vec2f spawn_point;
		
		// Get the game:
		
		GameCore * game = GameCore::GetSingleton();		
		
		#pragma region(PICK_SPAWN_POINT)
		
		// Do this a number of times unitl we find a satisfactory position to spawn:
		
		for ( unsigned i = 8 ; i != 0 ; ++i )
		{
			// Pick a radius away from us to spawn:
			
			float radius = random.NextFloat( SPAWN_RADIUS_MIN , SPAWN_RADIUS_MAX );
			
			// Pick a random angle away from us to spawn at:
			
			float angle = random.NextFloat() * Float::TwoPI();
			
			// Makeup position to spawn at:
			
			spawn_point = GetPosition() + Vec2f( Float::Cos(angle) , Float::Sin(angle) ) * radius;
			
			// This must be wrapped for the search functions used below:
			
			spawn_point = WrapCoordinates(spawn_point);
			
			// Get the obstacle manager from the ai manager:
			
			ObstacleManager * obs_mgr = GetAIManager().GetObstacleManager();
			
			// See if there:
			
			if ( obs_mgr )
			{
				// Get the two stacks from the game:
				
				Stack & s1 = game->GetStack();
				Stack & s2 = game->GetSecondaryStack();
				
				// Save the pointer for the first one: we are not interested in indiviual results
				
				void * stack_ptr = s1.GetPointer();
			
				// Do a search against obstacles to see if a wasp at this spawn point would collide with them: expand it's radius by 2 for safe measure
				
				unsigned num_collisions = obs_mgr->ObstacleCollide(spawn_point,enemy_circle_radius*2,s1,s2);
				
				// Restore the previous stack pointer:
				
				s1.SetPointer(stack_ptr);
				
				// If there were no collisions then we are peachy:
				
				if ( num_collisions == 0 ) break;
			}
			else
			{
				// No obstacles in the game: this spawn point is fine
				
				break;
			}
		}	
		
		#pragma endregion
		
		// See if we are to spawn a wasp or a predator:
		
		if ( GetHealth() < GetMaxHealth() )
		{
			#pragma region(SPAWN_PREDATOR)
		
			// Right: get the enemy predator manager
			
			EnemyPredatorManager * predator_mgr = ((EnemyFactoryManager&)(GetAIManager())).GetPredatorManager();
			
			// See if we can spawn:
			
			if ( predator_mgr && predator_mgr->GetUsedObjectCount() < predator_mgr->GetMaxObjectCount() )
			{
				// Do the spawning:
				
				AIControlled * predator = predator_mgr->AllocatePooledObject();
				
				// Make sure ok:
				
				ENSURE( predator , "The predator manager must never return null when allocating a predator from the pool when it is not full" )
				
				// Make sure ok:
				
				ENSURE( dynamic_cast<EnemyPredator*>(predator) , "The predator manager must return a predator when spawning" )
			
				// Set it's position:
			
				predator->SetPosition( spawn_point );
				
				// Reset it's state:
				
				((EnemyPredator*)(predator))->ResetState();
				
				// Must insert the object into the quad tree of the predator manager
				
				predator_mgr->InsertToQuadTree(predator);
			}		
			
			#pragma endregion
		}
		else
		{			
			#pragma region(SPAWN_WASP)
		
			// Right: get the enemy wasp manager
			
			EnemyWaspManager * wasp_mgr = ((EnemyFactoryManager&)(GetAIManager())).GetWaspManager();
			
			// See if we can spawn:
			
			if ( wasp_mgr && wasp_mgr->GetUsedObjectCount() < wasp_mgr->GetMaxObjectCount() )
			{
				// Do the spawning:
				
				AIControlled * wasp = wasp_mgr->AllocatePooledObject();
				
				// Make sure ok:
				
				ENSURE( wasp , "The wasp manager must never return null when allocating a wasp from the pool when it is not full" )
				
				// Make sure ok:
				
				ENSURE( dynamic_cast<EnemyWasp*>(wasp) , "The wasp manager must return a wasp when spawning" )
			
				// Set it's position:
			
				wasp->SetPosition( spawn_point );
				
				// Reset it's state:
				
				((EnemyWasp*)(wasp))->ResetState();
				
				// Must insert the object into the quad tree of the wasp manager
				
				wasp_mgr->InsertToQuadTree(wasp);
			}
			
			#pragma endregion
		}
	}
}
