AINodeStorage.h 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. /*
  2. * AINodeStorage.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. #define NKAI_PATHFINDER_TRACE_LEVEL 0
  12. constexpr int NKAI_GRAPH_TRACE_LEVEL = 0; // To actually enable graph visualization, enter `/vslog graph` in game chat
  13. #define NKAI_TRACE_LEVEL 0
  14. #include "../../../lib/pathfinder/CGPathNode.h"
  15. #include "../../../lib/pathfinder/INodeStorage.h"
  16. #include "../../../lib/mapObjects/CGHeroInstance.h"
  17. #include "../AIUtility.h"
  18. #include "../Engine/FuzzyHelper.h"
  19. #include "../Goals/AbstractGoal.h"
  20. #include "Actions/SpecialAction.h"
  21. #include "Actors.h"
  22. namespace NKAI
  23. {
  24. namespace AIPathfinding
  25. {
  26. const int CHAIN_MAX_DEPTH = 4;
  27. }
  28. enum DayFlags : ui8
  29. {
  30. NONE = 0,
  31. FLY_CAST = 1,
  32. WATER_WALK_CAST = 2
  33. };
  34. struct AIPathNode : public CGPathNode
  35. {
  36. std::shared_ptr<const SpecialAction> specialAction;
  37. const AIPathNode * chainOther = nullptr;
  38. const ChainActor * actor = nullptr;
  39. uint64_t danger;
  40. uint64_t armyLoss;
  41. uint32_t version;
  42. int16_t manaCost;
  43. DayFlags dayFlags;
  44. void addSpecialAction(std::shared_ptr<const SpecialAction> action);
  45. inline void reset(EPathfindingLayer layer, EPathAccessibility accessibility)
  46. {
  47. CGPathNode::reset();
  48. actor = nullptr;
  49. danger = 0;
  50. manaCost = 0;
  51. specialAction.reset();
  52. armyLoss = 0;
  53. chainOther = nullptr;
  54. dayFlags = DayFlags::NONE;
  55. this->layer = layer;
  56. accessible = accessibility;
  57. }
  58. };
  59. struct AIPathNodeInfo
  60. {
  61. float cost;
  62. uint8_t turns;
  63. int3 coord;
  64. EPathfindingLayer layer;
  65. uint64_t danger;
  66. const CGHeroInstance * targetHero;
  67. int parentIndex;
  68. uint64_t chainMask;
  69. std::shared_ptr<const SpecialAction> specialAction;
  70. bool actionIsBlocked;
  71. };
  72. struct AIPath
  73. {
  74. using NodesVector = boost::container::small_vector<AIPathNodeInfo, 16>;
  75. NodesVector nodes;
  76. uint64_t targetObjectDanger;
  77. uint64_t armyLoss;
  78. uint64_t targetObjectArmyLoss;
  79. const CGHeroInstance * targetHero;
  80. const CCreatureSet * heroArmy;
  81. uint64_t chainMask;
  82. uint8_t exchangeCount;
  83. AIPath();
  84. /// Gets danger of path excluding danger of visiting the target object like creature bank
  85. uint64_t getPathDanger() const;
  86. /// Gets danger of path including danger of visiting the target object like creature bank
  87. uint64_t getTotalDanger() const;
  88. /// Gets danger of path including danger of visiting the target object like creature bank
  89. uint64_t getTotalArmyLoss() const;
  90. int3 firstTileToGet() const;
  91. int3 targetTile() const;
  92. const AIPathNodeInfo & firstNode() const;
  93. const AIPathNodeInfo & targetNode() const;
  94. float movementCost() const;
  95. uint8_t turn() const;
  96. uint64_t getHeroStrength() const;
  97. std::string toString() const;
  98. std::shared_ptr<const SpecialAction> getFirstBlockedAction() const;
  99. bool containsHero(const CGHeroInstance * hero) const;
  100. };
  101. struct ExchangeCandidate : public AIPathNode
  102. {
  103. AIPathNode * carrierParent = nullptr;
  104. AIPathNode * otherParent = nullptr;
  105. };
  106. enum EHeroChainPass
  107. {
  108. INITIAL, // single heroes unlimited distance
  109. CHAIN, // chains with limited distance
  110. FINAL // same as SINGLE but for heroes from CHAIN pass
  111. };
  112. class AISharedStorage
  113. {
  114. // 1-3 - position on map[z][x][y]
  115. // 4 - chain + layer (normal, battle, spellcast and combinations, water, air)
  116. static std::shared_ptr<boost::multi_array<AIPathNode, 4>> shared;
  117. std::shared_ptr<boost::multi_array<AIPathNode, 4>> nodes;
  118. public:
  119. static boost::mutex locker;
  120. static uint32_t version;
  121. AISharedStorage(int3 sizes, int numChains);
  122. ~AISharedStorage();
  123. STRONG_INLINE
  124. boost::detail::multi_array::sub_array<AIPathNode, 1> get(int3 tile) const
  125. {
  126. return (*nodes)[tile.z][tile.x][tile.y];
  127. }
  128. };
  129. class AINodeStorage : public INodeStorage
  130. {
  131. private:
  132. int3 sizes;
  133. std::unique_ptr<boost::multi_array<EPathAccessibility, 4>> accessibility;
  134. const CPlayerSpecificInfoCallback * cb;
  135. const Nullkiller * ai;
  136. AISharedStorage nodes;
  137. std::vector<std::shared_ptr<ChainActor>> actors;
  138. std::vector<CGPathNode *> heroChain;
  139. EHeroChainPass heroChainPass; // true if we need to calculate hero chain
  140. uint64_t chainMask;
  141. int heroChainTurn;
  142. int heroChainMaxTurns;
  143. PlayerColor playerID;
  144. uint8_t turnDistanceLimit[2];
  145. public:
  146. /// more than 1 chain layer for each hero allows us to have more than 1 path to each tile so we can chose more optimal one.
  147. AINodeStorage(const Nullkiller * ai, const int3 & sizes);
  148. ~AINodeStorage();
  149. void initialize(const PathfinderOptions & options, const CGameState * gs) override;
  150. bool increaseHeroChainTurnLimit();
  151. bool selectFirstActor();
  152. bool selectNextActor();
  153. int getBucketCount() const;
  154. int getBucketSize() const;
  155. std::vector<CGPathNode *> getInitialNodes() override;
  156. virtual void calculateNeighbours(
  157. std::vector<CGPathNode *> & result,
  158. const PathNodeInfo & source,
  159. EPathfindingLayer layer,
  160. const PathfinderConfig * pathfinderConfig,
  161. const CPathfinderHelper * pathfinderHelper) override;
  162. virtual std::vector<CGPathNode *> calculateTeleportations(
  163. const PathNodeInfo & source,
  164. const PathfinderConfig * pathfinderConfig,
  165. const CPathfinderHelper * pathfinderHelper) override;
  166. void commit(CDestinationNodeInfo & destination, const PathNodeInfo & source) override;
  167. void commit(
  168. AIPathNode * destination,
  169. const AIPathNode * source,
  170. EPathNodeAction action,
  171. int turn,
  172. int movementLeft,
  173. float cost,
  174. bool saveToCommitted = true) const;
  175. inline const AIPathNode * getAINode(const CGPathNode * node) const
  176. {
  177. return static_cast<const AIPathNode *>(node);
  178. }
  179. inline void updateAINode(CGPathNode * node, std::function<void (AIPathNode *)> updater)
  180. {
  181. auto * aiNode = static_cast<AIPathNode *>(node);
  182. updater(aiNode);
  183. }
  184. inline const CGHeroInstance * getHero(const CGPathNode * node) const
  185. {
  186. const auto * aiNode = getAINode(node);
  187. return aiNode->actor->hero;
  188. }
  189. inline bool blocked(const int3 & tile, EPathfindingLayer layer) const
  190. {
  191. EPathAccessibility accessible = getAccessibility(tile, layer);
  192. return accessible == EPathAccessibility::NOT_SET
  193. || accessible == EPathAccessibility::BLOCKED;
  194. }
  195. bool hasBetterChain(const PathNodeInfo & source, CDestinationNodeInfo & destination) const;
  196. bool hasBetterChain(const CGPathNode * source, const AIPathNode & candidateNode) const;
  197. template<class NodeRange>
  198. bool hasBetterChain(
  199. const CGPathNode * source,
  200. const AIPathNode & destinationNode,
  201. const NodeRange & chains) const;
  202. bool isOtherChainBetter(
  203. const CGPathNode * source,
  204. const AIPathNode & candidateNode,
  205. const AIPathNode & other) const;
  206. bool isMovementInefficient(const PathNodeInfo & source, CDestinationNodeInfo & destination) const
  207. {
  208. return hasBetterChain(source, destination);
  209. }
  210. bool isDistanceLimitReached(const PathNodeInfo & source, CDestinationNodeInfo & destination) const;
  211. std::optional<AIPathNode *> getOrCreateNode(const int3 & coord, const EPathfindingLayer layer, const ChainActor * actor);
  212. void calculateChainInfo(std::vector<AIPath> & result, const int3 & pos, bool isOnLand) const;
  213. bool isTileAccessible(const HeroPtr & hero, const int3 & pos, const EPathfindingLayer layer) const;
  214. void setHeroes(std::map<const CGHeroInstance *, HeroRole> heroes);
  215. void setScoutTurnDistanceLimit(uint8_t distanceLimit) { turnDistanceLimit[HeroRole::SCOUT] = distanceLimit; }
  216. void setMainTurnDistanceLimit(uint8_t distanceLimit) { turnDistanceLimit[HeroRole::MAIN] = distanceLimit; }
  217. void setTownsAndDwellings(
  218. const std::vector<const CGTownInstance *> & towns,
  219. const std::set<const CGObjectInstance *> & visitableObjs);
  220. const std::set<const CGHeroInstance *> getAllHeroes() const;
  221. void clear();
  222. bool calculateHeroChain();
  223. bool calculateHeroChainFinal();
  224. uint64_t evaluateArmyLoss(const CGHeroInstance * hero, uint64_t armyValue, uint64_t danger) const;
  225. inline EPathAccessibility getAccessibility(const int3 & tile, EPathfindingLayer layer) const
  226. {
  227. return (*this->accessibility)[tile.z][tile.x][tile.y][layer];
  228. }
  229. inline void resetTile(const int3 & tile, EPathfindingLayer layer, EPathAccessibility tileAccessibility)
  230. {
  231. (*this->accessibility)[tile.z][tile.x][tile.y][layer] = tileAccessibility;
  232. }
  233. inline int getBucket(const ChainActor * actor) const
  234. {
  235. return ((uintptr_t)actor * 395) % getBucketCount();
  236. }
  237. void calculateTownPortalTeleportations(std::vector<CGPathNode *> & neighbours);
  238. void fillChainInfo(const AIPathNode * node, AIPath & path, int parentIndex) const;
  239. template<typename Fn>
  240. void iterateValidNodes(const int3 & pos, EPathfindingLayer layer, Fn fn)
  241. {
  242. if(blocked(pos, layer))
  243. return;
  244. auto chains = nodes.get(pos);
  245. for(AIPathNode & node : chains)
  246. {
  247. if(node.version != AISharedStorage::version || node.layer != layer)
  248. continue;
  249. fn(node);
  250. }
  251. }
  252. template<typename Fn>
  253. bool iterateValidNodesUntil(const int3 & pos, EPathfindingLayer layer, Fn predicate) const
  254. {
  255. if(blocked(pos, layer))
  256. return false;
  257. auto chains = nodes.get(pos);
  258. for(AIPathNode & node : chains)
  259. {
  260. if(node.version != AISharedStorage::version || node.layer != layer)
  261. continue;
  262. if(predicate(node))
  263. return true;
  264. }
  265. return false;
  266. }
  267. private:
  268. template<class TVector>
  269. void calculateTownPortal(
  270. const ChainActor * actor,
  271. const std::map<const CGHeroInstance *, int> & maskMap,
  272. const std::vector<CGPathNode *> & initialNodes,
  273. TVector & output);
  274. };
  275. }