CGameHandler.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. #pragma once
  2. #include "../client/FunctionList.h"
  3. #include "../lib/CGameState.h"
  4. #include "../lib/Connection.h"
  5. #include "../lib/IGameCallback.h"
  6. #include "../lib/BattleAction.h"
  7. #include "../lib/NetPacks.h"
  8. #include "CQuery.h"
  9. /*
  10. * CGameHandler.h, part of VCMI engine
  11. *
  12. * Authors: listed in file AUTHORS in main folder
  13. *
  14. * License: GNU General Public License v2.0 or later
  15. * Full text of license available in license.txt file, in main folder
  16. *
  17. */
  18. class CGameHandler;
  19. class CVCMIServer;
  20. class CGameState;
  21. struct StartInfo;
  22. class CCPPObjectScript;
  23. class CScriptCallback;
  24. struct BattleResult;
  25. struct BattleAttack;
  26. struct BattleStackAttacked;
  27. struct CPack;
  28. struct Query;
  29. struct SetGarrisons;
  30. struct SetResource;
  31. struct SetResources;
  32. struct NewStructures;
  33. class CGHeroInstance;
  34. class IMarket;
  35. extern std::map<ui32, CFunctionList<void(ui32)> > callbacks; //question id => callback functions - for selection dialogs
  36. extern boost::mutex gsm;
  37. struct PlayerStatus
  38. {
  39. bool makingTurn;
  40. PlayerStatus():makingTurn(false){};
  41. template <typename Handler> void serialize(Handler &h, const int version)
  42. {
  43. h & makingTurn;
  44. }
  45. };
  46. class PlayerStatuses
  47. {
  48. public:
  49. std::map<PlayerColor,PlayerStatus> players;
  50. boost::mutex mx;
  51. boost::condition_variable cv; //notifies when any changes are made
  52. void addPlayer(PlayerColor player);
  53. PlayerStatus operator[](PlayerColor player);
  54. bool checkFlag(PlayerColor player, bool PlayerStatus::*flag);
  55. void setFlag(PlayerColor player, bool PlayerStatus::*flag, bool val);
  56. template <typename Handler> void serialize(Handler &h, const int version)
  57. {
  58. h & players;
  59. }
  60. };
  61. struct CasualtiesAfterBattle
  62. {
  63. typedef std::pair<StackLocation, int> TStackAndItsNewCount;
  64. enum {ERASE = -1};
  65. std::vector<TStackAndItsNewCount> newStackCounts;
  66. ObjectInstanceID heroWithDeadCommander; //TODO: unify stack loactions
  67. CasualtiesAfterBattle(const CArmedInstance *army, BattleInfo *bat);
  68. void takeFromArmy(CGameHandler *gh);
  69. };
  70. class CGameHandler : public IGameCallback, CBattleInfoCallback
  71. {
  72. private:
  73. void makeStackDoNothing(const CStack * next);
  74. public:
  75. //use enums as parameters, because doMove(sth, true, false, true) is not readable
  76. enum EGuardLook {CHECK_FOR_GUARDS, IGNORE_GUARDS};
  77. enum EVisitDest {VISIT_DEST, DONT_VISIT_DEST};
  78. enum ELEaveTile {LEAVING_TILE, REMAINING_ON_TILE};
  79. CVCMIServer *s;
  80. std::map<PlayerColor, CConnection*> connections; //player color -> connection to client with interface of that player
  81. PlayerStatuses states; //player color -> player state
  82. std::set<CConnection*> conns;
  83. //queries stuff
  84. boost::recursive_mutex gsm;
  85. ui32 QID;
  86. Queries queries;
  87. //TODO get rid of cfunctionlist (or similar) and use serialziable callback structure
  88. std::map<ui32, CFunctionList<void(ui32)> > callbacks; //query id => callback function - for selection and yes/no dialogs
  89. bool isValidObject(const CGObjectInstance *obj) const;
  90. bool isBlockedByQueries(const CPack *pack, PlayerColor player);
  91. bool isAllowedExchange(ObjectInstanceID id1, ObjectInstanceID id2);
  92. void giveSpells(const CGTownInstance *t, const CGHeroInstance *h);
  93. int moveStack(int stack, BattleHex dest); //returned value - travelled distance
  94. void runBattle();
  95. void checkLossVictory(PlayerColor player);
  96. void winLoseHandle(ui8 players=255); //players: bit field - colours of players to be checked; default: all
  97. void getLossVicMessage(PlayerColor player, si8 standard, bool victory, InfoWindow &out) const;
  98. ////used only in endBattle - don't touch elsewhere
  99. bool visitObjectAfterVictory;
  100. //
  101. void endBattle(int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2); //ends battle
  102. void prepareAttack(BattleAttack &bat, const CStack *att, const CStack *def, int distance, int targetHex); //distance - number of hexes travelled before attacking
  103. void applyBattleEffects(BattleAttack &bat, const CStack *att, const CStack *def, int distance, bool secondary); //damage, drain life & fire shield
  104. void checkForBattleEnd();
  105. void setupBattle(int3 tile, const CArmedInstance *armies[2], const CGHeroInstance *heroes[2], bool creatureBank, const CGTownInstance *town);
  106. void setBattleResult(BattleResult::EResult resultType, int victoriusSide);
  107. CGameHandler(void);
  108. ~CGameHandler(void);
  109. //////////////////////////////////////////////////////////////////////////
  110. //from IGameCallback
  111. //do sth
  112. void changeSpells(const CGHeroInstance * hero, bool give, const std::set<SpellID> &spells) OVERRIDE;
  113. bool removeObject(const CGObjectInstance * obj) OVERRIDE;
  114. void setBlockVis(ObjectInstanceID objid, bool bv) OVERRIDE;
  115. void setOwner(const CGObjectInstance * obj, PlayerColor owner) OVERRIDE;
  116. void setHoverName(const CGObjectInstance * objid, MetaString * name) OVERRIDE;
  117. void changePrimSkill(const CGHeroInstance * hero, PrimarySkill::PrimarySkill which, si64 val, bool abs=false) OVERRIDE;
  118. void changeSecSkill(const CGHeroInstance * hero, SecondarySkill which, int val, bool abs=false) OVERRIDE;
  119. //void showInfoDialog(InfoWindow *iw) OVERRIDE;
  120. void showBlockingDialog(BlockingDialog *iw) OVERRIDE;
  121. void showGarrisonDialog(ObjectInstanceID upobj, ObjectInstanceID hid, bool removableUnits, const boost::function<void()> &cb) OVERRIDE;
  122. void showThievesGuildWindow(PlayerColor player, ObjectInstanceID requestingObjId) OVERRIDE;
  123. void giveResource(PlayerColor player, Res::ERes which, int val) OVERRIDE;
  124. void giveResources(PlayerColor player, TResources resources) OVERRIDE;
  125. void giveCreatures(const CArmedInstance *objid, const CGHeroInstance * h, const CCreatureSet &creatures, bool remove) OVERRIDE;
  126. void takeCreatures(ObjectInstanceID objid, const std::vector<CStackBasicDescriptor> &creatures) OVERRIDE;
  127. bool changeStackType(const StackLocation &sl, CCreature *c) OVERRIDE;
  128. bool changeStackCount(const StackLocation &sl, TQuantity count, bool absoluteValue = false) OVERRIDE;
  129. bool insertNewStack(const StackLocation &sl, const CCreature *c, TQuantity count) OVERRIDE;
  130. bool eraseStack(const StackLocation &sl, bool forceRemoval = false) OVERRIDE;
  131. bool swapStacks(const StackLocation &sl1, const StackLocation &sl2) OVERRIDE;
  132. bool addToSlot(const StackLocation &sl, const CCreature *c, TQuantity count) OVERRIDE;
  133. void tryJoiningArmy(const CArmedInstance *src, const CArmedInstance *dst, bool removeObjWhenFinished, bool allowMerging) OVERRIDE;
  134. bool moveStack(const StackLocation &src, const StackLocation &dst, TQuantity count = -1) OVERRIDE;
  135. void giveHeroNewArtifact(const CGHeroInstance *h, const CArtifact *artType, ArtifactPosition pos) OVERRIDE;
  136. void giveHeroArtifact(const CGHeroInstance *h, const CArtifactInstance *a, ArtifactPosition pos) OVERRIDE;
  137. void putArtifact(const ArtifactLocation &al, const CArtifactInstance *a) OVERRIDE;
  138. void removeArtifact(const ArtifactLocation &al) OVERRIDE;
  139. bool moveArtifact(const ArtifactLocation &al1, const ArtifactLocation &al2) OVERRIDE;
  140. void synchronizeArtifactHandlerLists() OVERRIDE;
  141. void showCompInfo(ShowInInfobox * comp) OVERRIDE;
  142. void heroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero) OVERRIDE;
  143. void stopHeroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero) OVERRIDE;
  144. //bool removeArtifact(const CArtifact* art, int hid) OVERRIDE;
  145. void startBattlePrimary(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool creatureBank = false, const CGTownInstance *town = NULL) OVERRIDE; //use hero=NULL for no hero
  146. void startBattleI(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, bool creatureBank = false) OVERRIDE; //if any of armies is hero, hero will be used
  147. 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//void startBattleI(int heroID, CCreatureSet army, int3 tile, boost::function<void(BattleResult*)> cb) OVERRIDE; //for hero<=>neutral army
  148. void setAmount(ObjectInstanceID objid, ui32 val) OVERRIDE;
  149. bool moveHero(ObjectInstanceID hid, int3 dst, ui8 teleporting, PlayerColor asker = PlayerColor::NEUTRAL) OVERRIDE;
  150. void giveHeroBonus(GiveBonus * bonus) OVERRIDE;
  151. void setMovePoints(SetMovePoints * smp) OVERRIDE;
  152. void setManaPoints(ObjectInstanceID hid, int val) OVERRIDE;
  153. void giveHero(ObjectInstanceID id, PlayerColor player) OVERRIDE;
  154. void changeObjPos(ObjectInstanceID objid, int3 newPos, ui8 flags) OVERRIDE;
  155. void heroExchange(ObjectInstanceID hero1, ObjectInstanceID hero2) OVERRIDE;
  156. //////////////////////////////////////////////////////////////////////////
  157. void useScholarSkill(ObjectInstanceID hero1, ObjectInstanceID hero2);
  158. void setPortalDwelling(const CGTownInstance * town, bool forced, bool clear);
  159. void visitObjectOnTile(const TerrainTile &t, const CGHeroInstance * h);
  160. bool teleportHero(ObjectInstanceID hid, ObjectInstanceID dstid, ui8 source, PlayerColor asker = PlayerColor::NEUTRAL);
  161. void vistiCastleObjects (const CGTownInstance *t, const CGHeroInstance *h);
  162. void levelUpHero(const CGHeroInstance * hero, SecondarySkill skill);//handle client respond and send one more request if needed
  163. void levelUpHero(const CGHeroInstance * hero);//initial call - check if hero have remaining levelups & handle them
  164. void levelUpCommander (const CCommanderInstance * c, int skill); //secondary skill 1 to 6, special skill : skill - 100
  165. void levelUpCommander (const CCommanderInstance * c);
  166. void expGiven(const CGHeroInstance *hero); //triggers needed level-ups, handles also commander of this hero
  167. //////////////////////////////////////////////////////////////////////////
  168. void commitPackage(CPackForClient *pack) OVERRIDE;
  169. void init(StartInfo *si);
  170. void handleConnection(std::set<PlayerColor> players, CConnection &c);
  171. PlayerColor getPlayerAt(CConnection *c) const;
  172. void playerMessage( PlayerColor player, const std::string &message);
  173. bool makeBattleAction(BattleAction &ba);
  174. bool makeAutomaticAction(const CStack *stack, BattleAction &ba); //used when action is taken by stack without volition of player (eg. unguided catapult attack)
  175. void handleSpellCasting(SpellID spellID, int spellLvl, BattleHex destination, ui8 casterSide, PlayerColor casterColor, const CGHeroInstance * caster, const CGHeroInstance * secHero,
  176. int usedSpellPower, ECastingMode::ECastingMode mode, const CStack * stack, si32 selectedStack = -1);
  177. bool makeCustomAction(BattleAction &ba);
  178. void stackTurnTrigger(const CStack * stack);
  179. void handleDamageFromObstacle(const CObstacleInstance &obstacle, const CStack * curStack); //checks if obstacle is land mine and handles possible consequences
  180. void removeObstacle(const CObstacleInstance &obstacle);
  181. bool queryReply( ui32 qid, ui32 answer, PlayerColor player );
  182. bool hireHero( const CGObjectInstance *obj, ui8 hid, PlayerColor player );
  183. bool buildBoat( ObjectInstanceID objid );
  184. bool setFormation( ObjectInstanceID hid, ui8 formation );
  185. bool tradeResources(const IMarket *market, ui32 val, PlayerColor player, ui32 id1, ui32 id2);
  186. bool sacrificeCreatures(const IMarket *market, const CGHeroInstance *hero, SlotID slot, ui32 count);
  187. bool sendResources(ui32 val, PlayerColor player, Res::ERes r1, PlayerColor r2);
  188. bool sellCreatures(ui32 count, const IMarket *market, const CGHeroInstance * hero, SlotID slot, Res::ERes resourceID);
  189. bool transformInUndead(const IMarket *market, const CGHeroInstance * hero, SlotID slot);
  190. bool assembleArtifacts (ObjectInstanceID heroID, ArtifactPosition artifactSlot, bool assemble, ArtifactID assembleTo);
  191. bool buyArtifact( ObjectInstanceID hid, ArtifactID aid ); //for blacksmith and mage guild only -> buying for gold in common buildings
  192. bool buyArtifact( const IMarket *m, const CGHeroInstance *h, Res::ERes rid, ArtifactID aid); //for artifact merchant and black market -> buying for any resource in special building / advobject
  193. bool sellArtifact( const IMarket *m, const CGHeroInstance *h, ArtifactInstanceID aid, Res::ERes rid); //for artifact merchant selling
  194. //void lootArtifacts (TArtHolder source, TArtHolder dest, std::vector<ui32> &arts); //after battle - move al arts to winer
  195. bool buySecSkill( const IMarket *m, const CGHeroInstance *h, SecondarySkill skill);
  196. bool garrisonSwap(ObjectInstanceID tid);
  197. bool upgradeCreature( ObjectInstanceID objid, SlotID pos, CreatureID upgID );
  198. bool recruitCreatures(ObjectInstanceID objid, CreatureID crid, ui32 cram, si32 level);
  199. bool buildStructure(ObjectInstanceID tid, BuildingID bid, bool force=false);//force - for events: no cost, no checkings
  200. bool razeStructure(ObjectInstanceID tid, BuildingID bid);
  201. bool disbandCreature( ObjectInstanceID id, SlotID pos );
  202. bool arrangeStacks( ObjectInstanceID id1, ObjectInstanceID id2, ui8 what, SlotID p1, SlotID p2, si32 val, PlayerColor player);
  203. void save(const std::string &fname);
  204. void close();
  205. void handleTimeEvents();
  206. void handleTownEvents(CGTownInstance *town, NewTurn &n);
  207. bool complain(const std::string &problem); //sends message to all clients, prints on the logs and return true
  208. void objectVisited( const CGObjectInstance * obj, const CGHeroInstance * h );
  209. void objectVisitEnded(const CObjectVisitQuery &query);
  210. void engageIntoBattle( PlayerColor player );
  211. bool dig(const CGHeroInstance *h);
  212. bool castSpell(const CGHeroInstance *h, SpellID spellID, const int3 &pos);
  213. void moveArmy(const CArmedInstance *src, const CArmedInstance *dst, bool allowMerging);
  214. template <typename Handler> void serialize(Handler &h, const int version)
  215. {
  216. h & QID & states & finishingBattle;
  217. }
  218. void sendMessageToAll(const std::string &message);
  219. void sendMessageTo(CConnection &c, const std::string &message);
  220. void sendToAllClients(CPackForClient * info);
  221. void sendAndApply(CPackForClient * info);
  222. void applyAndSend(CPackForClient * info);
  223. void sendAndApply(CGarrisonOperationPack * info);
  224. void sendAndApply(SetResource * info);
  225. void sendAndApply(SetResources * info);
  226. void sendAndApply(NewStructures * info);
  227. struct FinishingBattleHelper
  228. {
  229. FinishingBattleHelper();
  230. FinishingBattleHelper(shared_ptr<const CBattleQuery> Query, bool Duel, int RemainingBattleQueriesCount);
  231. shared_ptr<const CBattleQuery> query;
  232. const CGHeroInstance *winnerHero, *loserHero;
  233. PlayerColor victor, loser;
  234. bool duel;
  235. int remainingBattleQueriesCount;
  236. template <typename Handler> void serialize(Handler &h, const int version)
  237. {
  238. h & query & winnerHero & loserHero & victor & loser & duel & remainingBattleQueriesCount;
  239. }
  240. };
  241. unique_ptr<FinishingBattleHelper> finishingBattle;
  242. void battleAfterLevelUp(const BattleResult &result);
  243. void run(bool resume);
  244. void newTurn();
  245. void handleAttackBeforeCasting (const BattleAttack & bat);
  246. void handleAfterAttackCasting (const BattleAttack & bat);
  247. void attackCasting(const BattleAttack & bat, Bonus::BonusType attackMode, const CStack * attacker);
  248. bool sacrificeArtifact(const IMarket * m, const CGHeroInstance * hero, ArtifactPosition slot);
  249. void spawnWanderingMonsters(CreatureID creatureID);
  250. friend class CVCMIServer;
  251. friend class CScriptCallback;
  252. };
  253. void makeStackDoNothing();