//Copyright (C) 2007 SiegeLord
//See ReadMe.txt and License.txt for copying information

#include "rocket.h"
#include "explosion.h"
#include "ship.h"
#include "shipregistry.h"
#include "thruster.h"
#include "trails.h"

extern SObjectEx* g_obRootObject;

SRocket::~SRocket()
{
	thruster->target_object = 0;
}

int SRocket::Handle()
{
	life += g_fDelta;
	vector2d cur_pos = GetGlobalPosition();

	if(life > max_life)//ran out of fuelz
	{
		dead = true;
		trail->target_object = 0;
		thruster->target_object = 0;
		CreateExplosion(cur_pos, 0.5, 0xff05afff);
	}

	if(target_ship_id > -1)
	{
		SShip* ship = GetShipByID(target_ship_id);
		if(ship)
		{
			if(ship->global_bbox.PointTest(cur_pos))//we hit the ship
			{
				dead = true;
				trail->target_object = 0;
				thruster->target_object = 0;
				ship->Damage(min_damage, max_damage);
				CreateExplosion(cur_pos, 0.5, 0xff05afff);
				return 0;
			}
			target_loc = ship->GetGlobalPosition();
		}
		else//target was lost
			target_ship_id = -1;
	}
	vector2d dir = target_loc - cur_pos;

	if(dir.GetLengthSQ() < velocity.GetLengthSQ() * g_fDelta * g_fDelta)//we are at target
	{
		dead = true;
		trail->target_object = 0;
		thruster->target_object = 0;
		CreateExplosion(cur_pos, 0.5, 0xff05afff);
		return 0;
	}

	dir.Normalize();
	dir *= accel * g_fDelta;
	velocity += dir;

	vector2d old_velocity = velocity;

	if(velocity != g_vecZero)
	{
		float mag = velocity.GetLength();
		if(mag > max_speed)
		{
			velocity = velocity * max_speed / mag;
		}
	}

	if(!(old_velocity == velocity))
		thruster->throttle = 0;
	else
		thruster->throttle = 1;

	position += velocity * g_fDelta;

	SetPosition(position.x, position.y);
	SetRotation(atan2f(dir.y, dir.x));

	return 0;
}

void SRocket::Draw()
{
	SetModelMatrix(net_transform);

	DrawModeMask();

	DrawBitmap(image, 0, -image->h / 2, -10);

	DrawModeSolid();

	SetModelMatrix(g_trIdentity);
}

SRocket* CreateRocket(SObject* parent, vector2d& start_pos, vector2d& ini_vel, vector2d& destination, int ship_id)
{
	SRocket* rocket = new SRocket();
	InitObject(rocket, parent);

	rocket->target_ship_id = ship_id;
	rocket->target_loc = destination;

	rocket->max_speed = 100.0f;
	rocket->max_life = 5.0f;

	rocket->life = 0;

	rocket->accel = 50.0f;

	rocket->max_damage = 10.0f;
	rocket->min_damage = 10.0f;

	rocket->SetPosition(start_pos.x, start_pos.y);

	rocket->velocity = ini_vel;

	rocket->trail = CreateTrail(g_obRootObject, rocket, FindBitmap("trail.tga"), 0xff0011ff, 0.5);
	rocket->thruster = CreateThrusterParticleHolder(g_obRootObject, rocket, FindBitmap("part.tga"), 0xff0011ff);

	rocket->thruster->throttle = 0;
	rocket->thruster->SetRotation(AL_PI);

	rocket->image = FindBitmap("rocket.tga");

	return rocket;
}
