AINodeStorage.h 9.3 KB

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