/** 
 * \file Level.cpp
 * \brief CLevel member class functions implementation and actual game level logic.
 * 
 * \author Petar Bajic, MPE (C) All Rights Reserved, Homepage: www.mystic-peanut.com
 * \date January, 16 2007.
 */

#include "Level.h"
#include "Language.h"

/**
 * CLevel standard constructor. All level varibles are initialized to 0 or alike. 
 * To see some real initialization check out CLevel::Init() function.
 * \author Petar Bajic 
 * \date January, 16 2007.
 */
CLevel::CLevel()
{
	m_pTerrain = NULL;
	m_plevelTheme = NULL;
	m_pTurtle = NULL;
	m_LevelFinished = false;
	m_LevelPaused = false;
	m_aspectRatio = 0.0f;
	m_AdjustMovement = 10.0f;
	m_CAPSLOCK = false;
	m_Sheeps.clear();
	m_gun = NULL;
	m_shootingSound = NULL;
	m_MFSoundDouble = NULL;
	m_MFSoundHarmless = NULL;
	m_Timer = 0.0;
	m_LevelOutcome = LEVEL_OUTCOME_SUCCESS;
	m_LevelHard = 3.0f;
	m_LevelDetails = true;
	m_draw2D = NULL;
	m_MousePosX = 0;
	m_MousePosY = 0;
	m_EyeY = 0;
	m_pMFDouble = NULL;
	m_pMFHarmless = NULL;
	m_Language = NULL;
	m_LevelNumber = 1;
	m_LivesNumber = 3;
	m_GunDouble = false;
	m_GunHarmless = false;
}

/**
 * CLevel destructor. Deletes all that has been alocated in Level class. 
 * If you get memleak error after exiting program - here is the problem.
 * \author Petar Bajic 
 * \date January, 16 2007.
 */
CLevel::~CLevel()
{
	if(m_draw2D !=NULL)
		delete m_draw2D;
	if (m_plevelTheme != NULL)
		delete m_plevelTheme;
	SAFE_DELETE(m_shootingSound);
	SAFE_DELETE(m_MFSoundDouble);
	SAFE_DELETE(m_MFSoundHarmless);
	SAFE_DELETE(m_gun);
	SAFE_DELETE(m_pMFDouble);
	SAFE_DELETE(m_pMFHarmless);
	//Release the sheeps
	std::vector<CSheep*>::iterator it, end;
	it = m_Sheeps.begin();
	end = m_Sheeps.end();
	while (it != end)
	{
		if((*it) != NULL)
			delete (*it);
		it++;
	}
	//Release the dwarfs
	std::vector<CDwarf*>::iterator itd, endd;
	itd = m_Dwarfs.begin();
	endd = m_Dwarfs.end();
	while (itd != endd)
	{
		if((*itd) != NULL)
			delete (*itd);
		itd++;
	}
	//Release Roderick
}

/**
 * Init function initializes all level components. Music is loaded, models are created, everything is allocated here.
 * Some models are allocated before CLevel::Init (like sheep and turtle) because they are needed elsewhere (in movie, menu, etc.)
 * These models are sent to Init as pointers (pTurtle, pSheep, pTerrain), so CLevel can use them instead of doing new allocation.
 * \author Petar Bajic 
 * \date January, 16 2007.
 */
bool CLevel::Init(HWND hWnd, LPDIRECT3DDEVICE9 pd3dDevice, int screenWidth, int screenHeight, IDirectSound8* pDS, CTerrain* pTerrain, CTurtle* pTurtle, CSheep* pSheep, CLanguage* pLanguage)
{
	m_pTerrain = pTerrain;
	m_Language = pLanguage;
	m_aspectRatio = (float)screenWidth/(float)screenHeight;

	RECT rect;
	GetWindowRect(hWnd,&rect);
	m_MousePosX = screenWidth/2 + rect.left;
	m_MousePosY = screenHeight/2 + rect.top;

	m_Sheeps.clear();

	//Init Music 
	m_plevelTheme = new CMedia();
	if (!(m_plevelTheme->Init(hWnd, L"Media/Music/leveltheme.mp3")))
	{
		//If not loaded display window message and exit.
		MessageBox(hWnd,L"Could not load Media/Music/leveltheme.mp3 file",L"Error",MB_OK);
		return false;
	}

	//Init Sounds
	m_shootingSound = new CSound();
	if (!m_shootingSound->Init(pDS, L"Media/Sounds/shooting.wav"))
	{
		//If not loaded display window message and exit.
		MessageBox(hWnd,L"Could not load Media/Sounds/shooting.wav file",L"Error",MB_OK);
		return false;
	}
	m_MFSoundDouble = new CSound();
	if (!m_MFSoundDouble->Init(pDS, L"Media/Sounds/flower_double_eat.wav"))
	{
		//If not loaded display window message and exit.
		MessageBox(hWnd,L"Could not load Media/Sounds/flower_double_eat.wav file",L"Error",MB_OK);
		return false;
	}
	m_MFSoundHarmless = new CSound();
	if (!m_MFSoundHarmless->Init(pDS, L"Media/Sounds/flower_harmless_eat.wav"))
	{
		//If not loaded display window message and exit.
		MessageBox(hWnd,L"Could not load Media/Sounds/flower_harmless_eat.wav file",L"Error",MB_OK);
		return false;
	}

	//Fetch preloaded models
	m_pTurtle = pTurtle;

	//Create 5 Dwarfs
	CDwarf* firstDwarf = new CDwarf();
	if (!firstDwarf->Init(hWnd,pd3dDevice,pDS))
		return false;
	firstDwarf->m_Position = D3DXVECTOR3(20.0f,0.0f,20.0f);
	m_Dwarfs.push_back(firstDwarf);
	//Add 4 more dwarfs
	for (int i = 0; i<4; i++)
	{
		//This is special way of creating dwarfs, only first is made from scratch - loaded from x file,
		//other dwarfs are clones, using model data of first dwarf, 
		//so no need for loading from file 5 times! Much faster!!
		CDwarf* copyDwarf = new CDwarf(firstDwarf->m_Model);
		copyDwarf->InitSounds(hWnd,pDS); //sound initiation for first dwarf is done in default constructor!
		copyDwarf->m_Position = D3DXVECTOR3(10.0f,0.0f,(i-2)*10.0f);
		copyDwarf->m_Model->m_animController->AdvanceTime(2.0f, NULL);
		m_Dwarfs.push_back(copyDwarf);
	}

	//Init Turtle Gun
	m_gun = new CGun(200); //200 particles for gun fire
	m_gun->init(pd3dDevice,L"Media/Pics/bullet.png");

	//Init magic flowers
	m_pMFDouble = new CMagicFlower();
	if (!m_pMFDouble->Load(hWnd,pd3dDevice,L"Media//Models//",L"Media//Models//mfdouble.x",0xFF994499))
		return false;
	m_pMFHarmless = new CMagicFlower();
	if (!m_pMFHarmless->Load(hWnd,pd3dDevice,L"Media//Models//",L"Media//Models//mfharmless.x",0xFFFFFFFF))
		return false;

	//Init Sprites
	m_draw2D = new CLevel2D();
	if (!m_draw2D->Init(hWnd,pd3dDevice, screenWidth, screenHeight))
		return false;

	return true;
}

