code:
#pragma once

enum {
	PLAYERCONTROL_ENABLED = 0,
	PLAYERCONTROL_CAMERA = 1,
	PLAYERCONTROL_UNK2 = 2,
	PLAYERCONTROL_GARAGE = 4,
	PLAYERCONTROL_UNK8 = 8,
	PLAYERCONTROL_UNK10 = 16,
	PLAYERCONTROL_PLAYERINFO = 32,
	PLAYERCONTROL_PHONE = 64,
	PLAYERCONTROL_CUTSCENE = 128,
};

class CControllerState
{
public:
	int16 LeftStickX, LeftStickY;
	int16 RightStickX, RightStickY;
	int16 LeftShoulder1, LeftShoulder2;
	int16 RightShoulder1, RightShoulder2;
	int16 DPadUp, DPadDown, DPadLeft, DPadRight;
	int16 Start, Select;
	int16 Square, Triangle, Cross, Circle;
	int16 LeftShock, RightShock;
	int16 NetworkTalk;
	float GetLeftStickX(void) { return LeftStickX/32767.0f; };
	float GetLeftStickY(void) { return LeftStickY/32767.0f; };
	float GetRightStickX(void) { return RightStickX/32767.0f; };
	float GetRightStickY(void) { return RightStickY/32767.0f; };

	bool CheckForInput();
	void Clear(void);
};
VALIDATE_SIZE(CControllerState, 0x2A);

class CMouseControllerState
{
public:
	//uint32 btns;	// bit 0-2 button 1-3

	bool LMB;
	bool RMB;
	bool MMB;
	bool WHEELUP;
	bool WHEELDN;
	bool MXB1;
	bool MXB2;
	char _pad0;

	float x, y;

	CMouseControllerState();
	void Clear();
};

VALIDATE_SIZE(CMouseControllerState, 0x10);

class CMousePointerStateHelper
{
public:
	bool bInvertHorizontally;
	bool bInvertVertically;

	CMouseControllerState GetMouseSetUp();
};

VALIDATE_SIZE(CMousePointerStateHelper, 0x2);

extern CMousePointerStateHelper MousePointerStateHelper;

class CKeyboardState
{
public:
	int16 F[12];
	int16 VK_KEYS[256];
	int16 ESC;
	int16 INS;
	int16 DEL;
	int16 HOME;
	int16 END;
	int16 PGUP;
	int16 PGDN;
	int16 UP;
	int16 DOWN;
	int16 LEFT;
	int16 RIGHT;
	int16 SCROLLLOCK;
	int16 PAUSE;
	int16 NUMLOCK;
	int16 DIV;
	int16 MUL;
	int16 SUB;
	int16 ADD;
	int16 ENTER;
	int16 DECIMAL;
	int16 NUM1;
	int16 NUM2;
	int16 NUM3;
	int16 NUM4;
	int16 NUM5;
	int16 NUM6;
	int16 NUM7;
	int16 NUM8;
	int16 NUM9;
	int16 NUM0;
	int16 BACKSP;
	int16 TAB;
	int16 CAPSLOCK;
	int16 EXTENTER;
	int16 LSHIFT;
	int16 RSHIFT;
	int16 SHIFT;
	int16 LCTRL;
	int16 RCTRL;
	int16 LALT;
	int16 RALT;
	int16 LWIN;
	int16 RWIN;
	int16 APPS;

	void Clear();
};

VALIDATE_SIZE(CKeyboardState, 0x270);

enum
{
	// taken from miss2
	PAD1 = 0,
	PAD2,

	MAX_PADS
};

class CPad
{
public:
	enum
	{
		HORNHISTORY_SIZE = 5,
	};
	CControllerState NewState;
	CControllerState OldState;
	CControllerState PCTempKeyState;
	CControllerState PCTempJoyState;
	CControllerState PCTempMouseState;
	// straight out of my IDB
	int16 Phase;
	int16 Mode;
	int16 ShakeDur;
	uint8 ShakeFreq;
	bool bHornHistory[HORNHISTORY_SIZE];
	uint8 iCurrHornHistory;
	uint8 DisablePlayerControls;
	int8 bApplyBrakes;
	char CheatString[12];
	int32 LastTimeTouched;
	int32 AverageWeapon;
	int32 AverageEntries;

#ifdef DETECT_PAD_INPUT_SWITCH
	static bool IsAffectedByController;
#endif
	CPad() { }
	~CPad() { }

	static bool bDisplayNoControllerMessage;
	static bool bObsoleteControllerMessage;
	static bool bOldDisplayNoControllerMessage;
	static bool m_bMapPadOneToPadTwo;
#ifdef INVERT_LOOK_FOR_PAD
	static bool bInvertLook4Pad;
#endif

	static CKeyboardState OldKeyState;
	static CKeyboardState NewKeyState;
	static CKeyboardState TempKeyState;
	static char KeyBoardCheatString[20];
	static CMouseControllerState OldMouseControllerState;
	static CMouseControllerState NewMouseControllerState;
	static CMouseControllerState PCTempMouseControllerState;

#ifdef GTA_PS2_STUFF
	static void Initialise(void);
#endif
	void Clear(bool bResetPlayerControls);
	void ClearMouseHistory();
	void UpdateMouse();
	CControllerState ReconcileTwoControllersInput(CControllerState const &State1, CControllerState const &State2);
	void StartShake(int16 nDur, uint8 nFreq);
	void StartShake_Distance(int16 nDur, uint8 nFreq, float fX, float fY, float fz);
	void StartShake_Train(float fX, float fY);
#ifdef GTA_PS2_STUFF
	void AddToCheatString(char c);
#endif
	void AddToPCCheatString(char c);

	static void UpdatePads(void);
	void ProcessPCSpecificStuff(void);
	void Update(int16 pad);

	static void DoCheats(void);
	void DoCheats(int16 unk);

	static void StopPadsShaking(void);
	void StopShaking(int16 pad);

	static CPad *GetPad(int32 pad);

	int16 GetSteeringLeftRight(void);
	int16 GetSteeringUpDown(void);
	int16 GetCarGunUpDown(void);
	int16 GetCarGunLeftRight(void);
	int16 GetPedWalkLeftRight(void);
	int16 GetPedWalkUpDown(void);
	int16 GetAnalogueUpDown(void);
	bool GetLookLeft(void);
	bool GetLookRight(void);
	bool GetLookBehindForCar(void);
	bool GetLookBehindForPed(void);
	bool GetHorn(void);
	bool HornJustDown(void);
	bool GetCarGunFired(void);
	bool CarGunJustDown(void);
	int16 GetHandBrake(void);
	int16 GetBrake(void);
	bool GetExitVehicle(void);
	bool ExitVehicleJustDown(void);
	int32 GetWeapon(void);
	bool WeaponJustDown(void);
	int16 GetAccelerate(void);
	bool CycleCameraModeUpJustDown(void);
	bool CycleCameraModeDownJustDown(void);
	bool ChangeStationJustDown(void);
	bool CycleWeaponLeftJustDown(void);
	bool CycleWeaponRightJustDown(void);
	bool GetTarget(void);
	bool TargetJustDown(void);
	bool JumpJustDown(void);
	bool GetSprint(void);
	bool ShiftTargetLeftJustDown(void);
	bool ShiftTargetRightJustDown(void);
	bool GetAnaloguePadUp(void);
	bool GetAnaloguePadDown(void);
	bool GetAnaloguePadLeft(void);
	bool GetAnaloguePadRight(void);
	bool GetAnaloguePadLeftJustUp(void);
	bool GetAnaloguePadRightJustUp(void);
	bool ForceCameraBehindPlayer(void);
	bool SniperZoomIn(void);
	bool SniperZoomOut(void);
	int16 SniperModeLookLeftRight(void);
	int16 SniperModeLookUpDown(void);
	int16 LookAroundLeftRight(void);
	int16 LookAroundUpDown(void);
	void ResetAverageWeapon(void);
	static void PrintErrorMessage(void);
	static void ResetCheats(void);
	static char *EditString(char *pStr, int32 nSize);
	static int32 *EditCodesForControls(int32 *pRsKeys, int32 nSize);

#ifdef XINPUT
	static int XInputJoy1;
	static int XInputJoy2;
	void AffectFromXinput(uint32 pad);
#endif

	// mouse
	bool GetLeftMouseJustDown()           { return !!(NewMouseControllerState.LMB && !OldMouseControllerState.LMB); }
	bool GetRightMouseJustDown()          { return !!(NewMouseControllerState.RMB && !OldMouseControllerState.RMB); }
	bool GetMiddleMouseJustDown()         { return !!(NewMouseControllerState.MMB && !OldMouseControllerState.MMB); }
	bool GetMouseWheelUpJustDown()        { return !!(NewMouseControllerState.WHEELUP && !OldMouseControllerState.WHEELUP); }
	bool GetMouseWheelDownJustDown()      { return !!(NewMouseControllerState.WHEELDN && !OldMouseControllerState.WHEELDN);}
	bool GetMouseX1JustDown()             { return !!(NewMouseControllerState.MXB1    && !OldMouseControllerState.MXB1); }
	bool GetMouseX2JustDown()             { return !!(NewMouseControllerState.MXB2    && !OldMouseControllerState.MXB2); }

	bool GetLeftMouseJustUp() { return !!(!NewMouseControllerState.LMB && OldMouseControllerState.LMB); }
	bool GetRightMouseJustUp() { return !!(!NewMouseControllerState.RMB && OldMouseControllerState.RMB); }
	bool GetMiddleMouseJustUp() { return !!(!NewMouseControllerState.MMB && OldMouseControllerState.MMB); }
	bool GetMouseWheelUpJustUp() { return !!(!NewMouseControllerState.WHEELUP && OldMouseControllerState.WHEELUP); }
	bool GetMouseWheelDownJustUp() { return !!(!NewMouseControllerState.WHEELDN && OldMouseControllerState.WHEELDN); }
	bool GetMouseX1JustUp() { return !!(!NewMouseControllerState.MXB1 && OldMouseControllerState.MXB1); }
	bool GetMouseX2JustUp() { return !!(!NewMouseControllerState.MXB2 && OldMouseControllerState.MXB2); }

	bool GetLeftMouse()         { return NewMouseControllerState.LMB; }
	bool GetRightMouse()        { return NewMouseControllerState.RMB; }
	bool GetMiddleMouse()       { return NewMouseControllerState.MMB; }
	bool GetMouseWheelUp()      { return NewMouseControllerState.WHEELUP; }
	bool GetMouseWheelDown()    { return NewMouseControllerState.WHEELDN; }
	bool GetMouseX1()           { return NewMouseControllerState.MXB1; }
	bool GetMouseX2()           { return NewMouseControllerState.MXB2; }

	bool GetLeftMouseUp()       { return !OldMouseControllerState.LMB; }
	bool GetRightMouseUp()      { return !OldMouseControllerState.RMB; }
	bool GetMiddleMouseUp()     { return !OldMouseControllerState.MMB; }
	bool GetMouseWheelUpUp()    { return !OldMouseControllerState.WHEELUP; }
	bool GetMouseWheelDownUp()  { return !OldMouseControllerState.WHEELDN; }
	bool GetMouseX1Up()         { return !OldMouseControllerState.MXB1; }
	bool GetMouseX2Up()         { return !OldMouseControllerState.MXB2; }

	float GetMouseX() { return NewMouseControllerState.x; }
	float GetMouseY() { return NewMouseControllerState.y; }

	// keyboard

