CGameState.h 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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 "../bonuses/CBonusSystemNode.h"
  12. #include "../IGameCallback.h"
  13. #include "../GameCallbackHolder.h"
  14. #include "../LoadProgress.h"
  15. #include "RumorState.h"
  16. #include "GameStatistics.h"
  17. namespace boost
  18. {
  19. class shared_mutex;
  20. }
  21. VCMI_LIB_NAMESPACE_BEGIN
  22. class EVictoryLossCheckResult;
  23. class Services;
  24. class IMapService;
  25. class CMap;
  26. class CSaveFile;
  27. class CLoadFile;
  28. struct CPack;
  29. class CHeroClass;
  30. struct EventCondition;
  31. struct CampaignTravel;
  32. class CStackInstance;
  33. class CGameStateCampaign;
  34. class TavernHeroesPool;
  35. struct SThievesGuildInfo;
  36. class CRandomGenerator;
  37. class GameSettings;
  38. class BattleInfo;
  39. class UpgradeInfo;
  40. DLL_LINKAGE std::ostream & operator<<(std::ostream & os, const EVictoryLossCheckResult & victoryLossCheckResult);
  41. class DLL_LINKAGE CGameState : public CNonConstInfoCallback, public Serializeable, public GameCallbackHolder
  42. {
  43. friend class CGameStateCampaign;
  44. std::shared_ptr<StartInfo> initialOpts; //copy of settings received from pregame (not randomized)
  45. std::shared_ptr<StartInfo> scenarioOps;
  46. std::unique_ptr<CMap> map;
  47. void saveCompatibilityRegisterMissingArtifacts();
  48. public:
  49. ArtifactInstanceID saveCompatibilityLastAllocatedArtifactID;
  50. std::vector<std::shared_ptr<CArtifactInstance>> saveCompatibilityUnregisteredArtifacts;
  51. /// Stores number of times each artifact was placed on map via randomization
  52. std::map<ArtifactID, int> allocatedArtifacts;
  53. /// List of currently ongoing battles
  54. std::vector<std::unique_ptr<BattleInfo>> currentBattles;
  55. /// ID that can be allocated to next battle
  56. BattleID nextBattleID = BattleID(0);
  57. //we have here all heroes available on this map that are not hired
  58. std::unique_ptr<TavernHeroesPool> heroesPool;
  59. /// list of players currently making turn. Usually - just one, except for simturns
  60. std::set<PlayerColor> actingPlayers;
  61. CGameState(IGameCallback * callback);
  62. virtual ~CGameState();
  63. CGameState & gameState() final { return *this; }
  64. const CGameState & gameState() const final { return *this; }
  65. void preInit(Services * services);
  66. void init(const IMapService * mapService, StartInfo * si, Load::ProgressAccumulator &, bool allowSavingRandomMap = true);
  67. void updateOnLoad(StartInfo * si);
  68. ui32 day; //total number of days in game
  69. std::map<PlayerColor, PlayerState> players;
  70. std::map<TeamID, TeamState> teams;
  71. CBonusSystemNode globalEffects;
  72. RumorState currentRumor;
  73. StatisticDataSet statistic;
  74. // NOTE: effectively AI mutex, only used by adventure map AI
  75. static std::shared_mutex mutex;
  76. void updateEntity(Metatype metatype, int32_t index, const JsonNode & data) override;
  77. bool giveHeroArtifact(CGHeroInstance * h, const ArtifactID & aid);
  78. /// picks next free hero type of the H3 hero init sequence -> chosen starting hero, then unused hero type randomly
  79. HeroTypeID pickNextHeroType(const PlayerColor & owner);
  80. void apply(CPackForClient & pack);
  81. BattleField battleGetBattlefieldType(int3 tile, vstd::RNG & rand);
  82. void fillUpgradeInfo(const CArmedInstance *obj, SlotID stackPos, UpgradeInfo &out) const override;
  83. PlayerRelations getPlayerRelations(PlayerColor color1, PlayerColor color2) const override;
  84. bool checkForVisitableDir(const int3 & src, const int3 & dst) const; //check if src tile is visitable from dst tile
  85. void calculatePaths(const std::shared_ptr<PathfinderConfig> & config) const override;
  86. int3 guardingCreaturePosition (int3 pos) const override;
  87. std::vector<const CGObjectInstance*> guardingCreatures (int3 pos) const;
  88. /// Gets a artifact ID randomly and removes the selected artifact from this handler.
  89. ArtifactID pickRandomArtifact(vstd::RNG & rand, int flags);
  90. ArtifactID pickRandomArtifact(vstd::RNG & rand, std::function<bool(ArtifactID)> accepts);
  91. ArtifactID pickRandomArtifact(vstd::RNG & rand, int flags, std::function<bool(ArtifactID)> accepts);
  92. ArtifactID pickRandomArtifact(vstd::RNG & rand, std::set<ArtifactID> filtered);
  93. /// Creates instance of spell scroll artifact with provided spell
  94. CArtifactInstance * createScroll(const SpellID & spellId);
  95. /// Creates instance of requested artifact
  96. /// For combined artifact this method will also create alll required components
  97. /// For scrolls this method will also initialize its spell
  98. CArtifactInstance * createArtifact(const ArtifactID & artId, const SpellID & spellId = SpellID::NONE);
  99. /// Returns battle in which selected player is engaged, or nullptr if none.
  100. /// Can NOT be used with neutral player, use battle by ID instead
  101. const BattleInfo * getBattle(const PlayerColor & player) const;
  102. /// Returns battle by its unique identifier, or nullptr if not found
  103. const BattleInfo * getBattle(const BattleID & battle) const;
  104. BattleInfo * getBattle(const BattleID & battle);
  105. // ----- victory, loss condition checks -----
  106. EVictoryLossCheckResult checkForVictoryAndLoss(const PlayerColor & player) const;
  107. bool checkForVictory(const PlayerColor & player, const EventCondition & condition) const; //checks if given player is winner
  108. PlayerColor checkForStandardWin() const; //returns color of player that accomplished standard victory conditions or 255 (NEUTRAL) if no winner
  109. bool checkForStandardLoss(const PlayerColor & player) const; //checks if given player lost the game
  110. void obtainPlayersStats(SThievesGuildInfo & tgi, int level); //fills tgi with info about other players that is available at given level of thieves' guild
  111. const IGameSettings & getSettings() const;
  112. StartInfo * getStartInfo()
  113. {
  114. return scenarioOps.get();
  115. }
  116. const StartInfo * getStartInfo() const final
  117. {
  118. return scenarioOps.get();
  119. }
  120. const StartInfo * getInitialStartInfo() const final
  121. {
  122. return initialOpts.get();
  123. }
  124. CMap & getMap()
  125. {
  126. return *map;
  127. }
  128. const CMap & getMap() const
  129. {
  130. return *map;
  131. }
  132. bool isVisible(int3 pos, const std::optional<PlayerColor> & player) const override;
  133. bool isVisible(const CGObjectInstance * obj, const std::optional<PlayerColor> & player) const override;
  134. static int getDate(int day, Date mode);
  135. int getDate(Date mode=Date::DAY) const override; //mode=0 - total days in game, mode=1 - day of week, mode=2 - current week, mode=3 - current month
  136. // ----- getters, setters -----
  137. /// This RNG should only be used inside GS or CPackForClient-derived applyGs
  138. /// If this doesn't work for your code that mean you need a new netpack
  139. ///
  140. /// Client-side must use vstd::RNG::getDefault which is not serialized
  141. ///
  142. /// CGameHandler have it's own getter for vstd::RNG::getDefault
  143. /// Any server-side code outside of GH must use vstd::RNG::getDefault
  144. vstd::RNG & getRandomGenerator();
  145. void saveGame(CSaveFile & file) const;
  146. void loadGame(CLoadFile & file);
  147. template <typename Handler> void serialize(Handler &h)
  148. {
  149. h & scenarioOps;
  150. h & initialOpts;
  151. h & actingPlayers;
  152. h & day;
  153. h & map;
  154. if (!h.hasFeature(Handler::Version::NO_RAW_POINTERS_IN_SERIALIZER))
  155. saveCompatibilityRegisterMissingArtifacts();
  156. h & players;
  157. h & teams;
  158. if (h.hasFeature(Handler::Version::NO_RAW_POINTERS_IN_SERIALIZER))
  159. h & *heroesPool;
  160. else
  161. h & heroesPool;
  162. h & globalEffects;
  163. h & currentRumor;
  164. h & campaign;
  165. h & allocatedArtifacts;
  166. h & statistic;
  167. if(!h.saving && h.loadingGamestate)
  168. restoreBonusSystemTree();
  169. }
  170. private:
  171. // ----- initialization -----
  172. void initNewGame(const IMapService * mapService, bool allowSavingRandomMap, Load::ProgressAccumulator & progressTracking);
  173. void initGlobalBonuses();
  174. void initGrailPosition();
  175. void initRandomFactionsForPlayers();
  176. void initOwnedObjects();
  177. void randomizeMapObjects();
  178. void initPlayerStates();
  179. void placeStartingHeroes();
  180. void placeStartingHero(const PlayerColor & playerColor, const HeroTypeID & heroTypeId, int3 townPos);
  181. void removeHeroPlaceholders();
  182. void initDifficulty();
  183. void initHeroes();
  184. void placeHeroesInTowns();
  185. void initFogOfWar();
  186. void initStartingBonus();
  187. void initTowns();
  188. void initTownNames();
  189. void initMapObjects();
  190. void initVisitingAndGarrisonedHeroes();
  191. void initCampaign();
  192. // ----- bonus system handling -----
  193. void buildBonusSystemTree();
  194. void buildGlobalTeamPlayerTree();
  195. void restoreBonusSystemTree();
  196. // ---- misc helpers -----
  197. CGHeroInstance * getUsedHero(const HeroTypeID & hid) const;
  198. bool isUsedHero(const HeroTypeID & hid) const; //looks in heroes and prisons
  199. std::set<HeroTypeID> getUnusedAllowedHeroes(bool alsoIncludeNotAllowed = false) const;
  200. HeroTypeID pickUnusedHeroTypeRandomly(const PlayerColor & owner); // picks a unused hero type randomly
  201. UpgradeInfo fillUpgradeInfo(const CStackInstance &stack) const;
  202. // ---- data -----
  203. Services * services;
  204. /// Pointer to campaign state manager. Nullptr for single scenarios
  205. std::unique_ptr<CGameStateCampaign> campaign;
  206. friend class IGameCallback;
  207. friend class CMapHandler;
  208. friend class CGameHandler;
  209. };
  210. VCMI_LIB_NAMESPACE_END