/******************************************************************

  Module: Titan.h

  Author: 

  Description:

  Titan class definition

  Copyright 2005 Sony Online Entertainment.  All rights reserved.

*******************************************************************/

#ifndef __TITAN_H__
#define	__TITAN_H__

/*
**
**	 Forward Declarations
**
*/

class TitanPeeringNetwork;
class TitanInputHandler;
class TitanFXScriptDriver;
class SyFXScriptActorPair;
class cGameObjectRegistry;
class cGameObject;
class cCameraController;
class cDatabaseSys;
class cRuleSys;
class cAnimControllerSys;
class cRuleContainer;
class cInventoryRuleContainer;
class cTuningSys;
class cScriptSys;
class cStatsItemMaster;
class cItem;
class cDebrisSys;
class SyDamageNumMgr;
class T4utf;
class TitanT4File;
class TitanT4OS;
class cDebugOverlay;
class cGameErrorLog;
class SyRand;
class SyString;
class cServiceScheduler;
class cSoundManager;
/**/

/*
**
**	 Includes
**
*/

#include "TitanI.h"
#include "SyString.h"
#include "SyVector.h"
#include "SyPathname.h"

/**/
static const int MAX_CONTROLLERS = 4;
/*
**
**	 Type Definitions
**
*/



class Titan : public TitanI
{
public:
  // Initializes an instance of the Titan class.
  Titan( TitanUII* pTitanUI );
  
  // Destroys an instance of the Titan class.
  virtual ~Titan(void);

  // Allocates resources required by the Titan object.
  virtual bool Init( uint64 time, const SyParameterValidator& parameterValidator );

  // Releases resources acquired by the titan object.
  virtual void Close();

  // Updates the game state to the specified time.
  virtual void AdvanceTime( uint64 time );
  virtual void Update( uint64 time );

  // Updates the game state for props to the specified time - for use with havok stabilization
  virtual void UpdateJustProps( uint64 time );

  // Renders the scene.
  // Scene::BeginScene must be called before this method is invoked.
  // Scene::EndScene must be called after this method is invoked.
  virtual void Render();

  // render the HUD (dev info: performance stats, grid)
  virtual void RenderHUD();

  virtual TitanInputHandlerI* GetInputHandler( int controllerId );

  // use the specified XML file to construct all the initial game objects
  virtual void LoadLevel(const char *xmlFilename);

  // save the binary of the level after physical simulation calms down 
  virtual void SaveLevel(const char8* filePrefix);

  // get the name of the current level
  virtual const char* GetLevelName() const;

  // nudge props
  virtual void NudgeProps();

  // restarts the current level and resets the player
  virtual void Restart();

  // clear out the current level before the next level load
  virtual void Reset();

  // tells it to join the specified existing network game
  // after network game is joined, you don't need to do anything else as all the initial state
  // will come from the peers in the game you are joining
  virtual void NetworkGameJoin(/*gift*/ PeeringNetwork::PeeringServerApi *api, int gameId);

  // tell it to create a new network game (and join it)
  // after the network game is created, you must call LoadXml or LoadSavedGame to populated the newly created game
  virtual void NetworkGameCreate(/*gift*/ PeeringNetwork::PeeringServerApi *api, const char *gameName);

  // this is a temporary hack function to startup a network game until the front-end is completed
  // once the front-end is completed, it will create the PeeringServerApi, do stuff with it, and then
  // pass it off via the NetworkGameJoin or NetworkGameCreate calls
  // This function will join the game with the specified name if it exists, otherwise it will create a game
  // with the specified name using the xmlFilename to setup the initial state of the world
  virtual void HackStartupNetwork(const char *playerName, const char *gameName, const char *xmlFilename, const char *recordFilename, const char *playbackFilename);

  virtual bool IsNetworkGame() { return mbNetworkGame; }

  // enables source level debuggin for Pawn scripting system
  virtual void ScriptEnableDebugging();

