Client.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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 "../lib/IGameCallback.h"
  12. #include "../lib/battle/BattleAction.h"
  13. #include "../lib/CStopWatch.h"
  14. #include "../lib/int3.h"
  15. struct CPack;
  16. class CCampaignState;
  17. class CBattleCallback;
  18. class IGameEventsReceiver;
  19. class IBattleEventsReceiver;
  20. class CBattleGameInterface;
  21. struct StartInfo;
  22. class CGameState;
  23. class CGameInterface;
  24. class CConnection;
  25. class CCallback;
  26. class BattleAction;
  27. struct SharedMemory;
  28. class CClient;
  29. class CScriptingModule;
  30. struct CPathsInfo;
  31. class BinaryDeserializer;
  32. class BinarySerializer;
  33. namespace boost { class thread; }
  34. /// structure to handle running server and connecting to it
  35. class CServerHandler
  36. {
  37. private:
  38. void callServer(); //calls server via system(), should be called as thread
  39. public:
  40. CStopWatch th;
  41. boost::thread *serverThread; //thread that called system to run server
  42. SharedMemory * shared;
  43. std::string uuid;
  44. bool verbose; //whether to print log msgs
  45. //functions setting up local server
  46. void startServer(); //creates a thread with callServer
  47. void waitForServer(); //waits till server is ready
  48. CConnection * connectToServer(); //connects to server
  49. //////////////////////////////////////////////////////////////////////////
  50. static CConnection * justConnectToServer(const std::string &host = "", const ui16 port = 0); //connects to given host without taking any other actions (like setting up server)
  51. static ui16 getDefaultPort();
  52. static std::string getDefaultPortStr();
  53. CServerHandler(bool runServer = false);
  54. virtual ~CServerHandler();
  55. };
  56. template<typename T>
  57. class ThreadSafeVector
  58. {
  59. typedef std::vector<T> TVector;
  60. typedef boost::unique_lock<boost::mutex> TLock;
  61. TVector items;
  62. boost::mutex mx;
  63. boost::condition_variable cond;
  64. public:
  65. void clear()
  66. {
  67. TLock lock(mx);
  68. items.clear();
  69. cond.notify_all();
  70. }
  71. void pushBack(const T &item)
  72. {
  73. TLock lock(mx);
  74. items.push_back(item);
  75. cond.notify_all();
  76. }
  77. // //to access list, caller must present a lock used to lock mx
  78. // TVector &getList(TLock &lockedLock)
  79. // {
  80. // assert(lockedLock.owns_lock() && lockedLock.mutex() == &mx);
  81. // return items;
  82. // }
  83. TLock getLock()
  84. {
  85. return TLock(mx);
  86. }
  87. void waitWhileContains(const T &item)
  88. {
  89. auto lock = getLock();
  90. while(vstd::contains(items, item))
  91. cond.wait(lock);
  92. }
  93. bool tryRemovingElement(const T&item) //returns false if element was not present
  94. {
  95. auto lock = getLock();
  96. auto itr = vstd::find(items, item);
  97. if(itr == items.end()) //not in container
  98. {
  99. return false;
  100. }
  101. items.erase(itr);
  102. cond.notify_all();
  103. return true;
  104. }
  105. };
  106. /// Class which handles client - server logic
  107. class CClient : public IGameCallback
  108. {
  109. std::unique_ptr<CPathsInfo> pathInfo;
  110. std::map<PlayerColor, std::shared_ptr<boost::thread>> playerActionThreads;
  111. public:
  112. std::map<PlayerColor,std::shared_ptr<CCallback> > callbacks; //callbacks given to player interfaces
  113. std::map<PlayerColor,std::shared_ptr<CBattleCallback> > battleCallbacks; //callbacks given to player interfaces
  114. std::vector<std::shared_ptr<IGameEventsReceiver>> privilegedGameEventReceivers; //scripting modules, spectator interfaces
  115. std::vector<std::shared_ptr<IBattleEventsReceiver>> privilegedBattleEventReceivers; //scripting modules, spectator interfaces
  116. std::map<PlayerColor, std::shared_ptr<CGameInterface>> playerint;
  117. std::map<PlayerColor, std::shared_ptr<CBattleGameInterface>> battleints;
  118. std::map<PlayerColor,std::vector<std::shared_ptr<IGameEventsReceiver>>> additionalPlayerInts;
  119. std::map<PlayerColor,std::vector<std::shared_ptr<IBattleEventsReceiver>>> additionalBattleInts;
  120. bool hotSeat;
  121. CConnection *serv;
  122. boost::optional<BattleAction> curbaction;
  123. CScriptingModule *erm;
  124. static ThreadSafeVector<int> waitingRequest;//FIXME: make this normal field (need to join all threads before client destruction)
  125. //void sendRequest(const CPackForServer *request, bool waitForRealization);
  126. CClient();
  127. CClient(CConnection *con, StartInfo *si);
  128. ~CClient();
  129. void init();
  130. void newGame(CConnection *con, StartInfo *si); //con - connection to server
  131. void loadNeutralBattleAI();
  132. void installNewPlayerInterface(std::shared_ptr<CGameInterface> gameInterface, boost::optional<PlayerColor> color, bool battlecb = false);
  133. void installNewBattleInterface(std::shared_ptr<CBattleGameInterface> battleInterface, boost::optional<PlayerColor> color, bool needCallback = true);
  134. std::string aiNameForPlayer(const PlayerSettings &ps, bool battleAI); //empty means no AI -> human
  135. std::string aiNameForPlayer(bool battleAI);
  136. void endGame(bool closeConnection = true);
  137. void stopConnection();
  138. void save(const std::string & fname);
  139. void loadGame(const std::string & fname, const bool server = true, const std::vector<int>& humanplayerindices = std::vector<int>(), const int loadnumplayers = 1, int player_ = -1, const std::string & ipaddr = "", const ui16 port = 0);
  140. void run();
  141. void campaignMapFinished( std::shared_ptr<CCampaignState> camp );
  142. void finishCampaign( std::shared_ptr<CCampaignState> camp );
  143. void proposeNextMission(std::shared_ptr<CCampaignState> camp);
  144. void invalidatePaths();
  145. const CPathsInfo * getPathsInfo(const CGHeroInstance *h);
  146. bool terminate; // tell to terminate
  147. std::unique_ptr<boost::thread> connectionHandler; //thread running run() method
  148. boost::mutex connectionHandlerMutex;
  149. //////////////////////////////////////////////////////////////////////////
  150. virtual PlayerColor getLocalPlayer() const override;
  151. //////////////////////////////////////////////////////////////////////////
  152. //not working yet, will be implement somewhen later with support for local-sim-based gameplay
  153. void changeSpells(const CGHeroInstance * hero, bool give, const std::set<SpellID> &spells) override {};
  154. bool removeObject(const CGObjectInstance * obj) override {return false;};
  155. void setBlockVis(ObjectInstanceID objid, bool bv) override {};
  156. void setOwner(const CGObjectInstance * obj, PlayerColor owner) override {};
  157. void changePrimSkill(const CGHeroInstance * hero, PrimarySkill::PrimarySkill which, si64 val, bool abs=false) override {};
  158. void changeSecSkill(const CGHeroInstance * hero, SecondarySkill which, int val, bool abs=false) override {};
  159. void showBlockingDialog(BlockingDialog *iw) override {};
  160. void showGarrisonDialog(ObjectInstanceID upobj, ObjectInstanceID hid, bool removableUnits) override {};
  161. void showTeleportDialog(TeleportDialog *iw) override {};
  162. void showThievesGuildWindow(PlayerColor player, ObjectInstanceID requestingObjId) override {};
  163. void giveResource(PlayerColor player, Res::ERes which, int val) override {};
  164. virtual void giveResources(PlayerColor player, TResources resources) override {};
  165. void giveCreatures(const CArmedInstance * objid, const CGHeroInstance * h, const CCreatureSet &creatures, bool remove) override {};
  166. void takeCreatures(ObjectInstanceID objid, const std::vector<CStackBasicDescriptor> &creatures) override {};
  167. bool changeStackType(const StackLocation &sl, const CCreature *c) override {return false;};
  168. bool changeStackCount(const StackLocation &sl, TQuantity count, bool absoluteValue = false) override {return false;};
  169. bool insertNewStack(const StackLocation &sl, const CCreature *c, TQuantity count) override {return false;};
  170. bool eraseStack(const StackLocation &sl, bool forceRemoval = false) override{return false;};
  171. bool swapStacks(const StackLocation &sl1, const StackLocation &sl2) override {return false;}
  172. bool addToSlot(const StackLocation &sl, const CCreature *c, TQuantity count) override {return false;}
  173. void tryJoiningArmy(const CArmedInstance *src, const CArmedInstance *dst, bool removeObjWhenFinished, bool allowMerging) override {}
  174. bool moveStack(const StackLocation &src, const StackLocation &dst, TQuantity count = -1) override {return false;}
  175. void removeAfterVisit(const CGObjectInstance *object) override {};
  176. void giveHeroNewArtifact(const CGHeroInstance *h, const CArtifact *artType, ArtifactPosition pos) override {};
  177. void giveHeroArtifact(const CGHeroInstance *h, const CArtifactInstance *a, ArtifactPosition pos) override {};
  178. void putArtifact(const ArtifactLocation &al, const CArtifactInstance *a) override {};
  179. void removeArtifact(const ArtifactLocation &al) override {};
  180. bool moveArtifact(const ArtifactLocation &al1, const ArtifactLocation &al2) override {return false;};
  181. void synchronizeArtifactHandlerLists() override {};
  182. void showCompInfo(ShowInInfobox * comp) override {};
  183. void heroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero) override {};
  184. void stopHeroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero) override {};
  185. 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
  186. void startBattleI(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, bool creatureBank = false) override {}; //if any of armies is hero, hero will be used
  187. 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
  188. void setAmount(ObjectInstanceID objid, ui32 val) override {};
  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, ui8 flags) override {};
  195. void sendAndApply(CPackForClient * info) override {};
  196. void heroExchange(ObjectInstanceID hero1, ObjectInstanceID hero2) override {};
  197. void changeFogOfWar(int3 center, ui32 radius, PlayerColor player, bool hide) override {}
  198. void changeFogOfWar(std::unordered_set<int3, ShashInt3> &tiles, PlayerColor player, bool hide) override {}
  199. //////////////////////////////////////////////////////////////////////////
  200. friend class CCallback; //handling players actions
  201. friend class CBattleCallback; //handling players actions
  202. int sendRequest(const CPack *request, PlayerColor player); //returns ID given to that request
  203. void handlePack( CPack * pack ); //applies the given pack and deletes it
  204. void battleStarted(const BattleInfo * info);
  205. void commenceTacticPhaseForInt(std::shared_ptr<CBattleGameInterface> battleInt); //will be called as separate thread
  206. void commitPackage(CPackForClient *pack) override;
  207. //////////////////////////////////////////////////////////////////////////
  208. void serialize(BinarySerializer & h, const int version);
  209. void serialize(BinaryDeserializer & h, const int version);
  210. void serialize(BinarySerializer & h, const int version, const std::set<PlayerColor>& playerIDs);
  211. void serialize(BinaryDeserializer & h, const int version, const std::set<PlayerColor>& playerIDs);
  212. void battleFinished();
  213. void startPlayerBattleAction(PlayerColor color);
  214. void stopPlayerBattleAction(PlayerColor color);
  215. void stopAllBattleActions();
  216. private:
  217. void waitForMoveAndSend(PlayerColor color);
  218. };