/**
 * Pause level will stop the music, show the cursor, pause action, write blinking: "Paused"
 * \author Petar Bajic 
 * \date January, 16 2007.
 */
void CLevel::Pause()
{
	m_plevelTheme->Pause();
	m_LevelPaused = true;
	ShowCursor(true);
}

/**
 * UnPause level will unpause the music, hide the cursor, and roll the action
 * \author Petar Bajic 
 * \date January, 16 2007.
 */
void CLevel::UnPause()
{
	m_plevelTheme->Play();
	m_LevelPaused = false;
	SetCursorPos(m_MousePosX, m_MousePosY);
	ShowCursor(false);
}
/**
 * When window is resized, this function is caled to set (invisible) mouse to new center of window.
 * \author Petar Bajic 
 * \date January, 16 2007.
 */
void CLevel::WindowMove(HWND hWnd, int screenWidth, int screenHeight)
{
	RECT rect;
	GetWindowRect(hWnd,&rect);
	m_MousePosX = screenWidth/2 + rect.left;
	m_MousePosY = screenHeight/2 + rect.top;
}

/**
 * Stopping Level Action
 * \author Petar Bajic 
 * \date January, 16 2007.
 */
void CLevel::LevelShutDown()
{
	m_plevelTheme->Stop();
	ShowCursor(true);
}

/**
 * Level parameter setup. This function is called when user starts New Game.
 * \author Petar Bajic 
 * \date January, 16 2007.
 */
void CLevel::LevelStart(float hardness, bool details, CSheep* pSheep)
{
	//hide the cursor (many will dislike this in windowed mode, don't do it like I did)
	SetCursorPos(m_MousePosX,m_MousePosY);
	ShowCursor(false); 

	m_LevelHard = hardness;
	m_LevelDetails = details;
	m_LivesNumber = 3;
	m_LevelNumber = 1;
	m_plevelTheme->Stop();
	m_plevelTheme->Play();
	m_LevelPaused = false;
	m_LevelFinished = false;
	m_Timer = 0.0;
	m_pTurtle->Restart();
	
	//Magic Flowers
	m_pMFDouble->m_Alive = false;
	m_pMFHarmless->m_Alive = false;
	GetRandomVectorCircle(&(m_pMFDouble->m_Position),30.0f);
	GetRandomVectorCircle(&(m_pMFHarmless->m_Position),30.0f);
	m_pMFDouble->m_TimeOn = GetRandomFloat(1.0f,(float)LEVEL_DURATION-20);
	m_pMFDouble->m_TimeOff = GetRandomFloat(m_pMFDouble->m_TimeOn,(float)LEVEL_DURATION-20);
	m_pMFHarmless->m_TimeOn = GetRandomFloat(1.0f,(float)LEVEL_DURATION-20);
	m_pMFHarmless->m_TimeOff = GetRandomFloat(m_pMFHarmless->m_TimeOn,(float)LEVEL_DURATION-20);

	//Restart Dwarfs
	std::vector<CDwarf*>::iterator itd, endd;
	itd = m_Dwarfs.begin();
	endd = m_Dwarfs.end();
	while (itd != endd)
	{
		(*itd)->DieOut();
		itd++;
	}

	//Restart Gun
	m_gun->m_double = false;
	m_gun->m_harmless = false;
	m_gun->SetParticleColor(D3DCOLOR_XRGB(55, 155, 55));
	m_gun->reset();

	//One Sheep for 1st level
	m_Sheeps.push_back(pSheep);
	DistributeSheepsForStart();
}
/**
 * Restarting Level parameters. This function is called every time level is started from begining, 
 * or new level is reached.
 * \author Petar Bajic 
 * \date January, 16 2007.
 */
void CLevel::LevelRestart()
{
	SetCursorPos(m_MousePosX,m_MousePosY);
	ShowCursor(false); //hide the cursor (many will dislike this in windowed mode, don't do it like I did)
	m_plevelTheme->Stop();
	m_plevelTheme->Play(); //start music from beginning
	m_LevelPaused = false;
	m_LevelFinished = false;
	m_Timer = 0.0;

	//Init turtle
	m_pTurtle->Restart();
	
	//Magic Flowers
	m_pMFDouble->m_Alive = false;
	m_pMFHarmless->m_Alive = false;
	GetRandomVectorCircle(&(m_pMFDouble->m_Position),30.0f);
	GetRandomVectorCircle(&(m_pMFHarmless->m_Position),30.0f);
	m_pMFDouble->m_TimeOn = GetRandomFloat(1.0f,(float)LEVEL_DURATION-20);
	m_pMFDouble->m_TimeOff = GetRandomFloat(m_pMFDouble->m_TimeOn,(float)LEVEL_DURATION-20);
	m_pMFHarmless->m_TimeOn = GetRandomFloat(1.0f,(float)LEVEL_DURATION-20);
	m_pMFHarmless->m_TimeOff = GetRandomFloat(m_pMFHarmless->m_TimeOn,(float)LEVEL_DURATION-20);

	//Restart Dwarfs
	std::vector<CDwarf*>::iterator itd, endd;
	itd = m_Dwarfs.begin();
	endd = m_Dwarfs.end();
	while (itd != endd)
	{
		(*itd)->DieOut();
		itd++;
	}

	//Restart Gun
	m_gun->m_harmless = false;
	m_gun->reset();

	//Restart Sheeps
	DistributeSheepsForStart();
}

/**
 * OnEvent is called from CGame::OnEvent()
 * This function handles all events while player is playing the level.
 * Keypress (ESC-exit, SPACE-pause, etc.)
 * Mouse move and mouse press is handled in function OnFrameMove() because windows event handler is just not fast enough.
 * \author Petar Bajic 
 * \date January, 16 2007.
 */