   // process cheat key
  virtual void CheatKey(KeyCode key);

  virtual int GetShowWaterInfo();
  virtual int GetShowPlayerAnims();
  virtual void SetFluidLevel( const char * FluidName, float fPercentTarget, float fOverTimeSeconds );
  virtual void SetNumLocalPlayers(int numplayers);
  virtual int  GetNumLocalPlayers();

  // add parameters to the SyParameterValidator that this object is interested in
  virtual void InitParameterValidator( SyParameterValidator* parameterValidator ) const;

  //============================================================================
  // Design Settings
  //============================================================================

  // Sets whether to log combat events and calculations to a file.
  virtual void SetLogMode(bool on);
  virtual bool GetLogMode();

  // Sets whether player is invulnerable or not
  virtual void SetGodMode(bool on);
  virtual bool GetGodMode();

  // Sets whether to log combat events and calculations to a file.
  virtual void SetInvisibleMode(bool on);
  virtual bool GetInvisibleMode();

  // Sets whether player is invulnerable or not
  virtual void SetShowDamageFlash(bool on);
  virtual bool GetShowDamageFlash();

  // Sets whether player is invulnerable or not
  virtual void SetUnlockAllAbilities(bool on);
  virtual bool GetUnlockAllAbilities();

  // Super-Speed mode
  virtual void SetSuperSpeedMode( bool );
  virtual bool GetSuperSpeedMode() const;

  // set whether or not game is paused...
  virtual void PauseGame();
  virtual void UnpauseGame();
  virtual bool IsPaused();

  virtual void SetTimeScale(float scale);
  virtual float GetTimeScale();

  // Gets or sets a value that indicates whether floating debug information is enabled
  virtual bool GetDebugLabel();
  virtual void SetDebugLabel(bool value);

  virtual void OverloadPlayerModel(const char *modelname);

  // Gets or sets a value that indicates whether floating debug information is enabled
  virtual bool GetPvPEnabled() { return mbPvPEnabled; }
  virtual void SetPvPEnabled(bool value) {mbPvPEnabled = value;}

  // Warp to a new level
  virtual void SetTransitionLevel(const char *newlevel,const char *markername);
  virtual bool IsTransitionLevelSet() const { return( mbTransitionLevelSet ); }

  virtual void ReverseCamera(bool bReverse) const;

  //============================================================================
  // Player Inventory
  //============================================================================

  virtual int           InventoryGetItemCount( int player );
  virtual bool          InventoryGetItemInfo(int player, int item, TiCharacterItemInfo* pInfo);
  void                  InventoryGetItemSpriteAndSlot (int player, int item, int& spriteHandle, int& slotId);
  virtual int           InventoryGetEquipSlot( int player, int item );
  virtual bool          InventoryIsEquipped( int player, int item );
  virtual bool          InventoryEquip( int player, int item );
  virtual void          InventoryUnequip( int player, int item );
  virtual bool          InventoryDrop( int player, int item );
  virtual bool			InventoryGetIsEnhancementValidInSlot( int player, int item, int slot );
  virtual int           InventoryGetEnhancementSlotType (int player, int item);
  virtual void          InventoryUseEnhancement(int player, int item, int slotType, bool bApplyCost);
  virtual int           InventoryGetWeaponEnhancementItem (int player, int slotType);
  virtual void			InventoryClearEnhancement( int player, int slotType );
  virtual void          InventoryConvertItemToEssence(int player, int item);

  //============================================================================
  // Merchant Inventory
  //============================================================================

  virtual int           MerchantGetItemCount();
  virtual bool          MerchantGetItemInfo(int item, TiCharacterItemInfo* pInfo);
  virtual void          MerchantBuyItem(int player, int item);

