AINodeStorage.h 7.8 KB

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