Client.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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. public:
  100. std::map<PlayerColor,shared_ptr<CCallback> > callbacks; //callbacks given to player interfaces
  101. std::map<PlayerColor,shared_ptr<CBattleCallback> > battleCallbacks; //callbacks given to player interfaces
  102. std::vector<shared_ptr<IGameEventsReceiver>> privilagedGameEventReceivers; //scripting modules, spectator interfaces
  103. std::vector<shared_ptr<IBattleEventsReceiver>> privilagedBattleEventReceivers; //scripting modules, spectator interfaces
  104. std::map<PlayerColor, shared_ptr<CGameInterface>> playerint;
  105. std::map<PlayerColor, shared_ptr<CBattleGameInterface>> battleints;
  106. std::map<PlayerColor,std::vector<shared_ptr<IGameEventsReceiver>>> additionalPlayerInts;
  107. std::map<PlayerColor,std::vector<shared_ptr<IBattleEventsReceiver>>> additionalBattleInts;
  108. bool hotSeat;
  109. CConnection *serv;
  110. boost::optional<BattleAction> curbaction;
  111. unique_ptr<CPathsInfo> pathInfo;
  112. boost::mutex pathMx; //protects the variable above
  113. CScriptingModule *erm;
  114. ThreadSafeVector<int> waitingRequest;
  115. void waitForMoveAndSend(PlayerColor color);
  116. //void sendRequest(const CPackForServer *request, bool waitForRealization);
  117. CClient(void);
  118. CClient(CConnection *con, StartInfo *si);
  119. ~CClient(void);
  120. void init();
  121. void newGame(CConnection *con, StartInfo *si); //con - connection to server
  122. void loadNeutralBattleAI();
  123. void installNewPlayerInterface(shared_ptr<CGameInterface> gameInterface, boost::optional<PlayerColor> color);
  124. void installNewBattleInterface(shared_ptr<CBattleGameInterface> battleInterface, boost::optional<PlayerColor> color, bool needCallback = true);
  125. std::string aiNameForPlayer(const PlayerSettings &ps, bool battleAI); //empty means no AI -> human
  126. void endGame(bool closeConnection = true);
  127. void stopConnection();
  128. void save(const std::string & fname);
  129. void loadGame(const std::string & fname);
  130. void run();
  131. void campaignMapFinished( shared_ptr<CCampaignState> camp );
  132. void finishCampaign( shared_ptr<CCampaignState> camp );
  133. void proposeNextMission(shared_ptr<CCampaignState> camp);
  134. void invalidatePaths(const CGHeroInstance *h = nullptr); //invalidates paths for hero h or for any hero if h is nullptr => they'll got recalculated when the next query comes
  135. void calculatePaths(const CGHeroInstance *h);
  136. void updatePaths(); //calls calculatePaths for same hero for which we previously calculated paths
  137. bool terminate; // tell to terminate
  138. boost::thread *connectionHandler; //thread running run() method
  139. //////////////////////////////////////////////////////////////////////////
  140. virtual PlayerColor getLocalPlayer() const override;
  141. //////////////////////////////////////////////////////////////////////////
  142. //not working yet, will be implement somewhen later with support for local-sim-based gameplay
  143. void changeSpells(const CGHeroInstance * hero, bool give, const std::set<SpellID> &spells) override {};
  144. bool removeObject(const CGObjectInstance * obj) override {return false;};
  145. void setBlockVis(ObjectInstanceID objid, bool bv) override {};
  146. void setOwner(const CGObjectInstance * obj, PlayerColor owner) override {};
  147. void changePrimSkill(const CGHeroInstance * hero, PrimarySkill::PrimarySkill which, si64 val, bool abs=false) override {};
  148. void changeSecSkill(const CGHeroInstance * hero, SecondarySkill which, int val, bool abs=false) override {};
  149. void showBlockingDialog(BlockingDialog *iw) override {};
  150. void showGarrisonDialog(ObjectInstanceID upobj, ObjectInstanceID hid, bool removableUnits) override {};
  151. void showThievesGuildWindow(PlayerColor player, ObjectInstanceID requestingObjId) override {};
  152. void giveResource(PlayerColor player, Res::ERes which, int val) override {};
  153. virtual void giveResources(PlayerColor player, TResources resources) override {};
  154. void giveCreatures(const CArmedInstance * objid, const CGHeroInstance * h, const CCreatureSet &creatures, bool remove) override {};
  155. void takeCreatures(ObjectInstanceID objid, const std::vector<CStackBasicDescriptor> &creatures) override {};
  156. bool changeStackType(const StackLocation &sl, CCreature *c) override {return false;};
  157. bool changeStackCount(const StackLocation &sl, TQuantity count, bool absoluteValue = false) override {return false;};
  158. bool insertNewStack(const StackLocation &sl, const CCreature *c, TQuantity count) override {return false;};
  159. bool eraseStack(const StackLocation &sl, bool forceRemoval = false){return false;};
  160. bool swapStacks(const StackLocation &sl1, const StackLocation &sl2) override {return false;}
  161. bool addToSlot(const StackLocation &sl, const CCreature *c, TQuantity count) override {return false;}
  162. void tryJoiningArmy(const CArmedInstance *src, const CArmedInstance *dst, bool removeObjWhenFinished, bool allowMerging) override {}
  163. bool moveStack(const StackLocation &src, const StackLocation &dst, TQuantity count = -1) override {return false;}
  164. void removeAfterVisit(const CGObjectInstance *object) override {};
  165. void giveHeroNewArtifact(const CGHeroInstance *h, const CArtifact *artType, ArtifactPosition pos) override {};
  166. void giveHeroArtifact(const CGHeroInstance *h, const CArtifactInstance *a, ArtifactPosition pos) override {};
  167. void putArtifact(const ArtifactLocation &al, const CArtifactInstance *a) override {};
  168. void removeArtifact(const ArtifactLocation &al) override {};
  169. bool moveArtifact(const ArtifactLocation &al1, const ArtifactLocation &al2) override {return false;};
  170. void synchronizeArtifactHandlerLists() override {};
  171. void showCompInfo(ShowInInfobox * comp) override {};
  172. void heroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero) override {};
  173. void stopHeroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero) override {};
  174. //void giveHeroArtifact(int artid, int hid, int position){};
  175. //void giveNewArtifact(int hid, int position){};
  176. 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
  177. void startBattleI(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, bool creatureBank = false) override {}; //if any of armies is hero, hero will be used
  178. 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
  179. void setAmount(ObjectInstanceID objid, ui32 val) override {};
  180. bool moveHero(ObjectInstanceID hid, int3 dst, ui8 teleporting, PlayerColor asker = PlayerColor::NEUTRAL) override {return false;};
  181. void giveHeroBonus(GiveBonus * bonus) override {};
  182. void setMovePoints(SetMovePoints * smp) override {};
  183. void setManaPoints(ObjectInstanceID hid, int val) override {};
  184. void giveHero(ObjectInstanceID id, PlayerColor player) override {};
  185. void changeObjPos(ObjectInstanceID objid, int3 newPos, ui8 flags) override {};
  186. void sendAndApply(CPackForClient * info) override {};
  187. void heroExchange(ObjectInstanceID hero1, ObjectInstanceID hero2) override {};
  188. void changeFogOfWar(int3 center, ui32 radius, PlayerColor player, bool hide) override {}
  189. void changeFogOfWar(std::unordered_set<int3, ShashInt3> &tiles, PlayerColor player, bool hide) override {}
  190. //////////////////////////////////////////////////////////////////////////
  191. friend class CCallback; //handling players actions
  192. friend class CBattleCallback; //handling players actions
  193. int sendRequest(const CPack *request, PlayerColor player); //returns ID given to that request
  194. void handlePack( CPack * pack ); //applies the given pack and deletes it
  195. void battleStarted(const BattleInfo * info);
  196. void commenceTacticPhaseForInt(shared_ptr<CBattleGameInterface> battleInt); //will be called as separate thread
  197. void commitPackage(CPackForClient *pack) override;
  198. //////////////////////////////////////////////////////////////////////////
  199. template <typename Handler> void serialize(Handler &h, const int version);
  200. void battleFinished();
  201. };