  //============================================================================
  // Save/Load Games
  //============================================================================
  virtual int           SaveGameGetCount();
  virtual bool          SaveGameGetInfo(int index, TitanSave* pInfo);
  virtual bool          SaveGameLoad(int index);
  virtual bool          SaveGameOverwrite(int index, const SyString& desc);
  virtual bool          SaveGameCreate(const SyString& desc);
  virtual bool          SaveGameOverwriteLast();
  virtual bool          SaveGameLoadLast();

  //============================================================================
  // Player Spells/Abilities
  //============================================================================

  virtual int           AbilityMappedGetIndex( int player, int button );

  virtual int           AbilityCurrentGetCount( int player );
  virtual bool          AbilityCurrentGetName( int player, int index, SyString& name );
  virtual bool          AbilityCurrentGetIDRank( int player, int index, int* pID, int* pRank );
  virtual bool          AbilityCurrentGetDescription( int player, int index, SyString& desc );
  virtual bool          AbilityCurrentIsActive( int player, int index );
  virtual void          AbilityCurrentMap( int player, int index, int button );

  virtual int           AbilityAvailableGetCount( int player );
  virtual bool          AbilityAvailableGetName( int player, int index, SyString& name );
  virtual int           AbilityAvailableGetCost( int player, int index );
  virtual bool          AbilityAvailableGetDescription( int player, int index, SyString& desc );
  virtual bool          AbilityAvailableIsBuyable( int player, int index );
  virtual void          AbilityAvailableBuy( int player, int index );

  // Added by Wiesman
  virtual int           AbilityGetNumPoints( int player );
  virtual bool          AbilityGetName(int32 iPlayer, SyResourceID idAbility, SyString &strName);
  virtual bool          AbilityGetDescription(int32 iPlayer, SyResourceID idAbility, SyString &strDescr);
  virtual SyResourceID  AbilityGetIcon(int32 iPlayer, SyResourceID idAbility);
  virtual int32         AbilityGetRank(int32 iPlayer, SyResourceID idAbility);
  virtual void          AbilityMapButton(int32 iPlayer, SyResourceID idAbility, int32 iButton);
  virtual int32         AbilityGetButtonForAbility(int32 iPlayer, SyResourceID idAbility);
  virtual SyResourceID  AbilityGetAbilityForButton(int32 iPlayer, int32 iButton);
  virtual void          AbilityBuy(int iPlayer, SyResourceID idAbility);

  //============================================================================
  // Scene options
  //============================================================================

  // Gets or sets a value that indicates whether the bloom post processing effect is enabled
  virtual bool GetBloom();
  virtual void SetBloom( bool value );

  virtual bool GetMultiPass();
  virtual void SetMultiPass( bool value );

  virtual void SetNoWaterRayCasts( bool value );
  virtual void SetNoPlunk( bool value );

  virtual DrawMode GetDrawMode();
  virtual void SetDrawMode( DrawMode value );


  //============================================================================
  // Performance Stats
  //============================================================================

  virtual int GetFPS();
  virtual int GetBatches();
  virtual int GetVertexes();
  virtual int GetTriangles();
  virtual uint32 GetPixels();
  virtual int GetDegenerateTriangles();

  virtual int GetAverageFPS();
  virtual int GetAverageBatches();
  virtual int GetAverageVertexes();
  virtual int GetAverageTriangles();
  virtual int GetAverageDegenerateTriangles();

  //============================================================================
  // Cut Scene Methods
  //============================================================================
  virtual int32 PlayScriptUsingNamedActors (int32 ScriptHandle);
  virtual int32 PlayScript (int32 ScriptHandle, int32 NumActorPairs, const SyFXScriptActorPair *pPairs );
  virtual bool isCutScenePlaying();

  virtual bool AllowCutSceneControllerMotion() { return mbAllowCutSceneControllerMotion; }
  virtual void StartCutScene(bool bAllowControllerMotion);
  virtual void EndCutScene();

  //============================================================================
  // Debug Methods (Jon Wiesman)
  //============================================================================

