CGameState.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. #ifndef __CGAMESTATE_H__
  2. #define __CGAMESTATE_H__
  3. #include "../global.h"
  4. #include <cassert>
  5. #ifndef _MSC_VER
  6. #include "CCreatureHandler.h"
  7. #include "VCMI_Lib.h"
  8. #include "map.h"
  9. #endif
  10. #include <set>
  11. #include <vector>
  12. #include <list>
  13. #include "HeroBonus.h"
  14. #include "CCreatureSet.h"
  15. #ifdef _WIN32
  16. #include <tchar.h>
  17. #else
  18. #include "../tchar_amigaos4.h"
  19. #endif
  20. #include "ConstTransitivePtr.h"
  21. #include "IGameCallback.h"
  22. #include "ResourceSet.h"
  23. /*
  24. * CGameState.h, part of VCMI engine
  25. *
  26. * Authors: listed in file AUTHORS in main folder
  27. *
  28. * License: GNU General Public License v2.0 or later
  29. * Full text of license available in license.txt file, in main folder
  30. *
  31. */
  32. class CTown;
  33. class CScriptCallback;
  34. class CCallback;
  35. class IGameCallback;
  36. class CLuaCallback;
  37. class CCPPObjectScript;
  38. class CCreatureSet;
  39. class CStack;
  40. class CGHeroInstance;
  41. class CGTownInstance;
  42. class CArmedInstance;
  43. class CGDwelling;
  44. class CGDefInfo;
  45. class CObjectScript;
  46. class CGObjectInstance;
  47. class CCreature;
  48. struct Mapa;
  49. struct StartInfo;
  50. struct SDL_Surface;
  51. class CMapHandler;
  52. class CPathfinder;
  53. struct SetObjectProperty;
  54. struct MetaString;
  55. struct CPack;
  56. class CSpell;
  57. struct TerrainTile;
  58. class CHeroClass;
  59. class CCampaign;
  60. class CCampaignState;
  61. class IModableArt;
  62. class CGGarrison;
  63. namespace boost
  64. {
  65. class shared_mutex;
  66. }
  67. //numbers of creatures are exact numbers if detailed else they are quantity ids (0 - a few, 1 - several and so on; additionally -1 - unknown)
  68. struct ArmyDescriptor : public std::map<TSlot, CStackBasicDescriptor>
  69. {
  70. bool isDetailed;
  71. DLL_EXPORT ArmyDescriptor(const CArmedInstance *army, bool detailed); //not detailed -> quantity ids as count
  72. DLL_EXPORT ArmyDescriptor();
  73. DLL_EXPORT int getStrength() const;
  74. };
  75. struct DLL_EXPORT InfoAboutHero
  76. {
  77. private:
  78. void assign(const InfoAboutHero & iah);
  79. public:
  80. struct DLL_EXPORT Details
  81. {
  82. std::vector<int> primskills;
  83. int mana, luck, morale;
  84. } *details;
  85. char owner;
  86. const CHeroClass *hclass;
  87. std::string name;
  88. int portrait;
  89. ArmyDescriptor army;
  90. InfoAboutHero();
  91. InfoAboutHero(const InfoAboutHero & iah);
  92. InfoAboutHero & operator=(const InfoAboutHero & iah);
  93. ~InfoAboutHero();
  94. void initFromHero(const CGHeroInstance *h, bool detailed);
  95. };
  96. /// Struct which holds a short information about a town
  97. struct DLL_EXPORT InfoAboutTown
  98. {
  99. struct Details
  100. {
  101. int hallLevel, goldIncome;
  102. bool customRes;
  103. bool garrisonedHero;
  104. } *details;
  105. const CArmedInstance * obj;
  106. char fortLevel; //0 - none
  107. char owner;
  108. std::string name;
  109. CTown *tType;
  110. bool built;
  111. ArmyDescriptor army; //numbers of creatures are valid only if details
  112. InfoAboutTown();
  113. ~InfoAboutTown();
  114. void initFromTown(const CGTownInstance *t, bool detailed);
  115. void initFromGarrison(const CGGarrison *garr, bool detailed);
  116. };
  117. // typedef si32 TResourceUnit;
  118. // typedef std::vector<si32> TResourceVector;
  119. // typedef std::set<si32> TResourceSet;
  120. struct DLL_EXPORT SThievesGuildInfo
  121. {
  122. std::vector<ui8> playerColors; //colors of players that are in-game
  123. std::vector< std::list< ui8 > > numOfTowns, numOfHeroes, gold, woodOre, mercSulfCrystGems, obelisks, artifacts, army, income; // [place] -> [colours of players]
  124. std::map<ui8, InfoAboutHero> colorToBestHero; //maps player's color to his best heros'
  125. std::map<ui8, si8> personality; // color to personality // -1 - human, AI -> (00 - random, 01 - warrior, 02 - builder, 03 - explorer)
  126. std::map<ui8, si32> bestCreature; // color to ID // id or -1 if not known
  127. // template <typename Handler> void serialize(Handler &h, const int version)
  128. // {
  129. // h & playerColors & numOfTowns & numOfHeroes & gold & woodOre & mercSulfCrystGems & obelisks & artifacts & army & income;
  130. // h & colorToBestHero & personality & bestCreature;
  131. // }
  132. };
  133. struct DLL_EXPORT PlayerState : public CBonusSystemNode
  134. {
  135. public:
  136. enum EStatus {INGAME, LOSER, WINNER};
  137. ui8 color;
  138. ui8 human; //true if human controlled player, false for AI
  139. ui32 currentSelection; //id of hero/town, 0xffffffff if none
  140. ui8 team;
  141. TResources resources;
  142. std::vector<ConstTransitivePtr<CGHeroInstance> > heroes;
  143. std::vector<ConstTransitivePtr<CGTownInstance> > towns;
  144. std::vector<ConstTransitivePtr<CGHeroInstance> > availableHeroes; //heroes available in taverns
  145. std::vector<ConstTransitivePtr<CGDwelling> > dwellings; //used for town growth
  146. ui8 enteredWinningCheatCode, enteredLosingCheatCode; //if true, this player has entered cheat codes for loss / victory
  147. ui8 status; //0 - in game, 1 - loser, 2 - winner <- uses EStatus enum
  148. ui8 daysWithoutCastle;
  149. PlayerState();
  150. std::string nodeName() const OVERRIDE;
  151. //override
  152. //void getParents(TCNodes &out, const CBonusSystemNode *root = NULL) const;
  153. //void getBonuses(BonusList &out, const CSelector &selector, const CBonusSystemNode *root = NULL) const;
  154. template <typename Handler> void serialize(Handler &h, const int version)
  155. {
  156. h & color & human & currentSelection & team & resources & status;
  157. h & heroes & towns & availableHeroes & dwellings & getBonusList();
  158. h & status & daysWithoutCastle;
  159. h & enteredLosingCheatCode & enteredWinningCheatCode;
  160. h & static_cast<CBonusSystemNode&>(*this);
  161. }
  162. };
  163. struct DLL_EXPORT TeamState : public CBonusSystemNode
  164. {
  165. public:
  166. ui8 id; //position in gameState::teams
  167. std::set<ui8> players; // members of this team
  168. std::vector<std::vector<std::vector<ui8> > > fogOfWarMap; //true - visible, false - hidden
  169. TeamState();
  170. template <typename Handler> void serialize(Handler &h, const int version)
  171. {
  172. h & id & players & fogOfWarMap;
  173. h & static_cast<CBonusSystemNode&>(*this);
  174. }
  175. };
  176. struct UpgradeInfo
  177. {
  178. int oldID; //creature to be upgraded
  179. std::vector<int> newID; //possible upgrades
  180. std::vector<TResources> cost; // cost[upgrade_serial] -> set of pairs<resource_ID,resource_amount>; cost is for single unit (not entire stack)
  181. UpgradeInfo(){oldID = -1;};
  182. };
  183. struct CPathNode
  184. {
  185. bool accessible; //true if a hero can be on this node
  186. int dist; //distance from the first node of searching; -1 is infinity
  187. CPathNode * theNodeBefore;
  188. int3 coord; //coordiantes
  189. bool visited;
  190. };
  191. struct CGPathNode
  192. {
  193. enum EAccessibility
  194. {
  195. ACCESSIBLE=1, //tile can be entered and passed
  196. VISITABLE, //tile can be entered as the last tile in path
  197. BLOCKVIS, //visitable from neighbouring tile but not passable
  198. BLOCKED //tile can't be entered nor visited
  199. };
  200. ui8 accessible; //the enum above
  201. ui8 land;
  202. ui8 turns;
  203. ui32 moveRemains;
  204. CGPathNode * theNodeBefore;
  205. int3 coord; //coordinates
  206. CGPathNode();
  207. };
  208. struct DLL_EXPORT CPath
  209. {
  210. std::vector<CPathNode> nodes; //just get node by node
  211. int3 startPos() const; // start point
  212. int3 endPos() const; //destination point
  213. void convert(ui8 mode); //mode=0 -> from 'manifest' to 'object'
  214. };
  215. struct DLL_EXPORT CGPath
  216. {
  217. std::vector<CGPathNode> nodes; //just get node by node
  218. int3 startPos() const; // start point
  219. int3 endPos() const; //destination point
  220. void convert(ui8 mode); //mode=0 -> from 'manifest' to 'object'
  221. };
  222. struct DLL_EXPORT CPathsInfo
  223. {
  224. bool isValid;
  225. const CGHeroInstance *hero;
  226. int3 hpos;
  227. int3 sizes;
  228. CGPathNode ***nodes; //[w][h][level]
  229. bool getPath(const int3 &dst, CGPath &out);
  230. CPathsInfo(const int3 &Sizes);
  231. ~CPathsInfo();
  232. };
  233. struct DLL_EXPORT DuelParameters
  234. {
  235. si32 terType, bfieldType;
  236. struct SideSettings
  237. {
  238. struct StackSettings
  239. {
  240. si32 type;
  241. si32 count;
  242. template <typename Handler> void serialize(Handler &h, const int version)
  243. {
  244. h & type & count;
  245. }
  246. StackSettings();
  247. StackSettings(si32 Type, si32 Count);
  248. } stacks[ARMY_SIZE];
  249. si32 heroId; //-1 if none
  250. std::set<si32> spells;
  251. SideSettings();
  252. template <typename Handler> void serialize(Handler &h, const int version)
  253. {
  254. h & stacks & heroId & spells;
  255. }
  256. } sides[2];
  257. DuelParameters();
  258. template <typename Handler> void serialize(Handler &h, const int version)
  259. {
  260. h & terType & bfieldType & sides;
  261. }
  262. };
  263. class CPathfinder : private CGameInfoCallback
  264. {
  265. public:
  266. bool useSubterraneanGates;
  267. bool allowEmbarkAndDisembark;
  268. CPathsInfo &out;
  269. const CGHeroInstance *hero;
  270. const std::vector<std::vector<std::vector<ui8> > > &FoW;
  271. std::list<CGPathNode*> mq; //BFS queue -> nodes to be checked
  272. int3 curPos;
  273. CGPathNode *cp; //current (source) path node -> we took it from the queue
  274. CGPathNode *dp; //destination node -> it's a neighbour of cp that we consider
  275. const TerrainTile *ct, *dt; //tile info for both nodes
  276. ui8 useEmbarkCost; //0 - usual movement; 1 - embark; 2 - disembark
  277. int destTopVisObjID;
  278. CPathfinder(CPathsInfo &_out, CGameState *_gs, const CGHeroInstance *_hero);;
  279. CGPathNode *getNode(const int3 &coord);
  280. void initializeGraph();
  281. CGPathNode::EAccessibility evaluateAccessibility(const TerrainTile *tinfo) const;
  282. void calculatePaths(int3 src = int3(-1,-1,-1), int movement = -1); //calculates possible paths for hero, by default uses current hero position and movement left; returns pointer to newly allocated CPath or NULL if path does not exists
  283. bool canMoveBetween(const int3 &a, const int3 &b) const; //checks only for visitable objects that may make moving between tiles impossible, not other conditions (like tiles itself accessibility)
  284. bool canStepOntoDst() const;
  285. bool goodForLandSeaTransition(); //checks if current move will be between sea<->land. If so, checks it legality (returns false if movement is not possible) and sets useEmbarkCost
  286. };
  287. struct BattleInfo;
  288. class DLL_EXPORT CGameState : public CNonConstInfoCallback
  289. {
  290. public:
  291. ConstTransitivePtr<StartInfo> scenarioOps, initialOpts; //second one is a copy of settings received from pregame (not randomized)
  292. ConstTransitivePtr<CCampaignState> campaign;
  293. ui32 seed;
  294. ui8 currentPlayer; //ID of player currently having turn
  295. ConstTransitivePtr<BattleInfo> curB; //current battle
  296. ui32 day; //total number of days in game
  297. ConstTransitivePtr<Mapa> map;
  298. bmap<ui8, PlayerState> players; //ID <-> player state
  299. bmap<ui8, TeamState> teams; //ID <-> team state
  300. bmap<int, ConstTransitivePtr<CGDefInfo> > villages, forts, capitols; //def-info for town graphics
  301. CBonusSystemNode globalEffects;
  302. bmap<const CGHeroInstance*, const CGObjectInstance*> ongoingVisits;
  303. struct DLL_EXPORT HeroesPool
  304. {
  305. bmap<ui32, ConstTransitivePtr<CGHeroInstance> > heroesPool; //[subID] - heroes available to buy; NULL if not available
  306. bmap<ui32,ui8> pavailable; // [subid] -> which players can recruit hero (binary flags)
  307. CGHeroInstance * pickHeroFor(bool native, int player, const CTown *town, bmap<ui32, ConstTransitivePtr<CGHeroInstance> > &available, const CHeroClass *bannedClass = NULL) const;
  308. template <typename Handler> void serialize(Handler &h, const int version)
  309. {
  310. h & heroesPool & pavailable;
  311. }
  312. } hpool; //we have here all heroes available on this map that are not hired
  313. boost::shared_mutex *mx;
  314. void init(StartInfo * si, ui32 checksum, int Seed);
  315. void loadTownDInfos();
  316. void randomizeObject(CGObjectInstance *cur);
  317. std::pair<int,int> pickObject(CGObjectInstance *obj); //chooses type of object to be randomized, returns <type, subtype>
  318. int pickHero(int owner);
  319. void apply(CPack *pack);
  320. int battleGetBattlefieldType(int3 tile = int3());// 1. sand/shore 2. sand/mesas 3. dirt/birches 4. dirt/hills 5. dirt/pines 6. grass/hills 7. grass/pines 8. lava 9. magic plains 10. snow/mountains 11. snow/trees 12. subterranean 13. swamp/trees 14. fiery fields 15. rock lands 16. magic clouds 17. lucid pools 18. holy ground 19. clover field 20. evil fog 21. "favourable winds" text on magic plains background 22. cursed ground 23. rough 24. ship to ship 25. ship
  321. UpgradeInfo getUpgradeInfo(const CStackInstance &stack);
  322. int getPlayerRelations(ui8 color1, ui8 color2);// 0 = enemy, 1 = ally, 2 = same player
  323. //float getMarketEfficiency(int player, int mode=0);
  324. bool checkForVisitableDir(const int3 & src, const int3 & dst) const; //check if src tile is visitable from dst tile
  325. bool checkForVisitableDir(const int3 & src, const TerrainTile *pom, const int3 & dst) const; //check if src tile is visitable from dst tile
  326. bool getPath(int3 src, int3 dest, const CGHeroInstance * hero, CPath &ret); //calculates path between src and dest; returns pointer to newly allocated CPath or NULL if path does not exists
  327. void calculatePaths(const CGHeroInstance *hero, CPathsInfo &out, int3 src = int3(-1,-1,-1), int movement = -1); //calculates possible paths for hero, by default uses current hero position and movement left; returns pointer to newly allocated CPath or NULL if path does not exists
  328. int3 guardingCreaturePosition (int3 pos) const;
  329. int victoryCheck(ui8 player) const; //checks if given player is winner; -1 if std victory, 1 if special victory, 0 else
  330. int lossCheck(ui8 player) const; //checks if given player is loser; -1 if std loss, 1 if special, 0 else
  331. ui8 checkForStandardWin() const; //returns color of player that accomplished standard victory conditions or 255 if no winner
  332. bool checkForStandardLoss(ui8 player) const; //checks if given player lost the game
  333. void obtainPlayersStats(SThievesGuildInfo & tgi, int level); //fills tgi with info about other players that is available at given level of thieves' guild
  334. bmap<ui32, ConstTransitivePtr<CGHeroInstance> > unusedHeroesFromPool(); //heroes pool without heroes that are available in taverns
  335. BattleInfo * setupBattle(int3 tile, const CArmedInstance *armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance *town);
  336. void buildBonusSystemTree();
  337. void attachArmedObjects();
  338. void buildGlobalTeamPlayerTree();
  339. void deserializationFix();
  340. bool isVisible(int3 pos, int player);
  341. bool isVisible(const CGObjectInstance *obj, int player);
  342. CGameState(); //c-tor
  343. ~CGameState(); //d-tor
  344. void getNeighbours(const TerrainTile &srct, int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand, bool limitCoastSailing);
  345. int getMovementCost(const CGHeroInstance *h, const int3 &src, const int3 &dest, int remainingMovePoints=-1, bool checkLast=true);
  346. int getDate(int mode=0) const; //mode=0 - total days in game, mode=1 - day of week, mode=2 - current week, mode=3 - current month
  347. template <typename Handler> void serialize(Handler &h, const int version)
  348. {
  349. h & scenarioOps & initialOpts & seed & currentPlayer & day & map & players & teams & hpool & globalEffects & campaign;
  350. h & villages & forts & capitols;
  351. if(!h.saving)
  352. {
  353. loadTownDInfos();
  354. }
  355. BONUS_TREE_DESERIALIZATION_FIX
  356. }
  357. friend class CCallback;
  358. friend class CLuaCallback;
  359. friend class CClient;
  360. friend void initGameState(Mapa * map, CGameInfo * cgi);
  361. friend class IGameCallback;
  362. friend class CMapHandler;
  363. friend class CGameHandler;
  364. };
  365. #endif // __CGAMESTATE_H__