bool CLevel::OnEvent(LPDIRECT3DDEVICE9 pd3dDevice, IDirectSound8* pDS, HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam, int* code)
{
    switch( msg )
    {
		case WM_KEYDOWN:
		{
			if(wParam == VK_ESCAPE)
			{
				LevelShutDown();
				ReleaseSheeps();
				*code = LEVEL_RETURN_MENU;
				return true;
			}
			if(wParam == VK_F1)
			{
				m_LevelOutcome = LEVEL_OUTCOME_SUCCESS;
				m_LevelFinished = true;
				LevelShutDown();
				return true;
			}
			if(wParam == VK_SPACE)
			{
				if(!m_LevelFinished)
				{
					if(!m_LevelPaused)
					{
						//Pause game
						Pause();
					}
					else
					{
						//Unpause game
						UnPause();
					}
					return true;
				}
				else //SPACE will take us to next level
				{
					if(m_LevelOutcome == LEVEL_OUTCOME_SUCCESS)
					{
						//AddAnotherSheep();
						CSheep* temp = new CSheep(m_Sheeps.at(0)->m_Model); //clone first sheep
						temp->InitSounds(hWnd,pDS); //sound initiation for first sheep is done in regular constructor
						temp->m_Position = D3DXVECTOR3(0.0f,0.0f,3.0f);
						m_Sheeps.push_back(temp);
						m_LevelNumber++;
					}
					else if(m_LivesNumber == 0)
					{
						*code = LEVEL_RETURN_MENU;
						ReleaseSheeps();
						return true;
					}
					LevelRestart();
				}
			}
			if(wParam == VK_CAPITAL)
			{
				// Swich Run Mode
				if (!m_CAPSLOCK) m_CAPSLOCK = true;
				else m_CAPSLOCK = false;
				return true;
			}
		}
	}

	return false; //Level didn't handled event, let someone abouve handle it
}

/**
 * This function is called when device is being reset (switching to fullscreen and such)
 * Its important to call this function BEFORE device is reset.
 * Particles are making most problems when not properly restarted
 * because they are POOL resources as oposed to MANAGED resources.
 * \author Petar Bajic 
 * \date January, 16 2007.
 */
void CLevel::OnLostDevice()
{
	m_draw2D->OnLostDevice();
	m_pTerrain->OnLostDevice();  //terrain has particles (like grass etc.)
	m_pMFDouble->OnLostDevice();  //magic flower has particles smoking above it
	m_pMFHarmless->OnLostDevice();
	m_GunDouble = m_gun->m_double; //gun is particle!
	m_GunHarmless = m_gun->m_harmless;
	SAFE_DELETE(m_gun);
}
/**
 * This function is called when device is being reset (switching to fullscreen and such)
 * Its important to call this function AFTER device is reset
 * Particles are making most problems when not properly restarted
 * because they are POOL resources as oposed to MANAGED resources.
 * \author Petar Bajic 
 * \date January, 16 2007.
 */
void CLevel::OnResetDevice(HWND hWnd, LPDIRECT3DDEVICE9 pd3dDevice, int screenWidth, int screenHeight)
{
	//Important: this is not game level reset, game should continue intact.

	m_aspectRatio = (float)screenWidth/(float)screenHeight;
	m_gun = new CGun(200); //200 particles for gun fire
	m_gun->init(pd3dDevice, L"Media/Pics/bullet.png");

	m_gun->m_double = m_GunDouble;
	m_gun->m_harmless = m_GunHarmless;

	RECT rect;
	GetWindowRect(hWnd,&rect);
	m_MousePosX = screenWidth/2 + rect.left;
	m_MousePosY = screenHeight/2 + rect.top;

	m_draw2D->OnResetDevice(pd3dDevice, screenWidth, screenHeight);
	m_pTerrain->OnResetDevice(pd3dDevice);
	m_pMFDouble->OnResetDevice(pd3dDevice);
	m_pMFHarmless->OnResetDevice(pd3dDevice);
}

/**
 * Glorious Render function!
 *
 * In this function all models are rendered to the screen, as well as 2D interface.
 * Only Level mode is rendered here, when in menu or movie mode rendering is done in their Render functions.
 * Models are positioned in OnFrameMove funcition, here only matrices are set and models are rendered.
 * \param m_counter - number of frames per second
 * \author Petar Bajic 
 * \date January, 16 2007.
 */
void CLevel::OnRender(LPDIRECT3DDEVICE9 pd3dDevice, float fElapsedTime, int m_counter)
{
	float elapsed = fElapsedTime;

	//If level ended, stop 3D moving
	if(m_LevelFinished || m_LevelPaused)
	{
		//good overriddance
		elapsed = 0;
		//if elapsed is 0 nothing will move baby - you got your self a FREEZE!
	}

	//Render Turtle
	m_pTurtle->OnRender(pd3dDevice);

	//Render Sheeps
	//Move sheeps
	D3DXMATRIXA16 matWorld,matTrans,matY;
	std::vector<CSheep*>::iterator it, end;
	it = m_Sheeps.begin();
	end = m_Sheeps.end();
	while (it != end)
	{
		D3DXMatrixIdentity(&matWorld);
		D3DXMatrixRotationY(&matWorld, (*it)->m_Facing);
		D3DXMatrixTranslation( &matTrans, (*it)->m_Position.x, (*it)->m_Position.y+2, (*it)->m_Position.z );
		D3DXMatrixMultiply(&matWorld, &matWorld, &matTrans);
		pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld );
		(*it)->OnFrameMove(pd3dDevice, elapsed, &matWorld);
		(*it)->OnRender(pd3dDevice);
		it++;
	}
	//Render Dwarfs
	std::vector<CDwarf*>::iterator itd, endd;
	itd = m_Dwarfs.begin();
	endd = m_Dwarfs.end();
	while (itd != endd)
	{
		D3DXMatrixIdentity(&matWorld);
		if ((*itd)->m_Hit)
			D3DXMatrixRotationX(&matWorld, (*itd)->m_HitFall);
		D3DXMatrixRotationY(&matY, (*itd)->m_Facing);
		D3DXMatrixTranslation( &matTrans, (*itd)->m_Position.x, (*itd)->m_Position.y, (*itd)->m_Position.z );
		D3DXMatrixMultiply(&matWorld, &matWorld, &matY);
		D3DXMatrixMultiply(&matWorld, &matWorld, &matTrans);
		pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld );
		(*itd)->OnFrameMove(pd3dDevice, elapsed, &matWorld);
		(*itd)->OnRender(pd3dDevice);
		itd++;
	}

	D3DXMatrixIdentity(&matWorld);
	pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld );

	//Render Terrain
	m_pTerrain->OnRender(pd3dDevice, m_LevelDetails);

	//Render Magic Flowers
	m_pMFDouble->OnRender(pd3dDevice);
	m_pMFHarmless->OnRender(pd3dDevice);

	D3DXMatrixIdentity(&matWorld);
	pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld );

	if (m_gun)
		m_gun->Render();

	bool close_to_edge = (m_pTurtle->m_Position.z*m_pTurtle->m_Position.z + m_pTurtle->m_Position.x*m_pTurtle->m_Position.x > 1500);
	//Render 2D 
	m_draw2D->Render(pd3dDevice, m_LevelFinished, m_LevelOutcome, fElapsedTime, close_to_edge , m_gun->m_double, 
					 m_gun->m_harmless, m_LevelNumber, m_LivesNumber, (int) m_Timer, m_LevelPaused, m_Language);
}