	bool GetCharJustDown(int32 c) { return !!(NewKeyState.VK_KEYS[c] && !OldKeyState.VK_KEYS[c]); }
	bool GetFJustDown(int32 n)    { return !!(NewKeyState.F[n] && !OldKeyState.F[n]); }
	bool GetEscapeJustDown()      { return !!(NewKeyState.ESC && !OldKeyState.ESC); }
	bool GetInsertJustDown()      { return !!(NewKeyState.INS && !OldKeyState.INS); }
	bool GetDeleteJustDown()      { return !!(NewKeyState.DEL && !OldKeyState.DEL); }
	bool GetHomeJustDown()        { return !!(NewKeyState.HOME && !OldKeyState.HOME); }
	bool GetEndJustDown()         { return !!(NewKeyState.END && !OldKeyState.END); }
	bool GetPageUpJustDown()      { return !!(NewKeyState.PGUP && !OldKeyState.PGUP); }
	bool GetPageDownJustDown()    { return !!(NewKeyState.PGDN && !OldKeyState.PGDN); }
	bool GetUpJustDown()          { return !!(NewKeyState.UP && !OldKeyState.UP); }
	bool GetDownJustDown()        { return !!(NewKeyState.DOWN && !OldKeyState.DOWN); }
	bool GetLeftJustDown()        { return !!(NewKeyState.LEFT && !OldKeyState.LEFT); }
	bool GetRightJustDown()       { return !!(NewKeyState.RIGHT && !OldKeyState.RIGHT); }
	bool GetScrollLockJustDown()  { return !!(NewKeyState.SCROLLLOCK && !OldKeyState.SCROLLLOCK); }
	bool GetPauseJustDown()       { return !!(NewKeyState.PAUSE && !OldKeyState.PAUSE); }
	bool GetNumLockJustDown()     { return !!(NewKeyState.NUMLOCK && !OldKeyState.NUMLOCK); }
	bool GetDivideJustDown()      { return !!(NewKeyState.DIV && !OldKeyState.DIV); }
	bool GetTimesJustDown()       { return !!(NewKeyState.MUL && !OldKeyState.MUL); }
	bool GetMinusJustDown()       { return !!(NewKeyState.SUB && !OldKeyState.SUB); }
	bool GetPlusJustDown()        { return !!(NewKeyState.ADD && !OldKeyState.ADD); }
	bool GetPadEnterJustDown()    { return !!(NewKeyState.ENTER && !OldKeyState.ENTER); }
	bool GetPadDelJustDown()      { return !!(NewKeyState.DECIMAL && !OldKeyState.DECIMAL); }
	bool GetPad1JustDown()        { return !!(NewKeyState.NUM1 && !OldKeyState.NUM1); }
	bool GetPad2JustDown()        { return !!(NewKeyState.NUM2 && !OldKeyState.NUM2); }
	bool GetPad3JustDown()        { return !!(NewKeyState.NUM3 && !OldKeyState.NUM3); }
	bool GetPad4JustDown()        { return !!(NewKeyState.NUM4 && !OldKeyState.NUM4); }
	bool GetPad5JustDown()        { return !!(NewKeyState.NUM5 && !OldKeyState.NUM5); }
	bool GetPad6JustDown()        { return !!(NewKeyState.NUM6 && !OldKeyState.NUM6); }
	bool GetPad7JustDown()        { return !!(NewKeyState.NUM7 && !OldKeyState.NUM7); }
	bool GetPad8JustDown()        { return !!(NewKeyState.NUM8 && !OldKeyState.NUM8); }
	bool GetPad9JustDown()        { return !!(NewKeyState.NUM9 && !OldKeyState.NUM9); }
	bool GetPad0JustDown()        { return !!(NewKeyState.NUM0 && !OldKeyState.NUM0); }
	bool GetBackspaceJustDown()   { return !!(NewKeyState.BACKSP && !OldKeyState.BACKSP); }
	bool GetTabJustDown()         { return !!(NewKeyState.TAB && !OldKeyState.TAB); }
	bool GetCapsLockJustDown()    { return !!(NewKeyState.CAPSLOCK && !OldKeyState.CAPSLOCK); }
	bool GetReturnJustDown()       { return !!(NewKeyState.EXTENTER && !OldKeyState.EXTENTER); }
	bool GetLeftShiftJustDown()   { return !!(NewKeyState.LSHIFT && !OldKeyState.LSHIFT); }
	bool GetShiftJustDown()       { return !!(NewKeyState.SHIFT && !OldKeyState.SHIFT); }
	bool GetRightShiftJustDown()  { return !!(NewKeyState.RSHIFT && !OldKeyState.RSHIFT); }
	bool GetLeftCtrlJustDown()    { return !!(NewKeyState.LCTRL && !OldKeyState.LCTRL); }
	bool GetRightCtrlJustDown()   { return !!(NewKeyState.RCTRL && !OldKeyState.RCTRL); }
	bool GetLeftAltJustDown()     { return !!(NewKeyState.LALT && !OldKeyState.LALT); }
	bool GetRightAltJustDown()    { return !!(NewKeyState.RALT && !OldKeyState.RALT); }
	bool GetLeftWinJustDown()     { return !!(NewKeyState.LWIN && !OldKeyState.LWIN); }
	bool GetRightWinJustDown()    { return !!(NewKeyState.RWIN && !OldKeyState.RWIN); }
	bool GetAppsJustDown()        { return !!(NewKeyState.APPS && !OldKeyState.APPS); }
	bool GetEnterJustDown()       { return GetPadEnterJustDown() || GetReturnJustDown(); }
	bool GetAltJustDown()         { return GetLeftAltJustDown() || GetRightAltJustDown(); }

	bool GetLeftJustUp() { return !!(!NewKeyState.LEFT && OldKeyState.LEFT); }
	bool GetRightJustUp() { return !!(!NewKeyState.RIGHT && OldKeyState.RIGHT); }
	bool GetEnterJustUp() { return GetPadEnterJustUp() || GetReturnJustUp(); }
	bool GetReturnJustUp() { return !!(!NewKeyState.EXTENTER && OldKeyState.EXTENTER); }
	bool GetPadEnterJustUp() { return !!(!NewKeyState.ENTER && OldKeyState.ENTER); }

	bool GetChar(int32 c)         { return NewKeyState.VK_KEYS[c]; }
	bool GetF(int32 n)            { return NewKeyState.F[n]; }
	bool GetEscape()              { return NewKeyState.ESC; }
	bool GetInsert()              { return NewKeyState.INS; }
	bool GetDelete()              { return NewKeyState.DEL; }
	bool GetHome()                { return NewKeyState.HOME; }
	bool GetEnd()                 { return NewKeyState.END; }
	bool GetPageUp()              { return NewKeyState.PGUP; }
	bool GetPageDown()            { return NewKeyState.PGDN; }
	bool GetUp()                  { return NewKeyState.UP; }
	bool GetDown()                { return NewKeyState.DOWN; }
	bool GetLeft()                { return NewKeyState.LEFT; }
	bool GetRight()               { return NewKeyState.RIGHT; }
	bool GetScrollLock()          { return NewKeyState.SCROLLLOCK; }
	bool GetPause()               { return NewKeyState.PAUSE; }
	bool GetNumLock()             { return NewKeyState.NUMLOCK; }
	bool GetDivide()              { return NewKeyState.DIV; }
	bool GetTimes()               { return NewKeyState.MUL; }
	bool GetMinus()               { return NewKeyState.SUB; }
	bool GetPlus()                { return NewKeyState.ADD; }
	bool GetPadEnter()            { return NewKeyState.ENTER; } //  GetEnterJustDown
	bool GetPadDel()              { return NewKeyState.DECIMAL; }
	bool GetPad1()                { return NewKeyState.NUM1; }
	bool GetPad2()                { return NewKeyState.NUM2; }
	bool GetPad3()                { return NewKeyState.NUM3; }
	bool GetPad4()                { return NewKeyState.NUM4; }
	bool GetPad5()                { return NewKeyState.NUM5; }
	bool GetPad6()                { return NewKeyState.NUM6; }
	bool GetPad7()                { return NewKeyState.NUM7; }
	bool GetPad8()                { return NewKeyState.NUM8; }
	bool GetPad9()                { return NewKeyState.NUM9; }
	bool GetPad0()                { return NewKeyState.NUM0; }
	bool GetBackspace()           { return NewKeyState.BACKSP; }
	bool GetTab()                 { return NewKeyState.TAB; }
	bool GetCapsLock()            { return NewKeyState.CAPSLOCK; }
	bool GetEnter()               { return NewKeyState.EXTENTER; }
	bool GetLeftShift()           { return NewKeyState.LSHIFT; }
	bool GetShift()               { return NewKeyState.SHIFT; }
	bool GetRightShift()          { return NewKeyState.RSHIFT; }
	bool GetLeftCtrl()            { return NewKeyState.LCTRL; }
	bool GetRightCtrl()           { return NewKeyState.RCTRL; }
	bool GetLeftAlt()             { return NewKeyState.LALT; }
	bool GetRightAlt()            { return NewKeyState.RALT; }
	bool GetLeftWin()             { return NewKeyState.LWIN; }
	bool GetRightWin()            { return NewKeyState.RWIN; }
	bool GetApps()                { return NewKeyState.APPS; }
	// pad

	bool GetTriangleJustDown()       { return !!(NewState.Triangle && !OldState.Triangle); }
	bool GetCircleJustDown()         { return !!(NewState.Circle && !OldState.Circle); }
	bool GetCrossJustDown()          { return !!(NewState.Cross && !OldState.Cross); }
	bool GetSquareJustDown()         { return !!(NewState.Square && !OldState.Square); }
	bool GetDPadUpJustDown()         { return !!(NewState.DPadUp && !OldState.DPadUp); }
	bool GetDPadDownJustDown()       { return !!(NewState.DPadDown && !OldState.DPadDown); }
	bool GetDPadLeftJustDown()       { return !!(NewState.DPadLeft && !OldState.DPadLeft); }
	bool GetDPadRightJustDown()      { return !!(NewState.DPadRight && !OldState.DPadRight); }
	bool GetLeftShoulder1JustDown()  { return !!(NewState.LeftShoulder1 && !OldState.LeftShoulder1); }
	bool GetLeftShoulder2JustDown()  { return !!(NewState.LeftShoulder2 && !OldState.LeftShoulder2); }
	bool GetRightShoulder1JustDown() { return !!(NewState.RightShoulder1 && !OldState.RightShoulder1); }
	bool GetRightShoulder2JustDown() { return !!(NewState.RightShoulder2 && !OldState.RightShoulder2); }
	bool GetLeftShockJustDown()      { return !!(NewState.LeftShock && !OldState.LeftShock); }
	bool GetRightShockJustDown()     { return !!(NewState.RightShock && !OldState.RightShock); }
	bool GetStartJustDown()          { return !!(NewState.Start && !OldState.Start); }
	bool GetLeftStickXJustDown() { return !!(NewState.LeftStickX && !OldState.LeftStickX); }
	bool GetLeftStickYJustDown() { return !!(NewState.LeftStickY && !OldState.LeftStickY); }

	bool GetTriangleJustUp() { return !!(!NewState.Triangle && OldState.Triangle); }
	bool GetCircleJustUp() { return !!(!NewState.Circle && OldState.Circle); }
	bool GetCrossJustUp() { return !!(!NewState.Cross && OldState.Cross); }
	bool GetSquareJustUp() { return !!(!NewState.Square && OldState.Square); }
	bool GetDPadUpJustUp() { return !!(!NewState.DPadUp && OldState.DPadUp); }
	bool GetDPadDownJustUp() { return !!(!NewState.DPadDown && OldState.DPadDown); }
	bool GetDPadLeftJustUp() { return !!(!NewState.DPadLeft && OldState.DPadLeft); }
	bool GetDPadRightJustUp() { return !!(!NewState.DPadRight && OldState.DPadRight); }

	bool GetTriangle()           { return !!NewState.Triangle; }
	bool GetCircle()             { return !!NewState.Circle; }
	bool GetCross()              { return !!NewState.Cross; }
	bool GetSquare()             { return !!NewState.Square; }
	bool GetDPadUp()             { return !!NewState.DPadUp; }
	bool GetDPadDown()           { return !!NewState.DPadDown; }
	bool GetDPadLeft()           { return !!NewState.DPadLeft; }
	bool GetDPadRight()          { return !!NewState.DPadRight; }
	bool GetLeftShoulder1(void)  { return !!NewState.LeftShoulder1; }
	bool GetLeftShoulder2(void)  { return !!NewState.LeftShoulder2; }
	bool GetRightShoulder1(void) { return !!NewState.RightShoulder1; }
	bool GetRightShoulder2(void) { return !!NewState.RightShoulder2; }
	bool GetStart()              { return !!NewState.Start; }
	int16 GetLeftStickX(void)    { return NewState.LeftStickX; }
	int16 GetLeftStickY(void)    { return NewState.LeftStickY; }
	int16 GetRightStickX(void)    { return NewState.RightStickX; }
	int16 GetRightStickY(void)    { return NewState.RightStickY; }

	bool ArePlayerControlsDisabled(void) { return DisablePlayerControls != PLAYERCONTROL_ENABLED; }
	void SetDisablePlayerControls(uint8 who) { DisablePlayerControls |= who; }
	void SetEnablePlayerControls(uint8 who) { DisablePlayerControls &= ~who; }
	bool IsPlayerControlsDisabledBy(uint8 who) { return DisablePlayerControls & who; }

	int16 GetMode() { return Mode; }
	void SetMode(int16 mode) { Mode = mode; }

	static bool IsNoOrObsolete() { return bDisplayNoControllerMessage || bObsoleteControllerMessage; }
};

VALIDATE_SIZE(CPad, 0xFC);
extern CPad Pads[MAX_PADS];

#ifdef ALLCARSHELI_CHEAT
extern bool bAllCarCheat;
#endif


code:
#include "common.h"
#include "Placeable.h"

