Client.h 10 KB

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