/*
	Lan Wars.
	Copyright (c) 2009, 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		This helper class packages off objects created on the server for creation on the client.
///				It also performs the reverse on the client.
//=====================================================================================================================

#include "Precompiled.h"
#include "Game/GameNetSerializer.h"
#include "Game/GameCore.h"
#include "Game/GamePacket.h"
#include "Game/GameSession.h"
#include "Game/GameObjectManager.h"
#include "GameObjects/GamePlayer.h"
#include "GameObjects/GameMap.h"
#include "GameObjects/GameRocket.h"
#include "GameObjects/GameFireball.h"
#include "GameObjects/GameAmmo.h"
#include "GameObjects/GameHealth.h"
#include "GameObjects/GameEnemy.h"

using namespace Game;

//=====================================================================================================================
/// @brief		Packs the given net object within the packet for creation on a remote machine
/// @param		obj - the object to pack
/// @param		p - the packet to write the object into
/// @pre		This must only be called on the server
/// @pre		The object being packed must be supported for packing
/// @pre		The object being packet must be a networked obejct
//=====================================================================================================================

void GameNetSerializer::Pack( GameObjectBase & obj , GamePacket & p )
{
	// This must be only called on the server:
	
	ENSURE( GameSession::GetSingleton().IsServer() , "This must only be called on the server" )
	
	// Make sure ok:
	
	ENSURE( obj.IsNetworkedObject() , "The object being packet must be a networked obejct" )

	// See what type the object is:
	
	const type_info & t = typeid(obj);
	
	// Write the chunk id, as well as the net id and owner of this object
	
	p.WriteChunkId(GamePacketChunk::PKCKID_CREATE);
	p.WritePackedUint(obj.GetNetId());
	p.WritePackedUint(obj.GetOwnerPeerId());
	
	// See if it matches one of the supported types:
	
	if		( t == typeid(GamePlayer)	)	PackGamePlayer((GamePlayer&)obj,p);	
	else if ( t == typeid(GameMap)		)	PackGameMap((GameMap&)obj,p);
	else if ( t == typeid(GameRocket)	)	PackGameRocket((GameRocket&)obj,p);
	else if ( t == typeid(GameAmmo)		)	PackGameAmmo((GameAmmo&)obj,p);
	else if ( t == typeid(GameHealth)	)	PackGameHealth((GameHealth&)obj,p);
	else if ( t == typeid(GameEnemy)	)	PackGameEnemy((GameEnemy&)obj,p);
	else if ( t == typeid(GameFireball)	)	PackGameFireball((GameFireball&)obj,p);
	
	// Debug only:
	
	#ifdef DEBUG
	
		else
		{
			// Trying to pack an unknown object: failure
			
			#pragma warning(disable:4127)
			
				ENSURE( 0 , "The object being packed must be supported for packing" )
				
			#pragma warning(default:4127)
		}
	
	#endif
}

//=====================================================================================================================
/// @brief		Unpacks the given net object in the given packet for creation on the local machine
/// @param		p - the packet to unpack
/// @returns	The unpacked object or null on failure
/// @pre		This must only be called on the client
//=====================================================================================================================

GameObjectBase * GameNetSerializer::Unpack( GamePacket & p )
{
	// This must be only called on the client:
	
	ENSURE( GameSession::GetSingleton().IsClient() , "This must only be called on the client" )

	// Read the object type, it's net id, and the owner id:
	
	unsigned net_id = 0; unsigned owner_id = 0; unsigned type = 0; 
	
	// Do it:
	
	if ( p.ReadPackedUint(net_id) && p.ReadPackedUint(owner_id) && p.ReadPrecisionUint(type,TYPE_ID_BITS) )
	{
		// Ignore requests to create non-networked objects, or objects with an invalid net id:
		
		if ( net_id != NetObject::NET_ID_NONE && net_id != NetObject::NET_ID_INVALID )
		{
			// Store the type here:
			
			TypeId type_id = (TypeId)(type);
			
			// See what is to be created:
			
			switch ( type_id ) 
			{
				case TYPE_ID_GAME_PLAYER:	return UnpackGamePlayer(p,net_id,owner_id);
				case TYPE_ID_GAME_MAP:		return UnpackGameMap(p,net_id,owner_id);
				case TYPE_ID_GAME_ROCKET:	return UnpackGameRocket(p,net_id,owner_id);
				case TYPE_ID_GAME_ROCKETS:	return UnpackGameAmmo(p,net_id,owner_id);
				case TYPE_ID_GAME_HEALTH:	return UnpackGameHealth(p,net_id,owner_id);
				case TYPE_ID_GAME_ENEMY:	return UnpackGameEnemy(p,net_id,owner_id);
				case TYPE_ID_GAME_FIREBALL:	return UnpackGameFireball(p,net_id,owner_id);
			}		
		}
	}
	
	// Failed: return null
	
	return 0;
}

//=====================================================================================================================
/// @brief		Packs a GamePlayer object
/// @param		obj - the object to pack
/// @param		p - the packet to write the object into
//=====================================================================================================================

void GameNetSerializer::PackGamePlayer( GamePlayer & obj , GamePacket & p )
{
	// Write all data:

	p.WritePrecisionUint( TYPE_ID_GAME_PLAYER , TYPE_ID_BITS );
	p.Write( short( obj.GetPosition().x ) );
	p.Write( short( obj.GetPosition().y ) );
	p.Write( short( obj.GetPosition().z ) );
	p.WriteFP_4_8( Angle::Wrap(obj.GetRotationY()) );
}

//=====================================================================================================================
/// @brief		Unpacks a GamePlayer object
/// @param		p - packet to unpack from
/// @param		net_id - net id of the object being unpacked
/// @param		owner_id - owner id of the object being unpacked
/// @returns	The created object or null on failure
//=====================================================================================================================

GamePlayer * GameNetSerializer::UnpackGamePlayer( GamePacket & p , unsigned net_id , unsigned owner_id )
{
	// Read all data:
	
	bool	success		= true;				
	Vec3s	position	= Vec3s::Zero();
	float	y_rot		= 0;
	
	// Read:
	
	success = success && p.Read(position.x);
	success = success && p.Read(position.y);
	success = success && p.Read(position.z);
	success = success && p.ReadFP_4_8(y_rot);
	
	// Make sure all ok:
	
	if ( success )
	{
		// Make sure an object with this net id does not already exist:
		
		if ( GameCore::GetSingleton()->GetObjectManager()->FindByNetId(net_id) == 0 )
		{
			// Create the player:
			
			return new GamePlayer(owner_id,position,0,y_rot,net_id);
		}
	}
	
	// Failed: return null
	
	return 0;
}

//=====================================================================================================================
/// @brief		Packs a GameMap object
/// @param		obj - object to pack
/// @param		p - packet to pack it into
//=====================================================================================================================

#pragma warning(disable:4100)

void GameNetSerializer::PackGameMap( GameMap & obj , GamePacket & p )
{
	p.WritePrecisionUint( TYPE_ID_GAME_MAP , TYPE_ID_BITS );
}

#pragma warning(default:4100)

//=====================================================================================================================
/// @brief		Unpacks a GameMap object and creates it
/// @param		p - packet to unpack from
/// @param		net_id - net id of the object being unpacked
/// @param		owner_id - owner id of the object being unpacked
/// @returns	The created object or null on failure
//=====================================================================================================================

#pragma warning(disable:4100)

GameMap * GameNetSerializer::UnpackGameMap( GamePacket & p , unsigned net_id , unsigned owner_id )
{
	// Read the net id of the object

	return new GameMap(net_id);
}

#pragma warning(default:4100)

//=====================================================================================================================
/// @brief		Packs a GameRocket object
/// @param		obj - object to pack
/// @param		p - packet to pack it into
//=====================================================================================================================

void GameNetSerializer::PackGameRocket( GameRocket & obj , GamePacket & p )
{
	p.WritePrecisionUint( TYPE_ID_GAME_ROCKET , TYPE_ID_BITS );
	
	p.Write( Vec3s(obj.GetPosition()) );
	p.WriteNormalisedSignedFloat16( obj.GetDirection().x );
	p.WriteNormalisedSignedFloat16( obj.GetDirection().y );
	p.WriteNormalisedSignedFloat16( obj.GetDirection().z );
}

//=====================================================================================================================
/// @brief		Unpacks a GameRocket object
/// @param		p - packet to unpack from
/// @param		net_id - net id of the object being unpacked
/// @param		owner_id - owner id of the object being unpacked
/// @returns	The created object or null on failure
//=====================================================================================================================

#pragma warning(disable:4100)

GameRocket * GameNetSerializer::UnpackGameRocket( GamePacket & p , unsigned net_id , unsigned owner_id )
{
	// Store if successful:
	
	bool	success = true;
	Vec3s	pos		= Vec3f::Zero();
	Vec3f	dir		= Vec3f::Zero();
		
	success = success && p.Read(pos);	
	success = success && p.ReadNormalisedSignedFloat16(dir.x);
	success = success && p.ReadNormalisedSignedFloat16(dir.y);
	success = success && p.ReadNormalisedSignedFloat16(dir.z);
	
	// See if ok:
	
	if ( success )
	{
		// Make the rocket:
		
		return new GameRocket(pos,dir,net_id);
	}
	else
	{
		// Fail: 
		
		return 0;
	}
}

#pragma warning(default:4100)

//=====================================================================================================================
/// @brief		Packs a GameFireball object
/// @param		obj - object to pack
/// @param		p - packet to pack it into
//=====================================================================================================================

void GameNetSerializer::PackGameFireball( GameFireball & obj , GamePacket & p )
{
	p.WritePrecisionUint( TYPE_ID_GAME_FIREBALL , TYPE_ID_BITS );
	
	p.Write( Vec3s(obj.GetPosition()) );
	p.WriteNormalisedSignedFloat16( obj.GetDirection().x );
	p.WriteNormalisedSignedFloat16( obj.GetDirection().y );
	p.WriteNormalisedSignedFloat16( obj.GetDirection().z );
}

//=====================================================================================================================
/// @brief		Unpacks a GameFireball object
/// @param		p - packet to unpack from
/// @param		net_id - net id of the object being unpacked
/// @param		owner_id - owner id of the object being unpacked
/// @returns	The created object or null on failure
//=====================================================================================================================

#pragma warning(disable:4100)

GameFireball * GameNetSerializer::UnpackGameFireball( GamePacket & p , unsigned net_id , unsigned owner_id )
{
	// Store if successful:
	
	bool	success = true;
	Vec3s	pos		= Vec3f::Zero();
	Vec3f	dir		= Vec3f::Zero();
		
	success = success && p.Read(pos);	
	success = success && p.ReadNormalisedSignedFloat16(dir.x);
	success = success && p.ReadNormalisedSignedFloat16(dir.y);
	success = success && p.ReadNormalisedSignedFloat16(dir.z);
	
	// See if ok:
	
	if ( success )
	{
		// Make the rocket:
		
		return new GameFireball(pos,dir,net_id);
	}
	else
	{
		// Fail: 
		
		return 0;
	}
}

#pragma warning(default:4100)

//=====================================================================================================================
/// @brief		Packs a GameAmmo object
/// @param		obj - object to pack
/// @param		p - packet to pack it into
//=====================================================================================================================

void GameNetSerializer::PackGameAmmo( GameAmmo & obj , GamePacket & p )
{
	p.WritePrecisionUint( TYPE_ID_GAME_ROCKETS , TYPE_ID_BITS );
	p.Write( short(obj.GetPosition().x) );
	p.Write( short(obj.GetPosition().z) );
}

//=====================================================================================================================
/// @brief		Unpacks a GameAmmo object
/// @param		p - packet to unpack from
/// @param		net_id - net id of the object being unpacked
/// @param		owner_id - owner id of the object being unpacked
/// @returns	The created object or null on failure
//=====================================================================================================================

#pragma warning(disable:4100)

GameAmmo * GameNetSerializer::UnpackGameAmmo( GamePacket & p , unsigned net_id , unsigned owner_id )
{
	// Store if successful:
	
	bool success = true; Vec2s pos = Vec2s::Zero();
		
	success = success && p.Read(pos.x);	
	success = success && p.Read(pos.y);
	
	// See if ok:
	
	if ( success )
	{
		// Make the ammo:
		
		return new GameAmmo(pos,net_id);
	}
	else
	{
		// Fail: 
		
		return 0;
	}
}

#pragma warning(default:4100)

//=====================================================================================================================
/// @brief		Packs a GameHealth object
/// @param		obj - object to pack
/// @param		p - packet to pack it into
//=====================================================================================================================

void GameNetSerializer::PackGameHealth( GameHealth & obj , GamePacket & p )
{
	p.WritePrecisionUint( TYPE_ID_GAME_HEALTH , TYPE_ID_BITS );
	p.Write( short(obj.GetPosition().x) );
	p.Write( short(obj.GetPosition().z) );
}

//=====================================================================================================================
/// @brief		Unpacks a GameHealth object
/// @param		p - packet to unpack from
/// @param		net_id - net id of the object being unpacked
/// @param		owner_id - owner id of the object being unpacked
/// @returns	The created object or null on failure
//=====================================================================================================================

#pragma warning(disable:4100)

GameHealth * GameNetSerializer::UnpackGameHealth( GamePacket & p , unsigned net_id , unsigned owner_id )
{
	// Store if successful:
	
	bool success = true; Vec2s pos = Vec2s::Zero();
		
	success = success && p.Read(pos.x);	
	success = success && p.Read(pos.y);
	
	// See if ok:
	
	if ( success )
	{
		// Make the ammo:
		
		return new GameHealth(pos,net_id);
	}
	else
	{
		// Fail: 
		
		return 0;
	}
}

#pragma warning(default:4100)

//=====================================================================================================================
/// @brief		Packs a GameEnemy object
/// @param		obj - object to pack
/// @param		p - packet to pack it into
//=====================================================================================================================

void GameNetSerializer::PackGameEnemy( GameEnemy & obj , GamePacket & p )
{
	p.WritePrecisionUint( TYPE_ID_GAME_ENEMY , TYPE_ID_BITS );
	p.Write( Vec3s(obj.GetPosition()) );
	p.WriteAngle12( obj.GetRotationY() );
}

//=====================================================================================================================
/// @brief		Unpacks a GameEnemy object
/// @param		p - packet to unpack from
/// @param		net_id - net id of the object being unpacked
/// @param		owner_id - owner id of the object being unpacked
/// @returns	The created object or null on failure
//=====================================================================================================================

#pragma warning(disable:4100)

GameEnemy * GameNetSerializer::UnpackGameEnemy( GamePacket & p , unsigned net_id , unsigned owner_id )
{
	// Try to read all the fields

	Vec3s pos = Vec3s::Zero(); float rot = 0;

	// Read:

	if ( p.Read(pos) && p.ReadAngle12(rot) )
	{
		// Success:

		return new GameEnemy(pos,rot,net_id);
	}
	else
	{
		// Failed: return null

		return 0;
	}
}

#pragma warning(default:4100)
