AIGateway.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. /*
  2. * AIGateway.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 "AIUtility.h"
  12. #include "Goals/AbstractGoal.h"
  13. #include "../../lib/AI_Base.h"
  14. #include "../../CCallback.h"
  15. #include "../../lib/CThreadHelper.h"
  16. #include "../../lib/GameConstants.h"
  17. #include "../../lib/VCMI_Lib.h"
  18. #include "../../lib/CBuildingHandler.h"
  19. #include "../../lib/CCreatureHandler.h"
  20. #include "../../lib/CTownHandler.h"
  21. #include "../../lib/mapObjects/MiscObjects.h"
  22. #include "../../lib/spells/CSpellHandler.h"
  23. #include "../../lib/CondSh.h"
  24. #include "Pathfinding/AIPathfinder.h"
  25. #include "Engine/Nullkiller.h"
  26. namespace NKAI
  27. {
  28. class AIStatus
  29. {
  30. boost::mutex mx;
  31. boost::condition_variable cv;
  32. BattleState battle;
  33. std::map<QueryID, std::string> remainingQueries;
  34. std::map<int, QueryID> requestToQueryID; //IDs of answer-requests sent to server => query ids (so we can match answer confirmation from server to the query)
  35. std::vector<const CGObjectInstance *> objectsBeingVisited;
  36. bool ongoingHeroMovement;
  37. bool ongoingChannelProbing; // true if AI currently explore bidirectional teleport channel exits
  38. bool havingTurn;
  39. public:
  40. AIStatus();
  41. ~AIStatus();
  42. void setBattle(BattleState BS);
  43. void setMove(bool ongoing);
  44. void setChannelProbing(bool ongoing);
  45. bool channelProbing();
  46. BattleState getBattle();
  47. void addQuery(QueryID ID, std::string description);
  48. void removeQuery(QueryID ID);
  49. int getQueriesCount();
  50. void startedTurn();
  51. void madeTurn();
  52. void waitTillFree();
  53. bool haveTurn();
  54. void attemptedAnsweringQuery(QueryID queryID, int answerRequestID);
  55. void receivedAnswerConfirmation(int answerRequestID, int result);
  56. void heroVisit(const CGObjectInstance * obj, bool started);
  57. template<typename Handler> void serialize(Handler & h)
  58. {
  59. h & battle;
  60. h & remainingQueries;
  61. h & requestToQueryID;
  62. h & havingTurn;
  63. }
  64. };
  65. // The gateway is responsible for AI events handling. Copied from VCAI.h and refined a bit
  66. // Probably we can use concept of hooks to handle event in their related goals
  67. class DLL_EXPORT AIGateway : public CAdventureAI
  68. {
  69. public:
  70. ObjectInstanceID destinationTeleport;
  71. int3 destinationTeleportPos;
  72. std::vector<ObjectInstanceID> teleportChannelProbingList; //list of teleport channel exits that not visible and need to be (re-)explored
  73. //std::vector<const CGObjectInstance *> visitedThisWeek; //only OPWs
  74. //std::set<HeroPtr> invalidPathHeroes; //FIXME, just a workaround
  75. //std::map<HeroPtr, Goals::TSubgoal> lockedHeroes; //TODO: allow non-elementar objectives
  76. //std::map<HeroPtr, std::set<const CGObjectInstance *>> reservedHeroesMap; //objects reserved by specific heroes
  77. //std::set<HeroPtr> heroesUnableToExplore; //these heroes will not be polled for exploration in current state of game
  78. //sets are faster to search, also do not contain duplicates
  79. //std::set<const CGObjectInstance *> reservedObjs; //to be visited by specific hero
  80. //std::map<HeroPtr, std::set<HeroPtr>> visitedHeroes; //visited this turn //FIXME: this is just bug workaround
  81. AIStatus status;
  82. std::string battlename;
  83. std::shared_ptr<CCallback> myCb;
  84. std::unique_ptr<boost::thread> makingTurn;
  85. private:
  86. boost::mutex turnInterruptionMutex;
  87. bool announcedCheatingProblem;
  88. public:
  89. ObjectInstanceID selectedObject;
  90. std::unique_ptr<Nullkiller> nullkiller;
  91. AIGateway();
  92. virtual ~AIGateway();
  93. //TODO: extract to apropriate goals
  94. void tryRealize(Goals::DigAtTile & g);
  95. void tryRealize(Goals::Trade & g);
  96. std::string getBattleAIName() const override;
  97. void initGameInterface(std::shared_ptr<Environment> env, std::shared_ptr<CCallback> CB) override;
  98. void yourTurn(QueryID queryID) override;
  99. void heroGotLevel(const CGHeroInstance * hero, PrimarySkill pskill, std::vector<SecondarySkill> & skills, QueryID queryID) override; //pskill is gained primary skill, interface has to choose one of given skills and call callback with selection id
  100. void commanderGotLevel(const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID) override; //TODO
  101. void showBlockingDialog(const std::string & text, const std::vector<Component> & components, QueryID askID, const int soundID, bool selection, bool cancel, bool safeToAutoaccept) override; //Show a dialog, player must take decision. If selection then he has to choose between one of given components, if cancel he is allowed to not choose. After making choice, CCallback::selectionMade should be called with number of selected component (1 - n) or 0 for cancel (if allowed) and askID.
  102. void showGarrisonDialog(const CArmedInstance * up, const CGHeroInstance * down, bool removableUnits, QueryID queryID) override; //all stacks operations between these objects become allowed, interface has to call onEnd when done
  103. void showTeleportDialog(const CGHeroInstance * hero, TeleportChannelID channel, TTeleportExitsList exits, bool impassable, QueryID askID) override;
  104. void showMapObjectSelectDialog(QueryID askID, const Component & icon, const MetaString & title, const MetaString & description, const std::vector<ObjectInstanceID> & objects) override;
  105. void saveGame(BinarySerializer & h) override; //saving
  106. void loadGame(BinaryDeserializer & h) override; //loading
  107. void finish() override;
  108. void availableCreaturesChanged(const CGDwelling * town) override;
  109. void heroMoved(const TryMoveHero & details, bool verbose = true) override;
  110. void heroInGarrisonChange(const CGTownInstance * town) override;
  111. void centerView(int3 pos, int focusTime) override;
  112. void tileHidden(const std::unordered_set<int3> & pos) override;
  113. void artifactMoved(const ArtifactLocation & src, const ArtifactLocation & dst) override;
  114. void artifactAssembled(const ArtifactLocation & al) override;
  115. void showTavernWindow(const CGObjectInstance * object, const CGHeroInstance * visitor, QueryID queryID) override;
  116. void showThievesGuildWindow(const CGObjectInstance * obj) override;
  117. void playerBlocked(int reason, bool start) override;
  118. void showPuzzleMap() override;
  119. void showShipyardDialog(const IShipyard * obj) override;
  120. void gameOver(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult) override;
  121. void artifactPut(const ArtifactLocation & al) override;
  122. void artifactRemoved(const ArtifactLocation & al) override;
  123. void artifactDisassembled(const ArtifactLocation & al) override;
  124. void heroVisit(const CGHeroInstance * visitor, const CGObjectInstance * visitedObj, bool start) override;
  125. void availableArtifactsChanged(const CGBlackMarket * bm = nullptr) override;
  126. void heroVisitsTown(const CGHeroInstance * hero, const CGTownInstance * town) override;
  127. void tileRevealed(const std::unordered_set<int3> & pos) override;
  128. void heroExchangeStarted(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID query) override;
  129. void heroPrimarySkillChanged(const CGHeroInstance * hero, PrimarySkill which, si64 val) override;
  130. void showRecruitmentDialog(const CGDwelling * dwelling, const CArmedInstance * dst, int level, QueryID queryID) override;
  131. void heroMovePointsChanged(const CGHeroInstance * hero) override;
  132. void garrisonsChanged(ObjectInstanceID id1, ObjectInstanceID id2) override;
  133. void newObject(const CGObjectInstance * obj) override;
  134. void showHillFortWindow(const CGObjectInstance * object, const CGHeroInstance * visitor) override;
  135. void playerBonusChanged(const Bonus & bonus, bool gain) override;
  136. void heroCreated(const CGHeroInstance *) override;
  137. void advmapSpellCast(const CGHeroInstance * caster, SpellID spellID) override;
  138. void showInfoDialog(EInfoWindowMode type, const std::string & text, const std::vector<Component> & components, int soundID) override;
  139. void requestRealized(PackageApplied * pa) override;
  140. void receivedResource() override;
  141. void objectRemoved(const CGObjectInstance * obj, const PlayerColor & initiator) override;
  142. void showUniversityWindow(const IMarket * market, const CGHeroInstance * visitor, QueryID queryID) override;
  143. void heroManaPointsChanged(const CGHeroInstance * hero) override;
  144. void heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val) override;
  145. void battleResultsApplied() override;
  146. void beforeObjectPropertyChanged(const SetObjectProperty * sop) override;
  147. void objectPropertyChanged(const SetObjectProperty * sop) override;
  148. void buildChanged(const CGTownInstance * town, BuildingID buildingID, int what) override;
  149. void heroBonusChanged(const CGHeroInstance * hero, const Bonus & bonus, bool gain) override;
  150. void showMarketWindow(const IMarket * market, const CGHeroInstance * visitor, QueryID queryID) override;
  151. void showWorldViewEx(const std::vector<ObjectPosInfo> & objectPositions, bool showTerrain) override;
  152. std::optional<BattleAction> makeSurrenderRetreatDecision(const BattleID & battleID, const BattleStateInfoForRetreat & battleState) override;
  153. void battleStart(const BattleID & battleID, const CCreatureSet * army1, const CCreatureSet * army2, int3 tile, const CGHeroInstance * hero1, const CGHeroInstance * hero2, bool side, bool replayAllowed) override;
  154. void battleEnd(const BattleID & battleID, const BattleResult * br, QueryID queryID) override;
  155. void makeTurn();
  156. void buildArmyIn(const CGTownInstance * t);
  157. void endTurn();
  158. // TODO: all the routines like recruiting hero or building army should be removed from here and extracted to elementar goals or whatever
  159. void recruitCreatures(const CGDwelling * d, const CArmedInstance * recruiter);
  160. void pickBestCreatures(const CArmedInstance * army, const CArmedInstance * source); //called when we can't find a slot for new stack
  161. void pickBestArtifacts(const CGHeroInstance * h, const CGHeroInstance * other = nullptr);
  162. void moveCreaturesToHero(const CGTownInstance * t);
  163. void performObjectInteraction(const CGObjectInstance * obj, HeroPtr h);
  164. bool makePossibleUpgrades(const CArmedInstance * obj);
  165. bool moveHeroToTile(int3 dst, HeroPtr h);
  166. void buildStructure(const CGTownInstance * t, BuildingID building);
  167. void lostHero(HeroPtr h); //should remove all references to hero (assigned tasks and so on)
  168. void waitTillFree();
  169. void addVisitableObj(const CGObjectInstance * obj);
  170. void validateObject(const CGObjectInstance * obj); //checks if object is still visible and if not, removes references to it
  171. void validateObject(ObjectIdRef obj); //checks if object is still visible and if not, removes references to it
  172. void retrieveVisitableObjs();
  173. virtual std::vector<const CGObjectInstance *> getFlaggedObjects() const;
  174. void requestSent(const CPackForServer * pack, int requestID) override;
  175. void answerQuery(QueryID queryID, int selection);
  176. //special function that can be called ONLY from game events handling thread and will send request ASAP
  177. void requestActionASAP(std::function<void()> whatToDo);
  178. template<typename Handler> void serializeInternal(Handler & h)
  179. {
  180. #if 0
  181. h & nullkiller->memory->knownTeleportChannels;
  182. h & nullkiller->memory->knownSubterraneanGates;
  183. h & destinationTeleport;
  184. h & nullkiller->memory->visitableObjs;
  185. h & nullkiller->memory->alreadyVisited;
  186. h & status;
  187. h & battlename;
  188. #endif
  189. }
  190. };
  191. }