/*

Gamebots UT Copyright (c) 2002, Andrew N. Marshal, Gal Kaminka
GameBots - Pogamut3 derivation Copyright (c) 2010, Michal Bida

All rights reserved.

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 and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT OWNER OR CONTRIBUTORS 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.

This software must also be in compliance with the Epic Games Inc. license for mods which states the following: "Your mods must be distributed solely for free, period. Neither you, nor any other person or party, may sell them to anyone, commercially exploit them in any way, or charge anyone for receiving or using them without prior written consent of Epic Games Inc. You may exchange them at no charge among other end-users and distribute them to others over the Internet, on magazine cover disks, or otherwise for free." Please see http://www.epicgames.com/ut2k4_eula.html for more information.

*/
class RayManager extends Actor;

struct CustomRay{
	var() config string Id;
	var() config rotator Rotation;
	var() config float Length;
	var() config bool FastTrace;
	var() config bool TraceActors;
	var() config bool ProvideFloorCorrection;
	var() bool Hit;
	var() bool bChanged;	
	var RayVisualizer Vis;
	//var UTParticleSystemComponent ParticleSystemComponent;
};

var array<CustomRay> RayList;

var BotConnection myConnection;

simulated function PostBeginPlay()
{	
	myConnection = BotConnection(Owner);
	if (Owner == none || myConnection == none)
		destroy();
}
event Destroyed()
{
	super.Destroyed();
	RemoveCustomRay("All");
}

simulated function bool LaunchRay (
	vector From,
	vector RealRayDirection, //current bot rotation
	CustomRay Ray,
	out vector To,
	out optional vector HitNormal,
	out optional vector HitLocation,
	out optional string HitId
	)
{
	local Actor HitActor; //shouldnt be object?

	To = From + (RealRayDirection * Ray.Length);
	HitId = "None";

	if (Ray.FastTrace == true)
	{
		return !FastTrace(To, From);
	}
	else
	{
		HitActor = Trace(HitLocation, HitNormal, To, From, Ray.TraceActors);
		if ( (HitActor != None) && HitActor.IsA('Pawn'))
			HitId = Pawn(HitActor).Controller.PlayerReplicationInfo.PlayerName;
		else
			HitId = string(HitActor);

		return (HitActor != None);
	}
}

function StopRays()
{
	local int i;

	for (i = 0; i < RayList.Length; ++i)
	{
		RayList[i].Vis.Destroy();//.DeactivateSystem();
		RayList[i].Vis = none;
	}
}

simulated function AddCustomRay(string Id, vector Direction, float Length, bool FastTrace, bool TraceActors, bool ProvideFloorCorrection)
{
	local CustomRay Ray;
	local int i;

	//if the ray exists we will remove it
	for (i=0; i < RayList.Length; i++)
	{
		if (RayList[i].Id == Id)
		{
			if (RayList[i].Vis != none)
				RayList[i].Vis.Destroy();//ParticleSystemComponent.DeactivateSystem();

			RayList.Remove(i,1);
			break;
		}
	}

	Ray.Id = (Id != "") ? Id : ("Ray_" $ RayList.Length);
	Ray.Rotation = rotator(Direction);
	Ray.Length = Length;
	Ray.FastTrace = FastTrace;
	Ray.TraceActors = TraceActors;
	Ray.ProvideFloorCorrection = ProvideFloorCorrection;
	RayList[RayList.Length] = Ray;
}

simulated function RemoveCustomRay(string Id)
{
	local int i, RayListLength;

	if (Id == "All")
	{
		//destroy the visualizers
		for ( i=0; i < RayList.Length; i++ )
		{
			if (RayList[i].Vis != none)
				RayList[i].Vis.Destroy();//ParticleSystemComponent.DeactivateSystem();
		}

		RayList.Remove(0,RayList.Length);
		return;
	}

	RayListLength = RayList.Length;
	//log ("Length before removing "$RayList.Length);
	i = 0;
	while (i < RayListLength)
	{
		if (RayList[i].Id == Id)
		{
			if (RayList[i].Vis != none)
				RayList[i].Vis.Destroy();//ParticleSystemComponent.DeactivateSystem();
			RayList.Remove(i,1);
			break;
		}
		i++;
	}
		/*
	log ("Length after removing "$RayList.Length);
	log ("ID of last obj in list "$RayList[RayListLength - 2].Id);
	log ("ID of deleted obj in list "$RayList[RayListLength - 1].Id);
	*/
}

simulated function AddDefaultRays()
{
	local int i;

	//destroy the visualizers
	for ( i=0; i < RayList.Length; i++ )
	{
		if (RayList[i].Vis != none)
			RayList[i].Vis.Destroy();//ParticleSystemComponent.DeactivateSystem();
	}

	//delete all rays from list
	RayList.Remove(0, RayList.Length);

	AddCustomRay("StraightAhead", vect(1,0,0), 250, false, false, false);
	AddCustomRay("45toLeft", vect(1,-1,0), 200, false, false, false);
	AddCustomRay("45toRight", vect(1,1,0), 200, false, false, false);
}

function int RayCount()
{
	return RayList.Length;
}

