AINodeStorage.h 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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. #include <boost/container/small_vector.hpp>
  23. namespace NKAI
  24. {
  25. namespace AIPathfinding
  26. {
  27. const int CHAIN_MAX_DEPTH = 4;
  28. }
  29. enum DayFlags : ui8
  30. {
  31. NONE = 0,
  32. FLY_CAST = 1,
  33. WATER_WALK_CAST = 2
  34. };
  35. struct AIPathNode : public CGPathNode
  36. {
  37. std::shared_ptr<const SpecialAction> specialAction;
  38. const AIPathNode * chainOther;
  39. const ChainActor * actor;
  40. uint64_t danger;
  41. uint64_t armyLoss;
  42. uint32_t version;
  43. int16_t manaCost;
  44. DayFlags dayFlags;
  45. void addSpecialAction(std::shared_ptr<const SpecialAction> action);
  46. inline void reset(EPathfindingLayer layer, EPathAccessibility accessibility)
  47. {
  48. CGPathNode::reset();
  49. actor = nullptr;
  50. danger = 0;
  51. manaCost = 0;
  52. specialAction.reset();
  53. armyLoss = 0;
  54. chainOther = nullptr;
  55. dayFlags = DayFlags::NONE;
  56. this->layer = layer;
  57. accessible = accessibility;
  58. }
  59. };
  60. struct AIPathNodeInfo
  61. {
  62. float cost;
  63. uint8_t turns;
  64. int3 coord;
  65. EPathfindingLayer layer;
  66. uint64_t danger;
  67. const CGHeroInstance * targetHero;
  68. int parentIndex;
  69. uint64_t chainMask;
  70. std::shared_ptr<const SpecialAction> specialAction;
  71. bool actionIsBlocked;
  72. };
  73. struct AIPath
  74. {
  75. using NodesVector = boost::container::small_vector<AIPathNodeInfo, 16>;
  76. NodesVector nodes;
  77. uint64_t targetObjectDanger;
  78. uint64_t armyLoss;
  79. uint64_t targetObjectArmyLoss;
  80. const CGHeroInstance * targetHero;
  81. const CCreatureSet * heroArmy;
  82. uint64_t chainMask;
  83. uint8_t exchangeCount;
  84. AIPath();
  85. /// Gets danger of path excluding danger of visiting the target object like creature bank
  86. uint64_t getPathDanger() const;
  87. /// Gets danger of path including danger of visiting the target object like creature bank
  88. uint64_t getTotalDanger() const;
  89. /// Gets danger of path including danger of visiting the target object like creature bank
  90. uint64_t getTotalArmyLoss() const;
  91. int3 firstTileToGet() const;
  92. int3 targetTile() const;
  93. const AIPathNodeInfo & firstNode() const;
  94. const AIPathNodeInfo & targetNode() const;
  95. float movementCost() const;
  96. uint8_t turn() const;
  97. uint64_t getHeroStrength() const;
  98. std::string toString() const;
  99. std::shared_ptr<const SpecialAction> getFirstBlockedAction() const;
  100. bool containsHero(const CGHeroInstance * hero) const;
  101. };
  102. struct ExchangeCandidate : public AIPathNode
  103. {
  104. AIPathNode * carrierParent;
  105. AIPathNode * otherParent;
  106. };
  107. enum EHeroChainPass
  108. {
  109. INITIAL, // single heroes unlimited distance
  110. CHAIN, // chains with limited distance
  111. FINAL // same as SINGLE but for heroes from CHAIN pass
  112. };
  113. class AISharedStorage
  114. {
  115. // 1-3 - position on map[z][x][y]
  116. // 4 - chain + layer (normal, battle, spellcast and combinations, water, air)
  117. static std::shared_ptr<boost::multi_array<AIPathNode, 4>> shared;
  118. std::shared_ptr<boost::multi_array<AIPathNode, 4>> nodes;
  119. public:
  120. static boost::mutex locker;
  121. static uint32_t version;
  122. AISharedStorage(int3 sizes, int numChains);
  123. ~AISharedStorage();
  124. STRONG_INLINE
  125. boost::detail::multi_array::sub_array<AIPathNode, 1> get(int3 tile) const
  126. {
  127. return (*nodes)[tile.z][tile.x][tile.y];
  128. }
  129. };
  130. class AINodeStorage : public INodeStorage
  131. {
  132. private:
  133. int3 sizes;
  134. std::unique_ptr<boost::multi_array<EPathAccessibility, 4>> accessibility;
  135. const CPlayerSpecificInfoCallback * cb;
  136. const Nullkiller * ai;
  137. AISharedStorage nodes;
  138. std::vector<std::shared_ptr<ChainActor>> actors;
  139. std::vector<CGPathNode *> heroChain;
  140. EHeroChainPass heroChainPass; // true if we need to calculate hero chain
  141. uint64_t chainMask;
  142. int heroChainTurn;
  143. int heroChainMaxTurns;
  144. PlayerColor playerID;
  145. uint8_t turnDistanceLimit[2];
  146. public:
  147. /// 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.
  148. AINodeStorage(const Nullkiller * ai, const int3 & sizes);
  149. ~AINodeStorage();
  150. void initialize(const PathfinderOptions & options, const CGameState * gs) override;
  151. bool increaseHeroChainTurnLimit();
  152. bool selectFirstActor();
  153. bool selectNextActor();
  154. int getBucketCount() const;
  155. int getBucketSize() const;
  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. uint64_t evaluateArmyLoss(const CGHeroInstance * hero, uint64_t armyValue, uint64_t danger) const;
  226. inline EPathAccessibility getAccessibility(const int3 & tile, EPathfindingLayer layer) const
  227. {
  228. return (*this->accessibility)[tile.z][tile.x][tile.y][layer];
  229. }
  230. inline void resetTile(const int3 & tile, EPathfindingLayer layer, EPathAccessibility tileAccessibility)
  231. {
  232. (*this->accessibility)[tile.z][tile.x][tile.y][layer] = tileAccessibility;
  233. }
  234. inline int getBucket(const ChainActor * actor) const
  235. {
  236. return ((uintptr_t)actor * 395) % getBucketCount();
  237. }
  238. void calculateTownPortalTeleportations(std::vector<CGPathNode *> & neighbours);
  239. void fillChainInfo(const AIPathNode * node, AIPath & path, int parentIndex) const;
  240. template<typename Fn>
  241. void iterateValidNodes(const int3 & pos, EPathfindingLayer layer, Fn fn)
  242. {
  243. if(blocked(pos, layer))
  244. return;
  245. auto chains = nodes.get(pos);
  246. for(AIPathNode & node : chains)
  247. {
  248. if(node.version != AISharedStorage::version || node.layer != layer)
  249. continue;
  250. fn(node);
  251. }
  252. }
  253. template<typename Fn>
  254. bool iterateValidNodesUntil(const int3 & pos, EPathfindingLayer layer, Fn predicate) const
  255. {
  256. if(blocked(pos, layer))
  257. return false;
  258. auto chains = nodes.get(pos);
  259. for(AIPathNode & node : chains)
  260. {
  261. if(node.version != AISharedStorage::version || node.layer != layer)
  262. continue;
  263. if(predicate(node))
  264. return true;
  265. }
  266. return false;
  267. }
  268. private:
  269. template<class TVector>
  270. void calculateTownPortal(
  271. const ChainActor * actor,
  272. const std::map<const CGHeroInstance *, int> & maskMap,
  273. const std::vector<CGPathNode *> & initialNodes,
  274. TVector & output);
  275. };
  276. }