/**
 * Glorious OnFrameMove function!
 *
 * If you want to change game behaviour - you do it in this function.
 * Dwarfs are walking toward sheeps, snatching sheeps, running away, 
 * turtle is shooting, sheeps are pushing each other and jumping, 
 * dead dwarfs are flying away, magic flowers appear and disspear,
 * sound effects are fired, elapsed time is checked and number of lives is set... all in this function.
 *
 * If you want to add Dwarven spaceship flying above the field and snatching sheeps with a transportation beam - you do it here.
 * 
 * Mouse events are also handled here because this is the fastest function in the mexico. 
 * OnFrameMove is called 50 times per second, or whatever your framerate is.
 *
 * \author Petar Bajic 
 * \date January, 16 2007.
 */
void CLevel::OnFrameMove(LPDIRECT3DDEVICE9 pd3dDevice, double fTime, float fElapsedTime)
{
	float elapsed = fElapsedTime;

	//If level ended, stop 3D moving
	if(m_LevelFinished || m_LevelPaused)
	{
		//good overriddance
		elapsed = 0;
		//if elapsed is 0 nothing will move baby - you got your self a FREEZE!
	}

	//Schedule game action that depends on time 
	//Add magic flowers at random moment, add dwarfs every 5 secs, finish level if time is up, etc.
	ScheduleGameAction(elapsed);

	//Move terrain (obsolete if scenography is completely static)
	m_pTerrain->OnFrameMove(pd3dDevice,fTime,elapsed, m_LevelDetails);

	//Move magic flowers
	m_pMFDouble->OnFrameMove(pd3dDevice, elapsed);
	m_pMFHarmless->OnFrameMove(pd3dDevice, elapsed);

	//Move turtle
	if(!m_LevelFinished && !m_LevelPaused)
		UpdateTurtlePosition(elapsed);

	D3DXMATRIXA16 matWorld,matTrans;
	D3DXMatrixIdentity(&matWorld);
	D3DXMatrixRotationY( &matWorld, m_pTurtle->m_Facing + D3DX_PI);//we add + D3DX_PI cause model is rotated oposite
	D3DXMatrixTranslation( &matTrans, m_pTurtle->m_Position.x, m_pTurtle->m_Position.y, m_pTurtle->m_Position.z );
	D3DXMatrixMultiply(&matWorld, &matWorld, &matTrans);

	////Position view matrix (also known as Camera)
	D3DXMATRIX matView, m;
	D3DXVECTOR3 ModelFacing = D3DXVECTOR3( 0.0f, 0.0f, 1.0f );
	D3DXVec3TransformCoord(&ModelFacing, &ModelFacing, D3DXMatrixRotationY(&m, (m_pTurtle->m_Facing)));
	D3DXVECTOR3 vEye	( (m_pTurtle->m_Position.x), 15.0f, (m_pTurtle->m_Position.z));
	D3DXVECTOR3 vAt     ( (m_pTurtle->m_Position.x), 0.0f, (m_pTurtle->m_Position.z));
	D3DXVECTOR3 vUp     ( 0.0f, 1.0f, 0.0f );
	ModelFacing.x *= 15;
	ModelFacing.y = 0.0f;
	ModelFacing.z *= 15;
	vEye.y -= m_EyeY + 3;
	vAt.y += m_EyeY;
	vEye -= ModelFacing; //camera is behind model
	vAt += ModelFacing;  //looking in front of model
	D3DXMatrixLookAtLH( &matView, &vEye, &vAt, &vUp );
	pd3dDevice->SetTransform( D3DTS_VIEW, &matView );

	//Call OnFrameMove on turtle after view matrix is calculated to avoid strange glitches
	m_pTurtle->OnFrameMove(pd3dDevice, elapsed, &matWorld);	

	if(!m_LevelFinished)
	{
		static float sum = 0.0f;
		static float sheepJumpingTime = 0.0f;
		static bool bSheepMoved= false;

		//Shooting
		if ((GetAsyncKeyState(VK_RETURN) < 0)||GetAsyncKeyState(VK_LBUTTON))
		{
			sum += elapsed;
			if (sum > 0.1f)
			{
				sum = 0;
				m_gun->shootParticle(m_pTurtle->m_Position, m_pTurtle->m_Facing);
				m_shootingSound->Stop();
				m_shootingSound->Reset();
				m_shootingSound->Play();
			}
		}
		m_gun->Update(elapsed, false, false);
	
		//Magic Flowers
		if(m_pMFDouble->m_Alive && distance2(m_pTurtle->m_Position, m_pMFDouble->m_Position)<2)
		{
			m_gun->m_double = true;
			m_pMFDouble->m_Alive = false;
			m_MFSoundDouble->Play();
		}
		if(m_pMFHarmless->m_Alive && distance2(m_pTurtle->m_Position, m_pMFHarmless->m_Position)<2)
		{
			m_gun->m_harmless = true;
			m_gun->SetParticleColor(0xFFFFFFFF);
			m_pMFHarmless->m_Alive = false;
			m_MFSoundHarmless->Play();
		}
		
		//Move dwarfs
		std::vector<CDwarf*>::iterator itd, endd;
		itd = m_Dwarfs.begin();
		endd = m_Dwarfs.end();
		while (itd != endd)
		{
			//First Hitem then Killem than Movem
			if(!(*itd)->m_Hit && m_gun->checkHit((*itd)->m_Position, 1.0f))
			{
				(*itd)->m_Hit = true;
				(*itd)->m_HitAngle = facePoint((*itd)->m_Position,m_pTurtle->m_Position);

				if((*itd)->m_CarryingSheep)
				{
					(*itd)->m_TargetSheep->m_BeingCarriedAway = false;
					(*itd)->m_TargetSheep->m_Position.y = 0.3f;
					(*itd)->m_CarryingSheep = false;
					RedirectOtherDwarfs();
				}

				//pogodak sledja
				if(((*itd)->m_HitAngle < (*itd)->m_Facing + D3DX_PI/4)&&((*itd)->m_HitAngle > (*itd)->m_Facing - D3DX_PI/4))
				{
					(*itd)->m_HitFall = D3DX_PI/2;
					(*itd)->m_Facing = (*itd)->m_HitAngle;
					(*itd)->m_Model->SetAnimationSet(0);
					(*itd)->PlaySoundBouncingDying();
				}
				//problem resiti sa apsolutnim vrednostima
				else if(((*itd)->m_HitAngle < (*itd)->m_Facing + D3DX_PI + D3DX_PI/4)&&((*itd)->m_HitAngle > (*itd)->m_Facing  + D3DX_PI - D3DX_PI/4))
				{
					(*itd)->m_Facing = (*itd)->m_HitAngle + D3DX_PI;
					(*itd)->m_HitFall = -D3DX_PI/2;
					(*itd)->m_Model->SetAnimationSet(0);
					(*itd)->PlaySoundBouncingDying();
				}
				else
				{
					(*itd)->m_HitFall = 0.0f;
					(*itd)->m_HitFly = true;
					(*itd)->PlaySoundRikoshetDying();
				}
			}

			if((*itd)->m_Hit)
			{
				(*itd)->m_HitTime +=elapsed;
				if((*itd)->m_HitTime < .1)
				{
					(*itd)->m_Position.y +=elapsed*28;
				}
				else if((*itd)->m_HitTime < .2)
				{
					(*itd)->m_Position.y -=elapsed*28;
				}
				else if((*itd)->m_HitTime < .3)
				{
					(*itd)->m_Position.y +=elapsed*18;
				}
				else if((*itd)->m_HitTime < .4)
				{
					(*itd)->m_Position.y -=elapsed*18;
				}
				if ((*itd)->m_HitTime > .5)
				{
					(*itd)->DieOut();
				}
			}
		
			//If reached sheep - snatch it
			if(!(*itd)->m_Hit && (*itd)->m_Alive && !(*itd)->m_CarryingSheep && ((*itd)->m_TargetSheep != NULL))
			{
				if (CloseToSheep((*itd)->m_Position, (*itd)->m_TargetSheep->m_Position))
				{
					//go to picking up animation
					(*itd)->StartPickAnim();
				}

				if (ReachedSheep((*itd)->m_Position, (*itd)->m_TargetSheep->m_Position))
				{
					(*itd)->SnatchSheep();
					// If Any other Dwarf was aming for that sheep, Redirect him
					RedirectOtherDwarfs();
				}

			}

			//If reached outskirt carrying sheep end game, else restart him
			if(((*itd)->m_Position.x > 50) || ((*itd)->m_Position.z > 50) || ((*itd)->m_Position.z < -50) || ((*itd)->m_Position.x < -50))
			{
				if((*itd)->m_CarryingSheep)
				{
					//End level
					m_LevelOutcome = LEVEL_OUTCOME_SHEEPSTOLEN;
					m_LevelFinished = true;
					(*itd)->m_TargetSheep->m_Alive = false;
					(*itd)->m_Alive = false;
					m_gun->m_double = false;
					m_gun->m_harmless = false;
					m_gun->SetParticleColor(D3DCOLOR_XRGB(55, 155, 55));
					m_LivesNumber--;
					LevelShutDown();
					return;
				}
				else
				{
					(*itd)->DieOut();
				}
			}

			//Move depending on elapsed time
			(*itd)->Move(elapsed * m_AdjustMovement,fTime);
			itd++;
		}

		//Move Sheeps
		vector< CSheep* >::iterator itgCurrentSheep, itgEndSheep = m_Sheeps.end();
		for( itgCurrentSheep = m_Sheeps.begin(); itgCurrentSheep != itgEndSheep; ++ itgCurrentSheep )
		{
			if(!(*itgCurrentSheep)->m_BeingCarriedAway)
			{
				//check if sheep is shot
				if (!(m_gun->m_harmless) && (m_gun->checkHit((*itgCurrentSheep)->m_Position, 1.0f)))
				{
					//Play dying sound
					(*itgCurrentSheep)->PlaySoundDeath();
					//End level
					m_LevelOutcome = LEVEL_OUTCOME_SHEEPSHOT;
					m_LevelFinished = true;
					(*itgCurrentSheep)->m_Alive = false;
					m_gun->m_double = false;
					m_gun->m_harmless = false;
					m_gun->SetParticleColor(D3DCOLOR_XRGB(55, 155, 55));
					m_LivesNumber--;
					LevelShutDown();
					return;
				}

				// If Turtle pushing Sheeps
				if (distance2(m_pTurtle->m_Position,(*itgCurrentSheep)->m_Position) < 4)
				{
					//Sound
					(*itgCurrentSheep)->PlaySoundMove();
					(*itgCurrentSheep)->m_Moved = true;
					// New position of moved sheep
					(*itgCurrentSheep)->m_Model->SetAnimationSet(1);
					D3DXVECTOR3 chunk = D3DXVECTOR3((*itgCurrentSheep)->m_Position.x - m_pTurtle->m_Position.x, 0.0f, (*itgCurrentSheep)->m_Position.z - m_pTurtle->m_Position.z);
					D3DXVec3Normalize(&chunk, &chunk);
					(*itgCurrentSheep)->m_Position += chunk;
					// If some dwarf was going for this sheep, redirect him
					RedirectOtherDwarfs();
				}
				if ((*itgCurrentSheep)->m_Moved == true)
				{
					if((!m_LevelFinished) && (!m_LevelPaused))
					{
						sheepJumpingTime+=elapsed;
						D3DXVECTOR3 chunk = D3DXVECTOR3((*itgCurrentSheep)->m_Position.x - m_pTurtle->m_Position.x, 0.0f, (*itgCurrentSheep)->m_Position.z - m_pTurtle->m_Position.z);
						D3DXVec3Normalize(&chunk, &chunk);
						(*itgCurrentSheep)->m_Position += chunk/10;
						if(sheepJumpingTime > 1)
						{
							sheepJumpingTime = 0.0f;
							(*itgCurrentSheep)->m_Moved = false;
							(*itgCurrentSheep)->m_Model->SetAnimationSet(0);
							RedirectOtherDwarfs();
						}
					}
				}
				
				// Sheep pushing sheep
				vector< CSheep* >::iterator it2CurrentSheep, it2EndSheep = m_Sheeps.end();
				for( it2CurrentSheep = m_Sheeps.begin(); it2CurrentSheep != it2EndSheep; ++ it2CurrentSheep )
				{
					if ((*it2CurrentSheep)!=(*itgCurrentSheep) && !(*it2CurrentSheep)->m_BeingCarriedAway
						&& (distance2((*it2CurrentSheep)->m_Position,(*itgCurrentSheep)->m_Position) < 4))
					{
						//Sound
						(*it2CurrentSheep)->PlaySoundMove();
						// New position of moved sheep
						D3DXVECTOR3 chunk = D3DXVECTOR3((*it2CurrentSheep)->m_Position.x - (*itgCurrentSheep)->m_Position.x, 0.0f, (*it2CurrentSheep)->m_Position.z - (*itgCurrentSheep)->m_Position.z);
						D3DXVec3Normalize(&chunk, &chunk);
						(*it2CurrentSheep)->m_Position += chunk;
						// If some dwarf was going for this sheep, redirect him
						RedirectOtherDwarfs();
					}
				}
			}
		}
	}
}
/**
 * This function takes care of time, and events that happen in specified time interval.
 *
 * Magic flower appear at rendom moment each level.
 * Dwarfs are added every 5 seconds or so, they show up and go for the sheep.
 * If level time has been count down - level is finished here.
 * \author Petar Bajic 
 * \date January, 16 2007.
 */
