CGameHandler.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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. ui32 QID;
  62. SpellCastEnvironment * spellEnv;
  63. TurnTimerHandler turnTimerHandler;
  64. const Services * services() const override;
  65. const BattleCb * battle(const BattleID & battleID) const override;
  66. const GameCb * game() const override;
  67. vstd::CLoggerBase * logger() const override;
  68. events::EventBus * eventBus() const override;
  69. CVCMIServer * gameLobby() const;
  70. bool isValidObject(const CGObjectInstance *obj) const;
  71. bool isBlockedByQueries(const CPack *pack, PlayerColor player);
  72. bool isAllowedExchange(ObjectInstanceID id1, ObjectInstanceID id2);
  73. void giveSpells(const CGTownInstance *t, const CGHeroInstance *h);
  74. explicit CGameHandler(CVCMIServer * lobby);
  75. ~CGameHandler();
  76. //////////////////////////////////////////////////////////////////////////
  77. //from IGameCallback
  78. //do sth
  79. void changeSpells(const CGHeroInstance * hero, bool give, const std::set<SpellID> &spells) override;
  80. bool removeObject(const CGObjectInstance * obj, const PlayerColor & initiator) override;
  81. void createObject(const int3 & visitablePosition, const PlayerColor & initiator, MapObjectID type, MapObjectSubID subtype) override;
  82. void setOwner(const CGObjectInstance * obj, PlayerColor owner) override;
  83. void giveExperience(const CGHeroInstance * hero, TExpType val) override;
  84. void changePrimSkill(const CGHeroInstance * hero, PrimarySkill which, si64 val, bool abs=false) override;
  85. void changeSecSkill(const CGHeroInstance * hero, SecondarySkill which, int val, bool abs=false) override;
  86. void showBlockingDialog(BlockingDialog *iw) override;
  87. void showTeleportDialog(TeleportDialog *iw) override;
  88. void showGarrisonDialog(ObjectInstanceID upobj, ObjectInstanceID hid, bool removableUnits) override;
  89. void showObjectWindow(const CGObjectInstance * object, EOpenWindowMode window, const CGHeroInstance * visitor, bool addQuery) override;
  90. void giveResource(PlayerColor player, GameResID which, int val) override;
  91. void giveResources(PlayerColor player, TResources resources) override;
  92. void giveCreatures(const CArmedInstance *objid, const CGHeroInstance * h, const CCreatureSet &creatures, bool remove) override;
  93. void takeCreatures(ObjectInstanceID objid, const std::vector<CStackBasicDescriptor> &creatures) override;
  94. bool changeStackType(const StackLocation &sl, const CCreature *c) override;
  95. bool changeStackCount(const StackLocation &sl, TQuantity count, bool absoluteValue = false) override;
  96. bool insertNewStack(const StackLocation &sl, const CCreature *c, TQuantity count) override;
  97. bool eraseStack(const StackLocation &sl, bool forceRemoval = false) override;
  98. bool swapStacks(const StackLocation &sl1, const StackLocation &sl2) override;
  99. bool addToSlot(const StackLocation &sl, const CCreature *c, TQuantity count) override;
  100. void tryJoiningArmy(const CArmedInstance *src, const CArmedInstance *dst, bool removeObjWhenFinished, bool allowMerging) override;
  101. bool moveStack(const StackLocation &src, const StackLocation &dst, TQuantity count = -1) override;
  102. void removeAfterVisit(const CGObjectInstance *object) override;
  103. bool giveHeroNewArtifact(const CGHeroInstance * h, const CArtifact * artType, ArtifactPosition pos = ArtifactPosition::FIRST_AVAILABLE) override;
  104. bool putArtifact(const ArtifactLocation & al, const CArtifactInstance * art, std::optional<bool> askAssemble) override;
  105. void removeArtifact(const ArtifactLocation &al) override;
  106. bool moveArtifact(const PlayerColor & player, const ArtifactLocation & src, const ArtifactLocation & dst) override;
  107. bool bulkMoveArtifacts(const PlayerColor & player, ObjectInstanceID srcId, ObjectInstanceID dstId, bool swap, bool equipped, bool backpack);
  108. bool scrollBackpackArtifacts(const PlayerColor & player, const ObjectInstanceID heroID, bool left);
  109. bool eraseArtifactByClient(const ArtifactLocation & al);
  110. void synchronizeArtifactHandlerLists();
  111. void heroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero) override;
  112. void stopHeroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero) override;
  113. 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
  114. void startBattleI(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, bool creatureBank = false) override; //if any of armies is hero, hero will be used
  115. 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
  116. bool moveHero(ObjectInstanceID hid, int3 dst, ui8 teleporting, bool transit = false, PlayerColor asker = PlayerColor::NEUTRAL) override;
  117. void giveHeroBonus(GiveBonus * bonus) override;
  118. void setMovePoints(SetMovePoints * smp) override;
  119. void setMovePoints(ObjectInstanceID hid, int val, bool absolute) 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. const CGObjectInstance * getVisitingObject(const CGHeroInstance *hero);
  130. bool isVisitCoveredByAnotherQuery(const CGObjectInstance *obj, const CGHeroInstance *hero) override;
  131. void setObjPropertyValue(ObjectInstanceID objid, ObjProperty prop, int32_t value) override;
  132. void setObjPropertyID(ObjectInstanceID objid, ObjProperty prop, ObjPropertyID identifier) override;
  133. void showInfoDialog(InfoWindow * iw) override;
  134. //////////////////////////////////////////////////////////////////////////
  135. void useScholarSkill(ObjectInstanceID hero1, ObjectInstanceID hero2);
  136. void setPortalDwelling(const CGTownInstance * town, bool forced, bool clear);
  137. void visitObjectOnTile(const TerrainTile &t, const CGHeroInstance * h);
  138. bool teleportHero(ObjectInstanceID hid, ObjectInstanceID dstid, ui8 source, PlayerColor asker = PlayerColor::NEUTRAL);
  139. void visitCastleObjects(const CGTownInstance * obj, const CGHeroInstance * hero) override;
  140. void levelUpHero(const CGHeroInstance * hero, SecondarySkill skill);//handle client respond and send one more request if needed
  141. void levelUpHero(const CGHeroInstance * hero);//initial call - check if hero have remaining levelups & handle them
  142. void levelUpCommander (const CCommanderInstance * c, int skill); //secondary skill 1 to 6, special skill : skill - 100
  143. void levelUpCommander (const CCommanderInstance * c);
  144. void expGiven(const CGHeroInstance *hero); //triggers needed level-ups, handles also commander of this hero
  145. //////////////////////////////////////////////////////////////////////////
  146. void init(StartInfo *si, Load::ProgressAccumulator & progressTracking);
  147. void handleClientDisconnection(std::shared_ptr<CConnection> c);
  148. void handleReceivedPack(CPackForServer * pack);
  149. bool hasPlayerAt(PlayerColor player, std::shared_ptr<CConnection> c) const;
  150. bool hasBothPlayersAtSameConnection(PlayerColor left, PlayerColor right) const;
  151. bool queryReply( QueryID qid, std::optional<int32_t> reply, PlayerColor player );
  152. bool buildBoat( ObjectInstanceID objid, PlayerColor player );
  153. bool setFormation( ObjectInstanceID hid, EArmyFormation formation );
  154. bool tradeResources(const IMarket *market, ui32 amountToSell, PlayerColor player, GameResID toSell, GameResID toBuy);
  155. bool sacrificeCreatures(const IMarket * market, const CGHeroInstance * hero, const std::vector<SlotID> & slot, const std::vector<ui32> & count);
  156. bool sendResources(ui32 val, PlayerColor player, GameResID r1, PlayerColor r2);
  157. bool sellCreatures(ui32 count, const IMarket *market, const CGHeroInstance * hero, SlotID slot, GameResID resourceID);
  158. bool transformInUndead(const IMarket *market, const CGHeroInstance * hero, SlotID slot);
  159. bool assembleArtifacts (ObjectInstanceID heroID, ArtifactPosition artifactSlot, bool assemble, ArtifactID assembleTo);
  160. bool buyArtifact( ObjectInstanceID hid, ArtifactID aid ); //for blacksmith and mage guild only -> buying for gold in common buildings
  161. 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
  162. bool sellArtifact( const IMarket *m, const CGHeroInstance *h, ArtifactInstanceID aid, GameResID rid); //for artifact merchant selling
  163. //void lootArtifacts (TArtHolder source, TArtHolder dest, std::vector<ui32> &arts); //after battle - move al arts to winer
  164. bool buySecSkill( const IMarket *m, const CGHeroInstance *h, SecondarySkill skill);
  165. bool garrisonSwap(ObjectInstanceID tid);
  166. bool swapGarrisonOnSiege(ObjectInstanceID tid) override;
  167. bool upgradeCreature( ObjectInstanceID objid, SlotID pos, CreatureID upgID );
  168. bool recruitCreatures(ObjectInstanceID objid, ObjectInstanceID dst, CreatureID crid, ui32 cram, si32 level, PlayerColor player);
  169. bool buildStructure(ObjectInstanceID tid, BuildingID bid, bool force=false);//force - for events: no cost, no checkings
  170. bool razeStructure(ObjectInstanceID tid, BuildingID bid);
  171. bool disbandCreature( ObjectInstanceID id, SlotID pos );
  172. bool arrangeStacks( ObjectInstanceID id1, ObjectInstanceID id2, ui8 what, SlotID p1, SlotID p2, si32 val, PlayerColor player);
  173. bool bulkMoveArmy(ObjectInstanceID srcArmy, ObjectInstanceID destArmy, SlotID srcSlot);
  174. bool bulkSplitStack(SlotID src, ObjectInstanceID srcOwner, si32 howMany);
  175. bool bulkMergeStacks(SlotID slotSrc, ObjectInstanceID srcOwner);
  176. bool bulkSmartSplitStack(SlotID slotSrc, ObjectInstanceID srcOwner);
  177. void save(const std::string &fname);
  178. bool load(const std::string &fname);
  179. void onPlayerTurnStarted(PlayerColor which);
  180. void onPlayerTurnEnded(PlayerColor which);
  181. void onNewTurn();
  182. void handleTimeEvents();
  183. void handleTownEvents(CGTownInstance *town, NewTurn &n);
  184. bool complain(const std::string &problem); //sends message to all clients, prints on the logs and return true
  185. void objectVisited( const CGObjectInstance * obj, const CGHeroInstance * h );
  186. void objectVisitEnded(const CObjectVisitQuery &query);
  187. bool dig(const CGHeroInstance *h);
  188. void moveArmy(const CArmedInstance *src, const CArmedInstance *dst, bool allowMerging);
  189. template <typename Handler> void serialize(Handler &h)
  190. {
  191. h & QID;
  192. h & getRandomGenerator();
  193. h & *battles;
  194. h & *heroPool;
  195. h & *playerMessages;
  196. h & *turnOrder;
  197. #if SCRIPTING_ENABLED
  198. JsonNode scriptsState;
  199. if(h.saving)
  200. serverScripts->serializeState(h.saving, scriptsState);
  201. h & scriptsState;
  202. if(!h.saving)
  203. serverScripts->serializeState(h.saving, scriptsState);
  204. #endif
  205. }
  206. void sendToAllClients(CPackForClient * pack);
  207. void sendAndApply(CPackForClient * pack) override;
  208. void sendAndApply(CGarrisonOperationPack * pack);
  209. void sendAndApply(SetResources * pack);
  210. void sendAndApply(NewStructures * pack);
  211. void wrongPlayerMessage(CPackForServer * pack, PlayerColor expectedplayer);
  212. /// Unconditionally throws with "Action not allowed" message
  213. [[noreturn]] void throwNotAllowedAction(CPackForServer * pack);
  214. /// Throws if player stated in pack is not making turn right now
  215. void throwIfPlayerNotActive(CPackForServer * pack);
  216. /// Throws if object is not owned by pack sender
  217. void throwIfWrongOwner(CPackForServer * pack, ObjectInstanceID id);
  218. /// Throws if player is not present on connection of this pack
  219. void throwIfWrongPlayer(CPackForServer * pack, PlayerColor player);
  220. void throwIfWrongPlayer(CPackForServer * pack);
  221. [[noreturn]] void throwAndComplain(CPackForServer * pack, std::string txt);
  222. bool isPlayerOwns(CPackForServer * pack, ObjectInstanceID id);
  223. void start(bool resume);
  224. void tick(int millisecondsPassed);
  225. bool sacrificeArtifact(const IMarket * m, const CGHeroInstance * hero, const std::vector<ArtifactInstanceID> & arts);
  226. void spawnWanderingMonsters(CreatureID creatureID);
  227. // Check for victory and loss conditions
  228. void checkVictoryLossConditionsForPlayer(PlayerColor player);
  229. void checkVictoryLossConditions(const std::set<PlayerColor> & playerColors);
  230. void checkVictoryLossConditionsForAll();
  231. CRandomGenerator & getRandomGenerator();
  232. #if SCRIPTING_ENABLED
  233. scripting::Pool * getGlobalContextPool() const override;
  234. // scripting::Pool * getContextPool() const override;
  235. #endif
  236. friend class CVCMIServer;
  237. private:
  238. std::unique_ptr<events::EventBus> serverEventBus;
  239. #if SCRIPTING_ENABLED
  240. std::shared_ptr<scripting::PoolImpl> serverScripts;
  241. #endif
  242. void reinitScripting();
  243. void getVictoryLossMessage(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult, InfoWindow & out) const;
  244. const std::string complainNoCreatures;
  245. const std::string complainNotEnoughCreatures;
  246. const std::string complainInvalidSlot;
  247. };
  248. class ExceptionNotAllowedAction : public std::exception
  249. {
  250. };