VCAI.h 17 KB

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