Client.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. /*
  2. * Client.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 <memory>
  12. #include <vcmi/Environment.h>
  13. #include "../lib/IGameCallback.h"
  14. #include "../lib/battle/BattleAction.h"
  15. #include "../lib/battle/CBattleInfoCallback.h"
  16. #include "../lib/CStopWatch.h"
  17. #include "../lib/int3.h"
  18. #include "../lib/CondSh.h"
  19. #include "../lib/CPathfinder.h"
  20. VCMI_LIB_NAMESPACE_BEGIN
  21. struct CPack;
  22. struct CPackForServer;
  23. class CCampaignState;
  24. class IGameEventsReceiver;
  25. class IBattleEventsReceiver;
  26. class CBattleGameInterface;
  27. class CGameState;
  28. class CGameInterface;
  29. class BattleAction;
  30. struct CPathsInfo;
  31. class BinaryDeserializer;
  32. class BinarySerializer;
  33. template<typename T> class CApplier;
  34. #if SCRIPTING_ENABLED
  35. namespace scripting
  36. {
  37. class PoolImpl;
  38. }
  39. #endif
  40. namespace events
  41. {
  42. class EventBus;
  43. }
  44. VCMI_LIB_NAMESPACE_END
  45. class CBattleCallback;
  46. class CCallback;
  47. class CClient;
  48. class CBaseForCLApply;
  49. namespace boost { class thread; }
  50. template<typename T>
  51. class ThreadSafeVector
  52. {
  53. typedef std::vector<T> TVector;
  54. typedef boost::unique_lock<boost::mutex> TLock;
  55. TVector items;
  56. boost::mutex mx;
  57. boost::condition_variable cond;
  58. public:
  59. void clear()
  60. {
  61. TLock lock(mx);
  62. items.clear();
  63. cond.notify_all();
  64. }
  65. void pushBack(const T & item)
  66. {
  67. TLock lock(mx);
  68. items.push_back(item);
  69. cond.notify_all();
  70. }
  71. // //to access list, caller must present a lock used to lock mx
  72. // TVector &getList(TLock &lockedLock)
  73. // {
  74. // assert(lockedLock.owns_lock() && lockedLock.mutex() == &mx);
  75. // return items;
  76. // }
  77. TLock getLock()
  78. {
  79. return TLock(mx);
  80. }
  81. void waitWhileContains(const T & item)
  82. {
  83. auto lock = getLock();
  84. while(vstd::contains(items, item))
  85. cond.wait(lock);
  86. }
  87. bool tryRemovingElement(const T & item) //returns false if element was not present
  88. {
  89. auto lock = getLock();
  90. auto itr = vstd::find(items, item);
  91. if(itr == items.end()) //not in container
  92. {
  93. return false;
  94. }
  95. items.erase(itr);
  96. cond.notify_all();
  97. return true;
  98. }
  99. };
  100. class CPlayerEnvironment : public Environment
  101. {
  102. public:
  103. PlayerColor player;
  104. CClient * cl;
  105. std::shared_ptr<CCallback> mainCallback;
  106. CPlayerEnvironment(PlayerColor player_, CClient * cl_, std::shared_ptr<CCallback> mainCallback_);
  107. const Services * services() const override;
  108. vstd::CLoggerBase * logger() const override;
  109. events::EventBus * eventBus() const override;
  110. const BattleCb * battle() const override;
  111. const GameCb * game() const override;
  112. };
  113. /// Class which handles client - server logic
  114. class CClient : public IGameCallback, public CBattleInfoCallback, public Environment
  115. {
  116. public:
  117. std::map<PlayerColor, std::shared_ptr<CGameInterface>> playerint;
  118. std::map<PlayerColor, std::shared_ptr<CBattleGameInterface>> battleints;
  119. std::map<PlayerColor, std::vector<std::shared_ptr<IBattleEventsReceiver>>> additionalBattleInts;
  120. std::optional<BattleAction> curbaction;
  121. CClient();
  122. ~CClient();
  123. const Services * services() const override;
  124. const BattleCb * battle() const override;
  125. const GameCb * game() const override;
  126. vstd::CLoggerBase * logger() const override;
  127. events::EventBus * eventBus() const override;
  128. void newGame(CGameState * gameState);
  129. void loadGame(CGameState * gameState);
  130. void serialize(BinarySerializer & h, const int version);
  131. void serialize(BinaryDeserializer & h, const int version);
  132. void save(const std::string & fname);
  133. void endGame();
  134. void initMapHandler();
  135. void initPlayerEnvironments();
  136. void initPlayerInterfaces();
  137. std::string aiNameForPlayer(const PlayerSettings & ps, bool battleAI); //empty means no AI -> human
  138. std::string aiNameForPlayer(bool battleAI);
  139. void installNewPlayerInterface(std::shared_ptr<CGameInterface> gameInterface, PlayerColor color, bool battlecb = false);
  140. void installNewBattleInterface(std::shared_ptr<CBattleGameInterface> battleInterface, PlayerColor color, bool needCallback = true);
  141. static ThreadSafeVector<int> waitingRequest; //FIXME: make this normal field (need to join all threads before client destruction)
  142. void handlePack(CPack * pack); //applies the given pack and deletes it
  143. int sendRequest(const CPackForServer * request, PlayerColor player); //returns ID given to that request
  144. void battleStarted(const BattleInfo * info);
  145. void commenceTacticPhaseForInt(std::shared_ptr<CBattleGameInterface> battleInt); //will be called as separate thread
  146. void battleFinished();
  147. void startPlayerBattleAction(PlayerColor color);
  148. void stopPlayerBattleAction(PlayerColor color);
  149. void stopAllBattleActions();
  150. void invalidatePaths();
  151. std::shared_ptr<const CPathsInfo> getPathsInfo(const CGHeroInstance * h);
  152. virtual PlayerColor getLocalPlayer() const override;
  153. friend class CCallback; //handling players actions
  154. friend class CBattleCallback; //handling players actions
  155. void changeSpells(const CGHeroInstance * hero, bool give, const std::set<SpellID> & spells) override {};
  156. bool removeObject(const CGObjectInstance * obj) override {return false;};
  157. void setOwner(const CGObjectInstance * obj, PlayerColor owner) override {};
  158. void changePrimSkill(const CGHeroInstance * hero, PrimarySkill::PrimarySkill which, si64 val, bool abs = false) override {};
  159. void changeSecSkill(const CGHeroInstance * hero, SecondarySkill which, int val, bool abs = false) override {};
  160. void showBlockingDialog(BlockingDialog * iw) override {};
  161. void showGarrisonDialog(ObjectInstanceID upobj, ObjectInstanceID hid, bool removableUnits) override {};
  162. void showTeleportDialog(TeleportDialog * iw) override {};
  163. void showThievesGuildWindow(PlayerColor player, ObjectInstanceID requestingObjId) override {};
  164. void giveResource(PlayerColor player, GameResID which, int val) override {};
  165. virtual void giveResources(PlayerColor player, TResources resources) override {};
  166. void giveCreatures(const CArmedInstance * objid, const CGHeroInstance * h, const CCreatureSet & creatures, bool remove) override {};
  167. void takeCreatures(ObjectInstanceID objid, const std::vector<CStackBasicDescriptor> & creatures) override {};
  168. bool changeStackType(const StackLocation & sl, const CCreature * c) override {return false;};
  169. bool changeStackCount(const StackLocation & sl, TQuantity count, bool absoluteValue = false) override {return false;};
  170. bool insertNewStack(const StackLocation & sl, const CCreature * c, TQuantity count) override {return false;};
  171. bool eraseStack(const StackLocation & sl, bool forceRemoval = false) override {return false;};
  172. bool swapStacks(const StackLocation & sl1, const StackLocation & sl2) override {return false;}
  173. bool addToSlot(const StackLocation & sl, const CCreature * c, TQuantity count) override {return false;}
  174. void tryJoiningArmy(const CArmedInstance * src, const CArmedInstance * dst, bool removeObjWhenFinished, bool allowMerging) override {}
  175. bool moveStack(const StackLocation & src, const StackLocation & dst, TQuantity count = -1) override {return false;}
  176. void removeAfterVisit(const CGObjectInstance * object) override {};
  177. bool swapGarrisonOnSiege(ObjectInstanceID tid) override {return false;};
  178. bool giveHeroNewArtifact(const CGHeroInstance * h, const CArtifact * artType, ArtifactPosition pos) override {return false;}
  179. bool giveHeroArtifact(const CGHeroInstance * h, const CArtifactInstance * a, ArtifactPosition pos) override {return false;}
  180. void putArtifact(const ArtifactLocation & al, const CArtifactInstance * a) override {};
  181. void removeArtifact(const ArtifactLocation & al) override {};
  182. bool moveArtifact(const ArtifactLocation & al1, const ArtifactLocation & al2) override {return false;};
  183. void heroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero) override {};
  184. void visitCastleObjects(const CGTownInstance * obj, const CGHeroInstance * hero) override {};
  185. void stopHeroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero) override {};
  186. 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
  187. void startBattleI(const CArmedInstance * army1, const CArmedInstance * army2, int3 tile, bool creatureBank = false) override {}; //if any of armies is hero, hero will be used
  188. 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
  189. bool moveHero(ObjectInstanceID hid, int3 dst, ui8 teleporting, bool transit = false, PlayerColor asker = PlayerColor::NEUTRAL) override {return false;};
  190. void giveHeroBonus(GiveBonus * bonus) override {};
  191. void setMovePoints(SetMovePoints * smp) override {};
  192. void setManaPoints(ObjectInstanceID hid, int val) override {};
  193. void giveHero(ObjectInstanceID id, PlayerColor player) override {};
  194. void changeObjPos(ObjectInstanceID objid, int3 newPos) override {};
  195. void sendAndApply(CPackForClient * pack) override {};
  196. void heroExchange(ObjectInstanceID hero1, ObjectInstanceID hero2) override {};
  197. void castSpell(const spells::Caster * caster, SpellID spellID, const int3 &pos) override {};
  198. void changeFogOfWar(int3 center, ui32 radius, PlayerColor player, bool hide) override {}
  199. void changeFogOfWar(std::unordered_set<int3, ShashInt3> & tiles, PlayerColor player, bool hide) override {}
  200. void setObjProperty(ObjectInstanceID objid, int prop, si64 val) override {}
  201. void showInfoDialog(InfoWindow * iw) override {};
  202. void showInfoDialog(const std::string & msg, PlayerColor player) override {};
  203. void removeGUI();
  204. void cleanThreads();
  205. #if SCRIPTING_ENABLED
  206. scripting::Pool * getGlobalContextPool() const override;
  207. scripting::Pool * getContextPool() const override;
  208. #endif
  209. private:
  210. std::map<PlayerColor, std::shared_ptr<CBattleCallback>> battleCallbacks; //callbacks given to player interfaces
  211. std::map<PlayerColor, std::shared_ptr<CPlayerEnvironment>> playerEnvironments;
  212. #if SCRIPTING_ENABLED
  213. std::shared_ptr<scripting::PoolImpl> clientScripts;
  214. #endif
  215. std::unique_ptr<events::EventBus> clientEventBus;
  216. std::shared_ptr<CApplier<CBaseForCLApply>> applier;
  217. mutable boost::mutex pathCacheMutex;
  218. std::map<const CGHeroInstance *, std::shared_ptr<CPathsInfo>> pathCache;
  219. std::map<PlayerColor, std::shared_ptr<boost::thread>> playerActionThreads;
  220. std::map<PlayerColor, std::unique_ptr<boost::thread>> playerTacticThreads;
  221. void waitForMoveAndSend(PlayerColor color);
  222. void reinitScripting();
  223. };