simulated function AutoTrace()
{
	local vector from, to, RealRayDirection;
	local vector hitNormal, hitLocation;
	local string hitId;
	local int i, RayListLength;
	local vector FloorNormal, FloorLocation;
	local bool bOld;

	if (myConnection.theBot.Pawn == None)
		return;

	//we have to take into account also angle of the floor we are standing on
	FloorNormal = vect(0,0,0);
	Trace(FloorLocation, FloorNormal, myConnection.theBot.Pawn.Location + vect(0,0,-100),
		myConnection.theBot.Pawn.Location, false, ,);

	RayListLength = RayList.Length;
	for (i = 0;	i < RayListLength; ++i)
	{
		from = myConnection.theBot.Pawn.Location;
		RealRayDirection = vector(myConnection.theBot.Pawn.Rotation + RayList[i].Rotation);
		if (RayList[i].ProvideFloorCorrection)
		{
			//RealRayDirection += FloorNormal * (Normal(RealRayDirection) dot FloorNormal) * -1;
			RealRayDirection += FloorNormal * (RealRayDirection dot FloorNormal) * -1;
		}
		bOld = RayList[i].Hit;		
		RayList[i].Hit =
			LaunchRay(from, RealRayDirection, RayList[i], to, hitNormal, hitLocation, hitId );		
		RayList[i].bChanged = (bOld != RayList[i].Hit);

		//if (RayList[i].ParticleSystemComponent != none)
		//	RayList[i].ParticleSystemComponent.SetVectorParameter('LinkBeamEnd', to);

		if (myConnection.theBot.bDrawTraceLines)
			DrawRays();
			
		myConnection.SendLine("ATR {Id " $ RayList[i].Id $
			"} {From " $ from $
			"} {To " $ to $
			"} {FastTrace " $ RayList[i].fastTrace $
			"} {FloorCorrection " $ RayList[i].ProvideFloorCorrection $
			"} {Result " $ RayList[i].Hit $
			"} {HitNormal " $ hitNormal $
			"} {HitLocation " $ hitLocation $
			"} {TraceActors " $ RayList[i].traceActors $
			"} {HitId " $ hitId $
			"}");
	}

}

simulated function DrawRays()
{
	local int i;
	local Quat RayRotation;

	if ( myConnection.theBot.Pawn != none )
	{
		for (i = 0; i < RayList.Length; ++i)
		{
			if (RayList[i].Vis == none)
			{				

				if (RayList[i].Vis == none) {
					RayList[i].Vis = Spawn(class'RayVisualizer', myConnection.theBot.Pawn,, myConnection.theBot.Pawn.Location, myConnection.theBot.Pawn.Rotation);
					RayList[i].Vis.Instigator = myConnection.theBot.Pawn;
   					RayList[i].Vis.BeamDirection = RayList[i].Rotation;
   					RayList[i].Vis.BeamLength = RayList[i].Length;
   					RayList[i].Vis.bFloorCorrection = RayList[i].ProvideFloorCorrection;
					RayList[i].Vis.SetHidden(false);
				}

				/*
				RayList[i].ParticleSystemComponent = new(myConnection.theBot.Pawn) class'UTParticleSystemComponent';
				RayList[i].ParticleSystemComponent.SetHidden(false);
				RayList[i].ParticleSystemComponent.SetTemplate(ParticleSystem'WP_LinkGun.Effects.P_WP_Linkgun_Altbeam_Blue');
				RayList[i].ParticleSystemComponent.SetTickGroup( TG_PostUpdateWork );
				RayList[i].ParticleSystemComponent.SetDepthPriorityGroup(SDPG_World);
				RayList[i].ParticleSystemComponent.bUpdateComponentInTick = true;
				RayList[i].ParticleSystemComponent.SetIgnoreOwnerHidden(TRUE);
				RayList[i].ParticleSystemComponent.SetScale(0.5f);
				*/
				// this is required since a) b_Root is turned 0, -16834, 0 from pawns direction
				// b) b_Spine is even more complex
				// c) simple addition of rotator works only for certain limited cases
				// d) quaternions can be used to get a result of "adding" rotations (performing them in sequence)
				// by calculating their product
				RayRotation = QuatFromRotator(RayList[i].Rotation);
				RayRotation = QuatProduct(QuatFromRotator(rot(0, 16384, 0)), RayRotation);
				//myConnection.theBot.Pawn.Mesh.AttachComponent( RayList[i].Vis,
				//	'b_Root', vect(0, 0, 50), QuatToRotator(RayRotation));

				// vect(0, 1, 0), vect(0, 0, -1), vect(-1, 0, 0)
				// straight vect(0, 1, 0)
				// 45left vect(1, 1, 0)
				// 45right vect(-1, 1, 0)
				// AddCustomRay("StraightAhead", vect(1,0,0), 250, false, true, false);
				// AddCustomRay("45toLeft", vect(1,-1,0), 200, false, true, false);
				// AddCustomRay("45toRight", vect(1,1,0), 200, false, true, false);	
			}

			if (RayList[i].bChanged)
			{
				RayList[i].Vis.bHit = RayList[i].Hit;
				
				/*ParticleSystemComponent.DeactivateSystem();
				if (RayList[i].Hit)
				{
					RayList[i].ParticleSystemComponent.SetTemplate(ParticleSystem'WP_LinkGun.Effects.P_WP_Linkgun_Altbeam_Red');
				}
				else
				{
					RayList[i].ParticleSystemComponent.SetTemplate(ParticleSystem'WP_LinkGun.Effects.P_WP_Linkgun_Altbeam_Blue');
				}
				RayList[i].ParticleSystemComponent.ActivateSystem();*/
			}
		}		
	}
}

DefaultProperties
{
}
