Client.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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. class CISer;
  32. class COSer;
  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. SharedMem *shared; //interprocess memory (for waiting for server)
  43. bool verbose; //whether to print log msgs
  44. std::string port; //port number in text form
  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 std::string &port = ""); //connects to given host without taking any other actions (like setting up server)
  51. CServerHandler(bool runServer = false);
  52. ~CServerHandler();
  53. };
  54. template<typename T>
  55. class ThreadSafeVector
  56. {
  57. typedef std::vector<T> TVector;
  58. typedef boost::unique_lock<boost::mutex> TLock;
  59. TVector items;
  60. boost::mutex mx;
  61. boost::condition_variable cond;
  62. public:
  63. void pushBack(const T &item)
  64. {
  65. TLock lock(mx);
  66. items.push_back(item);
  67. cond.notify_all();
  68. }
  69. // //to access list, caller must present a lock used to lock mx
  70. // TVector &getList(TLock &lockedLock)
  71. // {
  72. // assert(lockedLock.owns_lock() && lockedLock.mutex() == &mx);
  73. // return items;
  74. // }
  75. TLock getLock()
  76. {
  77. return TLock(mx);
  78. }
  79. void waitWhileContains(const T &item)
  80. {
  81. auto lock = getLock();
  82. while(vstd::contains(items, item))
  83. cond.wait(lock);
  84. }
  85. bool tryRemovingElement(const T&item) //returns false if element was not present
  86. {
  87. auto lock = getLock();
  88. auto itr = vstd::find(items, item);
  89. if(itr == items.end()) //not in container
  90. {
  91. return false;
  92. }
  93. items.erase(itr);
  94. cond.notify_all();
  95. return true;
  96. }
  97. };
  98. /// Class which handles client - server logic
  99. class CClient : public IGameCallback
  100. {
  101. unique_ptr<CPathsInfo> pathInfo;
  102. public:
  103. std::map<PlayerColor,shared_ptr<CCallback> > callbacks; //callbacks given to player interfaces
  104. std::map<PlayerColor,shared_ptr<CBattleCallback> > battleCallbacks; //callbacks given to player interfaces
  105. std::vector<shared_ptr<IGameEventsReceiver>> privilagedGameEventReceivers; //scripting modules, spectator interfaces
  106. std::vector<shared_ptr<IBattleEventsReceiver>> privilagedBattleEventReceivers; //scripting modules, spectator interfaces
  107. std::map<PlayerColor, shared_ptr<CGameInterface>> playerint;
  108. std::map<PlayerColor, shared_ptr<CBattleGameInterface>> battleints;
  109. std::map<PlayerColor,std::vector<shared_ptr<IGameEventsReceiver>>> additionalPlayerInts;
  110. std::map<PlayerColor,std::vector<shared_ptr<IBattleEventsReceiver>>> additionalBattleInts;
  111. bool hotSeat;
  112. CConnection *serv;
  113. boost::optional<BattleAction> curbaction;
  114. CScriptingModule *erm;
  115. ThreadSafeVector<int> waitingRequest;
  116. void waitForMoveAndSend(PlayerColor color);
  117. //void sendRequest(const CPackForServer *request, bool waitForRealization);
  118. CClient(void);
  119. CClient(CConnection *con, StartInfo *si);
  120. ~CClient(void);
  121. void init();
  122. void newGame(CConnection *con, StartInfo *si); //con - connection to server
  123. void loadNeutralBattleAI();
  124. void installNewPlayerInterface(shared_ptr<CGameInterface> gameInterface, boost::optional<PlayerColor> color);
  125. void installNewBattleInterface(shared_ptr<CBattleGameInterface> battleInterface, boost::optional<PlayerColor> color, bool needCallback = true);
  126. std::string aiNameForPlayer(const PlayerSettings &ps, bool battleAI); //empty means no AI -> human
  127. void endGame(bool closeConnection = true);
  128. void stopConnection();
  129. void save(const std::string & fname);
  130. 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 = "");
  131. void run();
  132. void campaignMapFinished( shared_ptr<CCampaignState> camp );
  133. void finishCampaign( shared_ptr<CCampaignState> camp );
  134. void proposeNextMission(shared_ptr<CCampaignState> camp);
  135. void invalidatePaths();
  136. const CPathsInfo * getPathsInfo(const CGHeroInstance *h);
  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 showTeleportDialog(TeleportDialog *iw) override {};
  152. void showThievesGuildWindow(PlayerColor player, ObjectInstanceID requestingObjId) override {};
  153. void giveResource(PlayerColor player, Res::ERes which, int val) override {};
  154. virtual void giveResources(PlayerColor player, TResources resources) override {};
  155. void giveCreatures(const CArmedInstance * objid, const CGHeroInstance * h, const CCreatureSet &creatures, bool remove) override {};
  156. void takeCreatures(ObjectInstanceID objid, const std::vector<CStackBasicDescriptor> &creatures) override {};
  157. bool changeStackType(const StackLocation &sl, CCreature *c) override {return false;};
  158. bool changeStackCount(const StackLocation &sl, TQuantity count, bool absoluteValue = false) override {return false;};
  159. bool insertNewStack(const StackLocation &sl, const CCreature *c, TQuantity count) override {return false;};
  160. bool eraseStack(const StackLocation &sl, bool forceRemoval = false){return false;};
  161. bool swapStacks(const StackLocation &sl1, const StackLocation &sl2) override {return false;}
  162. bool addToSlot(const StackLocation &sl, const CCreature *c, TQuantity count) override {return false;}
  163. void tryJoiningArmy(const CArmedInstance *src, const CArmedInstance *dst, bool removeObjWhenFinished, bool allowMerging) override {}
  164. bool moveStack(const StackLocation &src, const StackLocation &dst, TQuantity count = -1) override {return false;}
  165. void removeAfterVisit(const CGObjectInstance *object) override {};
  166. void giveHeroNewArtifact(const CGHeroInstance *h, const CArtifact *artType, ArtifactPosition pos) override {};
  167. void giveHeroArtifact(const CGHeroInstance *h, const CArtifactInstance *a, ArtifactPosition pos) override {};
  168. void putArtifact(const ArtifactLocation &al, const CArtifactInstance *a) override {};
  169. void removeArtifact(const ArtifactLocation &al) override {};
  170. bool moveArtifact(const ArtifactLocation &al1, const ArtifactLocation &al2) override {return false;};
  171. void synchronizeArtifactHandlerLists() override {};
  172. void showCompInfo(ShowInInfobox * comp) override {};
  173. void heroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero) override {};
  174. void stopHeroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero) override {};
  175. //void giveHeroArtifact(int artid, int hid, int position){};
  176. //void giveNewArtifact(int hid, int position){};
  177. 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
  178. void startBattleI(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, bool creatureBank = false) override {}; //if any of armies is hero, hero will be used
  179. 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
  180. void setAmount(ObjectInstanceID objid, ui32 val) override {};
  181. bool moveHero(ObjectInstanceID hid, int3 dst, ui8 teleporting, bool transit = false, PlayerColor asker = PlayerColor::NEUTRAL) override {return false;};
  182. void giveHeroBonus(GiveBonus * bonus) override {};
  183. void setMovePoints(SetMovePoints * smp) override {};
  184. void setManaPoints(ObjectInstanceID hid, int val) override {};
  185. void giveHero(ObjectInstanceID id, PlayerColor player) override {};
  186. void changeObjPos(ObjectInstanceID objid, int3 newPos, ui8 flags) override {};
  187. void sendAndApply(CPackForClient * info) override {};
  188. void heroExchange(ObjectInstanceID hero1, ObjectInstanceID hero2) override {};
  189. void changeFogOfWar(int3 center, ui32 radius, PlayerColor player, bool hide) override {}
  190. void changeFogOfWar(std::unordered_set<int3, ShashInt3> &tiles, PlayerColor player, bool hide) override {}
  191. //////////////////////////////////////////////////////////////////////////
  192. friend class CCallback; //handling players actions
  193. friend class CBattleCallback; //handling players actions
  194. int sendRequest(const CPack *request, PlayerColor player); //returns ID given to that request
  195. void handlePack( CPack * pack ); //applies the given pack and deletes it
  196. void battleStarted(const BattleInfo * info);
  197. void commenceTacticPhaseForInt(shared_ptr<CBattleGameInterface> battleInt); //will be called as separate thread
  198. void commitPackage(CPackForClient *pack) override;
  199. //////////////////////////////////////////////////////////////////////////
  200. void serialize(COSer &h, const int version);
  201. void serialize(CISer &h, const int version);
  202. void serialize(COSer &h, const int version, const std::set<PlayerColor>& playerIDs);
  203. void serialize(CISer &h, const int version, const std::set<PlayerColor>& playerIDs);
  204. void battleFinished();
  205. };