AINodeStorage.h 7.9 KB

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