/*
	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 is the core game class. Handles the high level game logic.
//=====================================================================================================================

#include "Precompiled.h"
#include "Game\GameCore.h"
#include "Game\GameObjectManager.h"
#include "Game\GameSession.h"
#include "Game\GameMenus.h"
#include "Game\GameSpriteBank.h"
#include "GameObjects\GameMap.h"
#include "Doom\DoomLevel.h"
#include "Doom\DoomCollision.h"
#include "Windows\Window.h"
#include "Graphics\Display.h"
#include "Graphics\Camera3D.h"
#include "Graphics\BitmapFont.h"
#include "Graphics\PrimitivesRenderer.h"
#include "Graphics\BufferedPointRenderer.h"
#include "Graphics\BufferedLineRenderer.h"
#include "Graphics\SpriteRenderer.h"
#include "Resources\TextureManager.h"
#include "Resources\PixelShaderManager.h"
#include "Resources\VertexShaderManager.h"
#include "Resources\BitmapFontManager.h"

using namespace Game;

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

/// Title for the game

const char * GameCore::GAME_TITLE = "Lan Wars";

#ifdef USE_DEBUG_CONSOLE

	/// Title for the debug console

	const char * GameCore::DEBUG_CONSOLE_TITLE = "Debug Console";
	
#endif

/// Near plane value for the camera

const float GameCore::CAM_Z_NEAR = 1;

/// Far plane value for the camera

const float GameCore::CAM_Z_FAR = 10000;

/// Native view area: any screen resolutions other than this are scaled - keeping aspect correctness

const Vec2i GameCore::NATIVE_RES = Vec2i(1024,1024);

#ifdef USE_DEBUG_CONSOLE
	
	/// Debug only flag. Profile rendering ?
	
	bool GameCore::s_profile_render = false;
	
	/// Debug only flag. Profile update ?
	
	bool GameCore::s_profile_update = false;
	
	/// Debug only flag. Do collision for the server camera ?
	
	bool GameCore::s_server_cam_collide = false;

#endif

//=====================================================================================================================
// Statics
//=====================================================================================================================

/// Pointer to an instance of the game

GameCore * GameCore::s_this = 0;

Texture s_tex;

//=====================================================================================================================
/// @brief		Constructor. Creates the game.
/// @param		window - window used by the game
/// @pre		There must not be another game in existance
/// @pre		Given window must not be null 
/// @pre		Window display must be valid
/// @remarks	The game does NOT assume ownership of this window. This is to be managed by the app.
//=====================================================================================================================

GameCore::GameCore( Window * window ) : m_stack(0x100000) , m_secondary_stack(0x100000)
{
	// Make sure ok:
	
	ENSURE( s_this == 0												, "There must not be another game in existance" );
	ENSURE( window													, "Given window must not be null"				);	
	ENSURE( window->GetDisplay() && window->GetDisplay()->IsValid() , "Window display must be valid"				);

	// Save a static ref to us:

	s_this = this;	
	
	// Save the window:
	
	m_window = window;
	
	// Make this the current window listener
	
	m_window->SetEventListener(this);
	
	// Create all the managers:
		
	m_texture_manager		= new TextureManager( m_window->GetDisplay() );
	m_pixel_shader_manager	= new PixelShaderManager( m_window->GetDisplay() );
	m_vertex_shader_manager = new VertexShaderManager( m_window->GetDisplay() );
	
	m_bitmap_font_manager = new BitmapFontManager
	(
		m_window->GetDisplay()	,
		m_vertex_shader_manager	,
		m_pixel_shader_manager	,
		m_texture_manager	
	);
	
	// Create the game fonts:
	
	m_font			= new BitmapFont( m_bitmap_font_manager->GetBitmapFont("Fonts\\Game48.xml") );
	m_small_font	= new BitmapFont( m_bitmap_font_manager->GetBitmapFont("Fonts\\Game32.xml") );
	
	// Game object manager:
	
	m_game_object_manager = new GameObjectManager();
	
	// Make the primitives renderer:

	m_primitives_renderer = new PrimitivesRenderer
	(
		m_window->GetDisplay()	,
		m_vertex_shader_manager	,
		m_pixel_shader_manager
	);	
	
	// Make the sprite renderer
	
	m_sprite_renderer = new SpriteRenderer
	(
		m_window->GetDisplay()	,
		m_vertex_shader_manager	,
		m_pixel_shader_manager	
	);

	// Make the buffered points renderer and the buffered line renderer

	m_buffered_point_renderer = new BufferedPointRenderer
	( 
		m_window->GetDisplay()	, 
		m_vertex_shader_manager , 
		m_pixel_shader_manager
	);
	
	m_buffered_line_renderer = new BufferedLineRenderer
	(
		m_window->GetDisplay()	, 
		m_vertex_shader_manager , 
		m_pixel_shader_manager		
	);
	
	// Make our sprite bank:
	
	m_sprite_bank = new GameSpriteBank();

	// Make the camera

	m_camera = new Camera3D( m_window , Vec3f(0,10,0) , CAM_Z_NEAR , CAM_Z_FAR );

	// Console commands in debug:
	
	#ifdef USE_DEBUG_CONSOLE
	
		DebugConsole::AddCommand( "G_Profile"			, ConCmd_G_Profile				);
		DebugConsole::AddCommand( "R_Profile"			, ConCmd_R_Profile				);
		DebugConsole::AddCommand( "G_ServerCamCollide"	, ConCmd_G_ServerCamCollide		);
	
	#endif

	// All done: reset the frame timer to discount any setup time passed

	m_frame_timer.Reset();
	
	// Create the game session:
	
	m_session = new GameSession();
	
	// Create the game menus:
	
	m_menus = new GameMenus();
	
	// Go to the main menu:
	
	m_menus->SetMenu( GameMenus::MENU_START );
}

//=====================================================================================================================
/// @brief		Destructor. Destroys the game.
//=====================================================================================================================

GameCore::~GameCore()
{	
	// If we are the current event listener then remove us:
	
	if ( m_window->GetEventListener() == this ) m_window->SetEventListener(0);
	
	// Destroy the menus:
	
	m_menus->RemoveReference();
	
	// Done with the game session:
	
	m_session->Disconnect(); m_session->RemoveReference();
	
	// Get rid of the camera

	m_camera->RemoveReference();
	
	// Be sure to clear all the game objects:
	
	m_game_object_manager->Clear();
	
	// Done with the sprite bank:
	
	m_sprite_bank->RemoveReference();

	// Done with all of these:

	m_buffered_point_renderer->RemoveReference();
	m_buffered_line_renderer->RemoveReference();	
	m_primitives_renderer->RemoveReference();
	m_sprite_renderer->RemoveReference();
	
	// Done with our fonts:
	
	delete m_font;
	delete m_small_font;
	
	// Done with all our managers:
	
	m_game_object_manager->RemoveReference();
	m_bitmap_font_manager->RemoveReference();
	m_texture_manager->RemoveReference();
	m_pixel_shader_manager->RemoveReference();
	m_vertex_shader_manager->RemoveReference();

	// Remove static ref to us:

	s_this = 0;
	
	// Console commands in debug:
	
	#ifdef USE_DEBUG_CONSOLE
		
		DebugConsole::RemoveCommand( "G_Profile"			);
		DebugConsole::RemoveCommand( "G_SeverCamCollide"	);
		DebugConsole::RemoveCommand( "R_Profile"			);
	
	#endif
}

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

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

//=====================================================================================================================
/// @brief		Window redraw event - does the game loop
//=====================================================================================================================

void GameCore::OnWindowRedrawing()
{
	// Update the game timer

	GameFrameTimer::ActionFlags actions = m_frame_timer.Update();

	// See what we must do:

	if ( actions & GameFrameTimer::ACTION_UPDATE	) OnUpdate();
	if ( actions & GameFrameTimer::ACTION_RENDER	) OnRender();
}

//=====================================================================================================================
/// @brief		Called when the game is to do an update
//=====================================================================================================================

void GameCore::OnUpdate()
{	
	// Begin profile if enabled:
	
	#ifdef USE_DEBUG_CONSOLE
	
		if ( s_profile_update ) DebugConsole::BeginProfile("Update");
	
	#endif
	
	// Do network updates:
	
	m_session->Update();
	
	// Only do if in game:
	
	if ( m_menus->GetMenu() == GameMenus::MENU_NONE )
	{
		// Do an update for the server camera if we are a server:
		
		if ( m_session->IsConnected() && m_session->IsServer() ) ServerCameraMovement();
	
		// Update all objects:
				
		m_game_object_manager->Update( GameFrameTimer::FRAME_INTERVAL );
		
		// If we are a server then enable the mouse: otherwise hide if
		
		if ( m_session->IsConnected() )
		{
			if ( m_session->IsServer() )
			{
				Mouse::SetMouseCursor(m_window,Mouse::CURSOR_ARROW);
			}
			else
			{
				Mouse::SetMouseCursor(m_window,Mouse::CURSOR_NONE);
			}			
		}
		else
		{
			Mouse::SetMouseCursor(m_window,Mouse::CURSOR_ARROW);		
		}
	}
	else
	{
		Mouse::SetMouseCursor(m_window,Mouse::CURSOR_ARROW);
	}
	
	// Do input for the current menu
	
	m_menus->DoInput();
		
	// If select is pressed on the gamepad then close the window
	
	Gamepad::State gps = Gamepad::GetState(Gamepad::PLAYER_ONE);
	
	// See if pressed:
	
	if ( gps.m_connected && gps.m_back )
	{
		m_window->Close();
	}
	
	// End profile if enabled:
	
	#ifdef USE_DEBUG_CONSOLE
	
		if ( s_profile_update ) DebugConsole::EndProfile("Update");
	
	#endif		
}

//=====================================================================================================================
/// @brief		Called when the game is to do a render
//=====================================================================================================================

void GameCore::OnRender()
{
	// Only if the window is not minimized or if we have not lost the device:

	if ( m_window->IsMinimized() || m_window->GetDisplay()->RequiresReset() ) return;

	// Begin profile if enabled:
	
	#ifdef USE_DEBUG_CONSOLE
	
		if ( s_profile_render ) DebugConsole::BeginProfile("Render");
	
	#endif

	// Clear the display:

	m_window->GetDisplay()->Clear( Color::Black() , 0, 1 );

	// Begin rendering:

	m_window->GetDisplay()->BeginDraw();
	
		// Only if showing no menu:
		
		if ( m_menus->GetMenu() == GameMenus::MENU_NONE )
		{		
			// Draw
	
			m_game_object_manager->Draw( m_camera );
			
			// Draw all sprites that were batched:
			
			m_sprite_renderer->DrawAll(m_camera);
		}
		
		// Draw:
		
		m_menus->Draw();
		
		// End profile if enabled:
		
		#ifdef USE_DEBUG_CONSOLE
		
			if ( s_profile_render ) DebugConsole::EndProfile("Render");
		
		#endif
	
	// End rendering:

	m_window->GetDisplay()->EndDraw();

	// Present the rendered frame:
	
	m_window->GetDisplay()->Present();
}

//=====================================================================================================================
///	@brief		Called when the keyboard is pressed
/// @param		key_code - Virtual key code of the key pressed
//=====================================================================================================================

void GameCore::OnKeyboardReleased( Keyboard::Key key_code )
{
	// Quit to main menu or quit game:
	
	if ( key_code == Keyboard::KB_ESCAPE && m_window->HasFocus() ) 
	{
		if ( m_menus->GetMenu() == GameMenus::MENU_START )
		{
			// On the main menu: quit entirely
		
			m_window->Close();
		}
		else
		{
			// Disconnect if connected.
		
			m_session->Disconnect(); 
			
			// Go to the main menu.
			
			m_menus->SetMenu(GameMenus::MENU_START);
		}
	}
}

//=====================================================================================================================
/// @brief		Called when the window gains focus
//=====================================================================================================================

void GameCore::OnWindowFocusGained()
{
	// Only if we are connected and if we are a client:
	
	if ( m_session->IsConnected() && m_session->IsClient() )
	{
		Mouse::CenterInWindow(m_window);
	}
}


//=====================================================================================================================
/// @brief		Does camera movement for the server
//=====================================================================================================================

void GameCore::ServerCameraMovement()
{
	// Only if the window has focus:
	
	if ( m_window->HasFocus() == false ) return;

	// Movement speed:
	
	const float S = 10.0f;

	// Turn speed:
	
	const float T = 0.05f;
	
	// Get the game
	
	GameCore * g = GameCore::GetSingleton();

	// See what keys are pressed:
	
	if ( Keyboard::IsKeyPressed( Keyboard::KB_W			) ) g->m_camera->MoveLocal( Vec3f(0,0,-S) );	
	if ( Keyboard::IsKeyPressed( Keyboard::KB_S			) ) g->m_camera->MoveLocal( Vec3f(0,0,+S) );
	if ( Keyboard::IsKeyPressed( Keyboard::KB_A			) ) g->m_camera->MoveLocal( Vec3f(-S,0,0) );	
	if ( Keyboard::IsKeyPressed( Keyboard::KB_D			) ) g->m_camera->MoveLocal( Vec3f(+S,0,0) );
	if ( Keyboard::IsKeyPressed( Keyboard::KB_Q			) ) g->m_camera->MoveLocal( Vec3f(0,+S,0) );	
	if ( Keyboard::IsKeyPressed( Keyboard::KB_E			) ) g->m_camera->MoveLocal( Vec3f(0,-S,0) );
	if ( Keyboard::IsKeyPressed( Keyboard::KB_LEFT		) ) g->m_camera->RotateLocalY(T);
	if ( Keyboard::IsKeyPressed( Keyboard::KB_RIGHT		) ) g->m_camera->RotateLocalY(-T);
	if ( Keyboard::IsKeyPressed( Keyboard::KB_UP		) ) g->m_camera->RotateX(T);
	if ( Keyboard::IsKeyPressed( Keyboard::KB_DOWN		) ) g->m_camera->RotateX(-T);

	#ifdef USE_DEBUG_CONSOLE
	
		// Do collision detection for the camera if specified:
		
		if ( s_server_cam_collide )
		{
			// Get the map object:
			
			GameMap * map = dynamic_cast<GameMap*>( m_game_object_manager->FindByType<GameMap>("GameMap") );
			
			// See if found:
			
			if ( map )
			{
				// Apply gravity:
				
				m_camera->SetPosition( m_camera->GetPosition() - Vec3f::UnitY() * 3.0f );
				
				// Jump if space is pressed:
				
				if ( Keyboard::IsKeyPressed( Keyboard::KB_SPACE ) )
				{
					m_camera->SetPosition( m_camera->GetPosition() + Vec3f::UnitY() * 12.0f );	
				}
				
				// Collide with the map:
				
				m_camera->SetPosition( map->GetLevel().GetCollision().Collide( m_camera->GetPosition() , 32 , 48 ) );			
			}
		}
	
	#endif
}

#ifdef USE_DEBUG_CONSOLE

//=====================================================================================================================
/// @brief		Debug only console command: enables / disables profiling of updates
/// @param		arg - argument from the console
/// @param		arg_given - if an argument was given
/// @returns	value of the parameter
//=====================================================================================================================

bool GameCore::ConCmd_G_Profile( bool arg , bool arg_given )
{
	if ( arg_given ) s_profile_update = arg; return s_profile_update;
}

//=====================================================================================================================
/// @brief		Debug only console command: enables / disables profiling of rendering
/// @param		arg - argument from the console
/// @param		arg_given - if an argument was given
/// @returns	value of the parameter
//=====================================================================================================================

bool GameCore::ConCmd_R_Profile( bool arg , bool arg_given )
{
	if ( arg_given ) s_profile_render = arg; return s_profile_render;
}

//=====================================================================================================================
/// @brief		Debug only console command: enables / disables collision with the server camera
/// @param		arg - argument from the console
/// @param		arg_given - if an argument was given
/// @returns	value of the parameter
//=====================================================================================================================

bool GameCore::ConCmd_G_ServerCamCollide( bool arg , bool arg_given )
{
	if ( arg_given ) s_server_cam_collide = arg; return s_server_cam_collide;
}

#endif	// #ifdef USE_DEBUG_CONSOLE
