AINodeStorage.h 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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 = 5;
  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. STRONG_INLINE
  47. bool blocked() const
  48. {
  49. return accessible == EPathAccessibility::NOT_SET
  50. || accessible == EPathAccessibility::BLOCKED;
  51. }
  52. void addSpecialAction(std::shared_ptr<const SpecialAction> action);
  53. };
  54. struct AIPathNodeInfo
  55. {
  56. float cost;
  57. uint8_t turns;
  58. int3 coord;
  59. EPathfindingLayer layer;
  60. uint64_t danger;
  61. const CGHeroInstance * targetHero;
  62. int parentIndex;
  63. uint64_t chainMask;
  64. std::shared_ptr<const SpecialAction> specialAction;
  65. bool actionIsBlocked;
  66. };
  67. struct AIPath
  68. {
  69. std::vector<AIPathNodeInfo> nodes;
  70. uint64_t targetObjectDanger;
  71. uint64_t armyLoss;
  72. uint64_t targetObjectArmyLoss;
  73. const CGHeroInstance * targetHero;
  74. const CCreatureSet * heroArmy;
  75. uint64_t chainMask;
  76. uint8_t exchangeCount;
  77. AIPath();
  78. /// Gets danger of path excluding danger of visiting the target object like creature bank
  79. uint64_t getPathDanger() const;
  80. /// Gets danger of path including danger of visiting the target object like creature bank
  81. uint64_t getTotalDanger() const;
  82. /// Gets danger of path including danger of visiting the target object like creature bank
  83. uint64_t getTotalArmyLoss() const;
  84. int3 firstTileToGet() const;
  85. int3 targetTile() const;
  86. const AIPathNodeInfo & firstNode() const;
  87. const AIPathNodeInfo & targetNode() const;
  88. float movementCost() const;
  89. uint8_t turn() const;
  90. uint64_t getHeroStrength() const;
  91. std::string toString() const;
  92. std::shared_ptr<const SpecialAction> getFirstBlockedAction() const;
  93. bool containsHero(const CGHeroInstance * hero) const;
  94. };
  95. struct ExchangeCandidate : public AIPathNode
  96. {
  97. AIPathNode * carrierParent;
  98. AIPathNode * otherParent;
  99. };
  100. enum EHeroChainPass
  101. {
  102. INITIAL, // single heroes unlimited distance
  103. CHAIN, // chains with limited distance
  104. FINAL // same as SINGLE but for heroes from CHAIN pass
  105. };
  106. class AISharedStorage
  107. {
  108. // 1 - layer (air, water, land)
  109. // 2-4 - position on map[z][x][y]
  110. // 5 - chain (normal, battle, spellcast and combinations)
  111. static std::shared_ptr<boost::multi_array<AIPathNode, 5>> shared;
  112. std::shared_ptr<boost::multi_array<AIPathNode, 5>> nodes;
  113. public:
  114. static boost::mutex locker;
  115. AISharedStorage(int3 mapSize);
  116. ~AISharedStorage();
  117. STRONG_INLINE
  118. boost::detail::multi_array::sub_array<AIPathNode, 1> get(int3 tile, EPathfindingLayer layer) const
  119. {
  120. return (*nodes)[layer][tile.z][tile.x][tile.y];
  121. }
  122. };
  123. class AINodeStorage : public INodeStorage
  124. {
  125. private:
  126. int3 sizes;
  127. const CPlayerSpecificInfoCallback * cb;
  128. const Nullkiller * ai;
  129. std::unique_ptr<FuzzyHelper> dangerEvaluator;
  130. AISharedStorage nodes;
  131. std::vector<std::shared_ptr<ChainActor>> actors;
  132. std::vector<CGPathNode *> heroChain;
  133. EHeroChainPass heroChainPass; // true if we need to calculate hero chain
  134. uint64_t chainMask;
  135. int heroChainTurn;
  136. int heroChainMaxTurns;
  137. PlayerColor playerID;
  138. uint8_t turnDistanceLimit[2];
  139. public:
  140. /// 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.
  141. AINodeStorage(const Nullkiller * ai, const int3 & sizes);
  142. ~AINodeStorage();
  143. void initialize(const PathfinderOptions & options, const CGameState * gs) override;
  144. bool increaseHeroChainTurnLimit();
  145. bool selectFirstActor();
  146. bool selectNextActor();
  147. std::vector<CGPathNode *> getInitialNodes() override;
  148. virtual std::vector<CGPathNode *> calculateNeighbours(
  149. const PathNodeInfo & source,
  150. const PathfinderConfig * pathfinderConfig,
  151. const CPathfinderHelper * pathfinderHelper) override;
  152. virtual std::vector<CGPathNode *> calculateTeleportations(
  153. const PathNodeInfo & source,
  154. const PathfinderConfig * pathfinderConfig,
  155. const CPathfinderHelper * pathfinderHelper) override;
  156. void commit(CDestinationNodeInfo & destination, const PathNodeInfo & source) override;
  157. void commit(
  158. AIPathNode * destination,
  159. const AIPathNode * source,
  160. EPathNodeAction action,
  161. int turn,
  162. int movementLeft,
  163. float cost,
  164. bool saveToCommited = true) const;
  165. inline const AIPathNode * getAINode(const CGPathNode * node) const
  166. {
  167. return static_cast<const AIPathNode *>(node);
  168. }
  169. inline void updateAINode(CGPathNode * node, std::function<void (AIPathNode *)> updater)
  170. {
  171. auto * aiNode = static_cast<AIPathNode *>(node);
  172. updater(aiNode);
  173. }
  174. inline const CGHeroInstance * getHero(const CGPathNode * node) const
  175. {
  176. const auto * aiNode = getAINode(node);
  177. return aiNode->actor->hero;
  178. }
  179. bool hasBetterChain(const PathNodeInfo & source, CDestinationNodeInfo & destination) const;
  180. bool isMovementIneficient(const PathNodeInfo & source, CDestinationNodeInfo & destination) const
  181. {
  182. return hasBetterChain(source, destination);
  183. }
  184. bool isDistanceLimitReached(const PathNodeInfo & source, CDestinationNodeInfo & destination) const;
  185. template<class NodeRange>
  186. bool hasBetterChain(
  187. const CGPathNode * source,
  188. const AIPathNode * destinationNode,
  189. const NodeRange & chains) const;
  190. std::optional<AIPathNode *> getOrCreateNode(const int3 & coord, const EPathfindingLayer layer, const ChainActor * actor);
  191. std::vector<AIPath> getChainInfo(const int3 & pos, bool isOnLand) const;
  192. bool isTileAccessible(const HeroPtr & hero, const int3 & pos, const EPathfindingLayer layer) const;
  193. void setHeroes(std::map<const CGHeroInstance *, HeroRole> heroes);
  194. void setScoutTurnDistanceLimit(uint8_t distanceLimit) { turnDistanceLimit[HeroRole::SCOUT] = distanceLimit; }
  195. void setMainTurnDistanceLimit(uint8_t distanceLimit) { turnDistanceLimit[HeroRole::MAIN] = distanceLimit; }
  196. void setTownsAndDwellings(
  197. const std::vector<const CGTownInstance *> & towns,
  198. const std::set<const CGObjectInstance *> & visitableObjs);
  199. const std::set<const CGHeroInstance *> getAllHeroes() const;
  200. void clear();
  201. bool calculateHeroChain();
  202. bool calculateHeroChainFinal();
  203. inline uint64_t evaluateDanger(const int3 & tile, const CGHeroInstance * hero, bool checkGuards) const
  204. {
  205. return dangerEvaluator->evaluateDanger(tile, hero, checkGuards);
  206. }
  207. inline uint64_t evaluateArmyLoss(const CGHeroInstance * hero, uint64_t armyValue, uint64_t danger) const
  208. {
  209. double ratio = (double)danger / (armyValue * hero->getFightingStrength());
  210. return (uint64_t)(armyValue * ratio * ratio);
  211. }
  212. STRONG_INLINE
  213. void resetTile(const int3 & tile, EPathfindingLayer layer, EPathAccessibility accessibility);
  214. STRONG_INLINE int getBucket(const ChainActor * actor) const
  215. {
  216. return ((uintptr_t)actor * 395) % AIPathfinding::BUCKET_COUNT;
  217. }
  218. void calculateTownPortalTeleportations(std::vector<CGPathNode *> & neighbours);
  219. void fillChainInfo(const AIPathNode * node, AIPath & path, int parentIndex) const;
  220. private:
  221. template<class TVector>
  222. void calculateTownPortal(
  223. const ChainActor * actor,
  224. const std::map<const CGHeroInstance *, int> & maskMap,
  225. const std::vector<CGPathNode *> & initialNodes,
  226. TVector & output);
  227. };
  228. }