Client.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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 <memory>
  12. #include <vcmi/Environment.h>
  13. #include "../lib/IGameCallback.h"
  14. #include "../lib/ConditionalWait.h"
  15. VCMI_LIB_NAMESPACE_BEGIN
  16. struct CPackForServer;
  17. class IBattleEventsReceiver;
  18. class CBattleGameInterface;
  19. class CGameInterface;
  20. class BattleAction;
  21. class BattleInfo;
  22. struct BankConfig;
  23. #if SCRIPTING_ENABLED
  24. namespace scripting
  25. {
  26. class PoolImpl;
  27. }
  28. #endif
  29. namespace events
  30. {
  31. class EventBus;
  32. }
  33. VCMI_LIB_NAMESPACE_END
  34. class CBattleCallback;
  35. class CCallback;
  36. class CClient;
  37. class CBaseForCLApply;
  38. template<typename T>
  39. class ThreadSafeVector
  40. {
  41. using TLock = std::unique_lock<std::mutex>;
  42. std::vector<T> items;
  43. std::mutex mx;
  44. std::condition_variable cond;
  45. std::atomic<bool> isTerminating = false;
  46. public:
  47. void requestTermination()
  48. {
  49. isTerminating = true;
  50. clear();
  51. }
  52. void clear()
  53. {
  54. TLock lock(mx);
  55. items.clear();
  56. cond.notify_all();
  57. }
  58. void pushBack(const T & item)
  59. {
  60. assert(!isTerminating);
  61. TLock lock(mx);
  62. items.push_back(item);
  63. cond.notify_all();
  64. }
  65. void waitWhileContains(const T & item)
  66. {
  67. TLock lock(mx);
  68. while(vstd::contains(items, item))
  69. cond.wait(lock);
  70. if (isTerminating)
  71. throw TerminationRequestedException();
  72. }
  73. bool tryRemovingElement(const T & item) //returns false if element was not present
  74. {
  75. assert(!isTerminating);
  76. TLock lock(mx);
  77. auto itr = vstd::find(items, item);
  78. if(itr == items.end()) //not in container
  79. {
  80. return false;
  81. }
  82. items.erase(itr);
  83. cond.notify_all();
  84. return true;
  85. }
  86. };
  87. class CPlayerEnvironment : public Environment
  88. {
  89. public:
  90. PlayerColor player;
  91. CClient * cl;
  92. std::shared_ptr<CCallback> mainCallback;
  93. CPlayerEnvironment(PlayerColor player_, CClient * cl_, std::shared_ptr<CCallback> mainCallback_);
  94. const Services * services() const override;
  95. vstd::CLoggerBase * logger() const override;
  96. events::EventBus * eventBus() const override;
  97. const BattleCb * battle(const BattleID & battle) const override;
  98. const GameCb * game() const override;
  99. };
  100. /// Class which handles client - server logic
  101. class CClient : public IGameCallback, public Environment
  102. {
  103. std::shared_ptr<CGameState> gamestate;
  104. public:
  105. std::map<PlayerColor, std::shared_ptr<CGameInterface>> playerint;
  106. std::map<PlayerColor, std::shared_ptr<CBattleGameInterface>> battleints;
  107. std::map<PlayerColor, std::vector<std::shared_ptr<IBattleEventsReceiver>>> additionalBattleInts;
  108. std::unique_ptr<BattleAction> currentBattleAction;
  109. CClient();
  110. ~CClient();
  111. const Services * services() const override;
  112. const BattleCb * battle(const BattleID & battle) const override;
  113. const GameCb * game() const override;
  114. vstd::CLoggerBase * logger() const override;
  115. events::EventBus * eventBus() const override;
  116. CGameState & gameState() final { return *gamestate; }
  117. const CGameState & gameState() const final { return *gamestate; }
  118. void newGame(std::shared_ptr<CGameState> gameState);
  119. void loadGame(std::shared_ptr<CGameState> gameState);
  120. void save(const std::string & fname);
  121. void endNetwork();
  122. void finishGameplay();
  123. void endGame();
  124. void initMapHandler();
  125. void initPlayerEnvironments();
  126. void initPlayerInterfaces();
  127. std::string aiNameForPlayer(const PlayerSettings & ps, bool battleAI, bool alliedToHuman) const; //empty means no AI -> human
  128. std::string aiNameForPlayer(bool battleAI, bool alliedToHuman) const;
  129. void installNewPlayerInterface(std::shared_ptr<CGameInterface> gameInterface, PlayerColor color, bool battlecb = false);
  130. void installNewBattleInterface(std::shared_ptr<CBattleGameInterface> battleInterface, PlayerColor color, bool needCallback = true);
  131. ThreadSafeVector<int> waitingRequest;
  132. void handlePack(CPackForClient & pack); //applies the given pack and deletes it
  133. int sendRequest(const CPackForServer & request, PlayerColor player); //returns ID given to that request
  134. void battleStarted(const BattleID & battle);
  135. void battleFinished(const BattleID & battleID);
  136. void startPlayerBattleAction(const BattleID & battleID, PlayerColor color);
  137. friend class CCallback; //handling players actions
  138. friend class CBattleCallback; //handling players actions
  139. void changeSpells(const CGHeroInstance * hero, bool give, const std::set<SpellID> & spells) override {};
  140. void setResearchedSpells(const CGTownInstance * town, int level, const std::vector<SpellID> & spells, bool accepted) override {};
  141. bool removeObject(const CGObjectInstance * obj, const PlayerColor & initiator) override {return false;};
  142. void createBoat(const int3 & visitablePosition, BoatId type, PlayerColor initiator) override {};
  143. void setOwner(const CGObjectInstance * obj, PlayerColor owner) override {};
  144. void giveExperience(const CGHeroInstance * hero, TExpType val) override {};
  145. void changePrimSkill(const CGHeroInstance * hero, 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(const IObjectInterface * caller, BlockingDialog * iw) override {};
  148. void showGarrisonDialog(ObjectInstanceID upobj, ObjectInstanceID hid, bool removableUnits) override {};
  149. void showTeleportDialog(TeleportDialog * iw) override {};
  150. void showObjectWindow(const CGObjectInstance * object, EOpenWindowMode window, const CGHeroInstance * visitor, bool addQuery) override {};
  151. void giveResource(PlayerColor player, GameResID which, int val) override {};
  152. void giveResources(PlayerColor player, TResources resources) override {};
  153. void giveCreatures(const CArmedInstance * objid, const CGHeroInstance * h, const CCreatureSet & creatures, bool remove) override {};
  154. void takeCreatures(ObjectInstanceID objid, const std::vector<CStackBasicDescriptor> & creatures, bool forceRemoval) override {};
  155. bool changeStackType(const StackLocation & sl, const CCreature * c) override {return false;};
  156. bool changeStackCount(const StackLocation & sl, TQuantity count, bool absoluteValue = false) override {return false;};
  157. bool insertNewStack(const StackLocation & sl, const CCreature * c, TQuantity count) override {return false;};
  158. bool eraseStack(const StackLocation & sl, bool forceRemoval = false) override {return false;};
  159. bool swapStacks(const StackLocation & sl1, const StackLocation & sl2) override {return false;}
  160. bool addToSlot(const StackLocation & sl, const CCreature * c, TQuantity count) override {return false;}
  161. void tryJoiningArmy(const CArmedInstance * src, const CArmedInstance * dst, bool removeObjWhenFinished, bool allowMerging) override {}
  162. bool moveStack(const StackLocation & src, const StackLocation & dst, TQuantity count = -1) override {return false;}
  163. void removeAfterVisit(const ObjectInstanceID & id) override {};
  164. bool swapGarrisonOnSiege(ObjectInstanceID tid) override {return false;};
  165. bool giveHeroNewArtifact(const CGHeroInstance * h, const ArtifactID & artId, const ArtifactPosition & pos) override {return false;};
  166. bool giveHeroNewScroll(const CGHeroInstance * h, const SpellID & spellId, const ArtifactPosition & pos) override {return false;};
  167. bool putArtifact(const ArtifactLocation & al, const ArtifactInstanceID & id, std::optional<bool> askAssemble) override {return false;};
  168. void removeArtifact(const ArtifactLocation & al) override {};
  169. bool moveArtifact(const PlayerColor & player, const ArtifactLocation & al1, const ArtifactLocation & al2) override {return false;};
  170. void heroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero) override {};
  171. void visitCastleObjects(const CGTownInstance * obj, const CGHeroInstance * hero) override {};
  172. void stopHeroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero) override {};
  173. void startBattle(const CArmedInstance * army1, const CArmedInstance * army2, int3 tile, const CGHeroInstance * hero1, const CGHeroInstance * hero2, const BattleLayout & layout, const CGTownInstance * town) override {}; //use hero=nullptr for no hero
  174. void startBattle(const CArmedInstance * army1, const CArmedInstance * army2) override {}; //if any of armies is hero, hero will be used
  175. bool moveHero(ObjectInstanceID hid, int3 dst, EMovementMode movementMode, bool transit = false, PlayerColor asker = PlayerColor::NEUTRAL) override {return false;};
  176. void giveHeroBonus(GiveBonus * bonus) override {};
  177. void setMovePoints(SetMovePoints * smp) override {};
  178. void setMovePoints(ObjectInstanceID hid, int val, bool absolute) override {};
  179. void setManaPoints(ObjectInstanceID hid, int val) override {};
  180. void giveHero(ObjectInstanceID id, PlayerColor player, ObjectInstanceID boatId = ObjectInstanceID()) override {};
  181. void changeObjPos(ObjectInstanceID objid, int3 newPos, const PlayerColor & initiator) override {};
  182. void sendAndApply(CPackForClient & pack) override {};
  183. void heroExchange(ObjectInstanceID hero1, ObjectInstanceID hero2) override {};
  184. void castSpell(const spells::Caster * caster, SpellID spellID, const int3 &pos) override {};
  185. void changeFogOfWar(int3 center, ui32 radius, PlayerColor player, ETileVisibility mode) override {}
  186. void changeFogOfWar(const std::unordered_set<int3> & tiles, PlayerColor player, ETileVisibility mode) override {}
  187. void setObjPropertyValue(ObjectInstanceID objid, ObjProperty prop, int32_t value) override {};
  188. void setObjPropertyID(ObjectInstanceID objid, ObjProperty prop, ObjPropertyID identifier) override {};
  189. void setRewardableObjectConfiguration(ObjectInstanceID objid, const Rewardable::Configuration & configuration) override {};
  190. void setRewardableObjectConfiguration(ObjectInstanceID townInstanceID, BuildingID buildingID, const Rewardable::Configuration & configuration) override{};
  191. void showInfoDialog(InfoWindow * iw) override {};
  192. void removeGUI() const;
  193. vstd::RNG & getRandomGenerator() override;
  194. #if SCRIPTING_ENABLED
  195. scripting::Pool * getGlobalContextPool() const override;
  196. #endif
  197. private:
  198. std::map<PlayerColor, std::shared_ptr<CBattleCallback>> battleCallbacks; //callbacks given to player interfaces
  199. std::map<PlayerColor, std::shared_ptr<CPlayerEnvironment>> playerEnvironments;
  200. #if SCRIPTING_ENABLED
  201. std::shared_ptr<scripting::PoolImpl> clientScripts;
  202. #endif
  203. std::unique_ptr<events::EventBus> clientEventBus;
  204. void reinitScripting();
  205. };