/*
	Trampoline Sim.
	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		Simple object containing all of the bodies (rigid and soft) in the world. Handles updates.
//=====================================================================================================================

#include "Precompiled.h"
#include "Physics/SimulationWorld.h"
#include "Physics/Body.h"

using namespace Game;

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

#ifdef USE_DEBUG_CONSOLE

	/// True if contacts are to be debugged

	bool SimulationWorld::s_debug_contacts = true;

#endif

//=====================================================================================================================
/// @brief		Creates the world
//=====================================================================================================================

SimulationWorld::SimulationWorld()
{
	// No manual stepping initially

	m_manual_step		= false;
	m_step_frames_left	= 0;

	// Reset these

	for ( unsigned i = 0 ; i < 10 ; ++i )
	{
		m_step_keys_pressed[i] = false;
	}

	// Console commands

	#ifdef USE_DEBUG_CONSOLE

		DebugConsole::AddCommand( "P_ContactDebug" , ConCmd_P_ContactDebug );

	#endif
}

//=====================================================================================================================
/// @brief		Destroys the world
/// @pre		All objects must have been removed from the world
//=====================================================================================================================

SimulationWorld::~SimulationWorld()
{
	// Make sure ok
	
	ENSURE( m_bodies.size() == 0 , "All objects must have been removed from the world" )

	// Console commands

	#ifdef USE_DEBUG_CONSOLE

		DebugConsole::RemoveCommand( "P_ContactDebug" );

	#endif
}

//=====================================================================================================================
/// @brief		Adds an object into the world
/// @param		body - body to add
/// @remarks	This object does not take ownership of the body. Caller is responsible for cleanup after Remove().
/// @pre		Given body must not be null
/// @pre		Given body must not have been added already
//=====================================================================================================================

void SimulationWorld::Add( Body * body )
{
	// Debug only
	
	#ifdef DEBUG
	
		ENSURE( body , "Given body must not be null" )
		
		// Check for this:
		
		{		
			std::list<Body*>::iterator i = m_bodies.begin();
			std::list<Body*>::iterator e = m_bodies.end();
			
			while ( i != e )
			{
				ENSURE( *i != body , "Given body must not have been added already" )
				
				i++;
			}	
		}
		
	#endif
	
	// Add:
	
	m_bodies.push_back(body);
}

//=====================================================================================================================
/// @brief		Removes an object from the world
/// @param		body - body to remove
/// @remarks	This object does not take ownership of the body. Caller is responsible for cleanup after Remove().
/// @pre		Given body must not be null
/// @pre		Given body must be in the scene
//=====================================================================================================================

void SimulationWorld::Remove( Body * body )
{
	// Debug only
	
	#ifdef DEBUG
	
		ENSURE( body , "Given body must not be null" )
		
		// Check for this:
		
		ENSURE( std::find(m_bodies.begin(),m_bodies.end(),body) != m_bodies.end() , "Given body must be in the scene" )
		
	#endif
	
	// Remove:
	
	m_bodies.remove(body);
}

//=====================================================================================================================
/// @brief		Runs the simulation for one step
/// @param		iterations - number of iterations to use
//=====================================================================================================================

void SimulationWorld::StepSimulation( float time_delta , unsigned iterations )
{
	// Do keyboard input:

	DoKeyboardInput();

	// Figure out the time delta per iteration

	float t = time_delta / float(iterations);

	// Do each iteration:

	for ( unsigned iteration = 0 ; iteration < iterations ; ++iteration )
	{
		// Quit if manual step frame count has been reached:

		if ( ( m_manual_step && m_step_frames_left == 0 ) && time_delta > 0.00002f ) 
		{
			break; 
		}
		else if ( m_manual_step && time_delta > 0.00002f ) 
		{
			m_step_frames_left--;
		}

		// Integrate all objects:
		
		{
			std::list<Body*>::iterator i = m_bodies.begin();
			std::list<Body*>::iterator e = m_bodies.end();
			
			while ( i != e )
			{
				(*i)->Integrate(t); i++;
			}
		}

		// Do collision detection and response:
		
		{
			std::list<Body*>::iterator i = m_bodies.begin();
			std::list<Body*>::iterator e = m_bodies.end();
			
			while ( i != e )
			{
				// Get iterator to the next objcet:
				
				std::list<Body*>::iterator j = i; j++;
				
				// Collide with the other objects:
				
				while ( j != e )
				{
					// Collide with this object:
						
					(*i)->Collide(t,**j); j++;
				}
				
				// Move along:
				
				i++;
			}
		}

		// Done update for all objects:
		
		{
			std::list<Body*>::iterator i = m_bodies.begin();
			std::list<Body*>::iterator e = m_bodies.end();
			
			while ( i != e )
			{
				(*i)->EndUpdate(); i++;
			}
		}
	}
}

//=====================================================================================================================
/// @brief		Does keyboard input for controlling stepping of simulation
//=====================================================================================================================

void SimulationWorld::DoKeyboardInput()
{
	// See if we are to step manually or not:

	if ( Keyboard::IsKeyPressed(Keyboard::KB_F1) ) m_manual_step = false;
	if ( Keyboard::IsKeyPressed(Keyboard::KB_F2) ) m_manual_step = true;

	// Manual step advancement keys:

	if ( Keyboard::IsKeyPressed(Keyboard::KB_F3) )
	{
		if ( m_step_keys_pressed[0] == false )
		{
			m_step_frames_left += 1;
		}

		m_step_keys_pressed[0] = true;
	}
	else
	{
		m_step_keys_pressed[0] = false;
	}

	if ( Keyboard::IsKeyPressed(Keyboard::KB_F4) )
	{
		if ( m_step_keys_pressed[1] == false )
		{
			m_step_frames_left += 2;
		}

		m_step_keys_pressed[1] = true;
	}
	else
	{
		m_step_keys_pressed[1] = false;
	}

	if ( Keyboard::IsKeyPressed(Keyboard::KB_F4) )
	{
		if ( m_step_keys_pressed[2] == false )
		{
			m_step_frames_left += 4;
		}

		m_step_keys_pressed[2] = true;
	}
	else
	{
		m_step_keys_pressed[2] = false;
	}

	if ( Keyboard::IsKeyPressed(Keyboard::KB_F5) )
	{
		if ( m_step_keys_pressed[3] == false )
		{
			m_step_frames_left += 8;
		}

		m_step_keys_pressed[3] = true;
	}
	else
	{
		m_step_keys_pressed[3] = false;
	}

	if ( Keyboard::IsKeyPressed(Keyboard::KB_F6) )
	{
		if ( m_step_keys_pressed[4] == false )
		{
			m_step_frames_left += 16;
		}

		m_step_keys_pressed[4] = true;
	}
	else
	{
		m_step_keys_pressed[4] = false;
	}

	if ( Keyboard::IsKeyPressed(Keyboard::KB_F7) )
	{
		if ( m_step_keys_pressed[5] == false )
		{
			m_step_frames_left += 32;
		}

		m_step_keys_pressed[5] = true;
	}
	else
	{
		m_step_keys_pressed[5] = false;
	}

	if ( Keyboard::IsKeyPressed(Keyboard::KB_F8) )
	{
		if ( m_step_keys_pressed[6] == false )
		{
			m_step_frames_left += 64;
		}

		m_step_keys_pressed[6] = true;
	}
	else
	{
		m_step_keys_pressed[6] = false;
	}

	if ( Keyboard::IsKeyPressed(Keyboard::KB_F9) )
	{
		if ( m_step_keys_pressed[7] == false )
		{
			m_step_frames_left += 128;
		}

		m_step_keys_pressed[7] = true;
	}
	else
	{
		m_step_keys_pressed[7] = false;
	}
}

#ifdef USE_DEBUG_CONSOLE

//=====================================================================================================================
/// @brief		Enables/disables contact debugging
/// @param		arg - value of argument
/// @param		arg_given - true if an argument was given
/// @returns	Value of the argument
//=====================================================================================================================

bool SimulationWorld::ConCmd_P_ContactDebug( bool arg , bool arg_given )
{
	if ( arg_given ) s_debug_contacts = arg; return s_debug_contacts;
}

#endif