CGameState.h 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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 "../LoadProgress.h"
  14. #include "../ConstTransitivePtr.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. template<typename T> class CApplier;
  36. class CBaseForGSApply;
  37. struct UpgradeInfo
  38. {
  39. CreatureID oldID; //creature to be upgraded
  40. std::vector<CreatureID> newID; //possible upgrades
  41. std::vector<ResourceSet> cost; // cost[upgrade_serial] -> set of pairs<resource_ID,resource_amount>; cost is for single unit (not entire stack)
  42. UpgradeInfo(){oldID = CreatureID::NONE;};
  43. };
  44. class BattleInfo;
  45. DLL_LINKAGE std::ostream & operator<<(std::ostream & os, const EVictoryLossCheckResult & victoryLossCheckResult);
  46. class DLL_LINKAGE CGameState : public CNonConstInfoCallback, public Serializeable
  47. {
  48. friend class CGameStateCampaign;
  49. public:
  50. /// Stores number of times each artifact was placed on map via randomization
  51. std::map<ArtifactID, int> allocatedArtifacts;
  52. /// List of currently ongoing battles
  53. std::vector<std::unique_ptr<BattleInfo>> currentBattles;
  54. /// ID that can be allocated to next battle
  55. BattleID nextBattleID = BattleID(0);
  56. //we have here all heroes available on this map that are not hired
  57. std::unique_ptr<TavernHeroesPool> heroesPool;
  58. /// list of players currently making turn. Usually - just one, except for simturns
  59. std::set<PlayerColor> actingPlayers;
  60. IGameCallback * callback;
  61. CGameState();
  62. virtual ~CGameState();
  63. void preInit(Services * services, IGameCallback * callback);
  64. void init(const IMapService * mapService, StartInfo * si, Load::ProgressAccumulator &, bool allowSavingRandomMap = true);
  65. void updateOnLoad(StartInfo * si);
  66. ConstTransitivePtr<StartInfo> scenarioOps;
  67. ConstTransitivePtr<StartInfo> initialOpts; //copy of settings received from pregame (not randomized)
  68. ui32 day; //total number of days in game
  69. ConstTransitivePtr<CMap> map;
  70. std::map<PlayerColor, PlayerState> players;
  71. std::map<TeamID, TeamState> teams;
  72. CBonusSystemNode globalEffects;
  73. RumorState currentRumor;
  74. StatisticDataSet statistic;
  75. static boost::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(CPack *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 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
  86. void calculatePaths(const std::shared_ptr<PathfinderConfig> & config) override;
  87. int3 guardingCreaturePosition (int3 pos) const override;
  88. std::vector<CGObjectInstance*> guardingCreatures (int3 pos) const;
  89. RumorState pickNewRumor();
  90. /// Gets a artifact ID randomly and removes the selected artifact from this handler.
  91. ArtifactID pickRandomArtifact(vstd::RNG & rand, int flags);
  92. ArtifactID pickRandomArtifact(vstd::RNG & rand, std::function<bool(ArtifactID)> accepts);
  93. ArtifactID pickRandomArtifact(vstd::RNG & rand, int flags, std::function<bool(ArtifactID)> accepts);
  94. ArtifactID pickRandomArtifact(vstd::RNG & rand, std::set<ArtifactID> filtered);
  95. /// Returns battle in which selected player is engaged, or nullptr if none.
  96. /// Can NOT be used with neutral player, use battle by ID instead
  97. const BattleInfo * getBattle(const PlayerColor & player) const;
  98. /// Returns battle by its unique identifier, or nullptr if not found
  99. const BattleInfo * getBattle(const BattleID & battle) const;
  100. BattleInfo * getBattle(const BattleID & battle);
  101. // ----- victory, loss condition checks -----
  102. EVictoryLossCheckResult checkForVictoryAndLoss(const PlayerColor & player) const;
  103. bool checkForVictory(const PlayerColor & player, const EventCondition & condition) const; //checks if given player is winner
  104. PlayerColor checkForStandardWin() const; //returns color of player that accomplished standard victory conditions or 255 (NEUTRAL) if no winner
  105. bool checkForStandardLoss(const PlayerColor & player) const; //checks if given player lost the game
  106. void obtainPlayersStats(SThievesGuildInfo & tgi, int level); //fills tgi with info about other players that is available at given level of thieves' guild
  107. bool isVisible(int3 pos, const std::optional<PlayerColor> & player) const override;
  108. bool isVisible(const CGObjectInstance * obj, const std::optional<PlayerColor> & player) const override;
  109. static int getDate(int day, Date mode);
  110. 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
  111. // ----- getters, setters -----
  112. /// This RNG should only be used inside GS or CPackForClient-derived applyGs
  113. /// If this doesn't work for your code that mean you need a new netpack
  114. ///
  115. /// Client-side must use vstd::RNG::getDefault which is not serialized
  116. ///
  117. /// CGameHandler have it's own getter for vstd::RNG::getDefault
  118. /// Any server-side code outside of GH must use vstd::RNG::getDefault
  119. vstd::RNG & getRandomGenerator();
  120. template <typename Handler> void serialize(Handler &h)
  121. {
  122. h & scenarioOps;
  123. h & initialOpts;
  124. h & actingPlayers;
  125. h & day;
  126. h & map;
  127. h & players;
  128. h & teams;
  129. h & heroesPool;
  130. h & globalEffects;
  131. if (h.version < Handler::Version::REMOVE_LIB_RNG)
  132. {
  133. std::string oldStateOfRNG;
  134. h & oldStateOfRNG;
  135. }
  136. h & currentRumor;
  137. h & campaign;
  138. h & allocatedArtifacts;
  139. if (h.version >= Handler::Version::STATISTICS)
  140. h & statistic;
  141. BONUS_TREE_DESERIALIZATION_FIX
  142. }
  143. private:
  144. // ----- initialization -----
  145. void initNewGame(const IMapService * mapService, bool allowSavingRandomMap, Load::ProgressAccumulator & progressTracking);
  146. void initGlobalBonuses();
  147. void initGrailPosition();
  148. void initRandomFactionsForPlayers();
  149. void randomizeMapObjects();
  150. void initPlayerStates();
  151. void placeStartingHeroes();
  152. void placeStartingHero(const PlayerColor & playerColor, const HeroTypeID & heroTypeId, int3 townPos);
  153. void removeHeroPlaceholders();
  154. void initDifficulty();
  155. void initHeroes();
  156. void placeHeroesInTowns();
  157. void initFogOfWar();
  158. void initStartingBonus();
  159. void initTowns();
  160. void initTownNames();
  161. void initMapObjects();
  162. void initVisitingAndGarrisonedHeroes();
  163. void initCampaign();
  164. // ----- bonus system handling -----
  165. void buildBonusSystemTree();
  166. void attachArmedObjects();
  167. void buildGlobalTeamPlayerTree();
  168. void deserializationFix();
  169. // ---- misc helpers -----
  170. CGHeroInstance * getUsedHero(const HeroTypeID & hid) const;
  171. bool isUsedHero(const HeroTypeID & hid) const; //looks in heroes and prisons
  172. std::set<HeroTypeID> getUnusedAllowedHeroes(bool alsoIncludeNotAllowed = false) const;
  173. HeroTypeID pickUnusedHeroTypeRandomly(const PlayerColor & owner); // picks a unused hero type randomly
  174. UpgradeInfo fillUpgradeInfo(const CStackInstance &stack) const;
  175. // ---- data -----
  176. std::shared_ptr<CApplier<CBaseForGSApply>> applier;
  177. Services * services;
  178. /// Pointer to campaign state manager. Nullptr for single scenarios
  179. std::unique_ptr<CGameStateCampaign> campaign;
  180. friend class IGameCallback;
  181. friend class CMapHandler;
  182. friend class CGameHandler;
  183. };
  184. VCMI_LIB_NAMESPACE_END