Client.h 11 KB

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