CPlaceable::CPlaceable(void)
{
	m_matrix.SetScale(1.0f);
}

CPlaceable::~CPlaceable(void)
{
}

void
CPlaceable::SetHeading(float angle)
{
	CVector pos = GetMatrix().GetPosition();
	m_matrix.SetRotateZ(angle);
	GetMatrix().Translate(pos);
}

bool
CPlaceable::IsWithinArea(float x1, float y1, float x2, float y2)
{
	float tmp;

	if(x1 > x2){
		tmp = x1;
		x1 = x2;
		x2 = tmp;
	}
	if(y1 > y2){
		tmp = y1;
		y1 = y2;
		y2 = tmp;
	}

	return x1 <= GetPosition().x && GetPosition().x <= x2 &&
	       y1 <= GetPosition().y && GetPosition().y <= y2;
}

bool
CPlaceable::IsWithinArea(float x1, float y1, float z1, float x2, float y2, float z2)
{
	float tmp;

	if(x1 > x2){
		tmp = x1;
		x1 = x2;
		x2 = tmp;
	}
	if(y1 > y2){
		tmp = y1;
		y1 = y2;
		y2 = tmp;
	}
	if(z1 > z2){
		tmp = z1;
		z1 = z2;
		z2 = tmp;
	}

	return x1 <= GetPosition().x && GetPosition().x <= x2 &&
	       y1 <= GetPosition().y && GetPosition().y <= y2 &&
	       z1 <= GetPosition().z && GetPosition().z <= z2;
}

license: mit


code:
#pragma once

class CPlaceable
{
protected:
	CMatrix m_matrix;

public:
	// disable allocation
	static void *operator new(size_t) throw();

	CPlaceable(void);
	virtual ~CPlaceable(void);
	const CVector &GetPosition(void) { return m_matrix.GetPosition(); }
	void SetPosition(float x, float y, float z) {
		m_matrix.GetPosition().x = x;
		m_matrix.GetPosition().y = y;
		m_matrix.GetPosition().z = z;
	}
	void SetPosition(const CVector &pos) { m_matrix.GetPosition() = pos; }
	CVector &GetRight(void) { return m_matrix.GetRight(); }
	CVector &GetForward(void) { return m_matrix.GetForward(); }
	CVector &GetUp(void) { return m_matrix.GetUp(); }
	CMatrix &GetMatrix(void) { return m_matrix; }
	void SetMatrix(CMatrix &newMatrix) { m_matrix = newMatrix; }
	void SetTransform(RwMatrix *m) { m_matrix = CMatrix(m, false); }
	void SetHeading(float angle);
	void SetOrientation(float x, float y, float z){
		CVector pos = m_matrix.GetPosition();
		m_matrix.SetRotate(x, y, z);
		m_matrix.Translate(pos);
	}
	bool IsWithinArea(float x1, float y1, float x2, float y2);
	bool IsWithinArea(float x1, float y1, float z1, float x2, float y2, float z2);
};

VALIDATE_SIZE(CPlaceable, 0x4C);


code:
#include "common.h"

#include "Automobile.h"
#include "Bridge.h"
#include "Camera.h"
#include "CarCtrl.h"
#include "Cranes.h"
#include "Darkel.h"
#include "Explosion.h"
#include "Fire.h"
#include "Frontend.h"
#include "General.h"
#include "HandlingMgr.h"
#include "Messages.h"
#include "Pad.h"
#include "PathFind.h"
#include "PlayerInfo.h"
#include "PlayerPed.h"
#include "PlayerSkin.h"
#include "ProjectileInfo.h"
#include "Remote.h"
#include "Renderer.h"
#include "Replay.h"
#include "Script.h"
#include "SpecialFX.h"
#include "Stats.h"
#include "Streaming.h"
#include "Text.h"
#include "Wanted.h"
#include "WaterLevel.h"
#include "World.h"
#include "ZoneCull.h"
#include "main.h"

void
CPlayerInfo::Clear(void)
{
	m_pPed = nil;
	m_pRemoteVehicle = nil;
	if (m_pVehicleEx) {
		m_pVehicleEx->bUsingSpecialColModel = false;
		m_pVehicleEx = nil;
	}
	m_nVisibleMoney = 0;
	m_nMoney = m_nVisibleMoney;
	m_WBState = WBSTATE_PLAYING;
	m_nWBTime = 0;
	m_nTrafficMultiplier = 0;
	m_fRoadDensity = 1.0f;
	m_bInRemoteMode = false;
	m_bUnusedTaxiThing = false;
	m_nUnusedTaxiTimer = 0;
	m_nCollectedPackages = 0;
	m_nTotalPackages = 3;
	m_nTimeLastHealthLoss = 0;
	m_nTimeLastArmourLoss = 0;
	m_nNextSexFrequencyUpdateTime = 0;
	m_nNextSexMoneyUpdateTime = 0;
	m_nSexFrequency = 0;
	m_pHooker = nil;
	m_nTimeTankShotGun = 0;
	field_248 = 0;
	m_nUpsideDownCounter = 0;
	m_bInfiniteSprint = false;
	m_bFastReload = false;
	m_bGetOutOfJailFree = false;
	m_bGetOutOfHospitalFree = false;
	m_nPreviousTimeRewardedForExplosion = 0;
	m_nExplosionsSinceLastReward = 0;
}

void
CPlayerInfo::Process(void)
{
#ifdef FIX_BUGS
	if (CReplay::IsPlayingBack())
		return;
#endif
	// Unused taxi feature. Gives you a dollar for every second with a passenger. Can be toggled via 0x29A opcode.
	bool startTaxiTimer = true;
	if (m_bUnusedTaxiThing && m_pPed->bInVehicle) {
		CVehicle *veh = m_pPed->m_pMyVehicle;
		if ((veh->GetModelIndex() == MI_TAXI || veh->GetModelIndex() == MI_CABBIE || veh->GetModelIndex() == MI_BORGNINE)
			&& veh->pDriver == m_pPed && veh->m_nNumPassengers != 0) {
			for (uint32 timePassed = CTimer::GetTimeInMilliseconds() - m_nUnusedTaxiTimer; timePassed >= 1000; m_nUnusedTaxiTimer += 1000) {
				timePassed -= 1000;
				++m_nMoney;
			}
			startTaxiTimer = false;
		}
	}
	if (startTaxiTimer)
		m_nUnusedTaxiTimer = CTimer::GetTimeInMilliseconds();

	// The effect that makes money counter does while earning/losing money
	if (m_nVisibleMoney != m_nMoney) {
		int diff = m_nMoney - m_nVisibleMoney;
		int diffAbs = Abs(diff);
		int changeBy;

		if (diffAbs > 100000)
			changeBy = 12345;
		else if (diffAbs > 10000)
			changeBy = 1234;
		else if (diffAbs > 1000)
			changeBy = 123;
		else if (diffAbs > 50)
			changeBy = 42;
		else
			changeBy = 1;

		if (diff < 0)
			m_nVisibleMoney -= changeBy;
		else
			m_nVisibleMoney += changeBy;
	}

	if (!(CTimer::GetFrameCounter() & 15)) {
		CVector2D playerPos = m_pPed->bInVehicle ? m_pPed->m_pMyVehicle->GetPosition() : m_pPed->GetPosition();
		m_fRoadDensity = ThePaths.CalcRoadDensity(playerPos.x, playerPos.y);
	}

	m_fRoadDensity = Clamp(m_fRoadDensity, 0.4f, 1.45f);

	// Because vehicle enter/exit use same key binding.
	bool enterOrExitVeh;
	if (m_pPed->bVehExitWillBeInstant && m_pPed->bInVehicle)
		enterOrExitVeh = CPad::GetPad(0)->ExitVehicleJustDown();
	else
		enterOrExitVeh = CPad::GetPad(0)->GetExitVehicle();

	if (enterOrExitVeh && m_pPed->m_nPedState != PED_SNIPER_MODE && m_pPed->m_nPedState != PED_ROCKET_MODE) {
		if (m_pPed->bInVehicle) {
			if (!m_pRemoteVehicle) {
				CEntity *surfaceBelowVeh = m_pPed->m_pMyVehicle->m_pCurGroundEntity;
				if (!surfaceBelowVeh || !CBridge::ThisIsABridgeObjectMovingUp(surfaceBelowVeh->GetModelIndex())) {
					CVehicle *veh = m_pPed->m_pMyVehicle;
					if (!veh->IsBoat() || veh->m_nDoorLock == CARLOCK_LOCKED_PLAYER_INSIDE) {

						// This condition will always return true, else block was probably WIP Miami code.
						if (veh->m_vehType != VEHICLE_TYPE_BIKE || veh->m_nDoorLock == CARLOCK_LOCKED_PLAYER_INSIDE) {
							if (veh->GetStatus() != STATUS_WRECKED && veh->GetStatus() != STATUS_TRAIN_MOVING && veh->m_nDoorLock != CARLOCK_LOCKED_PLAYER_INSIDE) {
								if (veh->m_vecMoveSpeed.Magnitude() < 0.17f && CTimer::GetTimeScale() >= 0.5f && !veh->bIsInWater) {
									m_pPed->SetObjective(OBJECTIVE_LEAVE_CAR, veh);
								}
							}
						} else {
							CVector sth = 0.7f * veh->GetRight() + veh->GetPosition();
							bool found = false;
							float groundZ = CWorld::FindGroundZFor3DCoord(sth.x, sth.y, 2.0f + sth.z, &found);

							if (found)
								sth.z = 1.0f + groundZ;
							m_pPed->SetPedState(PED_IDLE);
							m_pPed->SetMoveState(PEDMOVE_STILL);
							CPed::PedSetOutCarCB(0, m_pPed);
							CAnimManager::BlendAnimation(m_pPed->GetClump(), m_pPed->m_animGroup, ANIM_STD_IDLE, 100.0f);
							CAnimManager::BlendAnimation(m_pPed->GetClump(), ASSOCGRP_STD, ANIM_STD_FALL_LAND, 100.0f);
							m_pPed->SetPosition(sth);
							m_pPed->SetMoveState(PEDMOVE_STILL);
							m_pPed->m_vecMoveSpeed = veh->m_vecMoveSpeed;
						}
					} else {
						// The code in here was under CPed::SetExitBoat in VC, did the same for here.
						m_pPed->SetExitBoat(veh);
						m_pPed->bTryingToReachDryLand = true;
					}
				}
			}
		} else {
			// Enter vehicle
			if (CPad::GetPad(0)->ExitVehicleJustDown()) {
				bool weAreOnBoat = false;
				float lastCloseness = 0.0f;
				CVehicle *carBelow = nil;
				CEntity *surfaceBelow = m_pPed->m_pCurrentPhysSurface;
				if (surfaceBelow && surfaceBelow->IsVehicle()) {
					carBelow = (CVehicle*)surfaceBelow;
					if (carBelow->IsBoat()) {
						weAreOnBoat = true;
						m_pPed->bOnBoat = true;
#ifdef VC_PED_PORTS
						if (carBelow->GetStatus() != STATUS_WRECKED && carBelow->GetUp().z > 0.3f)
#else
						if (carBelow->GetStatus() != STATUS_WRECKED)
#endif
							m_pPed->SetSeekBoatPosition(carBelow);
					}
				}
				// Find closest car
				if (!weAreOnBoat) {
					float minX = m_pPed->GetPosition().x - 10.0f;
					float maxX = 10.0f + m_pPed->GetPosition().x;
					float minY = m_pPed->GetPosition().y - 10.0f;
					float maxY = 10.0f + m_pPed->GetPosition().y;

					int minXSector = CWorld::GetSectorIndexX(minX);
					if (minXSector < 0) minXSector = 0;
					int minYSector = CWorld::GetSectorIndexY(minY);
					if (minYSector < 0) minYSector = 0;
					int maxXSector = CWorld::GetSectorIndexX(maxX);
					if (maxXSector > NUMSECTORS_X - 1) maxXSector = NUMSECTORS_X - 1;
					int maxYSector = CWorld::GetSectorIndexY(maxY);
					if (maxYSector > NUMSECTORS_Y - 1) maxYSector = NUMSECTORS_Y - 1;

					CWorld::AdvanceCurrentScanCode();

					for (int curY = minYSector; curY <= maxYSector; curY++) {
						for (int curX = minXSector; curX <= maxXSector; curX++) {
							CSector *sector = CWorld::GetSector(curX, curY);
							FindClosestCarSectorList(sector->m_lists[ENTITYLIST_VEHICLES], m_pPed,
								minX, minY, maxX, maxY, &lastCloseness, &carBelow);
							FindClosestCarSectorList(sector->m_lists[ENTITYLIST_VEHICLES_OVERLAP], m_pPed,
								minX, minY, maxX, maxY, &lastCloseness, &carBelow);
						}
					}
				}
				// carBelow is now closest vehicle
				if (carBelow && !weAreOnBoat) {
					if (carBelow->GetStatus() == STATUS_TRAIN_NOT_MOVING) {
						m_pPed->SetObjective(OBJECTIVE_ENTER_CAR_AS_PASSENGER, carBelow);
					} else if (carBelow->IsBoat()) {
						if (!carBelow->pDriver) {
							m_pPed->m_vehDoor = 0;
							m_pPed->SetEnterCar(carBelow, m_pPed->m_vehDoor);
						}
					} else {
						m_pPed->SetObjective(OBJECTIVE_ENTER_CAR_AS_DRIVER, carBelow);
					}
				}
			}
		}
	}
	if (m_bInRemoteMode) {
		uint32 timeWithoutRemoteCar = CTimer::GetTimeInMilliseconds() - m_nTimeLostRemoteCar;
		if (CTimer::GetPreviousTimeInMilliseconds() - m_nTimeLostRemoteCar < 1000 && timeWithoutRemoteCar >= 1000 && m_WBState == WBSTATE_PLAYING) {
			TheCamera.SetFadeColour(0, 0, 0);
			TheCamera.Fade(1.0f, FADE_OUT);
		}
		if (timeWithoutRemoteCar > 2000) {
			if (m_WBState == WBSTATE_PLAYING) {
				TheCamera.RestoreWithJumpCut();
				TheCamera.SetFadeColour(0, 0, 0);
				TheCamera.Fade(1.0f, FADE_IN);
				TheCamera.Process();
				CTimer::Stop();
				CCullZones::ForceCullZoneCoors(TheCamera.GetPosition());
				CRenderer::RequestObjectsInFrustum();
				CStreaming::LoadAllRequestedModels(false);
				CTimer::Update();
			}
			m_bInRemoteMode = false;
			CWorld::Players[CWorld::PlayerInFocus].m_pRemoteVehicle = nil;
			if (FindPlayerVehicle()) {
				FindPlayerVehicle()->SetStatus(STATUS_PLAYER);
			}
		}
	}
	if (!(CTimer::GetFrameCounter() & 31)) {
		CVehicle *veh = FindPlayerVehicle();
		if (veh && m_pPed->bInVehicle && veh->GetUp().z < 0.0f
			&& veh->m_vecMoveSpeed.Magnitude() < 0.05f && veh->IsCar() && !veh->bIsInWater) {

			if (veh->GetUp().z < -0.5f) {
				m_nUpsideDownCounter += 2;

			} else {
				m_nUpsideDownCounter++;
			}
		} else {
			m_nUpsideDownCounter = 0;
		}

		if (m_nUpsideDownCounter > 6 && veh->bCanBeDamaged) {
			veh->m_fHealth = 249.0f < veh->m_fHealth ? 249.0f : veh->m_fHealth;
			if (veh->IsCar()) {
				CAutomobile* car = (CAutomobile*)veh;
				car->Damage.SetEngineStatus(225);
				car->m_pSetOnFireEntity = nil;
			}
		}
	}
	if (FindPlayerVehicle()) {
		CVehicle *veh = FindPlayerVehicle();
		veh->m_nZoneLevel = LEVEL_IGNORE;
		for (int i = 0; i < ARRAY_SIZE(veh->pPassengers); i++) {
			if (veh->pPassengers[i])
				veh->pPassengers[i]->m_nZoneLevel = LEVEL_GENERIC;
		}
		CStats::DistanceTravelledInVehicle += veh->m_fDistanceTravelled;
	} else {
		CStats::DistanceTravelledOnFoot += FindPlayerPed()->m_fDistanceTravelled;
	}
}

