CGameState.h 8.0 KB

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