AINodeStorage.h 9.0 KB

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