bool
CPlayerInfo::IsPlayerInRemoteMode()
{
	return m_pRemoteVehicle || m_bInRemoteMode;
}

void
CPlayerInfo::SavePlayerInfo(uint8 *buf, uint32 *size)
{
	// Interesting
	*size = sizeof(CPlayerInfo);

#define CopyToBuf(buf, data) memcpy(buf, &data, sizeof(data)); buf += sizeof(data);
	CopyToBuf(buf, CWorld::Players[CWorld::PlayerInFocus].m_nMoney);
	CopyToBuf(buf, CWorld::Players[CWorld::PlayerInFocus].m_WBState);
	CopyToBuf(buf, CWorld::Players[CWorld::PlayerInFocus].m_nWBTime);
	CopyToBuf(buf, CWorld::Players[CWorld::PlayerInFocus].m_nTrafficMultiplier);
	CopyToBuf(buf, CWorld::Players[CWorld::PlayerInFocus].m_fRoadDensity);
	CopyToBuf(buf, CWorld::Players[CWorld::PlayerInFocus].m_nVisibleMoney);
	CopyToBuf(buf, CWorld::Players[CWorld::PlayerInFocus].m_nCollectedPackages);
	CopyToBuf(buf, CWorld::Players[CWorld::PlayerInFocus].m_nTotalPackages);
	CopyToBuf(buf, CWorld::Players[CWorld::PlayerInFocus].m_bInfiniteSprint);
	CopyToBuf(buf, CWorld::Players[CWorld::PlayerInFocus].m_bFastReload);
	CopyToBuf(buf, CWorld::Players[CWorld::PlayerInFocus].m_bGetOutOfJailFree);
	CopyToBuf(buf, CWorld::Players[CWorld::PlayerInFocus].m_bGetOutOfHospitalFree);
	CopyToBuf(buf, CWorld::Players[CWorld::PlayerInFocus].m_aPlayerName);
#undef CopyToBuf
}

void
CPlayerInfo::LoadPlayerInfo(uint8 *buf, uint32 size)
{
#define CopyFromBuf(buf, data) memcpy(&data, buf, sizeof(data)); buf += sizeof(data);
	CopyFromBuf(buf, CWorld::Players[CWorld::PlayerInFocus].m_nMoney);
	CopyFromBuf(buf, CWorld::Players[CWorld::PlayerInFocus].m_WBState);
	CopyFromBuf(buf, CWorld::Players[CWorld::PlayerInFocus].m_nWBTime);
	CopyFromBuf(buf, CWorld::Players[CWorld::PlayerInFocus].m_nTrafficMultiplier);
	CopyFromBuf(buf, CWorld::Players[CWorld::PlayerInFocus].m_fRoadDensity);
	CopyFromBuf(buf, CWorld::Players[CWorld::PlayerInFocus].m_nVisibleMoney);
	CopyFromBuf(buf, CWorld::Players[CWorld::PlayerInFocus].m_nCollectedPackages);
	CopyFromBuf(buf, CWorld::Players[CWorld::PlayerInFocus].m_nTotalPackages);
	CopyFromBuf(buf, CWorld::Players[CWorld::PlayerInFocus].m_bInfiniteSprint);
	CopyFromBuf(buf, CWorld::Players[CWorld::PlayerInFocus].m_bFastReload);
	CopyFromBuf(buf, CWorld::Players[CWorld::PlayerInFocus].m_bGetOutOfJailFree);
	CopyFromBuf(buf, CWorld::Players[CWorld::PlayerInFocus].m_bGetOutOfHospitalFree);
	CopyFromBuf(buf, CWorld::Players[CWorld::PlayerInFocus].m_aPlayerName)
#undef CopyFromBuf
}

void
CPlayerInfo::FindClosestCarSectorList(CPtrList& carList, CPed* ped, float unk1, float unk2, float unk3, float unk4, float* lastCloseness, CVehicle** closestCarOutput)
{
	for (CPtrNode* node = carList.first; node; node = node->next) {
		CVehicle *car = (CVehicle*)node->item;
		if(car->m_scanCode != CWorld::GetCurrentScanCode()) {
			if (!car->bUsesCollision || !car->IsVehicle())
				continue;

			car->m_scanCode = CWorld::GetCurrentScanCode();
			if (car->GetStatus() != STATUS_WRECKED && car->GetStatus() != STATUS_TRAIN_MOVING
				&& (car->GetUp().z > 0.3f || (car->IsVehicle() && ((CVehicle*)car)->m_vehType == VEHICLE_TYPE_BIKE))) {
				CVector carCentre = car->GetBoundCentre();

				if (Abs(ped->GetPosition().z - carCentre.z) < 2.0f) {
					float dist = (ped->GetPosition() - carCentre).Magnitude2D();
					if (dist <= 10.0f && !CCranes::IsThisCarBeingCarriedByAnyCrane(car)) {
						EvaluateCarPosition(car, ped, dist, lastCloseness, closestCarOutput);
					}
				}
			}
		}
	}
}

// lastCloseness is passed to other calls of this function
void
CPlayerInfo::EvaluateCarPosition(CEntity *carToTest, CPed *player, float carBoundCentrePedDist, float *lastCloseness, CVehicle **closestCarOutput)
{
	// This dist used for determining the angle to face
	CVector2D dist(carToTest->GetPosition() - player->GetPosition());
	float neededTurn = CGeneral::GetATanOfXY(player->GetForward().x, player->GetForward().y) - CGeneral::GetATanOfXY(dist.x, dist.y);
	while (neededTurn >= PI) {
		neededTurn -= 2 * PI;
	}

	while (neededTurn < -PI) {
		neededTurn += 2 * PI;
	}

	// This dist used for evaluating cars' distances, weird...
	// Accounts inverted needed turn (or needed turn in long way) and car dist.
	float closeness = (1.0f - Abs(neededTurn) / TWOPI) * (10.0f - carBoundCentrePedDist);
	if (closeness > *lastCloseness) {
		*lastCloseness = closeness;
		*closestCarOutput = (CVehicle*)carToTest;
	}
}

const CVector &
CPlayerInfo::GetPos()
{
#ifdef FIX_BUGS
	if (!m_pPed)
		return TheCamera.GetPosition();
#endif
	if (m_pPed->InVehicle())
		return m_pPed->m_pMyVehicle->GetPosition();
	return m_pPed->GetPosition();
}

CVector
FindPlayerCoors(void)
{
#ifdef FIX_BUGS
	if (CReplay::IsPlayingBack())
		return TheCamera.GetPosition();
#endif
	CPlayerPed *ped = FindPlayerPed();
	if(ped->InVehicle())
		return ped->m_pMyVehicle->GetPosition();
	else
		return ped->GetPosition();
}

const CVector &
FindPlayerSpeed(void)
{
#ifdef FIX_BUGS
	static CVector vecTmpVector(0.0f, 0.0f, 0.0f);
	if (CReplay::IsPlayingBack())
		return vecTmpVector;
#endif
	CPlayerPed *ped = FindPlayerPed();
	if(ped->InVehicle())
		return ped->m_pMyVehicle->m_vecMoveSpeed;
	else
		return ped->m_vecMoveSpeed;
}

CVehicle *
FindPlayerVehicle(void)
{
	CPlayerPed *ped = FindPlayerPed();
	if(ped && ped->InVehicle()) return ped->m_pMyVehicle;
	return nil;
}

CEntity *
FindPlayerEntity(void)
{
	CPlayerPed *ped = FindPlayerPed();
	if(ped->InVehicle())
		return ped->m_pMyVehicle;
	else
		return ped;
}

CVehicle *
FindPlayerTrain(void)
{
	if(FindPlayerVehicle() && FindPlayerVehicle()->IsTrain())
		return FindPlayerVehicle();
	else
		return nil;
}

CPlayerPed *
FindPlayerPed(void)
{
	return CWorld::Players[CWorld::PlayerInFocus].m_pPed;
}

const CVector &
FindPlayerCentreOfWorld(int32 player)
{
#ifdef FIX_BUGS
	if(CReplay::IsPlayingBack()) return TheCamera.GetPosition();
#endif
	if(CCarCtrl::bCarsGeneratedAroundCamera) return TheCamera.GetPosition();
	if(CWorld::Players[player].m_pRemoteVehicle) return CWorld::Players[player].m_pRemoteVehicle->GetPosition();
	if(FindPlayerVehicle()) return FindPlayerVehicle()->GetPosition();
	return CWorld::Players[player].m_pPed->GetPosition();
}

const CVector &
FindPlayerCentreOfWorld_NoSniperShift(void)
{
#ifdef FIX_BUGS
	if (CReplay::IsPlayingBack()) return TheCamera.GetPosition();
#endif
	if(CCarCtrl::bCarsGeneratedAroundCamera) return TheCamera.GetPosition();
	if(CWorld::Players[CWorld::PlayerInFocus].m_pRemoteVehicle)
		return CWorld::Players[CWorld::PlayerInFocus].m_pRemoteVehicle->GetPosition();
	if(FindPlayerVehicle()) return FindPlayerVehicle()->GetPosition();
	return FindPlayerPed()->GetPosition();
}

