CGameState.h 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. /*
  2. * CGameState.h, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #pragma once
  11. #include "CCreatureHandler.h"
  12. #include "VCMI_Lib.h"
  13. #include "HeroBonus.h"
  14. #include "CCreatureSet.h"
  15. #include "ConstTransitivePtr.h"
  16. #include "IGameCallback.h"
  17. #include "ResourceSet.h"
  18. #include "int3.h"
  19. #include "CRandomGenerator.h"
  20. #include "CGameStateFwd.h"
  21. #include "CPathfinder.h"
  22. class CTown;
  23. class CCallback;
  24. class IGameCallback;
  25. class CCreatureSet;
  26. class CQuest;
  27. class CGHeroInstance;
  28. class CGTownInstance;
  29. class CArmedInstance;
  30. class CGDwelling;
  31. class CObjectScript;
  32. class CGObjectInstance;
  33. class CCreature;
  34. class CMap;
  35. struct StartInfo;
  36. class CMapHandler;
  37. struct SetObjectProperty;
  38. struct MetaString;
  39. struct CPack;
  40. class CSpell;
  41. struct TerrainTile;
  42. class CHeroClass;
  43. class CCampaign;
  44. class CCampaignState;
  45. class IModableArt;
  46. class CGGarrison;
  47. class CGameInfo;
  48. struct QuestInfo;
  49. class CQuest;
  50. class CCampaignScenario;
  51. struct EventCondition;
  52. class CScenarioTravel;
  53. class IMapService;
  54. namespace boost
  55. {
  56. class shared_mutex;
  57. }
  58. struct DLL_LINKAGE SThievesGuildInfo
  59. {
  60. std::vector<PlayerColor> playerColors; //colors of players that are in-game
  61. std::vector< std::vector< PlayerColor > > numOfTowns, numOfHeroes, gold, woodOre, mercSulfCrystGems, obelisks, artifacts, army, income; // [place] -> [colours of players]
  62. std::map<PlayerColor, InfoAboutHero> colorToBestHero; //maps player's color to his best heros'
  63. std::map<PlayerColor, EAiTactic::EAiTactic> personality; // color to personality // ai tactic
  64. std::map<PlayerColor, si32> bestCreature; // color to ID // id or -1 if not known
  65. // template <typename Handler> void serialize(Handler &h, const int version)
  66. // {
  67. // h & playerColors;
  68. // h & numOfTowns;
  69. // h & numOfHeroes;
  70. // h & gold;
  71. // h & woodOre;
  72. // h & mercSulfCrystGems;
  73. // h & obelisks;
  74. // h & artifacts;
  75. // h & army;
  76. // h & income;
  77. // h & colorToBestHero;
  78. // h & personality;
  79. // h & bestCreature;
  80. // }
  81. };
  82. struct DLL_LINKAGE RumorState
  83. {
  84. enum ERumorType : ui8
  85. {
  86. TYPE_NONE = 0, TYPE_RAND, TYPE_SPECIAL, TYPE_MAP
  87. };
  88. enum ERumorTypeSpecial : ui8
  89. {
  90. RUMOR_OBELISKS = 208,
  91. RUMOR_ARTIFACTS = 209,
  92. RUMOR_ARMY = 210,
  93. RUMOR_INCOME = 211,
  94. RUMOR_GRAIL = 212
  95. };
  96. ERumorType type;
  97. std::map<ERumorType, std::pair<int, int>> last;
  98. RumorState(){type = TYPE_NONE;};
  99. bool update(int id, int extra);
  100. template <typename Handler> void serialize(Handler &h, const int version)
  101. {
  102. h & type;
  103. h & last;
  104. }
  105. };
  106. struct UpgradeInfo
  107. {
  108. CreatureID oldID; //creature to be upgraded
  109. std::vector<CreatureID> newID; //possible upgrades
  110. std::vector<TResources> cost; // cost[upgrade_serial] -> set of pairs<resource_ID,resource_amount>; cost is for single unit (not entire stack)
  111. UpgradeInfo(){oldID = CreatureID::NONE;};
  112. };
  113. class BattleInfo;
  114. DLL_LINKAGE std::ostream & operator<<(std::ostream & os, const EVictoryLossCheckResult & victoryLossCheckResult);
  115. class DLL_LINKAGE CGameState : public CNonConstInfoCallback
  116. {
  117. public:
  118. struct DLL_LINKAGE HeroesPool
  119. {
  120. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > heroesPool; //[subID] - heroes available to buy; nullptr if not available
  121. std::map<ui32,ui8> pavailable; // [subid] -> which players can recruit hero (binary flags)
  122. CGHeroInstance * pickHeroFor(bool native, PlayerColor player, const CTown *town,
  123. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > &available, CRandomGenerator & rand, const CHeroClass *bannedClass = nullptr) const;
  124. template <typename Handler> void serialize(Handler &h, const int version)
  125. {
  126. h & heroesPool;
  127. h & pavailable;
  128. }
  129. } hpool; //we have here all heroes available on this map that are not hired
  130. CGameState();
  131. virtual ~CGameState();
  132. void init(const IMapService * mapService, StartInfo * si, bool allowSavingRandomMap = false);
  133. ConstTransitivePtr<StartInfo> scenarioOps, initialOpts; //second one is a copy of settings received from pregame (not randomized)
  134. PlayerColor currentPlayer; //ID of player currently having turn
  135. ConstTransitivePtr<BattleInfo> curB; //current battle
  136. ui32 day; //total number of days in game
  137. ConstTransitivePtr<CMap> map;
  138. std::map<PlayerColor, PlayerState> players;
  139. std::map<TeamID, TeamState> teams;
  140. CBonusSystemNode globalEffects;
  141. RumorState rumor;
  142. static boost::shared_mutex mutex;
  143. void giveHeroArtifact(CGHeroInstance *h, ArtifactID aid);
  144. void apply(CPack *pack);
  145. BFieldType battleGetBattlefieldType(int3 tile, CRandomGenerator & rand);
  146. UpgradeInfo getUpgradeInfo(const CStackInstance &stack);
  147. PlayerRelations::PlayerRelations getPlayerRelations(PlayerColor color1, PlayerColor color2);
  148. bool checkForVisitableDir(const int3 & src, const int3 & dst) const; //check if src tile is visitable from dst tile
  149. void calculatePaths(const CGHeroInstance *hero, CPathsInfo &out); //calculates possible paths for hero, by default uses current hero position and movement left; returns pointer to newly allocated CPath or nullptr if path does not exists
  150. int3 guardingCreaturePosition (int3 pos) const;
  151. std::vector<CGObjectInstance*> guardingCreatures (int3 pos) const;
  152. void updateRumor();
  153. // ----- victory, loss condition checks -----
  154. EVictoryLossCheckResult checkForVictoryAndLoss(PlayerColor player) const;
  155. bool checkForVictory(PlayerColor player, const EventCondition & condition) const; //checks if given player is winner
  156. PlayerColor checkForStandardWin() const; //returns color of player that accomplished standard victory conditions or 255 (NEUTRAL) if no winner
  157. bool checkForStandardLoss(PlayerColor player) const; //checks if given player lost the game
  158. void obtainPlayersStats(SThievesGuildInfo & tgi, int level); //fills tgi with info about other players that is available at given level of thieves' guild
  159. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > unusedHeroesFromPool(); //heroes pool without heroes that are available in taverns
  160. bool isVisible(int3 pos, PlayerColor player);
  161. bool isVisible(const CGObjectInstance *obj, boost::optional<PlayerColor> player);
  162. int getDate(Date::EDateType mode=Date::DAY) const; //mode=0 - total days in game, mode=1 - day of week, mode=2 - current week, mode=3 - current month
  163. // ----- getters, setters -----
  164. /// This RNG should only be used inside GS or CPackForClient-derived applyGs
  165. /// If this doesn't work for your code that mean you need a new netpack
  166. ///
  167. /// Client-side must use CRandomGenerator::getDefault which is not serialized
  168. ///
  169. /// CGameHandler have it's own getter for CRandomGenerator::getDefault
  170. /// Any server-side code outside of GH must use CRandomGenerator::getDefault
  171. CRandomGenerator & getRandomGenerator();
  172. template <typename Handler> void serialize(Handler &h, const int version)
  173. {
  174. h & scenarioOps;
  175. h & initialOpts;
  176. h & currentPlayer;
  177. h & day;
  178. h & map;
  179. h & players;
  180. h & teams;
  181. h & hpool;
  182. h & globalEffects;
  183. h & rand;
  184. if(version >= 755) //save format backward compatibility
  185. {
  186. h & rumor;
  187. }
  188. else if(!h.saving)
  189. {
  190. rumor = RumorState();
  191. }
  192. BONUS_TREE_DESERIALIZATION_FIX
  193. }
  194. private:
  195. struct CrossoverHeroesList
  196. {
  197. std::vector<CGHeroInstance *> heroesFromPreviousScenario, heroesFromAnyPreviousScenarios;
  198. void addHeroToBothLists(CGHeroInstance * hero);
  199. void removeHeroFromBothLists(CGHeroInstance * hero);
  200. };
  201. struct CampaignHeroReplacement
  202. {
  203. CampaignHeroReplacement(CGHeroInstance * hero, ObjectInstanceID heroPlaceholderId);
  204. CGHeroInstance * hero;
  205. ObjectInstanceID heroPlaceholderId;
  206. };
  207. // ----- initialization -----
  208. void initNewGame(const IMapService * mapService, bool allowSavingRandomMap);
  209. void initCampaign(const IMapService * mapService);
  210. void checkMapChecksum();
  211. void initGrailPosition();
  212. void initRandomFactionsForPlayers();
  213. void randomizeMapObjects();
  214. void randomizeObject(CGObjectInstance *cur);
  215. void initPlayerStates();
  216. void placeCampaignHeroes();
  217. CrossoverHeroesList getCrossoverHeroesFromPreviousScenarios() const;
  218. /// returns heroes and placeholders in where heroes will be put
  219. std::vector<CampaignHeroReplacement> generateCampaignHeroesToReplace(CrossoverHeroesList & crossoverHeroes);
  220. /// gets prepared and copied hero instances with crossover heroes from prev. scenario and travel options from current scenario
  221. void prepareCrossoverHeroes(std::vector<CampaignHeroReplacement> & campaignHeroReplacements, const CScenarioTravel & travelOptions);
  222. void replaceHeroesPlaceholders(const std::vector<CampaignHeroReplacement> & campaignHeroReplacements);
  223. void placeStartingHeroes();
  224. void placeStartingHero(PlayerColor playerColor, HeroTypeID heroTypeId, int3 townPos);
  225. void initStartingResources();
  226. void initHeroes();
  227. void giveCampaignBonusToHero(CGHeroInstance * hero);
  228. void initFogOfWar();
  229. void initStartingBonus();
  230. void initTowns();
  231. void initMapObjects();
  232. void initVisitingAndGarrisonedHeroes();
  233. // ----- bonus system handling -----
  234. void buildBonusSystemTree();
  235. void attachArmedObjects();
  236. void buildGlobalTeamPlayerTree();
  237. void deserializationFix();
  238. // ---- misc helpers -----
  239. CGHeroInstance * getUsedHero(HeroTypeID hid) const;
  240. bool isUsedHero(HeroTypeID hid) const; //looks in heroes and prisons
  241. std::set<HeroTypeID> getUnusedAllowedHeroes(bool alsoIncludeNotAllowed = false) const;
  242. std::pair<Obj,int> pickObject(CGObjectInstance *obj); //chooses type of object to be randomized, returns <type, subtype>
  243. int pickUnusedHeroTypeRandomly(PlayerColor owner); // picks a unused hero type randomly
  244. int pickNextHeroType(PlayerColor owner); // picks next free hero type of the H3 hero init sequence -> chosen starting hero, then unused hero type randomly
  245. // ---- data -----
  246. CRandomGenerator rand;
  247. friend class CCallback;
  248. friend class CClient;
  249. friend class IGameCallback;
  250. friend class CMapHandler;
  251. friend class CGameHandler;
  252. };