void CLevel::ScheduleGameAction(float fElapsedTime)
{
	if(!m_LevelFinished)
	{
		m_Timer += fElapsedTime;
		static double dwarfTime = 0;
		dwarfTime += fElapsedTime;
		static double magicEffectTimer = 0;

		if ((m_Timer > 4)&&(m_Timer < LEVEL_DURATION))
		{
			if (dwarfTime > m_LevelHard) 
			{
				dwarfTime = 0.0;
				AddDwarf();
			}
		}
		if (m_Timer > LEVEL_DURATION)
		{
			//End Level
			m_LevelFinished = true;
			m_LevelOutcome = LEVEL_OUTCOME_SUCCESS;
			LevelShutDown();
			return;
		}

		//Magic FLowers
		if(!m_gun->m_double && (m_Timer > m_pMFDouble->m_TimeOn))
		{
			m_pMFDouble->m_Alive = true;
		}
		if(!m_gun->m_harmless && (m_Timer > m_pMFHarmless->m_TimeOn))
		{
			m_pMFHarmless->m_Alive = true;
		}
		if(m_pMFDouble->m_Alive && (m_Timer > m_pMFDouble->m_TimeOff))
		{
			m_pMFDouble->m_Alive = false;
		}
		if(m_pMFHarmless->m_Alive && (m_Timer > m_pMFHarmless->m_TimeOff))
		{
			m_pMFHarmless->m_Alive = false;
		}
	}
}