  virtual int Debug_AddItemToPlayerInventory( int32 nPlayerId, const char8 *pszItem );

  //============================================================================
  // Player Stats
  //============================================================================

  virtual int   GetPlayerName( int32 PlayerId, char8* pBuffer, int32 BuffLen ) const;
  virtual void  SetPlayerName( int32 PlayerId, const char8* pName );

  virtual int GetPlayerHealthMax( int32 PlayerId );
  virtual int GetPlayerHealth( int32 PlayerId );
  virtual int GetPlayerBlockMax( int32 PlayerId );
  virtual int GetPlayerBlock( int32 PlayerId );
  virtual int GetPlayerMana( int32 PlayerId );
  virtual int GetPlayerManaMax( int32 PlayerId );
  virtual int GetPlayerEssence( int32 PlayerId );
  virtual int GetPlayerLevel( int32 PlayerId );
  virtual int GetPlayerCurExp( int32 PlayerId );
  virtual int GetPlayerNextLevelExp( int32 PlayerId );
  virtual int GetPlayerPrevLevelExp( int32 PlayerId );
  virtual int GetPlayerLocation(int32 iPlayer, SyVect3 &vecLocation);
  virtual float GetPlayerHeading( int32 iPlayer ) const; 

  virtual void SetPlayerCharacter(int iPlayer, const char* characterMasterName);

  virtual float GetCameraHeading();

  virtual int GetDifficultySetting();
  virtual void SetDifficultySetting(int ds);
  // Begin Added by Jon Wiesman
  virtual int32 GetPlayerAttackPower(int32 iPlayer) const ;
  virtual int32 GetPlayerMagicPower(int32 iPlayer) const ;
  virtual int32 GetPlayerMeleeDefense(int32 iPlayer) const ;
  virtual int32 GetPlayerSpellDefense(int32 iPlayer) const ;
  virtual int32 GetPlayerBonusPoints(int32 iPlayer) const ;
  virtual void AddHealthPoints(int32 iPlayer, int32 nPoints) ;
  virtual void AddManaPoints(int32 iPlayer, int32 nPoints) ;
  virtual void AddAttackPowerPoints(int32 iPlayer, int32 nPoints) ;
  virtual void AddMagicPowerPoints(int32 iPlayer, int32 nPoints) ;
  virtual void AddMeleeDefensePoints(int32 iPlayer, int32 nPoints) ;
  virtual void AddSpellDefensePoints(int32 iPlayer, int32 nPoints) ;
  // End Added by Jon Wiesman

  //============================================================================
  // NPC Stats
  //============================================================================
  virtual bool GetFirstNPCInfo(int player, int& health, int& healthmax, int& block, int& blockmax, int& x, int& y, bool& offscreen, bool& isBlocking);
  virtual bool GetNextNPCInfo(int player, int& health, int& healthmax, int& block, int& blockmax, int& x, int& y, bool& offscreen, bool& isBlocking);

  //============================================================================
  // UI Activate String
  //============================================================================

  virtual bool GetActivateString(int playerId, char *buffer,int buffLen);

  //============================================================================
  // Subtitles 
  //============================================================================

  virtual bool GetSubtitleText(char *buffer,int buffLen);
  virtual void SetSubtitleText(char *text,float time);

  //============================================================================
  // Localized Text
  //============================================================================

  // main translation methods
  virtual void  InitT4WithLanguage(int32 iLanguage);
  virtual int32 GetT4Language() const {return m_iLanguage;}
  virtual int32 T4Lookup( char8* pBuffer, int BufLen, uint32 StringId );
  virtual int32 T4Expand( char8* pBuffer, int BufLen, uint32 StringId, float32 Faction = 0.5f );

