VCAI.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. #pragma once
  2. #include "../../lib/AI_Base.h"
  3. #include "../../CCallback.h"
  4. #include "../../lib/CDefObjInfoHandler.h"
  5. #include "../../lib/CObjectHandler.h"
  6. #include "../../lib/CThreadHelper.h"
  7. #include "../../lib/VCMI_Lib.h"
  8. #include "../../lib/CBuildingHandler.h"
  9. #include "../../lib/CCreatureHandler.h"
  10. #include "../../lib/CTownHandler.h"
  11. #include "../../lib/CSpellHandler.h"
  12. #include "../../lib/CObjectHandler.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. #include "../../lib/CStopWatch.h"
  19. struct QuestInfo;
  20. typedef const int3& crint3;
  21. typedef const std::string& crstring;
  22. //provisional class for AI to store a reference to an owned hero object
  23. //checks if it's valid on access, should be used in place of const CGHeroInstance*
  24. struct HeroPtr
  25. {
  26. const CGHeroInstance *h;
  27. ObjectInstanceID hid;
  28. public:
  29. std::string name;
  30. HeroPtr();
  31. HeroPtr(const CGHeroInstance *H);
  32. ~HeroPtr();
  33. operator bool() const
  34. {
  35. return validAndSet();
  36. }
  37. bool operator<(const HeroPtr &rhs) const;
  38. const CGHeroInstance *operator->() const;
  39. const CGHeroInstance *operator*() const; //not that consistent with -> but all interfaces use CGHeroInstance*, so it's convenient
  40. const CGHeroInstance *get(bool doWeExpectNull = false) const;
  41. bool validAndSet() const;
  42. template <typename Handler> void serialize(Handler &h, const int version)
  43. {
  44. h & this->h & hid & name;
  45. }
  46. };
  47. enum BattleState
  48. {
  49. NO_BATTLE,
  50. UPCOMING_BATTLE,
  51. ONGOING_BATTLE,
  52. ENDING_BATTLE
  53. };
  54. class AIStatus
  55. {
  56. boost::mutex mx;
  57. boost::condition_variable cv;
  58. BattleState battle;
  59. std::map<QueryID, std::string> remainingQueries;
  60. 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)
  61. bool havingTurn;
  62. public:
  63. AIStatus();
  64. ~AIStatus();
  65. void setBattle(BattleState BS);
  66. BattleState getBattle();
  67. void addQuery(QueryID ID, std::string description);
  68. void removeQuery(QueryID ID);
  69. int getQueriesCount();
  70. void startedTurn();
  71. void madeTurn();
  72. void waitTillFree();
  73. bool haveTurn();
  74. void attemptedAnsweringQuery(QueryID queryID, int answerRequestID);
  75. void receivedAnswerConfirmation(int answerRequestID, int result);
  76. template <typename Handler> void serialize(Handler &h, const int version)
  77. {
  78. h & battle & remainingQueries & requestToQueryID & havingTurn;
  79. }
  80. };
  81. enum EGoals
  82. {
  83. INVALID = -1,
  84. WIN, DO_NOT_LOSE, CONQUER, BUILD, //build needs to get a real reasoning
  85. EXPLORE, GATHER_ARMY, BOOST_HERO,
  86. RECRUIT_HERO,
  87. BUILD_STRUCTURE, //if hero set, then in visited town
  88. COLLECT_RES,
  89. GATHER_TROOPS, // val of creatures with objid
  90. OBJECT_GOALS_BEGIN,
  91. GET_OBJ, //visit or defeat or collect the object
  92. FIND_OBJ, //find and visit any obj with objid + resid //TODO: consider universal subid for various types (aid, bid)
  93. VISIT_HERO, //heroes can move around - set goal abstract and track hero every turn
  94. GET_ART_TYPE,
  95. //BUILD_STRUCTURE,
  96. ISSUE_COMMAND,
  97. VISIT_TILE, //tile, in conjunction with hero elementar; assumes tile is reachable
  98. CLEAR_WAY_TO,
  99. DIG_AT_TILE //elementar with hero on tile
  100. };
  101. struct CGoal;
  102. typedef CGoal TSubgoal;
  103. #define SETTER(type, field) CGoal &set ## field(const type &rhs) { field = rhs; return *this; }
  104. #if 0
  105. #define SETTER
  106. #endif // _DEBUG
  107. enum {LOW_PR = -1};
  108. struct CGoal
  109. {
  110. EGoals goalType;
  111. bool isElementar; SETTER(bool, isElementar)
  112. bool isAbstract; SETTER(bool, isAbstract) //allows to remember abstract goals
  113. int priority; SETTER(bool, priority)
  114. std::string name() const;
  115. virtual TSubgoal whatToDoToAchieve();
  116. CGoal(EGoals goal = INVALID) : goalType(goal)
  117. {
  118. priority = 0;
  119. isElementar = false;
  120. isAbstract = false;
  121. value = 0;
  122. aid = -1;
  123. resID = -1;
  124. tile = int3(-1, -1, -1);
  125. town = NULL;
  126. }
  127. bool invalid() const;
  128. static TSubgoal goVisitOrLookFor(const CGObjectInstance *obj); //if obj is NULL, then we'll explore
  129. static TSubgoal lookForArtSmart(int aid); //checks non-standard ways of obtaining art (merchants, quests, etc.)
  130. static TSubgoal tryRecruitHero();
  131. int value; SETTER(int, value)
  132. int resID; SETTER(int, resID)
  133. int objid; SETTER(int, objid)
  134. int aid; SETTER(int, aid)
  135. int3 tile; SETTER(int3, tile)
  136. HeroPtr hero; SETTER(HeroPtr, hero)
  137. const CGTownInstance *town; SETTER(CGTownInstance *, town)
  138. int bid; SETTER(int, bid)
  139. bool operator== (CGoal &g)
  140. {
  141. switch (goalType)
  142. {
  143. case EGoals::GET_OBJ:
  144. return objid == g.objid;
  145. }
  146. return false;
  147. }
  148. template <typename Handler> void serialize(Handler &h, const int version)
  149. {
  150. h & goalType & isElementar & isAbstract & priority;
  151. h & value & resID & objid & aid & tile & hero & town & bid;
  152. }
  153. };
  154. enum {NOT_VISIBLE = 0, NOT_CHECKED = 1, NOT_AVAILABLE};
  155. struct SectorMap
  156. {
  157. //a sector is set of tiles that would be mutually reachable if all visitable objs would be passable (incl monsters)
  158. struct Sector
  159. {
  160. int id;
  161. std::vector<int3> tiles;
  162. std::vector<int3> embarkmentPoints; //tiles of other sectors onto which we can (dis)embark
  163. bool water; //all tiles of sector are land or water
  164. Sector()
  165. {
  166. id = -1;
  167. }
  168. };
  169. bool valid; //some kind of lazy eval
  170. std::map<int3, int3> parent;
  171. std::vector<std::vector<std::vector<unsigned char>>> sector;
  172. //std::vector<std::vector<std::vector<unsigned char>>> pathfinderSector;
  173. std::map<int, Sector> infoOnSectors;
  174. SectorMap();
  175. void update();
  176. void clear();
  177. void exploreNewSector(crint3 pos, int num);
  178. void write(crstring fname);
  179. unsigned char &retreiveTile(crint3 pos);
  180. void makeParentBFS(crint3 source);
  181. int3 firstTileToGet(HeroPtr h, crint3 dst); //if h wants to reach tile dst, which tile he should visit to clear the way?
  182. };
  183. struct CIssueCommand : CGoal
  184. {
  185. boost::function<bool()> command;
  186. CIssueCommand(boost::function<bool()> _command): CGoal(ISSUE_COMMAND), command(_command) {}
  187. };
  188. // AI lives in a dangerous world. CGObjectInstances under pointer may got deleted/hidden.
  189. // This class stores object id, so we can detect when we lose access to the underlying object.
  190. struct ObjectIdRef
  191. {
  192. ObjectInstanceID id;
  193. const CGObjectInstance *operator->() const;
  194. operator const CGObjectInstance *() const;
  195. ObjectIdRef(ObjectInstanceID _id);
  196. ObjectIdRef(const CGObjectInstance *obj);
  197. bool operator<(const ObjectIdRef &rhs) const;
  198. template <typename Handler> void serialize(Handler &h, const int version)
  199. {
  200. h & id;
  201. }
  202. };
  203. class ObjsVector : public std::vector<ObjectIdRef>
  204. {
  205. private:
  206. };
  207. class VCAI : public CAdventureAI
  208. {
  209. //internal methods for town development
  210. //try build an unbuilt structure in maxDays at most (0 = indefinite)
  211. bool tryBuildStructure(const CGTownInstance * t, BuildingID building, unsigned int maxDays=0);
  212. //try build ANY unbuilt structure
  213. bool tryBuildAnyStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays=0);
  214. //try build first unbuilt structure
  215. bool tryBuildNextStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays=0);
  216. public:
  217. friend class FuzzyHelper;
  218. std::map<const CGObjectInstance *, const CGObjectInstance *> knownSubterraneanGates;
  219. //std::vector<const CGObjectInstance *> visitedThisWeek; //only OPWs
  220. std::map<HeroPtr, std::vector<const CGTownInstance *> > townVisitsThisWeek;
  221. std::map<HeroPtr, CGoal> lockedHeroes; //TODO: allow non-elementar objectives
  222. std::map<HeroPtr, std::vector<const CGObjectInstance *> > reservedHeroesMap; //objects reserved by specific heroes
  223. std::vector<const CGObjectInstance *> visitableObjs;
  224. std::vector<const CGObjectInstance *> alreadyVisited;
  225. std::vector<const CGObjectInstance *> reservedObjs; //to be visited by specific hero
  226. TResources saving;
  227. AIStatus status;
  228. std::string battlename;
  229. shared_ptr<CCallback> myCb;
  230. unique_ptr<boost::thread> makingTurn;
  231. VCAI(void);
  232. ~VCAI(void);
  233. void tryRealize(CGoal g);
  234. int3 explorationBestNeighbour(int3 hpos, int radius, HeroPtr h);
  235. int3 explorationNewPoint(int radius, HeroPtr h, std::vector<std::vector<int3> > &tiles);
  236. void recruitHero();
  237. virtual std::string getBattleAIName() const OVERRIDE;
  238. virtual void init(shared_ptr<CCallback> CB) OVERRIDE;
  239. virtual void yourTurn() OVERRIDE;
  240. 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
  241. virtual void commanderGotLevel (const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID) OVERRIDE; //TODO
  242. 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.
  243. 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
  244. virtual void saveGame(COSer<CSaveFile> &h, const int version) OVERRIDE; //saving
  245. virtual void loadGame(CISer<CLoadFile> &h, const int version) OVERRIDE; //loading
  246. virtual void finish() OVERRIDE;
  247. virtual void availableCreaturesChanged(const CGDwelling *town) OVERRIDE;
  248. virtual void heroMoved(const TryMoveHero & details) OVERRIDE;
  249. virtual void stackChagedCount(const StackLocation &location, const TQuantity &change, bool isAbsolute) OVERRIDE;
  250. virtual void heroInGarrisonChange(const CGTownInstance *town) OVERRIDE;
  251. virtual void centerView(int3 pos, int focusTime) OVERRIDE;
  252. virtual void tileHidden(const boost::unordered_set<int3, ShashInt3> &pos) OVERRIDE;
  253. virtual void artifactMoved(const ArtifactLocation &src, const ArtifactLocation &dst) OVERRIDE;
  254. virtual void artifactAssembled(const ArtifactLocation &al) OVERRIDE;
  255. virtual void showTavernWindow(const CGObjectInstance *townOrTavern) OVERRIDE;
  256. virtual void showThievesGuildWindow (const CGObjectInstance * obj) OVERRIDE;
  257. virtual void playerBlocked(int reason) OVERRIDE;
  258. virtual void showPuzzleMap() OVERRIDE;
  259. virtual void showShipyardDialog(const IShipyard *obj) OVERRIDE;
  260. virtual void gameOver(PlayerColor player, bool victory) OVERRIDE;
  261. virtual void artifactPut(const ArtifactLocation &al) OVERRIDE;
  262. virtual void artifactRemoved(const ArtifactLocation &al) OVERRIDE;
  263. virtual void stacksErased(const StackLocation &location) OVERRIDE;
  264. virtual void artifactDisassembled(const ArtifactLocation &al) OVERRIDE;
  265. virtual void heroVisit(const CGHeroInstance *visitor, const CGObjectInstance *visitedObj, bool start) OVERRIDE;
  266. virtual void availableArtifactsChanged(const CGBlackMarket *bm = NULL) OVERRIDE;
  267. virtual void heroVisitsTown(const CGHeroInstance* hero, const CGTownInstance * town) OVERRIDE;
  268. virtual void tileRevealed(const boost::unordered_set<int3, ShashInt3> &pos) OVERRIDE;
  269. virtual void heroExchangeStarted(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID query) OVERRIDE;
  270. virtual void heroPrimarySkillChanged(const CGHeroInstance * hero, int which, si64 val) OVERRIDE;
  271. virtual void showRecruitmentDialog(const CGDwelling *dwelling, const CArmedInstance *dst, int level) OVERRIDE;
  272. virtual void heroMovePointsChanged(const CGHeroInstance * hero) OVERRIDE;
  273. virtual void stackChangedType(const StackLocation &location, const CCreature &newType) OVERRIDE;
  274. virtual void stacksRebalanced(const StackLocation &src, const StackLocation &dst, TQuantity count) OVERRIDE;
  275. virtual void newObject(const CGObjectInstance * obj) OVERRIDE;
  276. virtual void showHillFortWindow(const CGObjectInstance *object, const CGHeroInstance *visitor) OVERRIDE;
  277. virtual void playerBonusChanged(const Bonus &bonus, bool gain) OVERRIDE;
  278. virtual void newStackInserted(const StackLocation &location, const CStackInstance &stack) OVERRIDE;
  279. virtual void heroCreated(const CGHeroInstance*) OVERRIDE;
  280. virtual void advmapSpellCast(const CGHeroInstance * caster, int spellID) OVERRIDE;
  281. virtual void showInfoDialog(const std::string &text, const std::vector<Component*> &components, int soundID) OVERRIDE;
  282. virtual void requestRealized(PackageApplied *pa) OVERRIDE;
  283. virtual void receivedResource(int type, int val) OVERRIDE;
  284. virtual void stacksSwapped(const StackLocation &loc1, const StackLocation &loc2) OVERRIDE;
  285. virtual void objectRemoved(const CGObjectInstance *obj) OVERRIDE;
  286. virtual void showUniversityWindow(const IMarket *market, const CGHeroInstance *visitor) OVERRIDE;
  287. virtual void heroManaPointsChanged(const CGHeroInstance * hero) OVERRIDE;
  288. virtual void heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val) OVERRIDE;
  289. virtual void battleResultsApplied() OVERRIDE;
  290. virtual void objectPropertyChanged(const SetObjectProperty * sop) OVERRIDE;
  291. virtual void buildChanged(const CGTownInstance *town, BuildingID buildingID, int what) OVERRIDE;
  292. virtual void heroBonusChanged(const CGHeroInstance *hero, const Bonus &bonus, bool gain) OVERRIDE;
  293. virtual void showMarketWindow(const IMarket *market, const CGHeroInstance *visitor) OVERRIDE;
  294. virtual void battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool side) OVERRIDE;
  295. virtual void battleEnd(const BattleResult *br) OVERRIDE;
  296. void makeTurn();
  297. void makeTurnInternal();
  298. void performTypicalActions();
  299. void buildArmyIn(const CGTownInstance * t);
  300. void striveToGoal(const CGoal &ultimateGoal);
  301. void endTurn();
  302. void wander(HeroPtr h);
  303. void setGoal(HeroPtr h, const CGoal goal);
  304. void setGoal(HeroPtr h, EGoals goalType = INVALID);
  305. void completeGoal (const CGoal goal); //safely removes goal from reserved hero
  306. void striveToQuest (const QuestInfo &q);
  307. bool fulfillsGoal (CGoal &goal, CGoal &mainGoal);
  308. bool fulfillsGoal (CGoal &goal, const CGoal &mainGoal); //TODO: something smarter
  309. void recruitHero(const CGTownInstance * t, bool throwing = false);
  310. std::vector<const CGObjectInstance *> getPossibleDestinations(HeroPtr h);
  311. void buildStructure(const CGTownInstance * t);
  312. //void recruitCreatures(const CGTownInstance * t);
  313. void recruitCreatures(const CGDwelling * d);
  314. bool canGetArmy (const CGHeroInstance * h, const CGHeroInstance * source); //can we get any better stacks from other hero?
  315. void pickBestCreatures(const CArmedInstance * army, const CArmedInstance * source); //called when we can't find a slot for new stack
  316. void moveCreaturesToHero(const CGTownInstance * t);
  317. bool goVisitObj(const CGObjectInstance * obj, HeroPtr h);
  318. void performObjectInteraction(const CGObjectInstance * obj, HeroPtr h);
  319. bool moveHeroToTile(int3 dst, HeroPtr h);
  320. void lostHero(HeroPtr h); //should remove all references to hero (assigned tasks and so on)
  321. void waitTillFree();
  322. void addVisitableObj(const CGObjectInstance *obj);
  323. void markObjectVisited (const CGObjectInstance *obj);
  324. void reserveObject (HeroPtr h, const CGObjectInstance *obj);
  325. //void removeVisitableObj(const CGObjectInstance *obj);
  326. void validateObject(const CGObjectInstance *obj); //checks if object is still visible and if not, removes references to it
  327. void validateObject(ObjectIdRef obj); //checks if object is still visible and if not, removes references to it
  328. void validateVisitableObjs();
  329. void retreiveVisitableObjs(std::vector<const CGObjectInstance *> &out, bool includeOwned = false) const;
  330. std::vector<const CGObjectInstance *> getFlaggedObjects() const;
  331. const CGObjectInstance *lookForArt(int aid) const;
  332. bool isAccessible(const int3 &pos);
  333. HeroPtr getHeroWithGrail() const;
  334. const CGObjectInstance *getUnvisitedObj(const boost::function<bool(const CGObjectInstance *)> &predicate);
  335. bool isAccessibleForHero(const int3 & pos, HeroPtr h, bool includeAllies = false) const;
  336. const CGTownInstance *findTownWithTavern() const;
  337. std::vector<HeroPtr> getUnblockedHeroes() const;
  338. HeroPtr primaryHero() const;
  339. TResources estimateIncome() const;
  340. bool containsSavedRes(const TResources &cost) const;
  341. void checkHeroArmy (HeroPtr h);
  342. void requestSent(const CPackForServer *pack, int requestID) OVERRIDE;
  343. void answerQuery(QueryID queryID, int selection);
  344. //special function that can be called ONLY from game events handling thread and will send request ASAP
  345. void requestActionASAP(boost::function<void()> whatToDo);
  346. template <typename Handler> void serializeInternal(Handler &h, const int version)
  347. {
  348. h & knownSubterraneanGates & townVisitsThisWeek & lockedHeroes & reservedHeroesMap;
  349. h & visitableObjs & alreadyVisited & reservedObjs;
  350. h & saving & status & battlename;
  351. //myCB is restored after load by init call
  352. }
  353. };
  354. class cannotFulfillGoalException : public std::exception
  355. {
  356. std::string msg;
  357. public:
  358. explicit cannotFulfillGoalException(crstring _Message) : msg(_Message)
  359. {
  360. }
  361. virtual ~cannotFulfillGoalException() throw ()
  362. {
  363. };
  364. const char *what() const throw () OVERRIDE
  365. {
  366. return msg.c_str();
  367. }
  368. };
  369. class goalFulfilledException : public std::exception
  370. {
  371. public:
  372. CGoal goal;
  373. explicit goalFulfilledException(CGoal Goal) : goal(Goal)
  374. {
  375. }
  376. virtual ~goalFulfilledException() throw ()
  377. {
  378. };
  379. const char *what() const throw () OVERRIDE
  380. {
  381. return goal.name().c_str();
  382. }
  383. };
  384. template<int id>
  385. bool objWithID(const CGObjectInstance *obj)
  386. {
  387. return obj->ID == id;
  388. }
  389. bool isBlockedBorderGate(int3 tileToHit);
  390. bool isWeeklyRevisitable (const CGObjectInstance * obj);
  391. bool shouldVisit (HeroPtr h, const CGObjectInstance * obj);
  392. void makePossibleUpgrades(const CArmedInstance *obj);
  393. bool boundaryBetweenTwoPoints (int3 pos1, int3 pos2);