/**
 * Turtle is moved with mouse or keyborad, shooting and moving is handled here.
 * \author Petar Bajic 
 * \date January, 16 2007.
 */
void CLevel::UpdateTurtlePosition(float fElapsedTime)
{
	if(!m_LevelFinished)
	{
		float chunk = fElapsedTime * m_AdjustMovement; // with g_AdjustMovement we can speed up things
		bool rotating = false;

		//This is tricky mouse move calculation.
		//Mouse position is always set to center of window.
		//Every frame mouse movement is taken (offset from center) and that movement is used to rotate turtle.
		//Then position is set back to begining.
		POINT m_Point;
		GetCursorPos(&m_Point);
		if ((m_Point.x != m_MousePosX) || (m_Point.y != m_MousePosY))
		{
			m_pTurtle->m_Facing += (float)(m_Point.x-(m_MousePosX))/470;
			m_EyeY -= (float)(m_Point.y-(m_MousePosY))/55;
			if(m_EyeY > 10.0f) m_EyeY = 10.0f;
			if(m_EyeY < -10.0f) m_EyeY = -10.0f;
			SetCursorPos(m_MousePosX,m_MousePosY);
			rotating = true;
		}

		//Check keyboard state - if left arrow or 'Q' key are pressed, turtle turns left.
		if ((GetAsyncKeyState(VK_LEFT) < 0)||(GetAsyncKeyState(VK_Q) < 0))
		{
			m_pTurtle->m_Facing -= chunk/4;
			rotating = true;
		}
		//Check keyboard state - if right arrow or 'E' key are pressed, turtle turns right.
		if ((GetAsyncKeyState(VK_RIGHT) < 0)||(GetAsyncKeyState(VK_E) < 0))
		{
			m_pTurtle->m_Facing += chunk/4;
			rotating = true;
		}
		float temp;
		//Check keyboard state - A for striding left
		if (GetAsyncKeyState(VK_A) < 0)
		{
			temp = m_pTurtle->m_Position.z;
			m_pTurtle->m_Position.z += chunk * sin(m_pTurtle->m_Facing);
			//limit turtle movment to 40 feet radius circle
			if (m_pTurtle->m_Position.z*m_pTurtle->m_Position.z + m_pTurtle->m_Position.x*m_pTurtle->m_Position.x > 1600)
				m_pTurtle->m_Position.z = temp;

			temp = m_pTurtle->m_Position.x;
			m_pTurtle->m_Position.x -= chunk * cos(m_pTurtle->m_Facing);
			//limit turtle movment to 40 feet radius circle
			if (m_pTurtle->m_Position.z*m_pTurtle->m_Position.z + m_pTurtle->m_Position.x*m_pTurtle->m_Position.x > 1600)
				m_pTurtle->m_Position.x = temp;
			m_pTurtle->m_Model->SetAnimationSet(2);
		}
		//Check keyboard state - D for striding right
		if (GetAsyncKeyState(VK_D) < 0)
		{
			temp = m_pTurtle->m_Position.z;
			m_pTurtle->m_Position.z -= chunk * sin(m_pTurtle->m_Facing);
			//limit turtle movment to 40 feet radius circle
			if (m_pTurtle->m_Position.z*m_pTurtle->m_Position.z + m_pTurtle->m_Position.x*m_pTurtle->m_Position.x > 1600)
				m_pTurtle->m_Position.z = temp;

			temp = m_pTurtle->m_Position.x;
			m_pTurtle->m_Position.x += chunk * cos(m_pTurtle->m_Facing);
			//limit turtle movment to 40 feet radius circle
			if (m_pTurtle->m_Position.z*m_pTurtle->m_Position.z + m_pTurtle->m_Position.x*m_pTurtle->m_Position.x > 1600)
				m_pTurtle->m_Position.x = temp;
			m_pTurtle->m_Model->SetAnimationSet(2);
		}
		//Move Forward
		if ((GetAsyncKeyState(VK_UP) < 0)||(GetAsyncKeyState(VK_W) < 0))
		{
			if (!m_CAPSLOCK) // CAPS LOCK TURNED OFF
			{
				if (GetAsyncKeyState(VK_SHIFT) < 0)
				{//RUNNING
					if (m_pTurtle->m_isIdle || !m_pTurtle->m_isRunning)
					{
						//switch animation to running
						m_pTurtle->m_Model->SetAnimationSet(3);
						m_pTurtle->m_isRunning = true;
						m_pTurtle->m_isIdle = false;
					}
					temp = m_pTurtle->m_Position.z;
					m_pTurtle->m_Position.z += 2 * chunk * cos(m_pTurtle->m_Facing);
					//limit turtle movment to 40 feet radius circle
					if (m_pTurtle->m_Position.z*m_pTurtle->m_Position.z + m_pTurtle->m_Position.x*m_pTurtle->m_Position.x > 1600)
						m_pTurtle->m_Position.z = temp;

					temp = m_pTurtle->m_Position.x;
					m_pTurtle->m_Position.x += 2 * chunk * sin(m_pTurtle->m_Facing);
					if (m_pTurtle->m_Position.z*m_pTurtle->m_Position.z + m_pTurtle->m_Position.x*m_pTurtle->m_Position.x > 1600)
						m_pTurtle->m_Position.x = temp;
				}
				else 
				{//WALKING
					if (m_pTurtle->m_isIdle || m_pTurtle->m_isRunning)
					{
						//switch animation to walking
						m_pTurtle->m_Model->SetAnimationSet(2);
						m_pTurtle->m_isRunning = false;
						m_pTurtle->m_isIdle = false;
					}
					temp = m_pTurtle->m_Position.z;
					m_pTurtle->m_Position.z += chunk * cos(m_pTurtle->m_Facing);
					//limit turtle movment to 40 feet radius circle
					if (m_pTurtle->m_Position.z*m_pTurtle->m_Position.z + m_pTurtle->m_Position.x*m_pTurtle->m_Position.x > 1600)
						m_pTurtle->m_Position.z = temp;

					temp = m_pTurtle->m_Position.x;
					m_pTurtle->m_Position.x += chunk * sin(m_pTurtle->m_Facing);
					//limit turtle movment to 40 feet radius circle
					if (m_pTurtle->m_Position.z*m_pTurtle->m_Position.z + m_pTurtle->m_Position.x*m_pTurtle->m_Position.x > 1600)
						m_pTurtle->m_Position.x = temp;
				}
			}
			else
			{
				if (GetAsyncKeyState(VK_SHIFT) < 0)
				{//WALKING
					if (m_pTurtle->m_isIdle || m_pTurtle->m_isRunning)
					{
						//switch animation to walking
						m_pTurtle->m_Model->SetAnimationSet(2);
						m_pTurtle->m_isRunning = false;
						m_pTurtle->m_isIdle = false;
					}
					temp = m_pTurtle->m_Position.z;
					m_pTurtle->m_Position.z += chunk * cos(m_pTurtle->m_Facing);
					//limit turtle movment to 40 feet radius circle
					if (m_pTurtle->m_Position.z*m_pTurtle->m_Position.z + m_pTurtle->m_Position.x*m_pTurtle->m_Position.x > 1600)
						m_pTurtle->m_Position.z = temp;

					temp = m_pTurtle->m_Position.x;
					m_pTurtle->m_Position.x += chunk * sin(m_pTurtle->m_Facing);
					//limit turtle movment to 40 feet radius circle
					if (m_pTurtle->m_Position.z*m_pTurtle->m_Position.z + m_pTurtle->m_Position.x*m_pTurtle->m_Position.x > 1600)
						m_pTurtle->m_Position.x = temp;
				}
				else 
				{//RUNNING
					if (m_pTurtle->m_isIdle || !m_pTurtle->m_isRunning)
					{
						//switch animation to running
						m_pTurtle->m_Model->SetAnimationSet(3);
						m_pTurtle->m_isRunning = true;
						m_pTurtle->m_isIdle = false;
					}
					temp = m_pTurtle->m_Position.z;
					m_pTurtle->m_Position.z += 2 * chunk * cos(m_pTurtle->m_Facing);
					//limit turtle movment to 40 feet radius circle
					if (m_pTurtle->m_Position.z*m_pTurtle->m_Position.z + m_pTurtle->m_Position.x*m_pTurtle->m_Position.x > 1600)
						m_pTurtle->m_Position.z = temp;

					temp = m_pTurtle->m_Position.x;
					m_pTurtle->m_Position.x += 2 * chunk * sin(m_pTurtle->m_Facing);
					//limit turtle movment to 40 feet radius circle
					if (m_pTurtle->m_Position.z*m_pTurtle->m_Position.z + m_pTurtle->m_Position.x*m_pTurtle->m_Position.x > 1600)
						m_pTurtle->m_Position.x = temp;
				}
			}
		}
		// Move Backward
		else if((GetAsyncKeyState(VK_DOWN) < 0)||(GetAsyncKeyState(VK_S) < 0))
		{
			temp = m_pTurtle->m_Position.z;
			m_pTurtle->m_Position.z -= chunk * cos(m_pTurtle->m_Facing);
			//limit turtle movment to 40 feet radius circle
			if (m_pTurtle->m_Position.z*m_pTurtle->m_Position.z + m_pTurtle->m_Position.x*m_pTurtle->m_Position.x > 1600)
				m_pTurtle->m_Position.z = temp;

			temp = m_pTurtle->m_Position.x;
			m_pTurtle->m_Position.x -= chunk * sin(m_pTurtle->m_Facing);
			//limit turtle movment to 40 feet radius circle
			if (m_pTurtle->m_Position.z*m_pTurtle->m_Position.z + m_pTurtle->m_Position.x*m_pTurtle->m_Position.x > 1600)
				m_pTurtle->m_Position.x = temp;
			m_pTurtle->m_Model->SetAnimationSet(2);
			m_pTurtle->m_isIdle = false;
		}
		else
		{
			//standing in place
			if(rotating)
			{
				m_pTurtle->m_Model->SetAnimationSet(2);
				m_pTurtle->m_isIdle = false;
			}
			else if (!m_pTurtle->m_isIdle)
			{
				m_pTurtle->m_Model->SetAnimationSet(0);
				m_pTurtle->m_isIdle = true;
			}
		}
	}
}