  // support methods
  virtual int32 T4SetTopic( char8 Slot );
  virtual int32 T4SetContext( char8 Slot,
                            uint32 StringId,
                            int Gender = 0,
                            int Count = 1,
                            int BeingType = 0,
                            int RespectType = -3,
                            int Age = 0 );
  virtual int32 T4SetFinal( char8 Slot,
                          const char8* pText,
                          int Gender = 0,
                          int Count = 1,
                          int BeingType = 0,
                          int RespectType = -3,
                          int Age = 0 );

  //============================================================================
  // Implementation From Here On
  //============================================================================

  // Game Interface : Not exposed to UI or outside of Titan project
  static Titan*         Get() { return smpThis; }

  SyScene*              GetScene(){return mpTitanUI->GetScene();} // convenience function gets scene from TitanUI
  cGameObjectRegistry * GetRegistry(){return mpRegistry;}
  cDatabaseSys *        GetDatabaseSys(){return mpDatabaseSys;}
  cRuleSys *            GetRuleSys(){return mpRuleSys;}
  TitanUII  *           GetTitanUI(){return mpTitanUI;}
  cCameraController *   GetCameraController(){return mpCameraController;}
  cAnimControllerSys *  GetAnimControllerSys(){return mpAnimControllerSys;}
  cRuleContainer *      GetGlobalCharacterRules(){return mpGlobalCharacterRules;}
  cRuleContainer *      GetGlobalPropRules(){return mpGlobalPropRules;}
  cRuleContainer *      GetGlobalMarkerRules(){return mpGlobalMarkerRules;}
  cInventoryRuleContainer *     GetInventoryRules(){return mpInventoryRules;}
  TitanPeeringNetwork * GetPeeringNetwork(){return mpTitanPeeringNetwork;}
  cScriptSys *          GetScriptSys(){return mpScriptSys;};
  TitanFXScriptDriver * GetFXScriptDriver(){return mpTitanFXScriptDriver;};
  cDebrisSys *          GetDebrisSys(){return mpDebrisSys;};
  SyDamageNumMgr *      GetDamageNumMgr(){return mpDmgNumMgr;};
  cSoundManager *       GetSoundMgr(){return mpSoundMgr;};

  int                   Random(int min,int max);
  float                 RandomFloat(); // between 0 and 1
  uint64                GetTime() { return(mCurTime); }
  uint64                GetGameTime() { return(mGameTime); }
  // stops update processing; used when game has a modal window open
  virtual void          SetUnfocused(bool unfocus){mbUnfocused = unfocus;};

  void                  TransitionLevel();
  void                  SetInTransition(){mbInTransition=true;};

  void                  GetLocalPlayerName(int num,SyString *name);

  void                  SetGlobalAIAttackTimer();
  bool                  IsGlobalAIAttackTimerActive();
  cServiceScheduler *   GetServiceScheduler(){return mpServiceScheduler;};

	// loading/logging assets (.esf files)
  void  BeginLogging (const char * logfilename,   SyVector< SyPathname > *PackList);
	void  EndLogging ();
	void  LogEntry (const char * logString);
  bool  IsLogging() {return mLoggingFlag;}
	int32 LoadAssetSprite (SyESFParse &parser, const char * assetName, bool bOptional = false);
	int32 LoadAssetWorld (SyESFParse &parser, const char * assetName, bool isStreaming);
	int32 LoadAsset (SyESFParse &parser, const char * assetName, bool bOptional = false);
	int32 LoadAssetSound (SyESFParse &parser, const char * assetName);
	bool  GetUseWadFile();
	void  SetUseWadFile(bool wadFile);
  void  BlankScreen(bool blank){mbBlankScreen = blank;};
  void  SetMerchantID(int merchID) {mMerchantSetID = merchID;}
  
protected:

  void                  TransitionComplete();
  // loads things like debris models, popup damage numbers, etc...
  void                  LoadGlobalResources();
  void                  CreatePlayers();
  void                  EnterGame();
  void                  CheckPlayerModelOverride();

