VCAI.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. #pragma once
  2. typedef const int3& crint3;
  3. typedef const std::string& crstring;
  4. //provisional class for AI to store a reference to an owned hero object
  5. //checks if it's valid on access, should be used in place of const CGHeroInstance*
  6. struct HeroPtr
  7. {
  8. const CGHeroInstance *h;
  9. int hid; //hero id (object subID or type ID)
  10. public:
  11. std::string name;
  12. HeroPtr();
  13. HeroPtr(const CGHeroInstance *H);
  14. ~HeroPtr();
  15. operator bool() const
  16. {
  17. return validAndSet();
  18. }
  19. bool operator<(const HeroPtr &rhs) const;
  20. const CGHeroInstance *operator->() const;
  21. const CGHeroInstance *operator*() const; //not that consistent with -> but all interfaces use CGHeroInstance*, so it's convenient
  22. const CGHeroInstance *get(bool doWeExpectNull = false) const;
  23. bool validAndSet() const;
  24. };
  25. enum BattleState
  26. {
  27. NO_BATTLE,
  28. UPCOMING_BATTLE,
  29. ONGOING_BATTLE,
  30. ENDING_BATTLE
  31. };
  32. class AIStatus
  33. {
  34. boost::mutex mx;
  35. boost::condition_variable cv;
  36. BattleState battle;
  37. int remainingQueries;
  38. bool havingTurn;
  39. public:
  40. AIStatus();
  41. ~AIStatus();
  42. void setBattle(BattleState BS);
  43. BattleState getBattle();
  44. void addQueries(int val);
  45. void addQuery();
  46. void removeQuery();
  47. int getQueriesCount();
  48. void startedTurn();
  49. void madeTurn();
  50. void waitTillFree();
  51. bool haveTurn();
  52. };
  53. enum EGoals
  54. {
  55. INVALID = -1,
  56. WIN, DO_NOT_LOSE, CONQUER, BUILD, //build needs to get a real reasoning
  57. EXPLORE, GATHER_ARMY, BOOST_HERO,
  58. RECRUIT_HERO,
  59. BUILD_STRUCTURE, //if hero set, then in visited town
  60. COLLECT_RES,
  61. OBJECT_GOALS_BEGIN,
  62. GET_OBJ, //visit or defeat or collect the object
  63. GET_ART_TYPE,
  64. //BUILD_STRUCTURE,
  65. ISSUE_COMMAND,
  66. //hero
  67. //VISIT_OBJ, //hero + tile
  68. VISIT_TILE, //tile, in conjunction with hero elementar; assumes tile is reachable
  69. CLEAR_WAY_TO,
  70. DIG_AT_TILE //elementar with hero on tile
  71. };
  72. struct CGoal;
  73. typedef CGoal TSubgoal;
  74. #define SETTER(type, field) CGoal &set ## field(const type &rhs) { field = rhs; return *this; }
  75. #if 0
  76. #define SETTER
  77. #endif // _DEBUG
  78. enum {LOW_PR = -1};
  79. struct CGoal
  80. {
  81. EGoals goalType;
  82. bool isElementar; SETTER(bool, isElementar)
  83. bool isAbstract; SETTER(bool, isAbstract) //allows to remember abstract goals
  84. int priority; SETTER(bool, priority)
  85. virtual TSubgoal whatToDoToAchieve();
  86. bool isBlockedBorderGate(int3 tileToHit);
  87. CGoal(EGoals goal = INVALID) : goalType(goal)
  88. {
  89. priority = 0;
  90. isElementar = false;
  91. isAbstract = false;
  92. objid = -1;
  93. aid = -1;
  94. tile = int3(-1, -1, -1);
  95. town = NULL;
  96. }
  97. bool invalid() const;
  98. static TSubgoal goVisitOrLookFor(const CGObjectInstance *obj); //if obj is NULL, then we'll explore
  99. static TSubgoal lookForArtSmart(int aid); //checks non-standard ways of obtaining art (merchants, quests, etc.)
  100. static TSubgoal tryRecruitHero();
  101. int value; SETTER(int, value)
  102. int resID; SETTER(int, resID)
  103. int objid; SETTER(int, objid)
  104. int aid; SETTER(int, aid)
  105. int3 tile; SETTER(int3, tile)
  106. HeroPtr hero; SETTER(HeroPtr, hero)
  107. const CGTownInstance *town; SETTER(CGTownInstance *, town)
  108. int bid; SETTER(int, bid)
  109. };
  110. enum {NOT_VISIBLE = 0, NOT_CHECKED = 1, NOT_AVAILABLE};
  111. struct SectorMap
  112. {
  113. //a sector is set of tiles that would be mutually reachable if all visitable objs would be passable (incl monsters)
  114. struct Sector
  115. {
  116. int id;
  117. std::vector<int3> tiles;
  118. std::vector<int3> embarkmentPoints; //tiles of other sectors onto which we can (dis)embark
  119. bool water; //all tiles of sector are land or water
  120. Sector()
  121. {
  122. id = -1;
  123. }
  124. };
  125. bool valid; //some kind of lazy eval
  126. std::map<int3, int3> parent;
  127. std::vector<std::vector<std::vector<unsigned char>>> sector;
  128. //std::vector<std::vector<std::vector<unsigned char>>> pathfinderSector;
  129. std::map<int, Sector> infoOnSectors;
  130. SectorMap();
  131. void update();
  132. void clear();
  133. void exploreNewSector(crint3 pos, int num);
  134. void write(crstring fname);
  135. unsigned char &retreiveTile(crint3 pos);
  136. void makeParentBFS(crint3 source);
  137. int3 firstTileToGet(HeroPtr h, crint3 dst); //if h wants to reach tile dst, which tile he should visit to clear the way?
  138. };
  139. struct CIssueCommand : CGoal
  140. {
  141. boost::function<bool()> command;
  142. CIssueCommand(boost::function<bool()> _command): CGoal(ISSUE_COMMAND), command(_command) {}
  143. };
  144. // AI lives in a dangerous world. CGObjectInstances under pointer may got deleted/hidden.
  145. // This class stores object id, so we can detect when we lose access to the underlying object.
  146. struct ObjectIdRef
  147. {
  148. int id;
  149. const CGObjectInstance *operator->() const;
  150. operator const CGObjectInstance *() const;
  151. ObjectIdRef(int _id);
  152. ObjectIdRef(const CGObjectInstance *obj);
  153. bool operator<(const ObjectIdRef &rhs) const;
  154. };
  155. class ObjsVector : public std::vector<ObjectIdRef>
  156. {
  157. private:
  158. };
  159. class VCAI : public CAdventureAI
  160. {
  161. //internal methods for town development
  162. //try build an unbuilt structure in maxDays at most (0 = indefinite)
  163. bool tryBuildStructure(const CGTownInstance * t, int building, unsigned int maxDays=0);
  164. //try build ANY unbuilt structure
  165. bool tryBuildAnyStructure(const CGTownInstance * t, std::vector<int> buildList, unsigned int maxDays=0);
  166. //try build first unbuilt structure
  167. bool tryBuildNextStructure(const CGTownInstance * t, std::vector<int> buildList, unsigned int maxDays=0);
  168. public:
  169. friend class FuzzyHelper;
  170. std::map<const CGObjectInstance *, const CGObjectInstance *> knownSubterraneanGates;
  171. std::vector<const CGObjectInstance *> visitedThisWeek; //only OPWs
  172. std::map<HeroPtr, std::vector<const CGTownInstance *> > townVisitsThisWeek;
  173. std::map<HeroPtr, CGoal> lockedHeroes; //TODO: allow non-elementar objectives
  174. std::map<HeroPtr, std::vector<const CGObjectInstance *> > reservedHeroesMap; //objects reserved by specific heroes
  175. std::vector<const CGObjectInstance *> visitableObjs;
  176. std::vector<const CGObjectInstance *> alreadyVisited;
  177. std::vector<const CGObjectInstance *> reservedObjs; //to be visited by specific hero
  178. TResources saving;
  179. AIStatus status;
  180. std::string battlename;
  181. CCallback *myCb;
  182. VCAI(void);
  183. ~VCAI(void);
  184. CGObjectInstance * visitedObject; //remember currently viisted object
  185. boost::thread *makingTurn;
  186. void tryRealize(CGoal g);
  187. int3 explorationBestNeighbour(int3 hpos, int radius, HeroPtr h);
  188. int3 explorationNewPoint(int radius, HeroPtr h, std::vector<std::vector<int3> > &tiles);
  189. void recruitHero();
  190. virtual void init(CCallback * CB);
  191. virtual void yourTurn();
  192. virtual void heroGotLevel(const CGHeroInstance *hero, int pskill, std::vector<ui16> &skills, boost::function<void(ui32)> &callback) OVERRIDE; //pskill is gained primary skill, interface has to choose one of given skills and call callback with selection id
  193. virtual void commanderGotLevel (const CCommanderInstance * commander, std::vector<ui32> skills, boost::function<void(ui32)> &callback) {}; //TODO
  194. virtual void showBlockingDialog(const std::string &text, const std::vector<Component> &components, ui32 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.
  195. virtual void showGarrisonDialog(const CArmedInstance *up, const CGHeroInstance *down, bool removableUnits, boost::function<void()> &onEnd) OVERRIDE; //all stacks operations between these objects become allowed, interface has to call onEnd when done
  196. virtual void serialize(COSer<CSaveFile> &h, const int version) OVERRIDE; //saving
  197. virtual void serialize(CISer<CLoadFile> &h, const int version) OVERRIDE; //loading
  198. virtual void finish() OVERRIDE;
  199. virtual void availableCreaturesChanged(const CGDwelling *town) OVERRIDE;
  200. virtual void heroMoved(const TryMoveHero & details) OVERRIDE;
  201. virtual void stackChagedCount(const StackLocation &location, const TQuantity &change, bool isAbsolute) OVERRIDE;
  202. virtual void heroInGarrisonChange(const CGTownInstance *town) OVERRIDE;
  203. virtual void centerView(int3 pos, int focusTime) OVERRIDE;
  204. virtual void tileHidden(const boost::unordered_set<int3, ShashInt3> &pos) OVERRIDE;
  205. virtual void artifactMoved(const ArtifactLocation &src, const ArtifactLocation &dst) OVERRIDE;
  206. virtual void artifactAssembled(const ArtifactLocation &al) OVERRIDE;
  207. virtual void showTavernWindow(const CGObjectInstance *townOrTavern) OVERRIDE;
  208. virtual void showThievesGuildWindow (const CGObjectInstance * obj) OVERRIDE;
  209. virtual void playerBlocked(int reason) OVERRIDE;
  210. virtual void showPuzzleMap() OVERRIDE;
  211. virtual void showShipyardDialog(const IShipyard *obj) OVERRIDE;
  212. virtual void gameOver(ui8 player, bool victory) OVERRIDE;
  213. virtual void artifactPut(const ArtifactLocation &al) OVERRIDE;
  214. virtual void artifactRemoved(const ArtifactLocation &al) OVERRIDE;
  215. virtual void stacksErased(const StackLocation &location) OVERRIDE;
  216. virtual void artifactDisassembled(const ArtifactLocation &al) OVERRIDE;
  217. virtual void heroVisit(const CGHeroInstance *visitor, const CGObjectInstance *visitedObj, bool start) OVERRIDE;
  218. virtual void availableArtifactsChanged(const CGBlackMarket *bm = NULL) OVERRIDE;
  219. virtual void heroVisitsTown(const CGHeroInstance* hero, const CGTownInstance * town) OVERRIDE;
  220. virtual void tileRevealed(const boost::unordered_set<int3, ShashInt3> &pos) OVERRIDE;
  221. virtual void heroExchangeStarted(si32 hero1, si32 hero2) OVERRIDE;
  222. virtual void heroPrimarySkillChanged(const CGHeroInstance * hero, int which, si64 val) OVERRIDE;
  223. virtual void showRecruitmentDialog(const CGDwelling *dwelling, const CArmedInstance *dst, int level) OVERRIDE;
  224. virtual void heroMovePointsChanged(const CGHeroInstance * hero) OVERRIDE;
  225. virtual void stackChangedType(const StackLocation &location, const CCreature &newType) OVERRIDE;
  226. virtual void stacksRebalanced(const StackLocation &src, const StackLocation &dst, TQuantity count) OVERRIDE;
  227. virtual void newObject(const CGObjectInstance * obj) OVERRIDE;
  228. virtual void showHillFortWindow(const CGObjectInstance *object, const CGHeroInstance *visitor) OVERRIDE;
  229. virtual void playerBonusChanged(const Bonus &bonus, bool gain) OVERRIDE;
  230. virtual void newStackInserted(const StackLocation &location, const CStackInstance &stack) OVERRIDE;
  231. virtual void heroCreated(const CGHeroInstance*) OVERRIDE;
  232. virtual void advmapSpellCast(const CGHeroInstance * caster, int spellID) OVERRIDE;
  233. virtual void showInfoDialog(const std::string &text, const std::vector<Component*> &components, int soundID) OVERRIDE;
  234. virtual void requestRealized(PackageApplied *pa) OVERRIDE;
  235. virtual void receivedResource(int type, int val) OVERRIDE;
  236. virtual void stacksSwapped(const StackLocation &loc1, const StackLocation &loc2) OVERRIDE;
  237. virtual void objectRemoved(const CGObjectInstance *obj) OVERRIDE;
  238. virtual void showUniversityWindow(const IMarket *market, const CGHeroInstance *visitor) OVERRIDE;
  239. virtual void heroManaPointsChanged(const CGHeroInstance * hero) OVERRIDE;
  240. virtual void heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val) OVERRIDE;
  241. virtual void battleResultsApplied() OVERRIDE;
  242. virtual void objectPropertyChanged(const SetObjectProperty * sop) OVERRIDE;
  243. virtual void buildChanged(const CGTownInstance *town, int buildingID, int what) OVERRIDE;
  244. virtual void heroBonusChanged(const CGHeroInstance *hero, const Bonus &bonus, bool gain) OVERRIDE;
  245. virtual void showMarketWindow(const IMarket *market, const CGHeroInstance *visitor) OVERRIDE;
  246. virtual void battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool side) OVERRIDE;
  247. virtual void battleEnd(const BattleResult *br) OVERRIDE;
  248. void makeTurn();
  249. void makeTurnInternal();
  250. void performTypicalActions();
  251. void buildArmyIn(const CGTownInstance * t);
  252. void striveToGoal(const CGoal &ultimateGoal);
  253. void endTurn();
  254. void wander(HeroPtr h);
  255. void setGoal(HeroPtr h, const CGoal goal);
  256. void setGoal(HeroPtr h, EGoals goalType = INVALID);
  257. void completeGoal (const CGoal goal); //safely removes goal from reserved hero
  258. void recruitHero(const CGTownInstance * t);
  259. std::vector<const CGObjectInstance *> getPossibleDestinations(HeroPtr h);
  260. void buildStructure(const CGTownInstance * t);
  261. //void recruitCreatures(const CGTownInstance * t);
  262. void recruitCreatures(const CGDwelling * d);
  263. void pickBestCreatures(const CArmedInstance * army, const CArmedInstance * source); //called when we can't find a slot for new stack
  264. void moveCreaturesToHero(const CGTownInstance * t);
  265. bool goVisitObj(const CGObjectInstance * obj, HeroPtr h);
  266. void performObjectInteraction(const CGObjectInstance * obj, HeroPtr h);
  267. bool moveHeroToTile(int3 dst, HeroPtr h);
  268. void lostHero(HeroPtr h); //should remove all references to hero (assigned tasks and so on)
  269. void waitTillFree();
  270. void addVisitableObj(const CGObjectInstance *obj);
  271. void markObjectVisited (const CGObjectInstance *obj);
  272. void reserveObject (HeroPtr h, const CGObjectInstance *obj);
  273. //void removeVisitableObj(const CGObjectInstance *obj);
  274. void validateVisitableObjs();
  275. void retreiveVisitableObjs(std::vector<const CGObjectInstance *> &out, bool includeOwned = false) const;
  276. std::vector<const CGObjectInstance *> getFlaggedObjects() const;
  277. const CGObjectInstance *lookForArt(int aid) const;
  278. bool isAccessible(const int3 &pos);
  279. HeroPtr getHeroWithGrail() const;
  280. const CGObjectInstance *getUnvisitedObj(const boost::function<bool(const CGObjectInstance *)> &predicate);
  281. bool isAccessibleForHero(const int3 & pos, HeroPtr h, bool includeAllies = false) const;
  282. const CGTownInstance *findTownWithTavern() const;
  283. std::vector<HeroPtr> getUnblockedHeroes() const;
  284. HeroPtr primaryHero() const;
  285. TResources estimateIncome() const;
  286. bool containsSavedRes(const TResources &cost) const;
  287. //special function that can be called ONLY from game events handling thread and will send request ASAP
  288. void requestActionASAP(boost::function<void()> whatToDo);
  289. };
  290. template<int id>
  291. bool objWithID(const CGObjectInstance *obj)
  292. {
  293. return obj->ID == id;
  294. }
  295. bool isWeeklyRevisitable (const CGObjectInstance * obj);
  296. bool shouldVisit (HeroPtr h, const CGObjectInstance * obj);