CGameHandler.h 15 KB

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