VCAI.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. #pragma once
  2. #include "AIUtility.h"
  3. #include "Goals.h"
  4. #include "../../lib/AI_Base.h"
  5. #include "../../CCallback.h"
  6. #include "../../lib/CThreadHelper.h"
  7. #include "../../lib/GameConstants.h"
  8. #include "../../lib/VCMI_Lib.h"
  9. #include "../../lib/CBuildingHandler.h"
  10. #include "../../lib/CCreatureHandler.h"
  11. #include "../../lib/CTownHandler.h"
  12. #include "../../lib/CSpellHandler.h"
  13. #include "../../lib/Connection.h"
  14. #include "../../lib/CGameState.h"
  15. #include "../../lib/mapping/CMap.h"
  16. #include "../../lib/NetPacks.h"
  17. #include "../../lib/CondSh.h"
  18. struct QuestInfo;
  19. /*
  20. * VCAI.h, part of VCMI engine
  21. *
  22. * Authors: listed in file AUTHORS in main folder
  23. *
  24. * License: GNU General Public License v2.0 or later
  25. * Full text of license available in license.txt file, in main folder
  26. *
  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 havingTurn;
  38. public:
  39. AIStatus();
  40. ~AIStatus();
  41. void setBattle(BattleState BS);
  42. void setMove(bool ongoing);
  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 & remainingQueries & requestToQueryID & havingTurn;
  57. }
  58. };
  59. enum {NOT_VISIBLE = 0, NOT_CHECKED = 1, NOT_AVAILABLE};
  60. struct SectorMap
  61. {
  62. //a sector is set of tiles that would be mutually reachable if all visitable objs would be passable (incl monsters)
  63. struct Sector
  64. {
  65. int id;
  66. std::vector<int3> tiles;
  67. std::vector<int3> embarkmentPoints; //tiles of other sectors onto which we can (dis)embark
  68. std::vector<const CGObjectInstance *> subterraneanGates;
  69. bool water; //all tiles of sector are land or water
  70. Sector()
  71. {
  72. id = -1;
  73. }
  74. };
  75. bool valid; //some kind of lazy eval
  76. std::map<int3, int3> parent;
  77. std::vector<std::vector<std::vector<unsigned char>>> sector;
  78. //std::vector<std::vector<std::vector<unsigned char>>> pathfinderSector;
  79. std::map<int, Sector> infoOnSectors;
  80. SectorMap();
  81. SectorMap(HeroPtr h);
  82. void update();
  83. void clear();
  84. void exploreNewSector(crint3 pos, int num, CCallback * cbp);
  85. void write(crstring fname);
  86. unsigned char &retreiveTile(crint3 pos);
  87. void makeParentBFS(crint3 source);
  88. int3 firstTileToGet(HeroPtr h, crint3 dst); //if h wants to reach tile dst, which tile he should visit to clear the way?
  89. int3 findFirstVisitableTile(HeroPtr h, crint3 dst);
  90. };
  91. //Set of buildings for different goals. Does not include any prerequisites.
  92. const BuildingID essential[] = {BuildingID::TAVERN, BuildingID::TOWN_HALL};
  93. const BuildingID goldSource[] = {BuildingID::TOWN_HALL, BuildingID::CITY_HALL, BuildingID::CAPITOL};
  94. const BuildingID unitsSource[] = { BuildingID::DWELL_LVL_1, BuildingID::DWELL_LVL_2, BuildingID::DWELL_LVL_3,
  95. BuildingID::DWELL_LVL_4, BuildingID::DWELL_LVL_5, BuildingID::DWELL_LVL_6, BuildingID::DWELL_LVL_7};
  96. const BuildingID unitsUpgrade[] = { BuildingID::DWELL_LVL_1_UP, BuildingID::DWELL_LVL_2_UP, BuildingID::DWELL_LVL_3_UP,
  97. BuildingID::DWELL_LVL_4_UP, BuildingID::DWELL_LVL_5_UP, BuildingID::DWELL_LVL_6_UP, BuildingID::DWELL_LVL_7_UP};
  98. const BuildingID unitGrowth[] = { BuildingID::FORT, BuildingID::CITADEL, BuildingID::CASTLE, BuildingID::HORDE_1,
  99. BuildingID::HORDE_1_UPGR, BuildingID::HORDE_2, BuildingID::HORDE_2_UPGR};
  100. const BuildingID spells[] = {BuildingID::MAGES_GUILD_1, BuildingID::MAGES_GUILD_2, BuildingID::MAGES_GUILD_3,
  101. BuildingID::MAGES_GUILD_4, BuildingID::MAGES_GUILD_5};
  102. const BuildingID extra[] = {BuildingID::RESOURCE_SILO, BuildingID::SPECIAL_1, BuildingID::SPECIAL_2, BuildingID::SPECIAL_3,
  103. BuildingID::SPECIAL_4, BuildingID::SHIPYARD}; // all remaining buildings
  104. class VCAI : public CAdventureAI
  105. {
  106. public:
  107. //internal methods for town development
  108. //try build an unbuilt structure in maxDays at most (0 = indefinite)
  109. /*bool canBuildStructure(const CGTownInstance * t, BuildingID building, unsigned int maxDays=7);*/
  110. bool tryBuildStructure(const CGTownInstance * t, BuildingID building, unsigned int maxDays=7);
  111. //try build ANY unbuilt structure
  112. BuildingID canBuildAnyStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays=7);
  113. bool tryBuildAnyStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays=7);
  114. //try build first unbuilt structure
  115. bool tryBuildNextStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays=7);
  116. friend class FuzzyHelper;
  117. std::map<const CGObjectInstance *, const CGObjectInstance *> knownSubterraneanGates;
  118. //std::vector<const CGObjectInstance *> visitedThisWeek; //only OPWs
  119. std::map<HeroPtr, std::set<const CGTownInstance *> > townVisitsThisWeek;
  120. std::map<HeroPtr, Goals::TSubgoal> lockedHeroes; //TODO: allow non-elementar objectives
  121. std::map<HeroPtr, std::set<const CGObjectInstance *> > reservedHeroesMap; //objects reserved by specific heroes
  122. std::set<HeroPtr> heroesUnableToExplore; //these heroes will not be polled for exploration in current state of game
  123. //sets are faster to search, also do not contain duplicates
  124. std::set<const CGObjectInstance *> visitableObjs;
  125. std::set<const CGObjectInstance *> alreadyVisited;
  126. std::set<const CGObjectInstance *> reservedObjs; //to be visited by specific hero
  127. TResources saving;
  128. AIStatus status;
  129. std::string battlename;
  130. shared_ptr<CCallback> myCb;
  131. unique_ptr<boost::thread> makingTurn;
  132. VCAI(void);
  133. ~VCAI(void);
  134. //TODO: use only smart pointers?
  135. void tryRealize(Goals::Explore & g);
  136. void tryRealize(Goals::RecruitHero & g);
  137. void tryRealize(Goals::VisitTile & g);
  138. void tryRealize(Goals::VisitHero & g);
  139. void tryRealize(Goals::BuildThis & g);
  140. void tryRealize(Goals::DigAtTile & g);
  141. void tryRealize(Goals::CollectRes & g);
  142. void tryRealize(Goals::Build & g);
  143. void tryRealize(Goals::Invalid & g);
  144. void tryRealize(Goals::AbstractGoal & g);
  145. int3 explorationBestNeighbour(int3 hpos, int radius, HeroPtr h);
  146. int3 explorationNewPoint(HeroPtr h);
  147. int3 explorationDesperate(HeroPtr h);
  148. bool canReachTile (const CGHeroInstance * h, int3 t);
  149. void recruitHero();
  150. virtual std::string getBattleAIName() const override;
  151. virtual void init(shared_ptr<CCallback> CB) override;
  152. virtual void yourTurn() override;
  153. 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
  154. virtual void commanderGotLevel (const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID) override; //TODO
  155. 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.
  156. 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
  157. virtual void saveGame(COSer & h, const int version) override; //saving
  158. virtual void loadGame(CISer & h, const int version) override; //loading
  159. virtual void finish() override;
  160. virtual void availableCreaturesChanged(const CGDwelling *town) override;
  161. virtual void heroMoved(const TryMoveHero & details) override;
  162. virtual void stackChagedCount(const StackLocation &location, const TQuantity &change, bool isAbsolute) override;
  163. virtual void heroInGarrisonChange(const CGTownInstance *town) override;
  164. virtual void centerView(int3 pos, int focusTime) override;
  165. virtual void tileHidden(const std::unordered_set<int3, ShashInt3> &pos) override;
  166. virtual void artifactMoved(const ArtifactLocation &src, const ArtifactLocation &dst) override;
  167. virtual void artifactAssembled(const ArtifactLocation &al) override;
  168. virtual void showTavernWindow(const CGObjectInstance *townOrTavern) override;
  169. virtual void showThievesGuildWindow (const CGObjectInstance * obj) override;
  170. virtual void playerBlocked(int reason, bool start) override;
  171. virtual void showPuzzleMap() override;
  172. virtual void showShipyardDialog(const IShipyard *obj) override;
  173. virtual void gameOver(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult) override;
  174. virtual void artifactPut(const ArtifactLocation &al) override;
  175. virtual void artifactRemoved(const ArtifactLocation &al) override;
  176. virtual void stacksErased(const StackLocation &location) override;
  177. virtual void artifactDisassembled(const ArtifactLocation &al) override;
  178. virtual void heroVisit(const CGHeroInstance *visitor, const CGObjectInstance *visitedObj, bool start) override;
  179. virtual void availableArtifactsChanged(const CGBlackMarket *bm = nullptr) override;
  180. virtual void heroVisitsTown(const CGHeroInstance* hero, const CGTownInstance * town) override;
  181. virtual void tileRevealed(const std::unordered_set<int3, ShashInt3> &pos) override;
  182. virtual void heroExchangeStarted(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID query) override;
  183. virtual void heroPrimarySkillChanged(const CGHeroInstance * hero, int which, si64 val) override;
  184. virtual void showRecruitmentDialog(const CGDwelling *dwelling, const CArmedInstance *dst, int level) override;
  185. virtual void heroMovePointsChanged(const CGHeroInstance * hero) override;
  186. virtual void stackChangedType(const StackLocation &location, const CCreature &newType) override;
  187. virtual void stacksRebalanced(const StackLocation &src, const StackLocation &dst, TQuantity count) override;
  188. virtual void newObject(const CGObjectInstance * obj) override;
  189. virtual void showHillFortWindow(const CGObjectInstance *object, const CGHeroInstance *visitor) override;
  190. virtual void playerBonusChanged(const Bonus &bonus, bool gain) override;
  191. virtual void newStackInserted(const StackLocation &location, const CStackInstance &stack) override;
  192. virtual void heroCreated(const CGHeroInstance*) override;
  193. virtual void advmapSpellCast(const CGHeroInstance * caster, int spellID) override;
  194. virtual void showInfoDialog(const std::string &text, const std::vector<Component*> &components, int soundID) override;
  195. virtual void requestRealized(PackageApplied *pa) override;
  196. virtual void receivedResource(int type, int val) override;
  197. virtual void stacksSwapped(const StackLocation &loc1, const StackLocation &loc2) override;
  198. virtual void objectRemoved(const CGObjectInstance *obj) override;
  199. virtual void showUniversityWindow(const IMarket *market, const CGHeroInstance *visitor) override;
  200. virtual void heroManaPointsChanged(const CGHeroInstance * hero) override;
  201. virtual void heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val) override;
  202. virtual void battleResultsApplied() override;
  203. virtual void objectPropertyChanged(const SetObjectProperty * sop) override;
  204. virtual void buildChanged(const CGTownInstance *town, BuildingID buildingID, int what) override;
  205. virtual void heroBonusChanged(const CGHeroInstance *hero, const Bonus &bonus, bool gain) override;
  206. virtual void showMarketWindow(const IMarket *market, const CGHeroInstance *visitor) override;
  207. virtual void battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool side) override;
  208. virtual void battleEnd(const BattleResult *br) override;
  209. void makeTurn();
  210. void makeTurnInternal();
  211. void performTypicalActions();
  212. void buildArmyIn(const CGTownInstance * t);
  213. void striveToGoal(Goals::TSubgoal ultimateGoal);
  214. Goals::TSubgoal striveToGoalInternal(Goals::TSubgoal ultimateGoal, bool onlyAbstract);
  215. void endTurn();
  216. void wander(HeroPtr h);
  217. void setGoal(HeroPtr h, Goals::TSubgoal goal);
  218. void completeGoal (Goals::TSubgoal goal); //safely removes goal from reserved hero
  219. void striveToQuest (const QuestInfo &q);
  220. void recruitHero(const CGTownInstance * t, bool throwing = false);
  221. bool isGoodForVisit(const CGObjectInstance *obj, HeroPtr h);
  222. std::vector<const CGObjectInstance *> getPossibleDestinations(HeroPtr h);
  223. void buildStructure(const CGTownInstance * t);
  224. //void recruitCreatures(const CGTownInstance * t);
  225. void recruitCreatures(const CGDwelling * d, const CArmedInstance * recruiter);
  226. bool canGetArmy (const CGHeroInstance * h, const CGHeroInstance * source); //can we get any better stacks from other hero?
  227. void pickBestCreatures(const CArmedInstance * army, const CArmedInstance * source); //called when we can't find a slot for new stack
  228. void moveCreaturesToHero(const CGTownInstance * t);
  229. bool goVisitObj(const CGObjectInstance * obj, HeroPtr h);
  230. void performObjectInteraction(const CGObjectInstance * obj, HeroPtr h);
  231. bool moveHeroToTile(int3 dst, HeroPtr h);
  232. void lostHero(HeroPtr h); //should remove all references to hero (assigned tasks and so on)
  233. void waitTillFree();
  234. void addVisitableObj(const CGObjectInstance *obj);
  235. void markObjectVisited (const CGObjectInstance *obj);
  236. void reserveObject (HeroPtr h, const CGObjectInstance *obj); //TODO: reserve all objects that heroes attempt to visit
  237. void unreserveObject (HeroPtr h, const CGObjectInstance *obj);
  238. void markHeroUnableToExplore (HeroPtr h);
  239. void markHeroAbleToExplore (HeroPtr h);
  240. bool isAbleToExplore (HeroPtr h);
  241. void clearHeroesUnableToExplore();
  242. void validateObject(const CGObjectInstance *obj); //checks if object is still visible and if not, removes references to it
  243. void validateObject(ObjectIdRef obj); //checks if object is still visible and if not, removes references to it
  244. void validateVisitableObjs();
  245. void retreiveVisitableObjs(std::vector<const CGObjectInstance *> &out, bool includeOwned = false) const;
  246. void retreiveVisitableObjs(std::set<const CGObjectInstance *> &out, bool includeOwned = false) const;
  247. std::vector<const CGObjectInstance *> getFlaggedObjects() const;
  248. const CGObjectInstance *lookForArt(int aid) const;
  249. bool isAccessible(const int3 &pos);
  250. HeroPtr getHeroWithGrail() const;
  251. const CGObjectInstance *getUnvisitedObj(const std::function<bool(const CGObjectInstance *)> &predicate);
  252. bool isAccessibleForHero(const int3 & pos, HeroPtr h, bool includeAllies = false) const;
  253. const CGTownInstance *findTownWithTavern() const;
  254. bool canRecruitAnyHero(const CGTownInstance * t = NULL) const;
  255. Goals::TSubgoal getGoal (HeroPtr h) const;
  256. bool canAct(HeroPtr h) const;
  257. std::vector<HeroPtr> getUnblockedHeroes() const;
  258. HeroPtr primaryHero() const;
  259. TResources freeResources() const; //owned resources minus gold reserve
  260. TResources estimateIncome() const;
  261. bool containsSavedRes(const TResources &cost) const;
  262. void checkHeroArmy (HeroPtr h);
  263. void requestSent(const CPackForServer *pack, int requestID) override;
  264. void answerQuery(QueryID queryID, int selection);
  265. //special function that can be called ONLY from game events handling thread and will send request ASAP
  266. void requestActionASAP(std::function<void()> whatToDo);
  267. template <typename Handler> void registerGoals(Handler &h)
  268. {
  269. //h.template registerType<Goals::AbstractGoal, Goals::BoostHero>();
  270. h.template registerType<Goals::AbstractGoal, Goals::Build>();
  271. h.template registerType<Goals::AbstractGoal, Goals::BuildThis>();
  272. //h.template registerType<Goals::AbstractGoal, Goals::CIssueCommand>();
  273. h.template registerType<Goals::AbstractGoal, Goals::ClearWayTo>();
  274. h.template registerType<Goals::AbstractGoal, Goals::CollectRes>();
  275. h.template registerType<Goals::AbstractGoal, Goals::Conquer>();
  276. h.template registerType<Goals::AbstractGoal, Goals::DigAtTile>();
  277. h.template registerType<Goals::AbstractGoal, Goals::Explore>();
  278. h.template registerType<Goals::AbstractGoal, Goals::FindObj>();
  279. h.template registerType<Goals::AbstractGoal, Goals::GatherArmy>();
  280. h.template registerType<Goals::AbstractGoal, Goals::GatherTroops>();
  281. h.template registerType<Goals::AbstractGoal, Goals::GetArtOfType>();
  282. h.template registerType<Goals::AbstractGoal, Goals::GetObj>();
  283. h.template registerType<Goals::AbstractGoal, Goals::Invalid>();
  284. //h.template registerType<Goals::AbstractGoal, Goals::NotLose>();
  285. h.template registerType<Goals::AbstractGoal, Goals::RecruitHero>();
  286. h.template registerType<Goals::AbstractGoal, Goals::VisitHero>();
  287. h.template registerType<Goals::AbstractGoal, Goals::VisitTile>();
  288. h.template registerType<Goals::AbstractGoal, Goals::Win>();
  289. }
  290. template <typename Handler> void serializeInternal(Handler &h, const int version)
  291. {
  292. h & knownSubterraneanGates & townVisitsThisWeek & lockedHeroes & reservedHeroesMap; //FIXME: cannot instantiate abstract class
  293. h & visitableObjs & alreadyVisited & reservedObjs;
  294. h & saving & status & battlename;
  295. h & heroesUnableToExplore;
  296. //myCB is restored after load by init call
  297. }
  298. };
  299. class cannotFulfillGoalException : public std::exception
  300. {
  301. std::string msg;
  302. public:
  303. explicit cannotFulfillGoalException(crstring _Message) : msg(_Message)
  304. {
  305. }
  306. virtual ~cannotFulfillGoalException() throw ()
  307. {
  308. };
  309. const char *what() const throw () override
  310. {
  311. return msg.c_str();
  312. }
  313. };
  314. class goalFulfilledException : public std::exception
  315. {
  316. public:
  317. Goals::TSubgoal goal;
  318. explicit goalFulfilledException(Goals::TSubgoal Goal) : goal(Goal)
  319. {
  320. }
  321. virtual ~goalFulfilledException() throw ()
  322. {
  323. };
  324. const char *what() const throw () override
  325. {
  326. return goal->name().c_str();
  327. }
  328. };
  329. void makePossibleUpgrades(const CArmedInstance *obj);