#include "MW4Headers.hpp"
#include <Adept\CollisionGrid.hpp>
#include "aiutils.hpp"

using namespace MW4AI;
	
namespace MW4AI
{
	std::stack<__int64*> *g_TimerStack=NULL;
}


CTimeServer::CTimeServer (void)
{
	m_StartTime = 0;
	m_MarkTime = 0;
	m_Paused = 0;
	m_Running = false;
	m_PauseTime = 0;
	m_PauseStartTime = 0;
	m_StopTime = 0;
}

CTimeServer::~CTimeServer (void)
{

}

void CTimeServer::Start (void)
{
	m_Running = true;
	m_Paused = false;
	m_StopTime = 0;
	m_PauseTime = 0;
	m_PauseStartTime = 0;
	m_StartTime = gos_GetElapsedTime ();
}

void CTimeServer::Stop (void)
{
	if (!m_Running)
		return;
	m_StopTime = gos_GetElapsedTime ();
	m_Running = false;
}
void CTimeServer::Pause (bool on)
{
	if (!m_Running)
		return;
	if(on)
	{
		if(!m_Paused)
			m_PauseStartTime = gos_GetElapsedTime ();			
		m_Paused++;
		gosASSERT (m_Paused);
	}
	else
	{
		gosASSERT (m_Paused);
		m_Paused--;
		if(!m_Paused)
		{
			Stuff::Time elap;
			elap = gos_GetElapsedTime () - m_PauseStartTime;
			m_PauseTime += elap;
			m_MarkTime += elap;
		}
	}
}

Stuff::Time CTimeServer::ElapsedRaw (void)
{
	if(m_Running)
		return gos_GetElapsedTime () - m_MarkTime;
	else
		return m_StopTime - m_MarkTime;
}

Stuff::Time	CTimeServer::CurrTimeRaw (void)
{
	if(m_Running)
		return gos_GetElapsedTime () - m_StartTime - m_PauseTime;
	else
		return m_StopTime - m_StartTime - m_PauseTime;
}

Stuff::Scalar MW4AI::GetMapY(Stuff::Scalar x, Stuff::Scalar z,Entity *who,BYTE& material,Stuff::Scalar basey, Entity** entity_hit)
{
	// Find the ground

	//
	// make a line...
	//
	if (basey == -1.0f)
	{
		basey = 800.0f;
	}
	Stuff::Line3D line;
	line.m_length = 20.0f;
	line.m_direction = Vector3D::Down;
	line.m_origin.x = x;
	line.m_origin.z = z;
	line.m_origin.y = basey + 5.0f;	// pretty harsh hill!  =)

	//
	// Prepare query
	//	
	Stuff::Normal3D normal;
	Entity::CollisionQuery query(&line, &normal, Entity::CanBeWalkedOnFlag, who);

	Adept::Entity* extra_pointer = 0;
	if (entity_hit == 0)
	{
		entity_hit = &extra_pointer;
	}

	//
	// Cast ray
	//
	Check_Object(CollisionGrid::Instance);
	*entity_hit = CollisionGrid::Instance->ProjectLine(&query);

	if (*entity_hit != NULL)
	{
		Point3D tr;
		line.FindEnd(&tr);
		material = query.m_material;
		return tr.y;
	}
	else
	{
		Point3D tr;
		// Damnit...then find the ground aggresivly!!!!
		line.m_origin.x = x;
		line.m_origin.z = z;
		line.m_origin.y = basey + 100.0f;	// pretty harsh hill!  =)
		line.m_length = 1000.0f;
		*entity_hit = CollisionGrid::Instance->ProjectLine(&query);
		if (*entity_hit != NULL)
		{
			line.FindEnd(&tr);
			material = query.m_material;
			return tr.y;
		}
		else // now try up!
		{
			line.m_direction = Vector3D(0.0f, 1.0f, 0.0f);
			*entity_hit = CollisionGrid::Instance->ProjectLine(&query);
			if (*entity_hit != NULL)
			{
				line.FindEnd(&tr);
				material = query.m_material;
				return tr.y;
			}
		}
		// ok stop we are way off the map
	}
	return -1.0f;
}
