VCAI.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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.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. struct QuestInfo;
  25. class AIStatus
  26. {
  27. boost::mutex mx;
  28. boost::condition_variable cv;
  29. BattleState battle;
  30. std::map<QueryID, std::string> remainingQueries;
  31. 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)
  32. std::vector<const CGObjectInstance *> objectsBeingVisited;
  33. bool ongoingHeroMovement;
  34. bool ongoingChannelProbing; // true if AI currently explore bidirectional teleport channel exits
  35. bool havingTurn;
  36. public:
  37. AIStatus();
  38. ~AIStatus();
  39. void setBattle(BattleState BS);
  40. void setMove(bool ongoing);
  41. void setChannelProbing(bool ongoing);
  42. bool channelProbing();
  43. BattleState getBattle();
  44. void addQuery(QueryID ID, std::string description);
  45. void removeQuery(QueryID ID);
  46. int getQueriesCount();
  47. void startedTurn();
  48. void madeTurn();
  49. void waitTillFree();
  50. bool haveTurn();
  51. void attemptedAnsweringQuery(QueryID queryID, int answerRequestID);
  52. void receivedAnswerConfirmation(int answerRequestID, int result);
  53. void heroVisit(const CGObjectInstance * obj, bool started);
  54. template<typename Handler> void serialize(Handler & h, const int version)
  55. {
  56. h & battle;
  57. h & remainingQueries;
  58. h & requestToQueryID;
  59. h & havingTurn;
  60. }
  61. };
  62. enum
  63. {
  64. NOT_VISIBLE = 0,
  65. NOT_CHECKED = 1,
  66. NOT_AVAILABLE
  67. };
  68. struct SectorMap
  69. {
  70. //a sector is set of tiles that would be mutually reachable if all visitable objs would be passable (incl monsters)
  71. struct Sector
  72. {
  73. int id;
  74. std::vector<int3> tiles;
  75. std::vector<int3> embarkmentPoints; //tiles of other sectors onto which we can (dis)embark
  76. std::vector<const CGObjectInstance *> visitableObjs;
  77. bool water; //all tiles of sector are land or water
  78. Sector()
  79. {
  80. id = -1;
  81. water = false;
  82. }
  83. };
  84. typedef unsigned short TSectorID; //smaller than int to allow -1 value. Max number of sectors 65K should be enough for any proper map.
  85. typedef boost::multi_array<TSectorID, 3> TSectorArray;
  86. bool valid; //some kind of lazy eval
  87. std::map<int3, int3> parent;
  88. TSectorArray sector;
  89. //std::vector<std::vector<std::vector<unsigned char>>> pathfinderSector;
  90. std::map<int, Sector> infoOnSectors;
  91. std::shared_ptr<boost::multi_array<TerrainTile *, 3>> visibleTiles;
  92. SectorMap();
  93. SectorMap(HeroPtr h);
  94. void update();
  95. void clear();
  96. void exploreNewSector(crint3 pos, int num, CCallback * cbp);
  97. void write(crstring fname);
  98. bool markIfBlocked(TSectorID & sec, crint3 pos, const TerrainTile * t);
  99. bool markIfBlocked(TSectorID & sec, crint3 pos);
  100. TSectorID & retrieveTile(crint3 pos);
  101. TSectorID & retrieveTileN(TSectorArray & vectors, const int3 & pos);
  102. const TSectorID & retrieveTileN(const TSectorArray & vectors, const int3 & pos);
  103. TerrainTile * getTile(crint3 pos) const;
  104. std::vector<const CGObjectInstance *> getNearbyObjs(HeroPtr h, bool sectorsAround);
  105. void makeParentBFS(crint3 source);
  106. int3 firstTileToGet(HeroPtr h, crint3 dst); //if h wants to reach tile dst, which tile he should visit to clear the way?
  107. int3 findFirstVisitableTile(HeroPtr h, crint3 dst);
  108. };
  109. class VCAI : public CAdventureAI
  110. {
  111. public:
  112. //internal methods for town development
  113. //try build an unbuilt structure in maxDays at most (0 = indefinite)
  114. /*bool canBuildStructure(const CGTownInstance * t, BuildingID building, unsigned int maxDays=7);*/
  115. bool tryBuildStructure(const CGTownInstance * t, BuildingID building, unsigned int maxDays = 7) const;
  116. //try build ANY unbuilt structure
  117. BuildingID canBuildAnyStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays = 7) const;
  118. bool tryBuildAnyStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays = 7) const;
  119. //try build first unbuilt structure
  120. bool tryBuildNextStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays = 7) const;
  121. friend class FuzzyHelper;
  122. std::map<TeleportChannelID, std::shared_ptr<TeleportChannel>> knownTeleportChannels;
  123. std::map<const CGObjectInstance *, const CGObjectInstance *> knownSubterraneanGates;
  124. ObjectInstanceID destinationTeleport;
  125. int3 destinationTeleportPos;
  126. std::vector<ObjectInstanceID> teleportChannelProbingList; //list of teleport channel exits that not visible and need to be (re-)explored
  127. //std::vector<const CGObjectInstance *> visitedThisWeek; //only OPWs
  128. std::map<HeroPtr, std::set<const CGTownInstance *>> townVisitsThisWeek;
  129. std::map<HeroPtr, Goals::TSubgoal> lockedHeroes; //TODO: allow non-elementar objectives
  130. std::map<HeroPtr, std::set<const CGObjectInstance *>> reservedHeroesMap; //objects reserved by specific heroes
  131. std::set<HeroPtr> heroesUnableToExplore; //these heroes will not be polled for exploration in current state of game
  132. //sets are faster to search, also do not contain duplicates
  133. std::set<const CGObjectInstance *> visitableObjs;
  134. std::set<const CGObjectInstance *> alreadyVisited;
  135. std::set<const CGObjectInstance *> reservedObjs; //to be visited by specific hero
  136. std::map<HeroPtr, std::shared_ptr<SectorMap>> cachedSectorMaps; //TODO: serialize? not necessary
  137. TResources saving;
  138. AIStatus status;
  139. std::string battlename;
  140. std::shared_ptr<CCallback> myCb;
  141. std::unique_ptr<boost::thread> makingTurn;
  142. VCAI();
  143. virtual ~VCAI();
  144. //TODO: use only smart pointers?
  145. void tryRealize(Goals::Explore & g);
  146. void tryRealize(Goals::RecruitHero & g);
  147. void tryRealize(Goals::VisitTile & g);
  148. void tryRealize(Goals::VisitHero & g);
  149. void tryRealize(Goals::BuildThis & g);
  150. void tryRealize(Goals::DigAtTile & g);
  151. void tryRealize(Goals::CollectRes & g);
  152. void tryRealize(Goals::Build & g);
  153. void tryRealize(Goals::Invalid & g);
  154. void tryRealize(Goals::AbstractGoal & g);
  155. int3 explorationBestNeighbour(int3 hpos, int radius, HeroPtr h);
  156. int3 explorationNewPoint(HeroPtr h);
  157. int3 explorationDesperate(HeroPtr h);
  158. bool isTileNotReserved(const CGHeroInstance * h, int3 t); //the tile is not occupied by allied hero and the object is not reserved
  159. void recruitHero();
  160. virtual std::string getBattleAIName() const override;
  161. virtual void init(std::shared_ptr<CCallback> CB) override;
  162. virtual void yourTurn() override;
  163. virtual 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
  164. virtual void commanderGotLevel(const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID) override; //TODO
  165. virtual 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.
  166. virtual 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
  167. virtual void showTeleportDialog(TeleportChannelID channel, TTeleportExitsList exits, bool impassable, QueryID askID) override;
  168. void showMapObjectSelectDialog(QueryID askID, const Component & icon, const MetaString & title, const MetaString & description, const std::vector<ObjectInstanceID> & objects) override;
  169. virtual void saveGame(BinarySerializer & h, const int version) override; //saving
  170. virtual void loadGame(BinaryDeserializer & h, const int version) override; //loading
  171. virtual void finish() override;
  172. virtual void availableCreaturesChanged(const CGDwelling * town) override;
  173. virtual void heroMoved(const TryMoveHero & details) override;
  174. virtual void heroInGarrisonChange(const CGTownInstance * town) override;
  175. virtual void centerView(int3 pos, int focusTime) override;
  176. virtual void tileHidden(const std::unordered_set<int3, ShashInt3> & pos) override;
  177. virtual void artifactMoved(const ArtifactLocation & src, const ArtifactLocation & dst) override;
  178. virtual void artifactAssembled(const ArtifactLocation & al) override;
  179. virtual void showTavernWindow(const CGObjectInstance * townOrTavern) override;
  180. virtual void showThievesGuildWindow(const CGObjectInstance * obj) override;
  181. virtual void playerBlocked(int reason, bool start) override;
  182. virtual void showPuzzleMap() override;
  183. virtual void showShipyardDialog(const IShipyard * obj) override;
  184. virtual void gameOver(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult) override;
  185. virtual void artifactPut(const ArtifactLocation & al) override;
  186. virtual void artifactRemoved(const ArtifactLocation & al) override;
  187. virtual void artifactDisassembled(const ArtifactLocation & al) override;
  188. virtual void heroVisit(const CGHeroInstance * visitor, const CGObjectInstance * visitedObj, bool start) override;
  189. virtual void availableArtifactsChanged(const CGBlackMarket * bm = nullptr) override;
  190. virtual void heroVisitsTown(const CGHeroInstance * hero, const CGTownInstance * town) override;
  191. virtual void tileRevealed(const std::unordered_set<int3, ShashInt3> & pos) override;
  192. virtual void heroExchangeStarted(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID query) override;
  193. virtual void heroPrimarySkillChanged(const CGHeroInstance * hero, int which, si64 val) override;
  194. virtual void showRecruitmentDialog(const CGDwelling * dwelling, const CArmedInstance * dst, int level) override;
  195. virtual void heroMovePointsChanged(const CGHeroInstance * hero) override;
  196. virtual void garrisonsChanged(ObjectInstanceID id1, ObjectInstanceID id2) override;
  197. virtual void newObject(const CGObjectInstance * obj) override;
  198. virtual void showHillFortWindow(const CGObjectInstance * object, const CGHeroInstance * visitor) override;
  199. virtual void playerBonusChanged(const Bonus & bonus, bool gain) override;
  200. virtual void heroCreated(const CGHeroInstance *) override;
  201. virtual void advmapSpellCast(const CGHeroInstance * caster, int spellID) override;
  202. virtual void showInfoDialog(const std::string & text, const std::vector<Component> & components, int soundID) override;
  203. virtual void requestRealized(PackageApplied * pa) override;
  204. virtual void receivedResource() override;
  205. virtual void objectRemoved(const CGObjectInstance * obj) override;
  206. virtual void showUniversityWindow(const IMarket * market, const CGHeroInstance * visitor) override;
  207. virtual void heroManaPointsChanged(const CGHeroInstance * hero) override;
  208. virtual void heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val) override;
  209. virtual void battleResultsApplied() override;
  210. virtual void objectPropertyChanged(const SetObjectProperty * sop) override;
  211. virtual void buildChanged(const CGTownInstance * town, BuildingID buildingID, int what) override;
  212. virtual void heroBonusChanged(const CGHeroInstance * hero, const Bonus & bonus, bool gain) override;
  213. virtual void showMarketWindow(const IMarket * market, const CGHeroInstance * visitor) override;
  214. void showWorldViewEx(const std::vector<ObjectPosInfo> & objectPositions) override;
  215. virtual void battleStart(const CCreatureSet * army1, const CCreatureSet * army2, int3 tile, const CGHeroInstance * hero1, const CGHeroInstance * hero2, bool side) override;
  216. virtual void battleEnd(const BattleResult * br) override;
  217. void makeTurn();
  218. void makeTurnInternal();
  219. void performTypicalActions();
  220. void buildArmyIn(const CGTownInstance * t);
  221. void striveToGoal(Goals::TSubgoal ultimateGoal);
  222. Goals::TSubgoal striveToGoalInternal(Goals::TSubgoal ultimateGoal, bool onlyAbstract);
  223. void endTurn();
  224. void wander(HeroPtr h);
  225. void setGoal(HeroPtr h, Goals::TSubgoal goal);
  226. void evaluateGoal(HeroPtr h); //evaluates goal assigned to hero, if any
  227. void completeGoal(Goals::TSubgoal goal); //safely removes goal from reserved hero
  228. void striveToQuest(const QuestInfo & q);
  229. void recruitHero(const CGTownInstance * t, bool throwing = false);
  230. bool isGoodForVisit(const CGObjectInstance * obj, HeroPtr h, SectorMap & sm);
  231. void buildStructure(const CGTownInstance * t) const;
  232. //void recruitCreatures(const CGTownInstance * t);
  233. void recruitCreatures(const CGDwelling * d, const CArmedInstance * recruiter);
  234. bool canGetArmy(const CGHeroInstance * h, const CGHeroInstance * source); //can we get any better stacks from other hero?
  235. void pickBestCreatures(const CArmedInstance * army, const CArmedInstance * source); //called when we can't find a slot for new stack
  236. void pickBestArtifacts(const CGHeroInstance * h, const CGHeroInstance * other = nullptr);
  237. void moveCreaturesToHero(const CGTownInstance * t);
  238. bool goVisitObj(const CGObjectInstance * obj, HeroPtr h);
  239. void performObjectInteraction(const CGObjectInstance * obj, HeroPtr h);
  240. bool moveHeroToTile(int3 dst, HeroPtr h);
  241. void lostHero(HeroPtr h); //should remove all references to hero (assigned tasks and so on)
  242. void waitTillFree();
  243. void addVisitableObj(const CGObjectInstance * obj);
  244. void markObjectVisited(const CGObjectInstance * obj);
  245. void reserveObject(HeroPtr h, const CGObjectInstance * obj); //TODO: reserve all objects that heroes attempt to visit
  246. void unreserveObject(HeroPtr h, const CGObjectInstance * obj);
  247. void markHeroUnableToExplore(HeroPtr h);
  248. void markHeroAbleToExplore(HeroPtr h);
  249. bool isAbleToExplore(HeroPtr h);
  250. void clearPathsInfo();
  251. void validateObject(const CGObjectInstance * obj); //checks if object is still visible and if not, removes references to it
  252. void validateObject(ObjectIdRef obj); //checks if object is still visible and if not, removes references to it
  253. void validateVisitableObjs();
  254. void retrieveVisitableObjs(std::vector<const CGObjectInstance *> & out, bool includeOwned = false) const;
  255. void retrieveVisitableObjs();
  256. std::vector<const CGObjectInstance *> getFlaggedObjects() const;
  257. const CGObjectInstance * lookForArt(int aid) const;
  258. bool isAccessible(const int3 & pos);
  259. HeroPtr getHeroWithGrail() const;
  260. const CGObjectInstance * getUnvisitedObj(const std::function<bool(const CGObjectInstance *)> & predicate);
  261. bool isAccessibleForHero(const int3 & pos, HeroPtr h, bool includeAllies = false) const;
  262. //optimization - use one SM for every hero call
  263. std::shared_ptr<SectorMap> getCachedSectorMap(HeroPtr h);
  264. const CGTownInstance * findTownWithTavern() const;
  265. bool canRecruitAnyHero(const CGTownInstance * t = NULL) const;
  266. Goals::TSubgoal getGoal(HeroPtr h) const;
  267. bool canAct(HeroPtr h) const;
  268. std::vector<HeroPtr> getUnblockedHeroes() const;
  269. HeroPtr primaryHero() const;
  270. TResources freeResources() const; //owned resources minus gold reserve
  271. TResources estimateIncome() const;
  272. bool containsSavedRes(const TResources & cost) const;
  273. void checkHeroArmy(HeroPtr h);
  274. void requestSent(const CPackForServer * pack, int requestID) override;
  275. void answerQuery(QueryID queryID, int selection);
  276. //special function that can be called ONLY from game events handling thread and will send request ASAP
  277. void requestActionASAP(std::function<void()> whatToDo);
  278. #if 0
  279. //disabled due to issue 2890
  280. template<typename Handler> void registerGoals(Handler & h)
  281. {
  282. //h.template registerType<Goals::AbstractGoal, Goals::BoostHero>();
  283. h.template registerType<Goals::AbstractGoal, Goals::Build>();
  284. h.template registerType<Goals::AbstractGoal, Goals::BuildThis>();
  285. //h.template registerType<Goals::AbstractGoal, Goals::CIssueCommand>();
  286. h.template registerType<Goals::AbstractGoal, Goals::ClearWayTo>();
  287. h.template registerType<Goals::AbstractGoal, Goals::CollectRes>();
  288. h.template registerType<Goals::AbstractGoal, Goals::Conquer>();
  289. h.template registerType<Goals::AbstractGoal, Goals::DigAtTile>();
  290. h.template registerType<Goals::AbstractGoal, Goals::Explore>();
  291. h.template registerType<Goals::AbstractGoal, Goals::FindObj>();
  292. h.template registerType<Goals::AbstractGoal, Goals::GatherArmy>();
  293. h.template registerType<Goals::AbstractGoal, Goals::GatherTroops>();
  294. h.template registerType<Goals::AbstractGoal, Goals::GetArtOfType>();
  295. h.template registerType<Goals::AbstractGoal, Goals::GetObj>();
  296. h.template registerType<Goals::AbstractGoal, Goals::Invalid>();
  297. //h.template registerType<Goals::AbstractGoal, Goals::NotLose>();
  298. h.template registerType<Goals::AbstractGoal, Goals::RecruitHero>();
  299. h.template registerType<Goals::AbstractGoal, Goals::VisitHero>();
  300. h.template registerType<Goals::AbstractGoal, Goals::VisitTile>();
  301. h.template registerType<Goals::AbstractGoal, Goals::Win>();
  302. }
  303. #endif
  304. template<typename Handler> void serializeInternal(Handler & h, const int version)
  305. {
  306. h & knownTeleportChannels;
  307. h & knownSubterraneanGates;
  308. h & destinationTeleport;
  309. h & townVisitsThisWeek;
  310. #if 0
  311. //disabled due to issue 2890
  312. h & lockedHeroes;
  313. #else
  314. {
  315. ui32 length = 0;
  316. h & length;
  317. if(!h.saving)
  318. {
  319. std::set<ui32> loadedPointers;
  320. lockedHeroes.clear();
  321. for(ui32 index = 0; index < length; index++)
  322. {
  323. HeroPtr ignored1;
  324. h & ignored1;
  325. ui8 flag = 0;
  326. h & flag;
  327. if(flag)
  328. {
  329. ui32 pid = 0xffffffff;
  330. h & pid;
  331. if(!vstd::contains(loadedPointers, pid))
  332. {
  333. loadedPointers.insert(pid);
  334. ui16 typeId = 0;
  335. //this is the problem requires such hack
  336. //we have to explicitly ignore invalid goal class type id
  337. h & typeId;
  338. Goals::AbstractGoal ignored2;
  339. ignored2.serialize(h, version);
  340. }
  341. }
  342. }
  343. }
  344. }
  345. #endif
  346. h & reservedHeroesMap; //FIXME: cannot instantiate abstract class
  347. h & visitableObjs;
  348. h & alreadyVisited;
  349. h & reservedObjs;
  350. h & saving;
  351. h & status;
  352. h & battlename;
  353. h & heroesUnableToExplore;
  354. //myCB is restored after load by init call
  355. }
  356. };
  357. class cannotFulfillGoalException : public std::exception
  358. {
  359. std::string msg;
  360. public:
  361. explicit cannotFulfillGoalException(crstring _Message)
  362. : msg(_Message)
  363. {
  364. }
  365. virtual ~cannotFulfillGoalException() throw ()
  366. {
  367. };
  368. const char * what() const throw () override
  369. {
  370. return msg.c_str();
  371. }
  372. };
  373. class goalFulfilledException : public std::exception
  374. {
  375. std::string msg;
  376. public:
  377. Goals::TSubgoal goal;
  378. explicit goalFulfilledException(Goals::TSubgoal Goal)
  379. : goal(Goal)
  380. {
  381. msg = goal->name();
  382. }
  383. virtual ~goalFulfilledException() throw ()
  384. {
  385. };
  386. const char * what() const throw () override
  387. {
  388. return msg.c_str();
  389. }
  390. };
  391. void makePossibleUpgrades(const CArmedInstance * obj);