CGameHandler.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. /*
  2. * CGameHandler.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 <vcmi/Environment.h>
  12. #include "../lib/FunctionList.h"
  13. #include "../lib/IGameCallback.h"
  14. #include "../lib/battle/CBattleInfoCallback.h"
  15. #include "../lib/battle/BattleAction.h"
  16. #include "../lib/ScriptHandler.h"
  17. #include "CQuery.h"
  18. #include "TurnTimerHandler.h"
  19. VCMI_LIB_NAMESPACE_BEGIN
  20. class CGameState;
  21. struct StartInfo;
  22. struct BattleResult;
  23. struct SideInBattle;
  24. struct BattleAttack;
  25. struct BattleStackAttacked;
  26. struct CPack;
  27. struct Query;
  28. struct SetResources;
  29. struct NewStructures;
  30. class CGHeroInstance;
  31. class IMarket;
  32. class SpellCastEnvironment;
  33. #if SCRIPTING_ENABLED
  34. namespace scripting
  35. {
  36. class PoolImpl;
  37. }
  38. #endif
  39. template<typename T> class CApplier;
  40. VCMI_LIB_NAMESPACE_END
  41. class HeroPoolProcessor;
  42. class CGameHandler;
  43. class CVCMIServer;
  44. class CBaseForGHApply;
  45. class PlayerMessageProcessor;
  46. struct PlayerStatus
  47. {
  48. bool makingTurn;
  49. PlayerStatus():makingTurn(false){};
  50. template <typename Handler> void serialize(Handler &h, const int version)
  51. {
  52. h & makingTurn;
  53. }
  54. };
  55. class PlayerStatuses
  56. {
  57. public:
  58. std::map<PlayerColor,PlayerStatus> players;
  59. boost::mutex mx;
  60. boost::condition_variable cv; //notifies when any changes are made
  61. void addPlayer(PlayerColor player);
  62. PlayerStatus operator[](PlayerColor player);
  63. bool checkFlag(PlayerColor player, bool PlayerStatus::*flag);
  64. void setFlag(PlayerColor player, bool PlayerStatus::*flag, bool val);
  65. template <typename Handler> void serialize(Handler &h, const int version)
  66. {
  67. h & players;
  68. }
  69. };
  70. struct CasualtiesAfterBattle
  71. {
  72. using TStackAndItsNewCount = std::pair<StackLocation, int>;
  73. using TSummoned = std::map<CreatureID, TQuantity>;
  74. enum {ERASE = -1};
  75. const CArmedInstance * army;
  76. std::vector<TStackAndItsNewCount> newStackCounts;
  77. std::vector<ArtifactLocation> removedWarMachines;
  78. TSummoned summoned;
  79. ObjectInstanceID heroWithDeadCommander; //TODO: unify stack locations
  80. CasualtiesAfterBattle(const SideInBattle & battleSide, const BattleInfo * bat);
  81. void updateArmy(CGameHandler *gh);
  82. };
  83. class CGameHandler : public IGameCallback, public CBattleInfoCallback, public Environment
  84. {
  85. CVCMIServer * lobby;
  86. std::shared_ptr<CApplier<CBaseForGHApply>> applier;
  87. std::unique_ptr<boost::thread> battleThread;
  88. TurnTimerHandler turnTimerHandler;
  89. public:
  90. std::unique_ptr<HeroPoolProcessor> heroPool;
  91. using FireShieldInfo = std::vector<std::pair<const CStack *, int64_t>>;
  92. //use enums as parameters, because doMove(sth, true, false, true) is not readable
  93. enum EGuardLook {CHECK_FOR_GUARDS, IGNORE_GUARDS};
  94. enum EVisitDest {VISIT_DEST, DONT_VISIT_DEST};
  95. enum ELEaveTile {LEAVING_TILE, REMAINING_ON_TILE};
  96. std::unique_ptr<PlayerMessageProcessor> playerMessages;
  97. std::map<PlayerColor, std::set<std::shared_ptr<CConnection>>> connections; //player color -> connection to client with interface of that player
  98. PlayerStatuses states; //player color -> player state
  99. //queries stuff
  100. boost::recursive_mutex gsm;
  101. ui32 QID;
  102. Queries queries;
  103. SpellCastEnvironment * spellEnv;
  104. const Services * services() const override;
  105. const BattleCb * battle() const override;
  106. const GameCb * game() const override;
  107. vstd::CLoggerBase * logger() const override;
  108. events::EventBus * eventBus() const override;
  109. CVCMIServer * gameLobby() const;
  110. bool isValidObject(const CGObjectInstance *obj) const;
  111. bool isBlockedByQueries(const CPack *pack, PlayerColor player);
  112. bool isAllowedExchange(ObjectInstanceID id1, ObjectInstanceID id2);
  113. void giveSpells(const CGTownInstance *t, const CGHeroInstance *h);
  114. int moveStack(int stack, BattleHex dest); //returned value - travelled distance
  115. void runBattle();
  116. ////used only in endBattle - don't touch elsewhere
  117. bool visitObjectAfterVictory;
  118. //
  119. void endBattle(int3 tile, const CGHeroInstance * hero1, const CGHeroInstance * hero2); //ends battle
  120. void endBattleConfirm(const BattleInfo * battleInfo);
  121. void makeAttack(const CStack * attacker, const CStack * defender, int distance, BattleHex targetHex, bool first, bool ranged, bool counter);
  122. // damage, drain life & fire shield; returns amount of drained life
  123. int64_t applyBattleEffects(BattleAttack & bat, std::shared_ptr<battle::CUnitState> attackerState, FireShieldInfo & fireShield, const CStack * def, int distance, bool secondary);
  124. void sendGenericKilledLog(const CStack * defender, int32_t killed, bool multiple);
  125. void addGenericKilledLog(BattleLogMessage & blm, const CStack * defender, int32_t killed, bool multiple);
  126. void checkBattleStateChanges();
  127. void setupBattle(int3 tile, const CArmedInstance *armies[2], const CGHeroInstance *heroes[2], bool creatureBank, const CGTownInstance *town);
  128. void setBattleResult(BattleResult::EResult resultType, int victoriusSide);
  129. CGameHandler();
  130. CGameHandler(CVCMIServer * lobby);
  131. ~CGameHandler();
  132. //////////////////////////////////////////////////////////////////////////
  133. //from IGameCallback
  134. //do sth
  135. void changeSpells(const CGHeroInstance * hero, bool give, const std::set<SpellID> &spells) override;
  136. bool removeObject(const CGObjectInstance * obj) override;
  137. void createObject(const int3 & visitablePosition, Obj type, int32_t subtype ) override;
  138. void setOwner(const CGObjectInstance * obj, PlayerColor owner) override;
  139. void changePrimSkill(const CGHeroInstance * hero, PrimarySkill::PrimarySkill which, si64 val, bool abs=false) override;
  140. void changeSecSkill(const CGHeroInstance * hero, SecondarySkill which, int val, bool abs=false) override;
  141. void showBlockingDialog(BlockingDialog *iw) override;
  142. void showTeleportDialog(TeleportDialog *iw) override;
  143. void showGarrisonDialog(ObjectInstanceID upobj, ObjectInstanceID hid, bool removableUnits) override;
  144. void showThievesGuildWindow(PlayerColor player, ObjectInstanceID requestingObjId) override;
  145. void giveResource(PlayerColor player, GameResID which, int val) override;
  146. void giveResources(PlayerColor player, TResources resources) override;
  147. void giveCreatures(const CArmedInstance *objid, const CGHeroInstance * h, const CCreatureSet &creatures, bool remove) override;
  148. void takeCreatures(ObjectInstanceID objid, const std::vector<CStackBasicDescriptor> &creatures) override;
  149. bool changeStackType(const StackLocation &sl, const CCreature *c) override;
  150. bool changeStackCount(const StackLocation &sl, TQuantity count, bool absoluteValue = false) override;
  151. bool insertNewStack(const StackLocation &sl, const CCreature *c, TQuantity count) override;
  152. bool eraseStack(const StackLocation &sl, bool forceRemoval = false) override;
  153. bool swapStacks(const StackLocation &sl1, const StackLocation &sl2) override;
  154. bool addToSlot(const StackLocation &sl, const CCreature *c, TQuantity count) override;
  155. void tryJoiningArmy(const CArmedInstance *src, const CArmedInstance *dst, bool removeObjWhenFinished, bool allowMerging) override;
  156. bool moveStack(const StackLocation &src, const StackLocation &dst, TQuantity count = -1) override;
  157. void removeAfterVisit(const CGObjectInstance *object) override;
  158. bool giveHeroNewArtifact(const CGHeroInstance * h, const CArtifact * artType, ArtifactPosition pos = ArtifactPosition::FIRST_AVAILABLE) override;
  159. bool giveHeroArtifact(const CGHeroInstance * h, const CArtifactInstance * a, ArtifactPosition pos) override;
  160. void putArtifact(const ArtifactLocation &al, const CArtifactInstance *a) override;
  161. void removeArtifact(const ArtifactLocation &al) override;
  162. bool moveArtifact(const ArtifactLocation & al1, const ArtifactLocation & al2) override;
  163. bool bulkMoveArtifacts(ObjectInstanceID srcHero, ObjectInstanceID dstHero, bool swap);
  164. bool eraseArtifactByClient(const ArtifactLocation & al);
  165. void synchronizeArtifactHandlerLists();
  166. void heroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero) override;
  167. void stopHeroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero) override;
  168. 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
  169. void startBattleI(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, bool creatureBank = false) override; //if any of armies is hero, hero will be used
  170. 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
  171. bool moveHero(ObjectInstanceID hid, int3 dst, ui8 teleporting, bool transit = false, PlayerColor asker = PlayerColor::NEUTRAL) override;
  172. void giveHeroBonus(GiveBonus * bonus) override;
  173. void setMovePoints(SetMovePoints * smp) override;
  174. void setManaPoints(ObjectInstanceID hid, int val) override;
  175. void giveHero(ObjectInstanceID id, PlayerColor player, ObjectInstanceID boatId = ObjectInstanceID()) override;
  176. void changeObjPos(ObjectInstanceID objid, int3 newPos) override;
  177. void heroExchange(ObjectInstanceID hero1, ObjectInstanceID hero2) override;
  178. void changeFogOfWar(int3 center, ui32 radius, PlayerColor player, bool hide) override;
  179. void changeFogOfWar(std::unordered_set<int3> &tiles, PlayerColor player, bool hide) override;
  180. void castSpell(const spells::Caster * caster, SpellID spellID, const int3 &pos) override;
  181. bool isVisitCoveredByAnotherQuery(const CGObjectInstance *obj, const CGHeroInstance *hero) override;
  182. void setObjProperty(ObjectInstanceID objid, int prop, si64 val) override;
  183. void showInfoDialog(InfoWindow * iw) override;
  184. void showInfoDialog(const std::string & msg, PlayerColor player) override;
  185. //////////////////////////////////////////////////////////////////////////
  186. void useScholarSkill(ObjectInstanceID hero1, ObjectInstanceID hero2);
  187. void setPortalDwelling(const CGTownInstance * town, bool forced, bool clear);
  188. void visitObjectOnTile(const TerrainTile &t, const CGHeroInstance * h);
  189. bool teleportHero(ObjectInstanceID hid, ObjectInstanceID dstid, ui8 source, PlayerColor asker = PlayerColor::NEUTRAL);
  190. void visitCastleObjects(const CGTownInstance * obj, const CGHeroInstance * hero) override;
  191. void levelUpHero(const CGHeroInstance * hero, SecondarySkill skill);//handle client respond and send one more request if needed
  192. void levelUpHero(const CGHeroInstance * hero);//initial call - check if hero have remaining levelups & handle them
  193. void levelUpCommander (const CCommanderInstance * c, int skill); //secondary skill 1 to 6, special skill : skill - 100
  194. void levelUpCommander (const CCommanderInstance * c);
  195. void expGiven(const CGHeroInstance *hero); //triggers needed level-ups, handles also commander of this hero
  196. //////////////////////////////////////////////////////////////////////////
  197. void init(StartInfo *si);
  198. void handleClientDisconnection(std::shared_ptr<CConnection> c);
  199. void handleReceivedPack(CPackForServer * pack);
  200. PlayerColor getPlayerAt(std::shared_ptr<CConnection> c) const;
  201. bool hasPlayerAt(PlayerColor player, std::shared_ptr<CConnection> c) const;
  202. void updateGateState();
  203. bool makeBattleAction(BattleAction &ba);
  204. bool makeAutomaticAction(const CStack *stack, BattleAction &ba); //used when action is taken by stack without volition of player (eg. unguided catapult attack)
  205. bool makeCustomAction(BattleAction &ba);
  206. void stackEnchantedTrigger(const CStack * stack);
  207. void stackTurnTrigger(const CStack *stack);
  208. void removeObstacle(const CObstacleInstance &obstacle);
  209. bool queryReply( QueryID qid, const JsonNode & answer, PlayerColor player );
  210. bool buildBoat( ObjectInstanceID objid, PlayerColor player );
  211. bool setFormation( ObjectInstanceID hid, ui8 formation );
  212. bool tradeResources(const IMarket *market, ui32 val, PlayerColor player, ui32 id1, ui32 id2);
  213. bool sacrificeCreatures(const IMarket * market, const CGHeroInstance * hero, const std::vector<SlotID> & slot, const std::vector<ui32> & count);
  214. bool sendResources(ui32 val, PlayerColor player, GameResID r1, PlayerColor r2);
  215. bool sellCreatures(ui32 count, const IMarket *market, const CGHeroInstance * hero, SlotID slot, GameResID resourceID);
  216. bool transformInUndead(const IMarket *market, const CGHeroInstance * hero, SlotID slot);
  217. bool assembleArtifacts (ObjectInstanceID heroID, ArtifactPosition artifactSlot, bool assemble, ArtifactID assembleTo);
  218. bool buyArtifact( ObjectInstanceID hid, ArtifactID aid ); //for blacksmith and mage guild only -> buying for gold in common buildings
  219. bool buyArtifact( const IMarket *m, const CGHeroInstance *h, GameResID rid, ArtifactID aid); //for artifact merchant and black market -> buying for any resource in special building / advobject
  220. bool sellArtifact( const IMarket *m, const CGHeroInstance *h, ArtifactInstanceID aid, GameResID rid); //for artifact merchant selling
  221. //void lootArtifacts (TArtHolder source, TArtHolder dest, std::vector<ui32> &arts); //after battle - move al arts to winer
  222. bool buySecSkill( const IMarket *m, const CGHeroInstance *h, SecondarySkill skill);
  223. bool garrisonSwap(ObjectInstanceID tid);
  224. bool swapGarrisonOnSiege(ObjectInstanceID tid) override;
  225. bool upgradeCreature( ObjectInstanceID objid, SlotID pos, CreatureID upgID );
  226. bool recruitCreatures(ObjectInstanceID objid, ObjectInstanceID dst, CreatureID crid, ui32 cram, si32 level);
  227. bool buildStructure(ObjectInstanceID tid, BuildingID bid, bool force=false);//force - for events: no cost, no checkings
  228. bool razeStructure(ObjectInstanceID tid, BuildingID bid);
  229. bool disbandCreature( ObjectInstanceID id, SlotID pos );
  230. bool arrangeStacks( ObjectInstanceID id1, ObjectInstanceID id2, ui8 what, SlotID p1, SlotID p2, si32 val, PlayerColor player);
  231. bool bulkMoveArmy(ObjectInstanceID srcArmy, ObjectInstanceID destArmy, SlotID srcSlot);
  232. bool bulkSplitStack(SlotID src, ObjectInstanceID srcOwner, si32 howMany);
  233. bool bulkMergeStacks(SlotID slotSrc, ObjectInstanceID srcOwner);
  234. bool bulkSmartSplitStack(SlotID slotSrc, ObjectInstanceID srcOwner);
  235. void save(const std::string &fname);
  236. bool load(const std::string &fname);
  237. void handleTimeEvents();
  238. void handleTownEvents(CGTownInstance *town, NewTurn &n);
  239. bool complain(const std::string &problem); //sends message to all clients, prints on the logs and return true
  240. void objectVisited( const CGObjectInstance * obj, const CGHeroInstance * h );
  241. void objectVisitEnded(const CObjectVisitQuery &query);
  242. void engageIntoBattle( PlayerColor player );
  243. bool dig(const CGHeroInstance *h);
  244. void moveArmy(const CArmedInstance *src, const CArmedInstance *dst, bool allowMerging);
  245. template <typename Handler> void serialize(Handler &h, const int version)
  246. {
  247. h & QID;
  248. h & states;
  249. h & finishingBattle;
  250. h & heroPool;
  251. h & getRandomGenerator();
  252. h & playerMessages;
  253. if (!h.saving)
  254. deserializationFix();
  255. #if SCRIPTING_ENABLED
  256. JsonNode scriptsState;
  257. if(h.saving)
  258. serverScripts->serializeState(h.saving, scriptsState);
  259. h & scriptsState;
  260. if(!h.saving)
  261. serverScripts->serializeState(h.saving, scriptsState);
  262. #endif
  263. }
  264. void sendToAllClients(CPackForClient * pack);
  265. void sendAndApply(CPackForClient * pack) override;
  266. void applyAndSend(CPackForClient * pack);
  267. void sendAndApply(CGarrisonOperationPack * pack);
  268. void sendAndApply(SetResources * pack);
  269. void sendAndApply(NewStructures * pack);
  270. void wrongPlayerMessage(CPackForServer * pack, PlayerColor expectedplayer);
  271. void throwNotAllowedAction(CPackForServer * pack);
  272. void throwOnWrongOwner(CPackForServer * pack, ObjectInstanceID id);
  273. void throwOnWrongPlayer(CPackForServer * pack, PlayerColor player);
  274. void throwAndComplain(CPackForServer * pack, std::string txt);
  275. bool isPlayerOwns(CPackForServer * pack, ObjectInstanceID id);
  276. struct FinishingBattleHelper
  277. {
  278. FinishingBattleHelper();
  279. FinishingBattleHelper(std::shared_ptr<const CBattleQuery> Query, int RemainingBattleQueriesCount);
  280. inline bool isDraw() const {return winnerSide == 2;}
  281. const CGHeroInstance *winnerHero, *loserHero;
  282. PlayerColor victor, loser;
  283. ui8 winnerSide;
  284. int remainingBattleQueriesCount;
  285. template <typename Handler> void serialize(Handler &h, const int version)
  286. {
  287. h & winnerHero;
  288. h & loserHero;
  289. h & victor;
  290. h & loser;
  291. h & winnerSide;
  292. h & remainingBattleQueriesCount;
  293. }
  294. };
  295. std::unique_ptr<FinishingBattleHelper> finishingBattle;
  296. void battleAfterLevelUp(const BattleResult &result);
  297. void run(bool resume);
  298. void newTurn();
  299. void handleAttackBeforeCasting(bool ranged, const CStack * attacker, const CStack * defender);
  300. void handleAfterAttackCasting(bool ranged, const CStack * attacker, const CStack * defender);
  301. void attackCasting(bool ranged, BonusType attackMode, const battle::Unit * attacker, const battle::Unit * defender);
  302. bool sacrificeArtifact(const IMarket * m, const CGHeroInstance * hero, const std::vector<ArtifactPosition> & slot);
  303. void spawnWanderingMonsters(CreatureID creatureID);
  304. // Check for victory and loss conditions
  305. void checkVictoryLossConditionsForPlayer(PlayerColor player);
  306. void checkVictoryLossConditions(const std::set<PlayerColor> & playerColors);
  307. void checkVictoryLossConditionsForAll();
  308. CRandomGenerator & getRandomGenerator();
  309. #if SCRIPTING_ENABLED
  310. scripting::Pool * getGlobalContextPool() const override;
  311. scripting::Pool * getContextPool() const override;
  312. #endif
  313. std::list<PlayerColor> generatePlayerTurnOrder() const;
  314. friend class CVCMIServer;
  315. private:
  316. std::unique_ptr<events::EventBus> serverEventBus;
  317. #if SCRIPTING_ENABLED
  318. std::shared_ptr<scripting::PoolImpl> serverScripts;
  319. #endif
  320. void reinitScripting();
  321. void deserializationFix();
  322. void makeStackDoNothing(const CStack * next);
  323. void getVictoryLossMessage(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult, InfoWindow & out) const;
  324. const std::string complainNoCreatures;
  325. const std::string complainNotEnoughCreatures;
  326. const std::string complainInvalidSlot;
  327. };
  328. class ExceptionNotAllowedAction : public std::exception
  329. {
  330. };