  const cStatsItemMaster* GetItemMaster( int player, int item );   
  int                   SelectItemEquipSlot( cItem* pItem );

  void                  IncreaseTimeScale();
  void                  DecreaseTimeScale();

  bool                  GetNPCInfo( cGameObject* pNPC, int player,
                                    int& health, int& healthmax,
                                    int& block, int& blockmax,
                                    int& x, int& y,
                                    bool& offscreen, bool& isBlocking );

private:
  // Keep header dependencies under control, please don't embed structures
  // in this object, just pointers and ubiquitous types like int, float, SyString, etc.

  static Titan* smpThis;

  TitanUII*             mpTitanUI;

  static const int      MAX_NUM_LOCAL_PLAYERS = 2;
  TitanInputHandler*    mpInputHandler[MAX_NUM_LOCAL_PLAYERS];

  cGameObjectRegistry*  mpRegistry;

  cCameraController*    mpCameraController;

  cDatabaseSys*         mpDatabaseSys; 

  cRuleSys*             mpRuleSys;

  cAnimControllerSys*   mpAnimControllerSys;
  
  cRuleContainer *      mpGlobalCharacterRules;
  cRuleContainer *      mpGlobalPropRules;
  cRuleContainer *      mpGlobalMarkerRules;
  cInventoryRuleContainer * mpInventoryRules;

  TitanPeeringNetwork * mpTitanPeeringNetwork;

  cScriptSys *          mpScriptSys;

  cDebrisSys *          mpDebrisSys;

  SyDamageNumMgr*       mpDmgNumMgr;
                                   
  SyRand*               mpRand;

  cServiceScheduler*    mpServiceScheduler;
  
  cSoundManager*        mpSoundMgr;

  bool                  mbPaused; // true if game is currently paused
  uint64                mCurTime; // current UI system time
  uint64                mGameTime; // millisecs not spent in pause since Init
  uint64                mFrameTime; // millisecs not spent in pause since last frame
  uint64                mRealFrameTime; // millisecs not spent in pause since last frame
  float                 mTimeScale; // 1.0f = time progresses at normal rate

  bool                  mBloomEnabled;
  int                   mBloomEffectHandle;
  bool                  mMultiPassEnabled;
  DrawMode              mDrawMode;
  TitanFXScriptDriver*  mpTitanFXScriptDriver;
  SyString              mCurFilename;
  bool                  mbUnfocused;
  bool                  mbCheckArt;
  bool                  mbShowDmgFlash;
  bool                  mbTransitionLevelSet;
  bool                  mbInTransition;
  bool                  mbUnlockAllAbilities;
  bool                  mbSuperSpeedMode;
  SyString              mMarkername; // after transition

  int32                 m_iLanguage;
  T4utf*                mpT4;
  TitanT4File*          mpT4File;
  TitanT4OS*            mpT4OS;

  cDebugOverlay*        mpDebugOverlay;
  cGameErrorLog*        mpGameErrorLog;

  int                   mNumLocalPlayers;
  int                   mDifficultySetting;

  SyString              mPlayerModelOverride;
  SyString              mPlayerCharacterMasterNames[MAX_NUM_LOCAL_PLAYERS];

  float                 mItemEssenceConversionRate;

  float                 mGlobalAIAttackDelay;
  float                 mGlobalAIAttackTimer;
  int                   mNPCQueryID;

  int                   mMerchantSetID;

  bool                  mbAllowCutSceneControllerMotion;
  SyString              mSubtitle;
  float                 mSubtitleTime;
  FILE*                 mLogFile;
	SyVector< SyPathname > *mLogList;
	bool                  mLoggingFlag;
	bool                  mLoadingLevel;
  bool                  mbStartLevelCutscene;
	bool                  mUseWadFile;
  bool                  mbBlankScreen;
  bool                  mbPvPEnabled;
  bool                  mbNetworkGame;
  bool                  mbReloadTest;
};


#endif // __TITAN_H__








