CGameHandler.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. /*
  2. * CGameHandler.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 <vcmi/Environment.h>
  12. #include "../lib/IGameCallback.h"
  13. #include "../lib/LoadProgress.h"
  14. #include "../lib/ScriptHandler.h"
  15. #include "TurnTimerHandler.h"
  16. VCMI_LIB_NAMESPACE_BEGIN
  17. struct SideInBattle;
  18. class IMarket;
  19. class SpellCastEnvironment;
  20. class CConnection;
  21. class CCommanderInstance;
  22. class EVictoryLossCheckResult;
  23. struct CPack;
  24. struct CPackForServer;
  25. struct NewTurn;
  26. struct CGarrisonOperationPack;
  27. struct SetResources;
  28. struct NewStructures;
  29. #if SCRIPTING_ENABLED
  30. namespace scripting
  31. {
  32. class PoolImpl;
  33. }
  34. #endif
  35. template<typename T> class CApplier;
  36. VCMI_LIB_NAMESPACE_END
  37. class HeroPoolProcessor;
  38. class CVCMIServer;
  39. class CBaseForGHApply;
  40. class PlayerMessageProcessor;
  41. class BattleProcessor;
  42. class TurnOrderProcessor;
  43. class QueriesProcessor;
  44. class CObjectVisitQuery;
  45. class CGameHandler : public IGameCallback, public Environment
  46. {
  47. CVCMIServer * lobby;
  48. std::shared_ptr<CApplier<CBaseForGHApply>> applier;
  49. public:
  50. std::unique_ptr<HeroPoolProcessor> heroPool;
  51. std::unique_ptr<BattleProcessor> battles;
  52. std::unique_ptr<QueriesProcessor> queries;
  53. std::unique_ptr<TurnOrderProcessor> turnOrder;
  54. //use enums as parameters, because doMove(sth, true, false, true) is not readable
  55. enum EGuardLook {CHECK_FOR_GUARDS, IGNORE_GUARDS};
  56. enum EVisitDest {VISIT_DEST, DONT_VISIT_DEST};
  57. enum ELEaveTile {LEAVING_TILE, REMAINING_ON_TILE};
  58. std::unique_ptr<PlayerMessageProcessor> playerMessages;
  59. std::map<PlayerColor, std::set<std::shared_ptr<CConnection>>> connections; //player color -> connection to client with interface of that player
  60. //queries stuff
  61. boost::recursive_mutex gsm;
  62. ui32 QID;
  63. SpellCastEnvironment * spellEnv;
  64. TurnTimerHandler turnTimerHandler;
  65. const Services * services() const override;
  66. const BattleCb * battle(const BattleID & battleID) const override;
  67. const GameCb * game() const override;
  68. vstd::CLoggerBase * logger() const override;
  69. events::EventBus * eventBus() const override;
  70. CVCMIServer * gameLobby() const;
  71. bool isValidObject(const CGObjectInstance *obj) const;
  72. bool isBlockedByQueries(const CPack *pack, PlayerColor player);
  73. bool isAllowedExchange(ObjectInstanceID id1, ObjectInstanceID id2);
  74. void giveSpells(const CGTownInstance *t, const CGHeroInstance *h);
  75. CGameHandler();
  76. CGameHandler(CVCMIServer * lobby);
  77. ~CGameHandler();
  78. //////////////////////////////////////////////////////////////////////////
  79. //from IGameCallback
  80. //do sth
  81. void changeSpells(const CGHeroInstance * hero, bool give, const std::set<SpellID> &spells) override;
  82. bool removeObject(const CGObjectInstance * obj, const PlayerColor & initiator) override;
  83. void createObject(const int3 & visitablePosition, const PlayerColor & initiator, Obj type, int32_t subtype ) override;
  84. void setOwner(const CGObjectInstance * obj, PlayerColor owner) override;
  85. void changePrimSkill(const CGHeroInstance * hero, PrimarySkill which, si64 val, bool abs=false) override;
  86. void changeSecSkill(const CGHeroInstance * hero, SecondarySkill which, int val, bool abs=false) override;
  87. void showBlockingDialog(BlockingDialog *iw) override;
  88. void showTeleportDialog(TeleportDialog *iw) override;
  89. void showGarrisonDialog(ObjectInstanceID upobj, ObjectInstanceID hid, bool removableUnits) override;
  90. void showObjectWindow(const CGObjectInstance * object, EOpenWindowMode window, const CGHeroInstance * visitor, bool addQuery) override;
  91. void giveResource(PlayerColor player, GameResID which, int val) override;
  92. void giveResources(PlayerColor player, TResources resources) override;
  93. void giveCreatures(const CArmedInstance *objid, const CGHeroInstance * h, const CCreatureSet &creatures, bool remove) override;
  94. void takeCreatures(ObjectInstanceID objid, const std::vector<CStackBasicDescriptor> &creatures) override;
  95. bool changeStackType(const StackLocation &sl, const CCreature *c) override;
  96. bool changeStackCount(const StackLocation &sl, TQuantity count, bool absoluteValue = false) override;
  97. bool insertNewStack(const StackLocation &sl, const CCreature *c, TQuantity count) override;
  98. bool eraseStack(const StackLocation &sl, bool forceRemoval = false) override;
  99. bool swapStacks(const StackLocation &sl1, const StackLocation &sl2) override;
  100. bool addToSlot(const StackLocation &sl, const CCreature *c, TQuantity count) override;
  101. void tryJoiningArmy(const CArmedInstance *src, const CArmedInstance *dst, bool removeObjWhenFinished, bool allowMerging) override;
  102. bool moveStack(const StackLocation &src, const StackLocation &dst, TQuantity count = -1) override;
  103. void removeAfterVisit(const CGObjectInstance *object) override;
  104. bool giveHeroNewArtifact(const CGHeroInstance * h, const CArtifact * artType, ArtifactPosition pos = ArtifactPosition::FIRST_AVAILABLE) override;
  105. bool giveHeroArtifact(const CGHeroInstance * h, const CArtifactInstance * a, ArtifactPosition pos) override;
  106. void putArtifact(const ArtifactLocation &al, const CArtifactInstance *a) override;
  107. void removeArtifact(const ArtifactLocation &al) override;
  108. bool moveArtifact(const ArtifactLocation & al1, const ArtifactLocation & al2) override;
  109. bool bulkMoveArtifacts(ObjectInstanceID srcHero, ObjectInstanceID dstHero, bool swap, bool equipped, bool backpack);
  110. bool eraseArtifactByClient(const ArtifactLocation & al);
  111. void synchronizeArtifactHandlerLists();
  112. void heroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero) override;
  113. void stopHeroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero) override;
  114. void startBattlePrimary(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool creatureBank = false, const CGTownInstance *town = nullptr) override; //use hero=nullptr for no hero
  115. void startBattleI(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, bool creatureBank = false) override; //if any of armies is hero, hero will be used
  116. void startBattleI(const CArmedInstance *army1, const CArmedInstance *army2, bool creatureBank = false) override; //if any of armies is hero, hero will be used, visitable tile of second obj is place of battle
  117. bool moveHero(ObjectInstanceID hid, int3 dst, ui8 teleporting, bool transit = false, PlayerColor asker = PlayerColor::NEUTRAL) override;
  118. void giveHeroBonus(GiveBonus * bonus) override;
  119. void setMovePoints(SetMovePoints * smp) override;
  120. void setManaPoints(ObjectInstanceID hid, int val) override;
  121. void giveHero(ObjectInstanceID id, PlayerColor player, ObjectInstanceID boatId = ObjectInstanceID()) override;
  122. void changeObjPos(ObjectInstanceID objid, int3 newPos, const PlayerColor & initiator) override;
  123. void heroExchange(ObjectInstanceID hero1, ObjectInstanceID hero2) override;
  124. void changeFogOfWar(int3 center, ui32 radius, PlayerColor player, ETileVisibility mode) override;
  125. void changeFogOfWar(std::unordered_set<int3> &tiles, PlayerColor player,ETileVisibility mode) override;
  126. void castSpell(const spells::Caster * caster, SpellID spellID, const int3 &pos) override;
  127. /// Returns hero that is currently visiting this object, or nullptr if no visit is active
  128. const CGHeroInstance * getVisitingHero(const CGObjectInstance *obj);
  129. bool isVisitCoveredByAnotherQuery(const CGObjectInstance *obj, const CGHeroInstance *hero) override;
  130. void setObjProperty(ObjectInstanceID objid, int prop, si64 val) override;
  131. void showInfoDialog(InfoWindow * iw) override;
  132. void showInfoDialog(const std::string & msg, PlayerColor player) override;
  133. //////////////////////////////////////////////////////////////////////////
  134. void useScholarSkill(ObjectInstanceID hero1, ObjectInstanceID hero2);
  135. void setPortalDwelling(const CGTownInstance * town, bool forced, bool clear);
  136. void visitObjectOnTile(const TerrainTile &t, const CGHeroInstance * h);
  137. bool teleportHero(ObjectInstanceID hid, ObjectInstanceID dstid, ui8 source, PlayerColor asker = PlayerColor::NEUTRAL);
  138. void visitCastleObjects(const CGTownInstance * obj, const CGHeroInstance * hero) override;
  139. void levelUpHero(const CGHeroInstance * hero, SecondarySkill skill);//handle client respond and send one more request if needed
  140. void levelUpHero(const CGHeroInstance * hero);//initial call - check if hero have remaining levelups & handle them
  141. void levelUpCommander (const CCommanderInstance * c, int skill); //secondary skill 1 to 6, special skill : skill - 100
  142. void levelUpCommander (const CCommanderInstance * c);
  143. void expGiven(const CGHeroInstance *hero); //triggers needed level-ups, handles also commander of this hero
  144. //////////////////////////////////////////////////////////////////////////
  145. void init(StartInfo *si, Load::ProgressAccumulator & progressTracking);
  146. void handleClientDisconnection(std::shared_ptr<CConnection> c);
  147. void handleReceivedPack(CPackForServer * pack);
  148. bool hasPlayerAt(PlayerColor player, std::shared_ptr<CConnection> c) const;
  149. bool hasBothPlayersAtSameConnection(PlayerColor left, PlayerColor right) const;
  150. bool queryReply( QueryID qid, std::optional<int32_t> reply, PlayerColor player );
  151. bool buildBoat( ObjectInstanceID objid, PlayerColor player );
  152. bool setFormation( ObjectInstanceID hid, ui8 formation );
  153. bool tradeResources(const IMarket *market, ui32 val, PlayerColor player, ui32 id1, ui32 id2);
  154. bool sacrificeCreatures(const IMarket * market, const CGHeroInstance * hero, const std::vector<SlotID> & slot, const std::vector<ui32> & count);
  155. bool sendResources(ui32 val, PlayerColor player, GameResID r1, PlayerColor r2);
  156. bool sellCreatures(ui32 count, const IMarket *market, const CGHeroInstance * hero, SlotID slot, GameResID resourceID);
  157. bool transformInUndead(const IMarket *market, const CGHeroInstance * hero, SlotID slot);
  158. bool assembleArtifacts (ObjectInstanceID heroID, ArtifactPosition artifactSlot, bool assemble, ArtifactID assembleTo);
  159. bool buyArtifact( ObjectInstanceID hid, ArtifactID aid ); //for blacksmith and mage guild only -> buying for gold in common buildings
  160. bool buyArtifact( const IMarket *m, const CGHeroInstance *h, GameResID rid, ArtifactID aid); //for artifact merchant and black market -> buying for any resource in special building / advobject
  161. bool sellArtifact( const IMarket *m, const CGHeroInstance *h, ArtifactInstanceID aid, GameResID rid); //for artifact merchant selling
  162. //void lootArtifacts (TArtHolder source, TArtHolder dest, std::vector<ui32> &arts); //after battle - move al arts to winer
  163. bool buySecSkill( const IMarket *m, const CGHeroInstance *h, SecondarySkill skill);
  164. bool garrisonSwap(ObjectInstanceID tid);
  165. bool swapGarrisonOnSiege(ObjectInstanceID tid) override;
  166. bool upgradeCreature( ObjectInstanceID objid, SlotID pos, CreatureID upgID );
  167. bool recruitCreatures(ObjectInstanceID objid, ObjectInstanceID dst, CreatureID crid, ui32 cram, si32 level, PlayerColor player);
  168. bool buildStructure(ObjectInstanceID tid, BuildingID bid, bool force=false);//force - for events: no cost, no checkings
  169. bool razeStructure(ObjectInstanceID tid, BuildingID bid);
  170. bool disbandCreature( ObjectInstanceID id, SlotID pos );
  171. bool arrangeStacks( ObjectInstanceID id1, ObjectInstanceID id2, ui8 what, SlotID p1, SlotID p2, si32 val, PlayerColor player);
  172. bool bulkMoveArmy(ObjectInstanceID srcArmy, ObjectInstanceID destArmy, SlotID srcSlot);
  173. bool bulkSplitStack(SlotID src, ObjectInstanceID srcOwner, si32 howMany);
  174. bool bulkMergeStacks(SlotID slotSrc, ObjectInstanceID srcOwner);
  175. bool bulkSmartSplitStack(SlotID slotSrc, ObjectInstanceID srcOwner);
  176. void save(const std::string &fname);
  177. bool load(const std::string &fname);
  178. void onPlayerTurnStarted(PlayerColor which);
  179. void onPlayerTurnEnded(PlayerColor which);
  180. void onNewTurn();
  181. void handleTimeEvents();
  182. void handleTownEvents(CGTownInstance *town, NewTurn &n);
  183. bool complain(const std::string &problem); //sends message to all clients, prints on the logs and return true
  184. void objectVisited( const CGObjectInstance * obj, const CGHeroInstance * h );
  185. void objectVisitEnded(const CObjectVisitQuery &query);
  186. bool dig(const CGHeroInstance *h);
  187. void moveArmy(const CArmedInstance *src, const CArmedInstance *dst, bool allowMerging);
  188. template <typename Handler> void serialize(Handler &h, const int version)
  189. {
  190. h & QID;
  191. h & getRandomGenerator();
  192. h & *battles;
  193. h & *heroPool;
  194. h & *playerMessages;
  195. h & *turnOrder;
  196. #if SCRIPTING_ENABLED
  197. JsonNode scriptsState;
  198. if(h.saving)
  199. serverScripts->serializeState(h.saving, scriptsState);
  200. h & scriptsState;
  201. if(!h.saving)
  202. serverScripts->serializeState(h.saving, scriptsState);
  203. #endif
  204. }
  205. void sendToAllClients(CPackForClient * pack);
  206. void sendAndApply(CPackForClient * pack) override;
  207. void sendAndApply(CGarrisonOperationPack * pack);
  208. void sendAndApply(SetResources * pack);
  209. void sendAndApply(NewStructures * pack);
  210. void wrongPlayerMessage(CPackForServer * pack, PlayerColor expectedplayer);
  211. /// Unconditionally throws with "Action not allowed" message
  212. void throwNotAllowedAction(CPackForServer * pack);
  213. /// Throws if player stated in pack is not making turn right now
  214. void throwIfPlayerNotActive(CPackForServer * pack);
  215. /// Throws if object is not owned by pack sender
  216. void throwIfWrongOwner(CPackForServer * pack, ObjectInstanceID id);
  217. /// Throws if player is not present on connection of this pack
  218. void throwIfWrongPlayer(CPackForServer * pack, PlayerColor player);
  219. void throwIfWrongPlayer(CPackForServer * pack);
  220. void throwAndComplain(CPackForServer * pack, std::string txt);
  221. bool isPlayerOwns(CPackForServer * pack, ObjectInstanceID id);
  222. void run(bool resume);
  223. bool sacrificeArtifact(const IMarket * m, const CGHeroInstance * hero, const std::vector<ArtifactPosition> & slot);
  224. void spawnWanderingMonsters(CreatureID creatureID);
  225. // Check for victory and loss conditions
  226. void checkVictoryLossConditionsForPlayer(PlayerColor player);
  227. void checkVictoryLossConditions(const std::set<PlayerColor> & playerColors);
  228. void checkVictoryLossConditionsForAll();
  229. CRandomGenerator & getRandomGenerator();
  230. #if SCRIPTING_ENABLED
  231. scripting::Pool * getGlobalContextPool() const override;
  232. // scripting::Pool * getContextPool() const override;
  233. #endif
  234. friend class CVCMIServer;
  235. private:
  236. std::unique_ptr<events::EventBus> serverEventBus;
  237. #if SCRIPTING_ENABLED
  238. std::shared_ptr<scripting::PoolImpl> serverScripts;
  239. #endif
  240. void reinitScripting();
  241. void getVictoryLossMessage(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult, InfoWindow & out) const;
  242. const std::string complainNoCreatures;
  243. const std::string complainNotEnoughCreatures;
  244. const std::string complainInvalidSlot;
  245. };
  246. class ExceptionNotAllowedAction : public std::exception
  247. {
  248. };