/*
	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		Simple class that handles frame timing logic and frame rate control for the game.
//=====================================================================================================================

#include "Precompiled.h"
#include "Game\GameFrameTimer.h"
#include "Game\GameCore.h"

using namespace Game;

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

/// Target refresh interval in between game ticks - in seconds.

const float GameFrameTimer::FRAME_INTERVAL = 0.01666666666f;

/// Target refresh interval in between game ticks - in milliseconds

const unsigned GameFrameTimer::FRAME_INTERVAL_MS = 17;

/// Maximum number of frames that we can try to make up from frame skipping if we are behind real time

const unsigned GameFrameTimer::MAX_CATCHUP_FRAMES = 4;

//=====================================================================================================================
/// @brief		Creates the timer
//=====================================================================================================================

GameFrameTimer::GameFrameTimer()
{
	Reset();
}

//=====================================================================================================================
/// @brief		Resets the timer: forcing the next update to be both a render and update
///	@remarks	This function also calls the DiscountTimeDelta() function which discards 
///				any time that may have passed.
//=====================================================================================================================

void GameFrameTimer::Reset()
{
	// Discount the time delta:

	DiscountTimeDelta();

	// Force render of next frame

	m_rendered_last_frame = false;

	// Force update of next frmae

	m_time_since_update = FRAME_INTERVAL;
}

//=====================================================================================================================
/// @brief		Discounts all time passed between the last call to DoUpdate() or object creation. This time is 
///				regarded as not having passed.
//=====================================================================================================================

void GameFrameTimer::DiscountTimeDelta()
{
	// Reset the high resolution timer:

	HighResolutionTimer::Reset();
}

//=====================================================================================================================
/// @brief		Does an update of the timer and returns what action the game should take
/// @returns	What actions the game should take
/// @remarks	This function will sleep for a bit if the game is running really fast, and wait 
///				for a while until such time when it is time to do an update again.
//=====================================================================================================================

GameFrameTimer::ActionFlags GameFrameTimer::Update()
{
	// Update the timing values in the timer:
	
	HighResolutionTimer::Update();
	
	// Add the time delta to time elapsed:
	
	m_time_since_update += HighResolutionTimer::GetTimeDelta();
	
	// See if time for another frame:
	
	if ( m_time_since_update >= FRAME_INTERVAL )
	{
		// See if we are more than one frame behind:
		
		if ( m_time_since_update >= FRAME_INTERVAL * 2.0f )
		{
			// The action we will take:

			ActionFlags action = ACTION_IDLE;

			// Two or more frames behind: if we didn't skip the last frame skip this one
			
			if ( m_rendered_last_frame == true )
			{
				// Didn't render this frame:
				
				m_rendered_last_frame = false;
				
				// Simulated this much time:
				
				m_time_since_update -= FRAME_INTERVAL;	

				// Only do an update:
				
				action = ACTION_UPDATE;
			}
			else
			{					
				// Rendered this frame:
				
				m_rendered_last_frame = true;
				
				// Simulated this much time:
				
				m_time_since_update -= FRAME_INTERVAL;

				// Do an update and render:
				
				action = (ActionFlags)( ACTION_UPDATE | ACTION_RENDER );
								
				// If the window is minimised or the device has been lost then do no draw:
				
				if ( GameCore::GetSingleton()->GetWindow()->IsMinimized() || GameCore::GetSingleton()->GetWindow()->GetDisplay()->RequiresReset() )
				{
					action = ACTION_UPDATE;
				}				
			}
			
			// If we are falling way behind real time then limit the number of frames we try to catch up with:
			
			if ( m_time_since_update >= FRAME_INTERVAL * float(MAX_CATCHUP_FRAMES) )
			{
				// Figure out how much time we are going to discount:
				
				float discount_time = m_time_since_update - ( FRAME_INTERVAL * float(MAX_CATCHUP_FRAMES) );
				
				// Discount the time: we can't keep trying to catch up in an impossible situation
				
				m_time_since_update -= discount_time;
			}

			// Return the action to take:

			return action;
		}
		else
		{				
			// Rendered this frame:
			
			m_rendered_last_frame = true;
			
			// Simulated this much time:
			
			m_time_since_update -= FRAME_INTERVAL;
			
			// If the window is minimised or the device has been lost then do no draw:
			
			if ( GameCore::GetSingleton()->GetWindow()->IsMinimized() || GameCore::GetSingleton()->GetWindow()->GetDisplay()->RequiresReset() )
			{
				return ACTION_UPDATE;
			}				

			// Not behind: draw and render as usual
			
			return (ActionFlags)( ACTION_UPDATE | ACTION_RENDER );
		}
	}
	else
	{
		// Not time for an update: give up this processor time slice
		
		Sleep(0);

		// Do nothing:

		return ACTION_IDLE;
	}
}
