Client.h 11 KB

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