AINodeStorage.h 7.8 KB

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