Client.h 10 KB

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