/**
 * Add another dwarf in action
 * \author Petar Bajic 
 * \date January, 16 2007.
 */
void CLevel::AddDwarf()
{
	std::vector<CDwarf*>::iterator itCurrentDwarf, end;
	itCurrentDwarf = m_Dwarfs.begin();
	end = m_Dwarfs.end();
	while (itCurrentDwarf != end)
	{
		if(!((*itCurrentDwarf)->m_Alive))
		{
			//Init dwarf position
			(*itCurrentDwarf)->GetInTheGame();
			//Find him the closest sheep to go for, and set facing
			(*itCurrentDwarf)->m_TargetSheep = FindClosestSheep((*itCurrentDwarf));
			break;
		}
		itCurrentDwarf++;
	}
}



/**
 * This function is called when dwarf (carrying a sheep) is killed, or some sheep changed position, or dwarf snatched a sheep
 * Then all other dwarfs are redirected, so they can find another available sheep.
 * \author Petar Bajic 
 * \date January, 16 2007.
 */
void CLevel::RedirectOtherDwarfs()
{
	vector< CDwarf* >::iterator itgCurrentDwarf, itEndDwarf = m_Dwarfs.end();
	for( itgCurrentDwarf = m_Dwarfs.begin(); itgCurrentDwarf != itEndDwarf; ++ itgCurrentDwarf )
	{
		//Only alive ones, without sheeps, and not scared or obscured by other way
		if ((*itgCurrentDwarf)->m_Alive && !(*itgCurrentDwarf)->m_CarryingSheep && !(*itgCurrentDwarf)->m_Scared && !(*itgCurrentDwarf)->m_Hit)
		{
			(*itgCurrentDwarf)->m_WalkCenter = true;
			(*itgCurrentDwarf)->m_Model->SetAnimationSet(0);
			(*itgCurrentDwarf)->m_TargetSheep = FindClosestSheep(*itgCurrentDwarf);
		}
	}
}

