VCAI.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. /*
  2. * VCAI.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. struct QuestInfo;
  26. class AIhelper;
  27. class AIStatus
  28. {
  29. boost::mutex mx;
  30. boost::condition_variable cv;
  31. BattleState battle;
  32. std::map<QueryID, std::string> remainingQueries;
  33. 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)
  34. std::vector<const CGObjectInstance *> objectsBeingVisited;
  35. bool ongoingHeroMovement;
  36. bool ongoingChannelProbing; // true if AI currently explore bidirectional teleport channel exits
  37. bool havingTurn;
  38. public:
  39. AIStatus();
  40. ~AIStatus();
  41. void setBattle(BattleState BS);
  42. void setMove(bool ongoing);
  43. void setChannelProbing(bool ongoing);
  44. bool channelProbing();
  45. BattleState getBattle();
  46. void addQuery(QueryID ID, std::string description);
  47. void removeQuery(QueryID ID);
  48. int getQueriesCount();
  49. void startedTurn();
  50. void madeTurn();
  51. void waitTillFree();
  52. bool haveTurn();
  53. void attemptedAnsweringQuery(QueryID queryID, int answerRequestID);
  54. void receivedAnswerConfirmation(int answerRequestID, int result);
  55. void heroVisit(const CGObjectInstance * obj, bool started);
  56. template<typename Handler> void serialize(Handler & h, const int version)
  57. {
  58. h & battle;
  59. h & remainingQueries;
  60. h & requestToQueryID;
  61. h & havingTurn;
  62. }
  63. };
  64. class DLL_EXPORT VCAI : public CAdventureAI
  65. {
  66. public:
  67. friend class FuzzyHelper;
  68. friend class ResourceManager;
  69. friend class BuildingManager;
  70. std::map<TeleportChannelID, std::shared_ptr<TeleportChannel>> knownTeleportChannels;
  71. std::map<const CGObjectInstance *, const CGObjectInstance *> knownSubterraneanGates;
  72. ObjectInstanceID destinationTeleport;
  73. int3 destinationTeleportPos;
  74. std::vector<ObjectInstanceID> teleportChannelProbingList; //list of teleport channel exits that not visible and need to be (re-)explored
  75. //std::vector<const CGObjectInstance *> visitedThisWeek; //only OPWs
  76. std::map<HeroPtr, std::set<const CGTownInstance *>> townVisitsThisWeek;
  77. //part of mainLoop, but accessible from outisde
  78. std::vector<Goals::TSubgoal> basicGoals;
  79. Goals::TGoalVec goalsToRemove;
  80. Goals::TGoalVec goalsToAdd;
  81. std::map<Goals::TSubgoal, Goals::TGoalVec> ultimateGoalsFromBasic; //theoreticlaly same goal can fulfill multiple basic goals
  82. std::set<HeroPtr> invalidPathHeroes; //FIXME, just a workaround
  83. std::map<HeroPtr, Goals::TSubgoal> lockedHeroes; //TODO: allow non-elementar objectives
  84. std::map<HeroPtr, std::set<const CGObjectInstance *>> reservedHeroesMap; //objects reserved by specific heroes
  85. std::set<HeroPtr> heroesUnableToExplore; //these heroes will not be polled for exploration in current state of game
  86. //sets are faster to search, also do not contain duplicates
  87. std::set<const CGObjectInstance *> visitableObjs;
  88. std::set<const CGObjectInstance *> alreadyVisited;
  89. std::set<const CGObjectInstance *> reservedObjs; //to be visited by specific hero
  90. std::map<HeroPtr, std::set<HeroPtr>> visitedHeroes; //visited this turn //FIXME: this is just bug workaround
  91. AIStatus status;
  92. std::string battlename;
  93. std::shared_ptr<CCallback> myCb;
  94. std::unique_ptr<boost::thread> makingTurn;
  95. private:
  96. boost::mutex turnInterruptionMutex;
  97. public:
  98. ObjectInstanceID selectedObject;
  99. AIhelper * ah;
  100. VCAI();
  101. virtual ~VCAI();
  102. //TODO: use only smart pointers?
  103. void tryRealize(Goals::Explore & g);
  104. void tryRealize(Goals::RecruitHero & g);
  105. void tryRealize(Goals::VisitTile & g);
  106. void tryRealize(Goals::VisitObj & g);
  107. void tryRealize(Goals::VisitHero & g);
  108. void tryRealize(Goals::BuildThis & g);
  109. void tryRealize(Goals::DigAtTile & g);
  110. void tryRealize(Goals::Trade & g);
  111. void tryRealize(Goals::BuyArmy & g);
  112. void tryRealize(Goals::Invalid & g);
  113. void tryRealize(Goals::AbstractGoal & g);
  114. bool isTileNotReserved(const CGHeroInstance * h, int3 t) const; //the tile is not occupied by allied hero and the object is not reserved
  115. std::string getBattleAIName() const override;
  116. void init(std::shared_ptr<Environment> ENV, std::shared_ptr<CCallback> CB) override;
  117. void yourTurn() override;
  118. void heroGotLevel(const CGHeroInstance * hero, PrimarySkill::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
  119. void commanderGotLevel(const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID) override; //TODO
  120. void showBlockingDialog(const std::string & text, const std::vector<Component> & components, QueryID askID, const int soundID, bool selection, bool cancel) 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.
  121. 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
  122. void showTeleportDialog(TeleportChannelID channel, TTeleportExitsList exits, bool impassable, QueryID askID) override;
  123. void showMapObjectSelectDialog(QueryID askID, const Component & icon, const MetaString & title, const MetaString & description, const std::vector<ObjectInstanceID> & objects) override;
  124. void saveGame(BinarySerializer & h, const int version) override; //saving
  125. void loadGame(BinaryDeserializer & h, const int version) override; //loading
  126. void finish() override;
  127. void availableCreaturesChanged(const CGDwelling * town) override;
  128. void heroMoved(const TryMoveHero & details) override;
  129. void heroInGarrisonChange(const CGTownInstance * town) override;
  130. void centerView(int3 pos, int focusTime) override;
  131. void tileHidden(const std::unordered_set<int3, ShashInt3> & pos) override;
  132. void artifactMoved(const ArtifactLocation & src, const ArtifactLocation & dst) override;
  133. void artifactAssembled(const ArtifactLocation & al) override;
  134. void showTavernWindow(const CGObjectInstance * townOrTavern) override;
  135. void showThievesGuildWindow(const CGObjectInstance * obj) override;
  136. void playerBlocked(int reason, bool start) override;
  137. void showPuzzleMap() override;
  138. void showShipyardDialog(const IShipyard * obj) override;
  139. void gameOver(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult) override;
  140. void artifactPut(const ArtifactLocation & al) override;
  141. void artifactRemoved(const ArtifactLocation & al) override;
  142. void artifactDisassembled(const ArtifactLocation & al) override;
  143. void heroVisit(const CGHeroInstance * visitor, const CGObjectInstance * visitedObj, bool start) override;
  144. void availableArtifactsChanged(const CGBlackMarket * bm = nullptr) override;
  145. void heroVisitsTown(const CGHeroInstance * hero, const CGTownInstance * town) override;
  146. void tileRevealed(const std::unordered_set<int3, ShashInt3> & pos) override;
  147. void heroExchangeStarted(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID query) override;
  148. void heroPrimarySkillChanged(const CGHeroInstance * hero, int which, si64 val) override;
  149. void showRecruitmentDialog(const CGDwelling * dwelling, const CArmedInstance * dst, int level) override;
  150. void heroMovePointsChanged(const CGHeroInstance * hero) override;
  151. void garrisonsChanged(ObjectInstanceID id1, ObjectInstanceID id2) override;
  152. void newObject(const CGObjectInstance * obj) override;
  153. void showHillFortWindow(const CGObjectInstance * object, const CGHeroInstance * visitor) override;
  154. void playerBonusChanged(const Bonus & bonus, bool gain) override;
  155. void heroCreated(const CGHeroInstance *) override;
  156. void advmapSpellCast(const CGHeroInstance * caster, int spellID) override;
  157. void showInfoDialog(const std::string & text, const std::vector<Component> & components, int soundID) override;
  158. void requestRealized(PackageApplied * pa) override;
  159. void receivedResource() override;
  160. void objectRemoved(const CGObjectInstance * obj) override;
  161. void showUniversityWindow(const IMarket * market, const CGHeroInstance * visitor) override;
  162. void heroManaPointsChanged(const CGHeroInstance * hero) override;
  163. void heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val) override;
  164. void battleResultsApplied() override;
  165. void objectPropertyChanged(const SetObjectProperty * sop) override;
  166. void buildChanged(const CGTownInstance * town, BuildingID buildingID, int what) override;
  167. void heroBonusChanged(const CGHeroInstance * hero, const Bonus & bonus, bool gain) override;
  168. void showMarketWindow(const IMarket * market, const CGHeroInstance * visitor) override;
  169. void showWorldViewEx(const std::vector<ObjectPosInfo> & objectPositions) override;
  170. void battleStart(const CCreatureSet * army1, const CCreatureSet * army2, int3 tile, const CGHeroInstance * hero1, const CGHeroInstance * hero2, bool side) override;
  171. void battleEnd(const BattleResult * br) override;
  172. void makeTurn();
  173. void mainLoop();
  174. void performTypicalActions();
  175. void buildArmyIn(const CGTownInstance * t);
  176. void striveToGoal(Goals::TSubgoal ultimateGoal);
  177. Goals::TSubgoal decomposeGoal(Goals::TSubgoal ultimateGoal);
  178. void endTurn();
  179. void wander(HeroPtr h);
  180. void setGoal(HeroPtr h, Goals::TSubgoal goal);
  181. void evaluateGoal(HeroPtr h); //evaluates goal assigned to hero, if any
  182. void completeGoal(Goals::TSubgoal goal); //safely removes goal from reserved hero
  183. void recruitHero(const CGTownInstance * t, bool throwing = false);
  184. bool isGoodForVisit(const CGObjectInstance * obj, HeroPtr h, boost::optional<float> movementCostLimit = boost::none);
  185. bool isGoodForVisit(const CGObjectInstance * obj, HeroPtr h, const AIPath & path) const;
  186. //void recruitCreatures(const CGTownInstance * t);
  187. void recruitCreatures(const CGDwelling * d, const CArmedInstance * recruiter);
  188. void pickBestCreatures(const CArmedInstance * army, const CArmedInstance * source); //called when we can't find a slot for new stack
  189. void pickBestArtifacts(const CGHeroInstance * h, const CGHeroInstance * other = nullptr);
  190. void moveCreaturesToHero(const CGTownInstance * t);
  191. void performObjectInteraction(const CGObjectInstance * obj, HeroPtr h);
  192. bool moveHeroToTile(int3 dst, HeroPtr h);
  193. void buildStructure(const CGTownInstance * t, BuildingID building); //TODO: move to BuildingManager
  194. void lostHero(HeroPtr h); //should remove all references to hero (assigned tasks and so on)
  195. void waitTillFree();
  196. void addVisitableObj(const CGObjectInstance * obj);
  197. void markObjectVisited(const CGObjectInstance * obj);
  198. void reserveObject(HeroPtr h, const CGObjectInstance * obj); //TODO: reserve all objects that heroes attempt to visit
  199. void unreserveObject(HeroPtr h, const CGObjectInstance * obj);
  200. void markHeroUnableToExplore(HeroPtr h);
  201. void markHeroAbleToExplore(HeroPtr h);
  202. bool isAbleToExplore(HeroPtr h);
  203. void clearPathsInfo();
  204. void validateObject(const CGObjectInstance * obj); //checks if object is still visible and if not, removes references to it
  205. void validateObject(ObjectIdRef obj); //checks if object is still visible and if not, removes references to it
  206. void validateVisitableObjs();
  207. void retrieveVisitableObjs(std::vector<const CGObjectInstance *> & out, bool includeOwned = false) const;
  208. void retrieveVisitableObjs();
  209. virtual std::vector<const CGObjectInstance *> getFlaggedObjects() const;
  210. const CGObjectInstance * lookForArt(int aid) const;
  211. bool isAccessible(const int3 & pos) const;
  212. HeroPtr getHeroWithGrail() const;
  213. const CGObjectInstance * getUnvisitedObj(const std::function<bool(const CGObjectInstance *)> & predicate);
  214. bool isAccessibleForHero(const int3 & pos, HeroPtr h, bool includeAllies = false) const;
  215. //optimization - use one SM for every hero call
  216. const CGTownInstance * findTownWithTavern() const;
  217. bool canRecruitAnyHero(const CGTownInstance * t = NULL) const;
  218. Goals::TSubgoal getGoal(HeroPtr h) const;
  219. bool canAct(HeroPtr h) const;
  220. std::vector<HeroPtr> getUnblockedHeroes() const;
  221. std::vector<HeroPtr> getMyHeroes() const;
  222. HeroPtr primaryHero() const;
  223. void checkHeroArmy(HeroPtr h);
  224. void requestSent(const CPackForServer * pack, int requestID) override;
  225. void answerQuery(QueryID queryID, int selection);
  226. //special function that can be called ONLY from game events handling thread and will send request ASAP
  227. void requestActionASAP(std::function<void()> whatToDo);
  228. #if 0
  229. //disabled due to issue 2890
  230. template<typename Handler> void registerGoals(Handler & h)
  231. {
  232. //h.template registerType<Goals::AbstractGoal, Goals::BoostHero>();
  233. h.template registerType<Goals::AbstractGoal, Goals::Build>();
  234. h.template registerType<Goals::AbstractGoal, Goals::BuildThis>();
  235. //h.template registerType<Goals::AbstractGoal, Goals::CIssueCommand>();
  236. h.template registerType<Goals::AbstractGoal, Goals::ClearWayTo>();
  237. h.template registerType<Goals::AbstractGoal, Goals::CollectRes>();
  238. h.template registerType<Goals::AbstractGoal, Goals::Conquer>();
  239. h.template registerType<Goals::AbstractGoal, Goals::DigAtTile>();
  240. h.template registerType<Goals::AbstractGoal, Goals::Explore>();
  241. h.template registerType<Goals::AbstractGoal, Goals::FindObj>();
  242. h.template registerType<Goals::AbstractGoal, Goals::GatherArmy>();
  243. h.template registerType<Goals::AbstractGoal, Goals::GatherTroops>();
  244. h.template registerType<Goals::AbstractGoal, Goals::GetArtOfType>();
  245. h.template registerType<Goals::AbstractGoal, Goals::VisitObj>();
  246. h.template registerType<Goals::AbstractGoal, Goals::Invalid>();
  247. //h.template registerType<Goals::AbstractGoal, Goals::NotLose>();
  248. h.template registerType<Goals::AbstractGoal, Goals::RecruitHero>();
  249. h.template registerType<Goals::AbstractGoal, Goals::VisitHero>();
  250. h.template registerType<Goals::AbstractGoal, Goals::VisitTile>();
  251. h.template registerType<Goals::AbstractGoal, Goals::Win>();
  252. }
  253. #endif
  254. template<typename Handler> void serializeInternal(Handler & h, const int version)
  255. {
  256. h & knownTeleportChannels;
  257. h & knownSubterraneanGates;
  258. h & destinationTeleport;
  259. h & townVisitsThisWeek;
  260. #if 0
  261. //disabled due to issue 2890
  262. h & lockedHeroes;
  263. #else
  264. {
  265. ui32 length = 0;
  266. h & length;
  267. if(!h.saving)
  268. {
  269. std::set<ui32> loadedPointers;
  270. lockedHeroes.clear();
  271. for(ui32 index = 0; index < length; index++)
  272. {
  273. HeroPtr ignored1;
  274. h & ignored1;
  275. ui8 flag = 0;
  276. h & flag;
  277. if(flag)
  278. {
  279. ui32 pid = 0xffffffff;
  280. h & pid;
  281. if(!vstd::contains(loadedPointers, pid))
  282. {
  283. loadedPointers.insert(pid);
  284. ui16 typeId = 0;
  285. //this is the problem requires such hack
  286. //we have to explicitly ignore invalid goal class type id
  287. h & typeId;
  288. Goals::AbstractGoal ignored2;
  289. ignored2.serialize(h, version);
  290. }
  291. }
  292. }
  293. }
  294. }
  295. #endif
  296. h & reservedHeroesMap; //FIXME: cannot instantiate abstract class
  297. h & visitableObjs;
  298. h & alreadyVisited;
  299. h & reservedObjs;
  300. if (version < 788 && !h.saving)
  301. {
  302. TResources saving;
  303. h & saving; //mind the ambiguity
  304. }
  305. h & status;
  306. h & battlename;
  307. h & heroesUnableToExplore;
  308. //myCB is restored after load by init call
  309. }
  310. };
  311. class cannotFulfillGoalException : public std::exception
  312. {
  313. std::string msg;
  314. public:
  315. explicit cannotFulfillGoalException(crstring _Message)
  316. : msg(_Message)
  317. {
  318. }
  319. virtual ~cannotFulfillGoalException() throw ()
  320. {
  321. };
  322. const char * what() const throw () override
  323. {
  324. return msg.c_str();
  325. }
  326. };
  327. class goalFulfilledException : public std::exception
  328. {
  329. std::string msg;
  330. public:
  331. Goals::TSubgoal goal;
  332. explicit goalFulfilledException(Goals::TSubgoal Goal)
  333. : goal(Goal)
  334. {
  335. msg = goal->name();
  336. }
  337. virtual ~goalFulfilledException() throw ()
  338. {
  339. };
  340. const char * what() const throw () override
  341. {
  342. return msg.c_str();
  343. }
  344. };
  345. void makePossibleUpgrades(const CArmedInstance * obj);