AINodeStorage.h 7.7 KB

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