/**
 * Initializes sheep parameters and positiones sheep to random position in the field.
 * \author Petar Bajic 
 * \date January, 16 2007.
 */
void CLevel::DistributeSheepsForStart()
{
	int rand_positionx = 0;
	int rand_positionz = 0;
	std::vector<CSheep*>::iterator it, end;
	it = m_Sheeps.begin();
	end = m_Sheeps.end();
	while (it != end)
	{
		(*it)->m_Alive = true;
		(*it)->m_BeingCarriedAway = false;
		(*it)->m_Moved = false;
		(*it)->m_Model->SetAnimationSet(0);
		rand_positionx = (rand() % 20) - 10;// from -10 to 10;
		rand_positionz = (rand() % 20) - 10;// from -10 to 10;
		(*it)->m_Position.x = (float)rand_positionx; //position of first sheep
		(*it)->m_Position.z = (float)rand_positionz;
		(*it)->m_Position.y = 0.3f;
		//we need to check if there is not another sheep in that position (or too close)
		bool tooclose = true;
		while(tooclose)
		{
			tooclose = false;
			std::vector<CSheep*>::iterator it2, end2;
			it2 = m_Sheeps.begin();
			end2 = m_Sheeps.end();
			while (it2 != end2)
			{
				if (it2 != it)
				{
					//if too close to another sheep
					if (distance2((*it)->m_Position,(*it2)->m_Position) < 4)
					{
						tooclose = true;
						//pick another position
						rand_positionx = (rand() % 20) - 10;// from -10 to 10;
						rand_positionz = (rand() % 20) - 10;// from -10 to 10;
						(*it)->m_Position.x = (float)rand_positionx; //position of first sheep
						(*it)->m_Position.z = (float)rand_positionz;
						(*it)->m_Position.y = 0.0f;
						break;
					}
				}
				it2++;
			}
		}
		(*it)->m_Facing = ((float)rand_positionx)/5;
		it++;
	}
}

/**
 * When exiting level (to menu), all sheeps except first one are released.
 * If player returns from menu to play level - he starts from begining with only one sheep.
 * One remaining sheep is released when exiting game completely.
 * \author Petar Bajic 
 * \date January, 16 2007.
 */
void CLevel::ReleaseSheeps()
{
	std::vector<CSheep*>::iterator itCurrentSheep, begin;
	itCurrentSheep = m_Sheeps.end();
	begin = m_Sheeps.begin();
	itCurrentSheep--;
	while (itCurrentSheep != begin)
	{
		if((*itCurrentSheep) != NULL)
			delete (*itCurrentSheep);
		itCurrentSheep--;
	}
	m_Sheeps.clear();
}

/**
 * Find closest sheep to given dwarf, plus set facing of dwarf to face the closest sheep
 * If there is no sheep available, dwarf will move toward center futile.
 * \author Petar Bajic 
 * \date January, 16 2007.
 */
CSheep* CLevel::FindClosestSheep(CDwarf *dwarf)
{
	D3DXVECTOR3 prey = D3DXVECTOR3(0.0f, 0.0f, 0.0f);
	CSheep* returnSheep = NULL;
	float min = 10000.0f;
	float temp = 0.0f;
	dwarf->m_Facing = facePoint(dwarf->m_Position,prey);
	std::vector<CSheep*>::iterator itCurrentSheep, end;
	itCurrentSheep = m_Sheeps.begin();
	end = m_Sheeps.end();
	while (itCurrentSheep != end)
	{
		if (!(*itCurrentSheep)->m_BeingCarriedAway)
		{
			temp = D3DXVec3Length(D3DXVec3Subtract(&prey, &(dwarf->m_Position), &((*itCurrentSheep)->m_Position)));
			if (temp < min)
			{
				min = temp;
				returnSheep = (*itCurrentSheep);
				dwarf->m_Facing = facePoint(dwarf->m_Position,returnSheep->m_Position);
			}
		}
		itCurrentSheep++;
    }
	return returnSheep;
}
