CGameState.h 8.9 KB

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