CGameState.h 8.3 KB

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