float
FindPlayerHeading(void)
{
	if(CWorld::Players[CWorld::PlayerInFocus].m_pRemoteVehicle)
		return CWorld::Players[CWorld::PlayerInFocus].m_pRemoteVehicle->GetForward().Heading();
	if(FindPlayerVehicle()) return FindPlayerVehicle()->GetForward().Heading();
	return FindPlayerPed()->GetForward().Heading();
}

bool
CPlayerInfo::IsRestartingAfterDeath()
{
	return m_WBState == WBSTATE_WASTED;
}

bool
CPlayerInfo::IsRestartingAfterArrest()
{
	return m_WBState == WBSTATE_BUSTED;
}

void
CPlayerInfo::KillPlayer()
{
	if (m_WBState != WBSTATE_PLAYING) return;

	m_WBState = WBSTATE_WASTED;
	m_nWBTime = CTimer::GetTimeInMilliseconds();
	CDarkel::ResetOnPlayerDeath();
	CMessages::AddBigMessage(TheText.Get("DEAD"), 4000, 2);
	CStats::TimesDied++;
}

void
CPlayerInfo::ArrestPlayer()
{
	if (m_WBState != WBSTATE_PLAYING) return;

	m_WBState = WBSTATE_BUSTED;
	m_nWBTime = CTimer::GetTimeInMilliseconds();
	CDarkel::ResetOnPlayerDeath();
	CMessages::AddBigMessage(TheText.Get("BUSTED"), 5000, 2);
	CStats::TimesArrested++;
}

void
CPlayerInfo::PlayerFailedCriticalMission()
{
	if (m_WBState != WBSTATE_PLAYING)
		return;
	m_WBState = WBSTATE_FAILED_CRITICAL_MISSION;
	m_nWBTime = CTimer::GetTimeInMilliseconds();
	CDarkel::ResetOnPlayerDeath();
}

void
CPlayerInfo::CancelPlayerEnteringCars(CVehicle *car)
{
	if (!car || car == m_pPed->m_pMyVehicle) {
		if (m_pPed->EnteringCar())
			m_pPed->QuitEnteringCar();
	}
	if (m_pPed->m_objective == OBJECTIVE_ENTER_CAR_AS_PASSENGER || m_pPed->m_objective == OBJECTIVE_ENTER_CAR_AS_DRIVER)
		m_pPed->ClearObjective();
}

void
CPlayerInfo::MakePlayerSafe(bool toggle)
{
	if (toggle) {
		CTheScripts::ResetCountdownToMakePlayerUnsafe();
		m_pPed->m_pWanted->m_bIgnoredByEveryone = true;
		CWorld::StopAllLawEnforcersInTheirTracks();
		CPad::GetPad(0)->SetDisablePlayerControls(PLAYERCONTROL_PLAYERINFO);
		CPad::StopPadsShaking();
		m_pPed->bBulletProof = true;
		m_pPed->bFireProof = true;
		m_pPed->bCollisionProof = true;
		m_pPed->bMeleeProof = true;
		m_pPed->bOnlyDamagedByPlayer = true;
		m_pPed->bExplosionProof = true;
		m_pPed->m_bCanBeDamaged = false;
		((CPlayerPed*)m_pPed)->ClearAdrenaline();
		CancelPlayerEnteringCars(nil);
		gFireManager.ExtinguishPoint(GetPos(), 4000.0f);
		CExplosion::RemoveAllExplosionsInArea(GetPos(), 4000.0f);
		CProjectileInfo::RemoveAllProjectiles();
		CWorld::SetAllCarsCanBeDamaged(false);
		CWorld::ExtinguishAllCarFiresInArea(GetPos(), 4000.0f);
		CReplay::DisableReplays();

	} else if (!CGame::playingIntro && !CTheScripts::IsCountdownToMakePlayerUnsafeOn()) {
		m_pPed->m_pWanted->m_bIgnoredByEveryone = false;
		CPad::GetPad(0)->SetEnablePlayerControls(PLAYERCONTROL_PLAYERINFO);
		m_pPed->bBulletProof = false;
		m_pPed->bFireProof = false;
		m_pPed->bCollisionProof = false;
		m_pPed->bMeleeProof = false;
		m_pPed->bOnlyDamagedByPlayer = false;
		m_pPed->bExplosionProof = false;
		m_pPed->m_bCanBeDamaged = true;
		CWorld::SetAllCarsCanBeDamaged(true);
		CReplay::EnableReplays();
	}
}

void
CPlayerInfo::BlowUpRCBuggy(void)
{
	if (!m_pRemoteVehicle || m_pRemoteVehicle->bRemoveFromWorld)
		return;

	CRemote::TakeRemoteControlledCarFromPlayer();
	m_pRemoteVehicle->BlowUpCar(FindPlayerPed());
}

// There is something unfinished in here... Sadly all IDBs we have have it unfinished.
void
CPlayerInfo::AwardMoneyForExplosion(CVehicle *wreckedCar)
{
	if (CTimer::GetTimeInMilliseconds() - m_nPreviousTimeRewardedForExplosion < 6000)
		++m_nExplosionsSinceLastReward;
	else
		m_nExplosionsSinceLastReward = 1;

	m_nPreviousTimeRewardedForExplosion = CTimer::GetTimeInMilliseconds();
	int award = wreckedCar->pHandling->nMonetaryValue * 0.002f;
	sprintf(gString, "$%d", award);
#ifdef MONEY_MESSAGES
	// This line is a leftover from PS2, I don't know what it was meant to be.
	// CVector sth(TheCamera.GetPosition() * 4.0f);

	CMoneyMessages::RegisterOne(wreckedCar->GetPosition() + CVector(0.0f, 0.0f, 2.0f), gString, 0, 255, 0, 2.0f, 0.5f);
#endif
	CWorld::Players[CWorld::PlayerInFocus].m_nMoney += award;

	for (int i = m_nExplosionsSinceLastReward; i > 1; --i) {
		CGeneral::GetRandomNumber();
		CWorld::Players[CWorld::PlayerInFocus].m_nMoney += award;
	}
}

#ifdef GTA_PC
void
CPlayerInfo::SetPlayerSkin(const char *skin)
{
	strncpy(m_aSkinName, skin, 32);
	LoadPlayerSkin();
}

void
CPlayerInfo::LoadPlayerSkin()
{
	DeletePlayerSkin();

	m_pSkinTexture = CPlayerSkin::GetSkinTexture(m_aSkinName);
	if (!m_pSkinTexture)
		m_pSkinTexture = CPlayerSkin::GetSkinTexture(DEFAULT_SKIN_NAME);
}

void
CPlayerInfo::DeletePlayerSkin()
{
	if (m_pSkinTexture) {
		RwTextureDestroy(m_pSkinTexture);
		m_pSkinTexture = nil;
	}
}
#endif


code:
#pragma once

#include "ColModel.h"

enum eWastedBustedState
{
	WBSTATE_PLAYING,
	WBSTATE_WASTED,
	WBSTATE_BUSTED,
	WBSTATE_FAILED_CRITICAL_MISSION,
};

class CEntity;
class CPed;
class CVehicle;
class CPlayerPed;
class CCivilianPed;

class CPlayerInfo
{
public:
	CPlayerPed *m_pPed;
	CVehicle *m_pRemoteVehicle;
	CColModel m_ColModel;
	CVehicle *m_pVehicleEx;	// vehicle using the col model above
	char m_aPlayerName[70];
	int32 m_nMoney;
	int32 m_nVisibleMoney;
	int32 m_nCollectedPackages;
	int32 m_nTotalPackages;
	uint32 m_nLastBumpPlayerCarTimer;
	uint32 m_nUnusedTaxiTimer;
	bool m_bUnusedTaxiThing;
	uint32 m_nNextSexFrequencyUpdateTime;
	uint32 m_nNextSexMoneyUpdateTime;
	int32 m_nSexFrequency;
	CCivilianPed *m_pHooker;
	int8 m_WBState; // eWastedBustedState
	uint32 m_nWBTime;
	bool m_bInRemoteMode;
	uint32 m_nTimeLostRemoteCar;
	uint32 m_nTimeLastHealthLoss;
	uint32 m_nTimeLastArmourLoss;
	uint32 m_nTimeTankShotGun;
	int32 m_nUpsideDownCounter;
	int32 field_248;
	int16 m_nTrafficMultiplier;
	float m_fRoadDensity;
	uint32 m_nPreviousTimeRewardedForExplosion;
	int32 m_nExplosionsSinceLastReward;
	int32 field_268;
	int32 field_272;
	bool m_bInfiniteSprint;
	bool m_bFastReload;
	bool m_bGetOutOfJailFree;
	bool m_bGetOutOfHospitalFree;
#ifdef GTA_PC
	char m_aSkinName[32];
	RwTexture *m_pSkinTexture;
#endif

	void MakePlayerSafe(bool);
	void AwardMoneyForExplosion(CVehicle *vehicle);
	const CVector &GetPos();
	void Process(void);
	void KillPlayer(void);
	void ArrestPlayer(void);
	bool IsPlayerInRemoteMode(void);
	void PlayerFailedCriticalMission(void);
	void Clear(void);
	void BlowUpRCBuggy(void);
	void CancelPlayerEnteringCars(CVehicle*);
	bool IsRestartingAfterDeath(void);
	bool IsRestartingAfterArrest(void);
	void EvaluateCarPosition(CEntity*, CPed*, float, float*, CVehicle**);
	void LoadPlayerInfo(uint8 *buf, uint32 size);
	void SavePlayerInfo(uint8 *buf, uint32* size);
	void FindClosestCarSectorList(CPtrList&, CPed*, float, float, float, float, float*, CVehicle**);

#ifdef GTA_PC
	void LoadPlayerSkin();
	void SetPlayerSkin(const char *skin);
	void DeletePlayerSkin();
#endif
};

CPlayerPed *FindPlayerPed(void);
CVehicle *FindPlayerVehicle(void);
CVehicle *FindPlayerTrain(void);
CEntity *FindPlayerEntity(void);
CVector FindPlayerCoors(void);
const CVector &FindPlayerSpeed(void);
const CVector &FindPlayerCentreOfWorld(int32 player);
const CVector &FindPlayerCentreOfWorld_NoSniperShift(void);
float FindPlayerHeading(void);

VALIDATE_SIZE(CPlayerInfo, 0x13C);


code:
#include "common.h"

#include "Pools.h"

#include "Boat.h"
#include "CarCtrl.h"
#ifdef MISSION_REPLAY
#include "GenericGameStorage.h"
#endif
#include "Population.h"
#include "ProjectileInfo.h"
#include "SaveBuf.h"
#include "Streaming.h"
#include "Wanted.h"
#include "World.h"
#include "MemoryHeap.h"

CCPtrNodePool *CPools::ms_pPtrNodePool;
CEntryInfoNodePool *CPools::ms_pEntryInfoNodePool;
CPedPool *CPools::ms_pPedPool;
CVehiclePool *CPools::ms_pVehiclePool;
CBuildingPool *CPools::ms_pBuildingPool;
CTreadablePool *CPools::ms_pTreadablePool;
CObjectPool *CPools::ms_pObjectPool;
CDummyPool *CPools::ms_pDummyPool;
CAudioScriptObjectPool *CPools::ms_pAudioScriptObjectPool;

#ifdef GTA_PS2	// or USE_CUSTOM_ALLOCATOR
#define CHECKMEM(msg) CMemCheck::AllocateMemCheckBlock(msg)
#else
#define CHECKMEM(msg)
#endif

void
CPools::Initialise(void)
{
	PUSH_MEMID(MEMID_POOLS);
	CHECKMEM("before pools");
	ms_pPtrNodePool = new CCPtrNodePool(NUMPTRNODES);
	CHECKMEM("after CPtrNodePool");
	ms_pEntryInfoNodePool = new CEntryInfoNodePool(NUMENTRYINFOS);
	CHECKMEM("after CEntryInfoNodePool");
	ms_pPedPool = new CPedPool(NUMPEDS);
	CHECKMEM("after CPedPool");
	ms_pVehiclePool = new CVehiclePool(NUMVEHICLES);
	CHECKMEM("after CVehiclePool");
	ms_pBuildingPool = new CBuildingPool(NUMBUILDINGS);
	CHECKMEM("after CBuildingPool");
	ms_pTreadablePool = new CTreadablePool(NUMTREADABLES);
	CHECKMEM("after CTreadablePool");
	ms_pObjectPool = new CObjectPool(NUMOBJECTS);
	CHECKMEM("after CObjectPool");
	ms_pDummyPool = new CDummyPool(NUMDUMMIES);
	CHECKMEM("after CDummyPool");
	ms_pAudioScriptObjectPool = new CAudioScriptObjectPool(NUMAUDIOSCRIPTOBJECTS);
	CHECKMEM("after pools");
	POP_MEMID();
}

