CGameState.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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 "bonuses/Bonus.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. namespace boost
  23. {
  24. class shared_mutex;
  25. }
  26. VCMI_LIB_NAMESPACE_BEGIN
  27. class CTown;
  28. class IGameCallback;
  29. class CCreatureSet;
  30. class CQuest;
  31. class CGHeroInstance;
  32. class CGTownInstance;
  33. class CArmedInstance;
  34. class CGDwelling;
  35. class CObjectScript;
  36. class CGObjectInstance;
  37. class CCreature;
  38. class CMap;
  39. struct StartInfo;
  40. struct SetObjectProperty;
  41. struct MetaString;
  42. struct CPack;
  43. class CSpell;
  44. struct TerrainTile;
  45. class CHeroClass;
  46. class CCampaign;
  47. class CCampaignState;
  48. class IModableArt;
  49. class CGGarrison;
  50. struct QuestInfo;
  51. class CQuest;
  52. class CCampaignScenario;
  53. struct EventCondition;
  54. class CScenarioTravel;
  55. class IMapService;
  56. template<typename T> class CApplier;
  57. class CBaseForGSApply;
  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,
  123. const PlayerColor & player,
  124. const CTown * town,
  125. std::map<ui32, ConstTransitivePtr<CGHeroInstance>> & available,
  126. CRandomGenerator & rand,
  127. const CHeroClass * bannedClass = nullptr) const;
  128. template <typename Handler> void serialize(Handler &h, const int version)
  129. {
  130. h & heroesPool;
  131. h & pavailable;
  132. }
  133. } hpool; //we have here all heroes available on this map that are not hired
  134. CGameState();
  135. virtual ~CGameState();
  136. void preInit(Services * services);
  137. void init(const IMapService * mapService, StartInfo * si, bool allowSavingRandomMap = false);
  138. void updateOnLoad(StartInfo * si);
  139. ConstTransitivePtr<StartInfo> scenarioOps, initialOpts; //second one is a copy of settings received from pregame (not randomized)
  140. PlayerColor currentPlayer; //ID of player currently having turn
  141. ConstTransitivePtr<BattleInfo> curB; //current battle
  142. ui32 day; //total number of days in game
  143. ConstTransitivePtr<CMap> map;
  144. std::map<PlayerColor, PlayerState> players;
  145. std::map<TeamID, TeamState> teams;
  146. CBonusSystemNode globalEffects;
  147. RumorState rumor;
  148. static boost::shared_mutex mutex;
  149. void updateEntity(Metatype metatype, int32_t index, const JsonNode & data) override;
  150. bool giveHeroArtifact(CGHeroInstance * h, const ArtifactID & aid);
  151. void apply(CPack *pack);
  152. BattleField battleGetBattlefieldType(int3 tile, CRandomGenerator & rand);
  153. void fillUpgradeInfo(const CArmedInstance *obj, SlotID stackPos, UpgradeInfo &out) const override;
  154. PlayerRelations::PlayerRelations getPlayerRelations(PlayerColor color1, PlayerColor color2) const override;
  155. bool checkForVisitableDir(const int3 & src, const int3 & dst) const; //check if src tile is visitable from dst tile
  156. void calculatePaths(const CGHeroInstance *hero, CPathsInfo &out) override; //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
  157. void calculatePaths(const std::shared_ptr<PathfinderConfig> & config) override;
  158. int3 guardingCreaturePosition (int3 pos) const override;
  159. std::vector<CGObjectInstance*> guardingCreatures (int3 pos) const;
  160. void updateRumor();
  161. // ----- victory, loss condition checks -----
  162. EVictoryLossCheckResult checkForVictoryAndLoss(const PlayerColor & player) const;
  163. bool checkForVictory(const PlayerColor & player, const EventCondition & condition) const; //checks if given player is winner
  164. PlayerColor checkForStandardWin() const; //returns color of player that accomplished standard victory conditions or 255 (NEUTRAL) if no winner
  165. bool checkForStandardLoss(const PlayerColor & player) const; //checks if given player lost the game
  166. void obtainPlayersStats(SThievesGuildInfo & tgi, int level); //fills tgi with info about other players that is available at given level of thieves' guild
  167. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > unusedHeroesFromPool(); //heroes pool without heroes that are available in taverns
  168. bool isVisible(int3 pos, const std::optional<PlayerColor> & player) const override;
  169. bool isVisible(const CGObjectInstance * obj, const std::optional<PlayerColor> & player) const override;
  170. int getDate(Date::EDateType mode=Date::DAY) const override; //mode=0 - total days in game, mode=1 - day of week, mode=2 - current week, mode=3 - current month
  171. // ----- getters, setters -----
  172. /// This RNG should only be used inside GS or CPackForClient-derived applyGs
  173. /// If this doesn't work for your code that mean you need a new netpack
  174. ///
  175. /// Client-side must use CRandomGenerator::getDefault which is not serialized
  176. ///
  177. /// CGameHandler have it's own getter for CRandomGenerator::getDefault
  178. /// Any server-side code outside of GH must use CRandomGenerator::getDefault
  179. CRandomGenerator & getRandomGenerator();
  180. template <typename Handler> void serialize(Handler &h, const int version)
  181. {
  182. h & scenarioOps;
  183. h & initialOpts;
  184. h & currentPlayer;
  185. h & day;
  186. h & map;
  187. h & players;
  188. h & teams;
  189. h & hpool;
  190. h & globalEffects;
  191. h & rand;
  192. h & rumor;
  193. BONUS_TREE_DESERIALIZATION_FIX
  194. }
  195. private:
  196. struct CrossoverHeroesList
  197. {
  198. std::vector<CGHeroInstance *> heroesFromPreviousScenario, heroesFromAnyPreviousScenarios;
  199. void addHeroToBothLists(CGHeroInstance * hero);
  200. void removeHeroFromBothLists(CGHeroInstance * hero);
  201. };
  202. struct CampaignHeroReplacement
  203. {
  204. CampaignHeroReplacement(CGHeroInstance * hero, const ObjectInstanceID & heroPlaceholderId);
  205. CGHeroInstance * hero;
  206. ObjectInstanceID heroPlaceholderId;
  207. };
  208. // ----- initialization -----
  209. void preInitAuto();
  210. void initNewGame(const IMapService * mapService, bool allowSavingRandomMap);
  211. void initCampaign();
  212. void checkMapChecksum();
  213. void initGlobalBonuses();
  214. void initGrailPosition();
  215. void initRandomFactionsForPlayers();
  216. void randomizeMapObjects();
  217. void randomizeObject(CGObjectInstance *cur);
  218. void initPlayerStates();
  219. void placeCampaignHeroes();
  220. CrossoverHeroesList getCrossoverHeroesFromPreviousScenarios() const;
  221. /// returns heroes and placeholders in where heroes will be put
  222. std::vector<CampaignHeroReplacement> generateCampaignHeroesToReplace(CrossoverHeroesList & crossoverHeroes);
  223. /// gets prepared and copied hero instances with crossover heroes from prev. scenario and travel options from current scenario
  224. void prepareCrossoverHeroes(std::vector<CampaignHeroReplacement> & campaignHeroReplacements, const CScenarioTravel & travelOptions);
  225. void replaceHeroesPlaceholders(const std::vector<CampaignHeroReplacement> & campaignHeroReplacements);
  226. void placeStartingHeroes();
  227. void placeStartingHero(const PlayerColor & playerColor, const HeroTypeID & heroTypeId, int3 townPos);
  228. void initStartingResources();
  229. void initHeroes();
  230. void placeHeroesInTowns();
  231. void giveCampaignBonusToHero(CGHeroInstance * hero);
  232. void initFogOfWar();
  233. void initStartingBonus();
  234. void initTowns();
  235. void initMapObjects();
  236. void initVisitingAndGarrisonedHeroes();
  237. // ----- bonus system handling -----
  238. void buildBonusSystemTree();
  239. void attachArmedObjects();
  240. void buildGlobalTeamPlayerTree();
  241. void deserializationFix();
  242. // ---- misc helpers -----
  243. CGHeroInstance * getUsedHero(const HeroTypeID & hid) const;
  244. bool isUsedHero(const HeroTypeID & hid) const; //looks in heroes and prisons
  245. std::set<HeroTypeID> getUnusedAllowedHeroes(bool alsoIncludeNotAllowed = false) const;
  246. std::pair<Obj,int> pickObject(CGObjectInstance *obj); //chooses type of object to be randomized, returns <type, subtype>
  247. int pickUnusedHeroTypeRandomly(const PlayerColor & owner); // picks a unused hero type randomly
  248. int pickNextHeroType(const PlayerColor & owner); // picks next free hero type of the H3 hero init sequence -> chosen starting hero, then unused hero type randomly
  249. UpgradeInfo fillUpgradeInfo(const CStackInstance &stack) const;
  250. // ---- data -----
  251. std::shared_ptr<CApplier<CBaseForGSApply>> applier;
  252. CRandomGenerator rand;
  253. Services * services;
  254. friend class IGameCallback;
  255. friend class CMapHandler;
  256. friend class CGameHandler;
  257. };
  258. VCMI_LIB_NAMESPACE_END