void
CPools::ShutDown(void)
{
	debug("PtrNodes left %d\n", ms_pPtrNodePool->GetNoOfUsedSpaces());
	debug("EntryInfoNodes left %d\n", ms_pEntryInfoNodePool->GetNoOfUsedSpaces());
	debug("Peds left %d\n", ms_pPedPool->GetNoOfUsedSpaces());
	debug("Vehicles left %d\n", ms_pVehiclePool->GetNoOfUsedSpaces());
	debug("Buildings left %d\n", ms_pBuildingPool->GetNoOfUsedSpaces());
	debug("Treadables left %d\n", ms_pTreadablePool->GetNoOfUsedSpaces());
	debug("Objects left %d\n", ms_pObjectPool->GetNoOfUsedSpaces());
	debug("Dummys left %d\n", ms_pDummyPool->GetNoOfUsedSpaces());
	debug("AudioScriptObjects left %d\n", ms_pAudioScriptObjectPool->GetNoOfUsedSpaces());
	printf("Shutdown pool started\n");

	delete ms_pPtrNodePool;
	delete ms_pEntryInfoNodePool;
	delete ms_pPedPool;
	delete ms_pVehiclePool;
	delete ms_pBuildingPool;
	delete ms_pTreadablePool;
	delete ms_pObjectPool;
	delete ms_pDummyPool;
	delete ms_pAudioScriptObjectPool;

	printf("Shutdown pool done\n");
}

int32 CPools::GetPedRef(CPed *ped) { return ms_pPedPool->GetIndex(ped); }
CPed *CPools::GetPed(int32 handle) { return ms_pPedPool->GetAt(handle); }
int32 CPools::GetVehicleRef(CVehicle *vehicle) { return ms_pVehiclePool->GetIndex(vehicle); }
CVehicle *CPools::GetVehicle(int32 handle) { return ms_pVehiclePool->GetAt(handle); }
int32 CPools::GetObjectRef(CObject *object) { return ms_pObjectPool->GetIndex(object); }
CObject *CPools::GetObject(int32 handle) { return ms_pObjectPool->GetAt(handle); }

void
CPools::CheckPoolsEmpty()
{
	assert(ms_pPedPool->GetNoOfUsedSpaces() == 0);
	assert(ms_pVehiclePool->GetNoOfUsedSpaces() == 0);
	printf("pools have been cleared\n");
}

void
CPools::MakeSureSlotInObjectPoolIsEmpty(int32 slot)
{
	if (ms_pObjectPool->GetIsFree(slot)) return;

	CObject *object = ms_pObjectPool->GetSlot(slot);
	if (object->ObjectCreatedBy == TEMP_OBJECT) {
		CWorld::Remove(object);
		delete object;
	} else if (!CProjectileInfo::RemoveIfThisIsAProjectile(object)) {
		// relocate to another slot??
		CObject *newObject = new CObject(object->GetModelIndex(), false);
		CWorld::Remove(object);
#if 0 // todo better
		*newObject = *object;
#else
		memcpy(newObject, object, ms_pObjectPool->GetMaxEntrySize());
#endif
		CWorld::Add(newObject);
		object->m_rwObject = nil;
		delete object;
		newObject->m_pFirstReference = nil;
	}
}

#define CopyFromBuf(buf, data) memcpy(&data, buf, sizeof(data)); SkipSaveBuf(buf, sizeof(data));
#define CopyToBuf(buf, data) memcpy(buf, &data, sizeof(data)); SkipSaveBuf(buf, sizeof(data));

void CPools::LoadVehiclePool(uint8* buf, uint32 size)
{
INITSAVEBUF
	int nNumCars, nNumBoats;
	ReadSaveBuf(&nNumCars, buf);
	ReadSaveBuf(&nNumBoats, buf);
	for (int i = 0; i < nNumCars + nNumBoats; i++) {
		uint32 type;
		int16 model;
		int32 slot;

		ReadSaveBuf(&type, buf);
		ReadSaveBuf(&model, buf);
		CStreaming::RequestModel(model, STREAMFLAGS_DEPENDENCY);
		CStreaming::LoadAllRequestedModels(false);
		ReadSaveBuf(&slot, buf);
		CVehicle* pVehicle;
#ifdef COMPATIBLE_SAVES
		if (type == VEHICLE_TYPE_BOAT)
			pVehicle = new(slot) CBoat(model, RANDOM_VEHICLE);
		else if (type == VEHICLE_TYPE_CAR)
			pVehicle = new(slot) CAutomobile(model, RANDOM_VEHICLE);
		else
			assert(0);
		--CCarCtrl::NumRandomCars;
		pVehicle->Load(buf);
		CWorld::Add(pVehicle);
#else
		char* vbuf = new char[Max(CAutomobile::nSaveStructSize, CBoat::nSaveStructSize)];
		if (type == VEHICLE_TYPE_BOAT) {
			memcpy(vbuf, buf, sizeof(CBoat));
			SkipSaveBuf(buf, sizeof(CBoat));
			CBoat* pBoat = new(slot) CBoat(model, RANDOM_VEHICLE);
			pVehicle = pBoat;
			--CCarCtrl::NumRandomCars;
		}
		else if (type == VEHICLE_TYPE_CAR) {
			memcpy(vbuf, buf, sizeof(CAutomobile));
			SkipSaveBuf(buf, sizeof(CAutomobile));
			CStreaming::RequestModel(model, 0); // is it needed?
			CStreaming::LoadAllRequestedModels(false);
			CAutomobile* pAutomobile = new(slot) CAutomobile(model, RANDOM_VEHICLE);
			pVehicle = pAutomobile;
			CCarCtrl::NumRandomCars--; // why?
			pAutomobile->Damage = ((CAutomobile*)vbuf)->Damage;
			pAutomobile->SetupDamageAfterLoad();
		}
		else
			assert(0);
		CVehicle* pBufferVehicle = (CVehicle*)vbuf;
		pVehicle->GetMatrix() = pBufferVehicle->GetMatrix();
		pVehicle->VehicleCreatedBy = pBufferVehicle->VehicleCreatedBy;
		pVehicle->m_currentColour1 = pBufferVehicle->m_currentColour1;
		pVehicle->m_currentColour2 = pBufferVehicle->m_currentColour2;
		pVehicle->m_nAlarmState = pBufferVehicle->m_nAlarmState;
		pVehicle->m_nNumMaxPassengers = pBufferVehicle->m_nNumMaxPassengers;
		pVehicle->field_1D0[0] = pBufferVehicle->field_1D0[0];
		pVehicle->field_1D0[1] = pBufferVehicle->field_1D0[1];
		pVehicle->field_1D0[2] = pBufferVehicle->field_1D0[2];
		pVehicle->field_1D0[3] = pBufferVehicle->field_1D0[3];
		pVehicle->m_fSteerAngle = pBufferVehicle->m_fSteerAngle;
		pVehicle->m_fGasPedal = pBufferVehicle->m_fGasPedal;
		pVehicle->m_fBrakePedal = pBufferVehicle->m_fBrakePedal;
		pVehicle->bIsLawEnforcer = pBufferVehicle->bIsLawEnforcer;
		pVehicle->bIsLocked = pBufferVehicle->bIsLocked;
		pVehicle->bEngineOn = pBufferVehicle->bEngineOn;
		pVehicle->bIsHandbrakeOn = pBufferVehicle->bIsHandbrakeOn;
		pVehicle->bLightsOn = pBufferVehicle->bLightsOn;
		pVehicle->bFreebies = pBufferVehicle->bFreebies;
		pVehicle->m_fHealth = pBufferVehicle->m_fHealth;
		pVehicle->m_nCurrentGear = pBufferVehicle->m_nCurrentGear;
		pVehicle->m_fChangeGearTime = pBufferVehicle->m_fChangeGearTime;
		pVehicle->m_nTimeOfDeath = pBufferVehicle->m_nTimeOfDeath;
#ifdef FIX_BUGS //must be copypaste
		pVehicle->m_nBombTimer = pBufferVehicle->m_nBombTimer;
#else
		pVehicle->m_nTimeOfDeath = pBufferVehicle->m_nTimeOfDeath;
#endif
		pVehicle->m_nDoorLock = pBufferVehicle->m_nDoorLock;
		pVehicle->SetStatus(pBufferVehicle->GetStatus());
		pVehicle->SetType(pBufferVehicle->GetType());
		(pVehicle->GetAddressOfEntityProperties())[0] = (pBufferVehicle->GetAddressOfEntityProperties())[0];
		(pVehicle->GetAddressOfEntityProperties())[1] = (pBufferVehicle->GetAddressOfEntityProperties())[1];
		pVehicle->AutoPilot = pBufferVehicle->AutoPilot;
		CWorld::Add(pVehicle);
		delete[] vbuf;
#endif
	}
VALIDATESAVEBUF(size)
}

void CPools::SaveVehiclePool(uint8* buf, uint32* size)
{
INITSAVEBUF
	int nNumCars = 0;
	int nNumBoats = 0;
	int nPoolSize = GetVehiclePool()->GetSize();
	for (int i = 0; i < nPoolSize; i++) {
		CVehicle* pVehicle = GetVehiclePool()->GetSlot(i);
		if (!pVehicle)
			continue;
		bool bHasPassenger = false;
		for (int j = 0; j < ARRAY_SIZE(pVehicle->pPassengers); j++) {
			if (pVehicle->pPassengers[j])
				bHasPassenger = true;
		}
#ifdef MISSION_REPLAY
		bool bForceSaving = CWorld::Players[CWorld::PlayerInFocus].m_pPed->m_pMyVehicle == pVehicle && IsQuickSave;
#ifdef FIX_BUGS
		if ((!pVehicle->pDriver && !bHasPassenger) || bForceSaving) {
#else
		if (!pVehicle->pDriver && !bHasPassenger) {
#endif
			if (pVehicle->IsCar() && (pVehicle->VehicleCreatedBy == MISSION_VEHICLE || bForceSaving))
				++nNumCars;
			if (pVehicle->IsBoat() && (pVehicle->VehicleCreatedBy == MISSION_VEHICLE || bForceSaving))
				++nNumBoats;
#else
		if (!pVehicle->pDriver && !bHasPassenger) {
			if (pVehicle->IsCar() && pVehicle->VehicleCreatedBy == MISSION_VEHICLE)
				++nNumCars;
			if (pVehicle->IsBoat() && pVehicle->VehicleCreatedBy == MISSION_VEHICLE)
				++nNumBoats;
#endif
		}
	}
	*size = nNumCars * (sizeof(uint32) + sizeof(int16) + sizeof(int32) + CAutomobile::nSaveStructSize) + sizeof(int) +
		nNumBoats * (sizeof(uint32) + sizeof(int16) + sizeof(int32) + CBoat::nSaveStructSize) + sizeof(int);
	WriteSaveBuf(buf, nNumCars);
	WriteSaveBuf(buf, nNumBoats);
	for (int i = 0; i < nPoolSize; i++) {
		CVehicle* pVehicle = GetVehiclePool()->GetSlot(i);
		if (!pVehicle)
			continue;
		bool bHasPassenger = false;
		for (int j = 0; j < ARRAY_SIZE(pVehicle->pPassengers); j++) {
			if (pVehicle->pPassengers[j])
				bHasPassenger = true;
		}
#ifdef MISSION_REPLAY
		bool bForceSaving = CWorld::Players[CWorld::PlayerInFocus].m_pPed->m_pMyVehicle == pVehicle && IsQuickSave;
#endif
#if defined FIX_BUGS && defined MISSION_REPLAY
		if ((!pVehicle->pDriver && !bHasPassenger) || bForceSaving) {
#else
		if (!pVehicle->pDriver && !bHasPassenger) {
#endif
#ifdef COMPATIBLE_SAVES
#ifdef MISSION_REPLAY
			if ((pVehicle->IsCar() || pVehicle->IsBoat()) && (pVehicle->VehicleCreatedBy == MISSION_VEHICLE || bForceSaving)) {
#else
			if ((pVehicle->IsCar() || pVehicle->IsBoat()) && pVehicle->VehicleCreatedBy == MISSION_VEHICLE) {
#endif
				WriteSaveBuf(buf, pVehicle->m_vehType);
				WriteSaveBuf(buf, pVehicle->GetModelIndex());
				WriteSaveBuf(buf, GetVehicleRef(pVehicle));
				pVehicle->Save(buf);
			}
#else
#ifdef MISSION_REPLAY
			if (pVehicle->IsCar() && (pVehicle->VehicleCreatedBy == MISSION_VEHICLE || bForceSaving)) {
#else
			if (pVehicle->IsCar() && pVehicle->VehicleCreatedBy == MISSION_VEHICLE) {
#endif
				WriteSaveBuf(buf, pVehicle->m_vehType);
				WriteSaveBuf(buf, pVehicle->GetModelIndex());
				WriteSaveBuf(buf, GetVehicleRef(pVehicle));
				memcpy(buf, pVehicle, sizeof(CAutomobile));
				SkipSaveBuf(buf, sizeof(CAutomobile));
			}
#ifdef MISSION_REPLAY
			if (pVehicle->IsBoat() && (pVehicle->VehicleCreatedBy == MISSION_VEHICLE || bForceSaving)) {
#else
			if (pVehicle->IsBoat() && pVehicle->VehicleCreatedBy == MISSION_VEHICLE) {
#endif
				WriteSaveBuf(buf, pVehicle->m_vehType);
				WriteSaveBuf(buf, pVehicle->GetModelIndex());
				WriteSaveBuf(buf, GetVehicleRef(pVehicle));
				memcpy(buf, pVehicle, sizeof(CBoat));
				SkipSaveBuf(buf, sizeof(CBoat));
			}
#endif
		}
	}
VALIDATESAVEBUF(*size)
}

void CPools::SaveObjectPool(uint8* buf, uint32* size)
{
INITSAVEBUF
	CProjectileInfo::RemoveAllProjectiles();
	CObject::DeleteAllTempObjects();
	int nObjects = 0;
	int nPoolSize = GetObjectPool()->GetSize();
	for (int i = 0; i < nPoolSize; i++) {
		CObject* pObject = GetObjectPool()->GetSlot(i);
		if (!pObject)
			continue;
		if (pObject->ObjectCreatedBy == MISSION_OBJECT)
			++nObjects;
	}
	*size = nObjects * (sizeof(int16) + sizeof(int) + sizeof(CCompressedMatrix) +
		sizeof(float) + sizeof(CCompressedMatrix) + sizeof(int8) + 7 * sizeof(bool) + sizeof(float) +
		sizeof(int8) + sizeof(int8) + sizeof(uint32) + 2 * sizeof(uint32)) + sizeof(int);
	CopyToBuf(buf, nObjects);
	for (int i = 0; i < nPoolSize; i++) {
		CObject* pObject = GetObjectPool()->GetSlot(i);
		if (!pObject)
			continue;
		if (pObject->ObjectCreatedBy == MISSION_OBJECT) {
			bool bIsPickup = pObject->bIsPickup;
			bool bPickupObjWithMessage = pObject->bPickupObjWithMessage;
			bool bOutOfStock = pObject->bOutOfStock;
			bool bGlassCracked = pObject->bGlassCracked;
			bool bGlassBroken = pObject->bGlassBroken;
			bool bHasBeenDamaged = pObject->bHasBeenDamaged;
			bool bUseVehicleColours = pObject->bUseVehicleColours;
			CCompressedMatrix tmp;
			CopyToBuf(buf, pObject->m_modelIndex);
			int32 ref = GetObjectRef(pObject);
			CopyToBuf(buf, ref);
			tmp.CompressFromFullMatrix(pObject->GetMatrix());
			CopyToBuf(buf, tmp);
			CopyToBuf(buf, pObject->m_fUprootLimit);
			tmp.CompressFromFullMatrix(pObject->m_objectMatrix);
			CopyToBuf(buf, tmp);
			CopyToBuf(buf, pObject->ObjectCreatedBy);
			CopyToBuf(buf, bIsPickup);
			CopyToBuf(buf, bPickupObjWithMessage);
			CopyToBuf(buf, bOutOfStock);
			CopyToBuf(buf, bGlassCracked);
			CopyToBuf(buf, bGlassBroken);
			CopyToBuf(buf, bHasBeenDamaged);
			CopyToBuf(buf, bUseVehicleColours);
			CopyToBuf(buf, pObject->m_fCollisionDamageMultiplier);
			CopyToBuf(buf, pObject->m_nCollisionDamageEffect);
			CopyToBuf(buf, pObject->m_nSpecialCollisionResponseCases);
			CopyToBuf(buf, pObject->m_nEndOfLifeTime);
#ifdef COMPATIBLE_SAVES
			pObject->SaveEntityFlags(buf);
#else
			CopyToBuf(buf, (pObject->GetAddressOfEntityProperties())[0]);
			CopyToBuf(buf, (pObject->GetAddressOfEntityProperties())[1]);
#endif
		}
	}
VALIDATESAVEBUF(*size)
}

void CPools::LoadObjectPool(uint8* buf, uint32 size)
{
INITSAVEBUF
	int nObjects;
	CopyFromBuf(buf, nObjects);
	for (int i = 0; i < nObjects; i++) {
		int16 mi;
		CopyFromBuf(buf, mi);
		int ref;
		CopyFromBuf(buf, ref);
		char* obuf = new char[sizeof(CObject)];
		CObject* pBufferObject = (CObject*)obuf;
		CCompressedMatrix tmp;
		CopyFromBuf(buf, tmp);
		tmp.DecompressIntoFullMatrix(pBufferObject->GetMatrix());
		CopyFromBuf(buf, pBufferObject->m_fUprootLimit);
		CopyFromBuf(buf, tmp);
		tmp.DecompressIntoFullMatrix(pBufferObject->m_objectMatrix);
		CopyFromBuf(buf, pBufferObject->ObjectCreatedBy);
		int8 bitFlag;
		CopyFromBuf(buf, bitFlag);
		pBufferObject->bIsPickup = bitFlag;
		CopyFromBuf(buf, bitFlag);
		pBufferObject->bPickupObjWithMessage = bitFlag;
		CopyFromBuf(buf, bitFlag);
		pBufferObject->bOutOfStock = bitFlag;
		CopyFromBuf(buf, bitFlag);
		pBufferObject->bGlassCracked = bitFlag;
		CopyFromBuf(buf, bitFlag);
		pBufferObject->bGlassBroken = bitFlag;
		CopyFromBuf(buf, bitFlag);
		pBufferObject->bHasBeenDamaged = bitFlag;
		CopyFromBuf(buf, bitFlag);
		pBufferObject->bUseVehicleColours = bitFlag;
		CopyFromBuf(buf, pBufferObject->m_fCollisionDamageMultiplier);
		CopyFromBuf(buf, pBufferObject->m_nCollisionDamageEffect);
		CopyFromBuf(buf, pBufferObject->m_nSpecialCollisionResponseCases);
		CopyFromBuf(buf, pBufferObject->m_nEndOfLifeTime);
#ifndef COMPATIBLE_SAVES
		CopyFromBuf(buf, (pBufferObject->GetAddressOfEntityProperties())[0]);
		CopyFromBuf(buf, (pBufferObject->GetAddressOfEntityProperties())[1]);
#endif
		if (GetObjectPool()->GetSlot(ref >> 8))
			CPopulation::ConvertToDummyObject(GetObjectPool()->GetSlot(ref >> 8));
		CObject* pObject = new(ref) CObject(mi, false);
		pObject->GetMatrix() = pBufferObject->GetMatrix();
#ifdef COMPATIBLE_SAVES
		pObject->LoadEntityFlags(buf);
#endif
		pObject->m_fUprootLimit = pBufferObject->m_fUprootLimit;
		pObject->m_objectMatrix = pBufferObject->m_objectMatrix;
		pObject->ObjectCreatedBy = pBufferObject->ObjectCreatedBy;
		pObject->bIsPickup = pBufferObject->bIsPickup;
		pObject->bPickupObjWithMessage = pBufferObject->bPickupObjWithMessage;
		pObject->bOutOfStock = pBufferObject->bOutOfStock;
		pObject->bGlassCracked = pBufferObject->bGlassCracked;
		pObject->bGlassBroken = pBufferObject->bGlassBroken;
		pObject->bHasBeenDamaged = pBufferObject->bHasBeenDamaged;
		pObject->bUseVehicleColours = pBufferObject->bUseVehicleColours;
		pObject->m_fCollisionDamageMultiplier = pBufferObject->m_fCollisionDamageMultiplier;
		pObject->m_nCollisionDamageEffect = pBufferObject->m_nCollisionDamageEffect;
		pObject->m_nSpecialCollisionResponseCases = pBufferObject->m_nSpecialCollisionResponseCases;
		pObject->m_nEndOfLifeTime = pBufferObject->m_nEndOfLifeTime;
#ifndef COMPATIBLE_SAVES
		(pObject->GetAddressOfEntityProperties())[0] = (pBufferObject->GetAddressOfEntityProperties())[0];
		(pObject->GetAddressOfEntityProperties())[1] = (pBufferObject->GetAddressOfEntityProperties())[1];
#endif
		pObject->bHasCollided = false;
		CWorld::Add(pObject);
		delete[] obuf;
	}
VALIDATESAVEBUF(size)
}

void CPools::SavePedPool(uint8* buf, uint32* size)
{
INITSAVEBUF
	int nNumPeds = 0;
	int nPoolSize = GetPedPool()->GetSize();
	for (int i = 0; i < nPoolSize; i++) {
		CPed* pPed = GetPedPool()->GetSlot(i);
		if (!pPed)
			continue;
#ifdef MISSION_REPLAY
		if ((!pPed->bInVehicle || (pPed == CWorld::Players[CWorld::PlayerInFocus].m_pPed && IsQuickSave)) && pPed->m_nPedType == PEDTYPE_PLAYER1)
#else
		if (!pPed->bInVehicle && pPed->m_nPedType == PEDTYPE_PLAYER1)
#endif
			nNumPeds++;
	}
	*size = sizeof(int) + nNumPeds * (sizeof(uint32) + sizeof(int16) + sizeof(int) + CPlayerPed::nSaveStructSize +
		sizeof(CWanted::MaximumWantedLevel) + sizeof(CWanted::nMaximumWantedLevel) + MAX_MODEL_NAME);
	CopyToBuf(buf, nNumPeds);
	for (int i = 0; i < nPoolSize; i++) {
		CPed* pPed = GetPedPool()->GetSlot(i);
		if (!pPed)
			continue;
#ifdef MISSION_REPLAY
		if ((!pPed->bInVehicle || (pPed == CWorld::Players[CWorld::PlayerInFocus].m_pPed && IsQuickSave)) && pPed->m_nPedType == PEDTYPE_PLAYER1) {
#else
		if (!pPed->bInVehicle && pPed->m_nPedType == PEDTYPE_PLAYER1) {
#endif
			CopyToBuf(buf, pPed->m_nPedType);
			CopyToBuf(buf, pPed->m_modelIndex);
			int32 ref = GetPedRef(pPed);
			CopyToBuf(buf, ref);
#ifdef COMPATIBLE_SAVES
			pPed->Save(buf);
#else
			memcpy(buf, pPed, sizeof(CPlayerPed));
			SkipSaveBuf(buf, sizeof(CPlayerPed));
#endif
			CopyToBuf(buf, CWanted::MaximumWantedLevel);
			CopyToBuf(buf, CWanted::nMaximumWantedLevel);
			memcpy(buf, CModelInfo::GetModelInfo(pPed->GetModelIndex())->GetModelName(), MAX_MODEL_NAME);
			SkipSaveBuf(buf, MAX_MODEL_NAME);
		}
	}
VALIDATESAVEBUF(*size);
#undef CopyToBuf
}

void CPools::LoadPedPool(uint8* buf, uint32 size)
{
INITSAVEBUF
	int nPeds;
	CopyFromBuf(buf, nPeds);
	for (int i = 0; i < nPeds; i++) {
		uint32 pedtype;
		int16 model;
		int ref;

		CopyFromBuf(buf, pedtype);
		CopyFromBuf(buf, model);
		CopyFromBuf(buf, ref);
#ifdef COMPATIBLE_SAVES
		CPed* pPed;

		char name[MAX_MODEL_NAME];
		// Unfortunate hack: player model is stored after ped structure.
		// It could be avoided by just using "player" because in practice it is always true.
		memcpy(name, buf + CPlayerPed::nSaveStructSize + 2 * sizeof(int32), MAX_MODEL_NAME);
		CStreaming::RequestSpecialModel(model, name, STREAMFLAGS_DONT_REMOVE);
		CStreaming::LoadAllRequestedModels(false);

		if (pedtype == PEDTYPE_PLAYER1)
			pPed = new(ref) CPlayerPed();
		else
			assert(0);

		pPed->Load(buf);
		if (pedtype == PEDTYPE_PLAYER1) {
			CopyFromBuf(buf, CWanted::MaximumWantedLevel);
			CopyFromBuf(buf, CWanted::nMaximumWantedLevel);
			SkipSaveBuf(buf, MAX_MODEL_NAME);
		}

		if (pedtype == PEDTYPE_PLAYER1) {
			pPed->m_wepAccuracy = 100;
			CWorld::Players[0].m_pPed = (CPlayerPed*)pPed;
		}
		CWorld::Add(pPed);
#else
		char* pbuf = new char[sizeof(CPlayerPed)];
		CPlayerPed* pBufferPlayer = (CPlayerPed*)pbuf;
		CPed* pPed;
		char name[MAX_MODEL_NAME];
		// the code implies that there was idea to load non-player ped
		if (pedtype == PEDTYPE_PLAYER1) { // always true
			memcpy(pbuf, buf, sizeof(CPlayerPed));
			SkipSaveBuf(buf, sizeof(CPlayerPed));
			CopyFromBuf(buf, CWanted::MaximumWantedLevel);
			CopyFromBuf(buf, CWanted::nMaximumWantedLevel);
			CopyFromBuf(buf, name);
		}
		CStreaming::RequestSpecialModel(model, name, STREAMFLAGS_DONT_REMOVE);
		CStreaming::LoadAllRequestedModels(false);
		if (pedtype == PEDTYPE_PLAYER1) {
			CPlayerPed* pPlayerPed = new(ref) CPlayerPed();
			for (int i = 0; i < ARRAY_SIZE(pPlayerPed->m_nTargettableObjects); i++)
				pPlayerPed->m_nTargettableObjects[i] = pBufferPlayer->m_nTargettableObjects[i];
			pPlayerPed->m_fMaxStamina = pBufferPlayer->m_fMaxStamina;
			pPed = pPlayerPed;
		}
		pPed->SetPosition(pBufferPlayer->GetPosition());
		pPed->m_fHealth = pBufferPlayer->m_fHealth;
		pPed->m_fArmour = pBufferPlayer->m_fArmour;
		pPed->CharCreatedBy = pBufferPlayer->CharCreatedBy;
		pPed->m_currentWeapon = 0;
		pPed->m_maxWeaponTypeAllowed = pBufferPlayer->m_maxWeaponTypeAllowed;
		for (int i = 0; i < WEAPONTYPE_TOTAL_INVENTORY_WEAPONS; i++)
			pPed->m_weapons[i] = pBufferPlayer->m_weapons[i];

		if (pedtype == PEDTYPE_PLAYER1) {
			pPed->m_wepAccuracy = 100;
			CWorld::Players[0].m_pPed = (CPlayerPed*)pPed;
		}
		CWorld::Add(pPed);
		delete[] pbuf;
#endif
	}
VALIDATESAVEBUF(size)
}

#undef CopyFromBuf
#undef CopyToBuf


code:
#pragma once

#include "templates.h"
#include "Lists.h"
#include "Treadable.h"
#include "Object.h"
#include "CutsceneHead.h"
#include "PlayerPed.h"
#include "Automobile.h"
#include "DummyPed.h"
#include "AudioScriptObject.h"

typedef CPool<CPtrNode> CCPtrNodePool;
typedef CPool<CEntryInfoNode> CEntryInfoNodePool;
typedef CPool<CPed,CPlayerPed> CPedPool;
typedef CPool<CVehicle,CAutomobile> CVehiclePool;
typedef CPool<CBuilding> CBuildingPool;
typedef CPool<CTreadable> CTreadablePool;
typedef CPool<CObject, CCutsceneHead> CObjectPool;
typedef CPool<CDummy, CDummyPed> CDummyPool;
typedef CPool<cAudioScriptObject> CAudioScriptObjectPool;

class CPools
{
	static CCPtrNodePool *ms_pPtrNodePool;
	static CEntryInfoNodePool *ms_pEntryInfoNodePool;
	static CPedPool *ms_pPedPool;
	static CVehiclePool *ms_pVehiclePool;
	static CBuildingPool *ms_pBuildingPool;
	static CTreadablePool *ms_pTreadablePool;
	static CObjectPool *ms_pObjectPool;
	static CDummyPool *ms_pDummyPool;
	static CAudioScriptObjectPool *ms_pAudioScriptObjectPool;
public:
	static CCPtrNodePool *GetPtrNodePool(void) { return ms_pPtrNodePool; }
	static CEntryInfoNodePool *GetEntryInfoNodePool(void) { return ms_pEntryInfoNodePool; }
	static CPedPool *GetPedPool(void) { return ms_pPedPool; }
	static CVehiclePool *GetVehiclePool(void) { return ms_pVehiclePool; }
	static CBuildingPool *GetBuildingPool(void) { return ms_pBuildingPool; }
	static CTreadablePool *GetTreadablePool(void) { return ms_pTreadablePool; }
	static CObjectPool *GetObjectPool(void) { return ms_pObjectPool; }
	static CDummyPool *GetDummyPool(void) { return ms_pDummyPool; }
	static CAudioScriptObjectPool *GetAudioScriptObjectPool(void) { return ms_pAudioScriptObjectPool; }

	static void Initialise(void);
	static void ShutDown(void);
	static int32 GetPedRef(CPed *ped);
	static CPed *GetPed(int32 handle);
	static int32 GetVehicleRef(CVehicle *vehicle);
	static CVehicle *GetVehicle(int32 handle);
	static int32 GetObjectRef(CObject *object);
	static CObject *GetObject(int32 handle);
	static void CheckPoolsEmpty();
	static void MakeSureSlotInObjectPoolIsEmpty(int32 slot);
	static void LoadObjectPool(uint8 *buf, uint32 size);
	static void LoadPedPool(uint8 *buf, uint32 size);
	static void LoadVehiclePool(uint8 *buf, uint32 size);
	static void SaveObjectPool(uint8 *buf, uint32 *size);
	static void SavePedPool(uint8 *buf, uint32 *size);
	static void SaveVehiclePool(uint8 *buf, uint32 *size);
};


code:
#include "common.h"
#include "Profile.h"

#ifndef MASTER
float CProfile::ms_afStartTime[NUM_PROFILES];
float CProfile::ms_afCumulativeTime[NUM_PROFILES];
float CProfile::ms_afEndTime[NUM_PROFILES];
float CProfile::ms_afMaxEndTime[NUM_PROFILES];
float CProfile::ms_afMaxCumulativeTime[NUM_PROFILES];
Const char *CProfile::ms_pProfileString[NUM_PROFILES];
RwRGBA CProfile::ms_aBarColours[NUM_PROFILES];

void CProfile::Initialise()
{
	ms_afMaxEndTime[PROFILE_FRAME_RATE] = 0.0f;
	ms_afMaxEndTime[PROFILE_PHYSICS] = 0.0f;
	ms_afMaxEndTime[PROFILE_COLLISION] = 0.0f;
	ms_afMaxEndTime[PROFILE_PED_AI] = 0.0f;
	ms_afMaxEndTime[PROFILE_PROCESSING_TIME] = 0.0f;
	ms_afMaxEndTime[PROFILE_RENDERING_TIME] = 0.0f;
	ms_afMaxEndTime[PROFILE_TOTAL] = 0.0f;

	ms_pProfileString[PROFILE_FRAME_RATE] = "Frame rate";
	ms_pProfileString[PROFILE_PHYSICS] = "Physics";
	ms_pProfileString[PROFILE_COLLISION] = "Collision";
	ms_pProfileString[PROFILE_PED_AI] = "Ped AI";
	ms_pProfileString[PROFILE_PROCESSING_TIME] = "Processing time";
	ms_pProfileString[PROFILE_RENDERING_TIME] = "Rendering time";
	ms_pProfileString[PROFILE_TOTAL] = "Total";

	ms_afMaxCumulativeTime[PROFILE_FRAME_RATE] = 0.0f;
	ms_afMaxCumulativeTime[PROFILE_PHYSICS] = 0.0f;
	ms_afMaxCumulativeTime[PROFILE_COLLISION] = 0.0f;
	ms_afMaxCumulativeTime[PROFILE_PED_AI] = 0.0f;
	ms_afMaxCumulativeTime[PROFILE_PROCESSING_TIME] = 0.0f;
	ms_afMaxCumulativeTime[PROFILE_RENDERING_TIME] = 0.0f;
	ms_afMaxCumulativeTime[PROFILE_TOTAL] = 0.0f;

	ms_aBarColours[PROFILE_PHYSICS] = { 0, 127, 255, 255 };
	ms_aBarColours[PROFILE_COLLISION] = { 0, 255, 255, 255 };
	ms_aBarColours[PROFILE_PED_AI] = { 255, 0, 0, 255 };
	ms_aBarColours[PROFILE_PROCESSING_TIME] = { 0, 255, 0, 255 };
	ms_aBarColours[PROFILE_RENDERING_TIME] = { 0, 0, 255, 255 };
	ms_aBarColours[PROFILE_TOTAL] = { 255, 255, 255, 255 };
}

void CProfile::SuspendProfile(eProfile profile)
{
	ms_afEndTime[profile] = -ms_afStartTime[profile];
	ms_afCumulativeTime[profile] -= ms_afStartTime[profile];
}

void CProfile::ShowResults()
{
	ms_afMaxEndTime[PROFILE_FRAME_RATE] = Max(ms_afMaxEndTime[PROFILE_FRAME_RATE], ms_afEndTime[PROFILE_FRAME_RATE]);
	ms_afMaxEndTime[PROFILE_PHYSICS] = Max(ms_afMaxEndTime[PROFILE_PHYSICS], ms_afEndTime[PROFILE_PHYSICS]);
	ms_afMaxEndTime[PROFILE_COLLISION] = Max(ms_afMaxEndTime[PROFILE_COLLISION], ms_afEndTime[PROFILE_COLLISION]);
	ms_afMaxEndTime[PROFILE_PED_AI] = Max(ms_afMaxEndTime[PROFILE_PED_AI], ms_afEndTime[PROFILE_PED_AI]);
	ms_afMaxEndTime[PROFILE_PROCESSING_TIME] = Max(ms_afMaxEndTime[PROFILE_PROCESSING_TIME], ms_afEndTime[PROFILE_PROCESSING_TIME]);
	ms_afMaxEndTime[PROFILE_RENDERING_TIME] = Max(ms_afMaxEndTime[PROFILE_RENDERING_TIME], ms_afEndTime[PROFILE_RENDERING_TIME]);
	ms_afMaxEndTime[PROFILE_TOTAL] = Max(ms_afMaxEndTime[PROFILE_TOTAL], ms_afEndTime[PROFILE_TOTAL]);

	ms_afMaxCumulativeTime[PROFILE_FRAME_RATE] = Max(ms_afMaxCumulativeTime[PROFILE_FRAME_RATE], ms_afCumulativeTime[PROFILE_FRAME_RATE]);
	ms_afMaxCumulativeTime[PROFILE_PHYSICS] = Max(ms_afMaxCumulativeTime[PROFILE_PHYSICS], ms_afCumulativeTime[PROFILE_PHYSICS]);
	ms_afMaxCumulativeTime[PROFILE_COLLISION] = Max(ms_afMaxCumulativeTime[PROFILE_COLLISION], ms_afCumulativeTime[PROFILE_COLLISION]);
	ms_afMaxCumulativeTime[PROFILE_PED_AI] = Max(ms_afMaxCumulativeTime[PROFILE_PED_AI], ms_afCumulativeTime[PROFILE_PED_AI]);
	ms_afMaxCumulativeTime[PROFILE_PROCESSING_TIME] = Max(ms_afMaxCumulativeTime[PROFILE_PROCESSING_TIME], ms_afCumulativeTime[PROFILE_PROCESSING_TIME]);
	ms_afMaxCumulativeTime[PROFILE_RENDERING_TIME] = Max(ms_afMaxCumulativeTime[PROFILE_RENDERING_TIME], ms_afCumulativeTime[PROFILE_RENDERING_TIME]);
	ms_afMaxCumulativeTime[PROFILE_TOTAL] = Max(ms_afMaxCumulativeTime[PROFILE_TOTAL], ms_afCumulativeTime[PROFILE_TOTAL]);
}
#endif


code:
#pragma once

enum eProfile
{
	PROFILE_FRAME_RATE,
	PROFILE_PHYSICS,
	PROFILE_COLLISION,
	PROFILE_PED_AI,
	PROFILE_PROCESSING_TIME,
	PROFILE_RENDERING_TIME,
	PROFILE_TOTAL,
	NUM_PROFILES,
};

class CProfile
{
	static float ms_afStartTime[NUM_PROFILES];
	static float ms_afCumulativeTime[NUM_PROFILES];
	static float ms_afEndTime[NUM_PROFILES];
	static float ms_afMaxEndTime[NUM_PROFILES];
	static float ms_afMaxCumulativeTime[NUM_PROFILES];
	static Const char *ms_pProfileString[NUM_PROFILES];
	static RwRGBA ms_aBarColours[NUM_PROFILES];
public:
	static void Initialise();
	static void SuspendProfile(eProfile profile);
	static void ShowResults();
};