CPathfinder.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. /*
  2. * CPathfinder.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. #include "VCMI_Lib.h"
  12. #include "IGameCallback.h"
  13. #include "HeroBonus.h"
  14. #include "int3.h"
  15. #include <boost/heap/priority_queue.hpp>
  16. class CGHeroInstance;
  17. class CGObjectInstance;
  18. struct TerrainTile;
  19. class CPathfinderHelper;
  20. class CMap;
  21. class CGWhirlpool;
  22. class CPathfinderHelper;
  23. class CPathfinder;
  24. class PathfinderConfig;
  25. struct DLL_LINKAGE CGPathNode
  26. {
  27. typedef EPathfindingLayer ELayer;
  28. enum ENodeAction : ui8
  29. {
  30. UNKNOWN = 0,
  31. EMBARK = 1,
  32. DISEMBARK,
  33. NORMAL,
  34. BATTLE,
  35. VISIT,
  36. BLOCKING_VISIT,
  37. TELEPORT_NORMAL,
  38. TELEPORT_BLOCKING_VISIT,
  39. TELEPORT_BATTLE
  40. };
  41. enum EAccessibility : ui8
  42. {
  43. NOT_SET = 0,
  44. ACCESSIBLE = 1, //tile can be entered and passed
  45. VISITABLE, //tile can be entered as the last tile in path
  46. BLOCKVIS, //visitable from neighboring tile but not passable
  47. FLYABLE, //can only be accessed in air layer
  48. BLOCKED //tile can't be entered nor visited
  49. };
  50. CGPathNode * theNodeBefore;
  51. int3 coord; //coordinates
  52. ELayer layer;
  53. ui32 moveRemains; //remaining movement points after hero reaches the tile
  54. float cost; //total cost of the path to this tile measured in turns with fractions
  55. ui8 turns; //how many turns we have to wait before reaching the tile - 0 means current turn
  56. EAccessibility accessible;
  57. ENodeAction action;
  58. bool locked;
  59. CGPathNode()
  60. : coord(-1),
  61. layer(ELayer::WRONG)
  62. {
  63. reset();
  64. }
  65. STRONG_INLINE
  66. void reset()
  67. {
  68. locked = false;
  69. accessible = NOT_SET;
  70. moveRemains = 0;
  71. cost = std::numeric_limits<float>::max();
  72. turns = 255;
  73. theNodeBefore = nullptr;
  74. action = UNKNOWN;
  75. }
  76. STRONG_INLINE
  77. void update(const int3 & Coord, const ELayer Layer, const EAccessibility Accessible)
  78. {
  79. if(layer == ELayer::WRONG)
  80. {
  81. coord = Coord;
  82. layer = Layer;
  83. }
  84. else
  85. {
  86. reset();
  87. }
  88. accessible = Accessible;
  89. }
  90. STRONG_INLINE
  91. bool reachable() const
  92. {
  93. return turns < 255;
  94. }
  95. };
  96. struct DLL_LINKAGE CGPath
  97. {
  98. std::vector<CGPathNode> nodes; //just get node by node
  99. int3 startPos() const; // start point
  100. int3 endPos() const; //destination point
  101. void convert(ui8 mode); //mode=0 -> from 'manifest' to 'object'
  102. };
  103. struct DLL_LINKAGE CPathsInfo
  104. {
  105. typedef EPathfindingLayer ELayer;
  106. const CGHeroInstance * hero;
  107. int3 hpos;
  108. int3 sizes;
  109. boost::multi_array<CGPathNode, 4> nodes; //[w][h][level][layer]
  110. CPathsInfo(const int3 & Sizes, const CGHeroInstance * hero_);
  111. ~CPathsInfo();
  112. const CGPathNode * getPathInfo(const int3 & tile) const;
  113. bool getPath(CGPath & out, const int3 & dst) const;
  114. const CGPathNode * getNode(const int3 & coord) const;
  115. STRONG_INLINE
  116. CGPathNode * getNode(const int3 & coord, const ELayer layer)
  117. {
  118. return &nodes[coord.x][coord.y][coord.z][layer];
  119. }
  120. };
  121. struct DLL_LINKAGE PathNodeInfo
  122. {
  123. CGPathNode * node;
  124. const CGObjectInstance * nodeObject;
  125. const TerrainTile * tile;
  126. int3 coord;
  127. bool guarded;
  128. PlayerRelations::PlayerRelations objectRelations;
  129. PathNodeInfo();
  130. virtual void setNode(CGameState * gs, CGPathNode * n, bool excludeTopObject = false);
  131. bool isNodeObjectVisitable() const;
  132. };
  133. struct DLL_LINKAGE CDestinationNodeInfo : public PathNodeInfo
  134. {
  135. CGPathNode::ENodeAction action;
  136. int turn;
  137. int movementLeft;
  138. float cost; //same as CGPathNode::cost
  139. bool blocked;
  140. bool isGuardianTile;
  141. CDestinationNodeInfo();
  142. virtual void setNode(CGameState * gs, CGPathNode * n, bool excludeTopObject = false) override;
  143. virtual bool isBetterWay() const;
  144. };
  145. class IPathfindingRule
  146. {
  147. public:
  148. virtual void process(
  149. const PathNodeInfo & source,
  150. CDestinationNodeInfo & destination,
  151. const PathfinderConfig * pathfinderConfig,
  152. CPathfinderHelper * pathfinderHelper) const = 0;
  153. };
  154. class DLL_LINKAGE MovementCostRule : public IPathfindingRule
  155. {
  156. public:
  157. virtual void process(
  158. const PathNodeInfo & source,
  159. CDestinationNodeInfo & destination,
  160. const PathfinderConfig * pathfinderConfig,
  161. CPathfinderHelper * pathfinderHelper) const override;
  162. };
  163. class DLL_LINKAGE LayerTransitionRule : public IPathfindingRule
  164. {
  165. public:
  166. virtual void process(
  167. const PathNodeInfo & source,
  168. CDestinationNodeInfo & destination,
  169. const PathfinderConfig * pathfinderConfig,
  170. CPathfinderHelper * pathfinderHelper) const override;
  171. };
  172. class DLL_LINKAGE DestinationActionRule : public IPathfindingRule
  173. {
  174. public:
  175. virtual void process(
  176. const PathNodeInfo & source,
  177. CDestinationNodeInfo & destination,
  178. const PathfinderConfig * pathfinderConfig,
  179. CPathfinderHelper * pathfinderHelper) const override;
  180. };
  181. class DLL_LINKAGE PathfinderBlockingRule : public IPathfindingRule
  182. {
  183. public:
  184. virtual void process(
  185. const PathNodeInfo & source,
  186. CDestinationNodeInfo & destination,
  187. const PathfinderConfig * pathfinderConfig,
  188. CPathfinderHelper * pathfinderHelper) const override
  189. {
  190. auto blockingReason = getBlockingReason(source, destination, pathfinderConfig, pathfinderHelper);
  191. destination.blocked = blockingReason != BlockingReason::NONE;
  192. }
  193. protected:
  194. enum class BlockingReason
  195. {
  196. NONE = 0,
  197. SOURCE_GUARDED = 1,
  198. DESTINATION_GUARDED = 2,
  199. SOURCE_BLOCKED = 3,
  200. DESTINATION_BLOCKED = 4,
  201. DESTINATION_BLOCKVIS = 5,
  202. DESTINATION_VISIT = 6
  203. };
  204. virtual BlockingReason getBlockingReason(
  205. const PathNodeInfo & source,
  206. const CDestinationNodeInfo & destination,
  207. const PathfinderConfig * pathfinderConfig,
  208. const CPathfinderHelper * pathfinderHelper) const = 0;
  209. };
  210. class DLL_LINKAGE MovementAfterDestinationRule : public PathfinderBlockingRule
  211. {
  212. public:
  213. virtual void process(
  214. const PathNodeInfo & source,
  215. CDestinationNodeInfo & destination,
  216. const PathfinderConfig * pathfinderConfig,
  217. CPathfinderHelper * pathfinderHelper) const override;
  218. protected:
  219. virtual BlockingReason getBlockingReason(
  220. const PathNodeInfo & source,
  221. const CDestinationNodeInfo & destination,
  222. const PathfinderConfig * pathfinderConfig,
  223. const CPathfinderHelper * pathfinderHelper) const override;
  224. };
  225. class DLL_LINKAGE MovementToDestinationRule : public PathfinderBlockingRule
  226. {
  227. protected:
  228. virtual BlockingReason getBlockingReason(
  229. const PathNodeInfo & source,
  230. const CDestinationNodeInfo & destination,
  231. const PathfinderConfig * pathfinderConfig,
  232. const CPathfinderHelper * pathfinderHelper) const override;
  233. };
  234. struct DLL_LINKAGE PathfinderOptions
  235. {
  236. bool useFlying;
  237. bool useWaterWalking;
  238. bool useEmbarkAndDisembark;
  239. bool useTeleportTwoWay; // Two-way monoliths and Subterranean Gate
  240. bool useTeleportOneWay; // One-way monoliths with one known exit only
  241. bool useTeleportOneWayRandom; // One-way monoliths with more than one known exit
  242. bool useTeleportWhirlpool; // Force enabled if hero protected or unaffected (have one stack of one creature)
  243. /// TODO: Find out with client and server code, merge with normal teleporters.
  244. /// Likely proper implementation would require some refactoring of CGTeleport.
  245. /// So for now this is unfinished and disabled by default.
  246. bool useCastleGate;
  247. /// If true transition into air layer only possible from initial node.
  248. /// This is drastically decrease path calculation complexity (and time).
  249. /// Downside is less MP effective paths calculation.
  250. ///
  251. /// TODO: If this option end up useful for slow devices it's can be improved:
  252. /// - Allow transition into air layer not only from initial position, but also from teleporters.
  253. /// Movement into air can be also allowed when hero disembarked.
  254. /// - Other idea is to allow transition into air within certain radius of N tiles around hero.
  255. /// Patrol support need similar functionality so it's won't be ton of useless code.
  256. /// Such limitation could be useful as it's can be scaled depend on device performance.
  257. bool lightweightFlyingMode;
  258. /// This option enable one turn limitation for flying and water walking.
  259. /// So if we're out of MP while cp is blocked or water tile we won't add dest tile to queue.
  260. ///
  261. /// Following imitation is default H3 mechanics, but someone may want to disable it in mods.
  262. /// After all this limit should benefit performance on maps with tons of water or blocked tiles.
  263. ///
  264. /// TODO:
  265. /// - Behavior when option is disabled not implemented and will lead to crashes.
  266. bool oneTurnSpecialLayersLimit;
  267. /// VCMI have different movement rules to solve flaws original engine has.
  268. /// If this option enabled you'll able to do following things in fly:
  269. /// - Move from blocked tiles to visitable one
  270. /// - Move from guarded tiles to blockvis tiles without being attacked
  271. /// - Move from guarded tiles to guarded visitable tiles with being attacked after
  272. /// TODO:
  273. /// - Option should also allow same tile land <-> air layer transitions.
  274. /// Current implementation only allow go into (from) air layer only to neighbour tiles.
  275. /// I find it's reasonable limitation, but it's will make some movements more expensive than in H3.
  276. bool originalMovementRules;
  277. PathfinderOptions();
  278. };
  279. class DLL_LINKAGE INodeStorage
  280. {
  281. public:
  282. using ELayer = EPathfindingLayer;
  283. virtual CGPathNode * getInitialNode() = 0;
  284. virtual std::vector<CGPathNode *> calculateNeighbours(
  285. const PathNodeInfo & source,
  286. const PathfinderConfig * pathfinderConfig,
  287. const CPathfinderHelper * pathfinderHelper) = 0;
  288. virtual std::vector<CGPathNode *> calculateTeleportations(
  289. const PathNodeInfo & source,
  290. const PathfinderConfig * pathfinderConfig,
  291. const CPathfinderHelper * pathfinderHelper) = 0;
  292. virtual void commit(CDestinationNodeInfo & destination, const PathNodeInfo & source) = 0;
  293. virtual void initialize(const PathfinderOptions & options, const CGameState * gs, const CGHeroInstance * hero) = 0;
  294. };
  295. class DLL_LINKAGE NodeStorage : public INodeStorage
  296. {
  297. private:
  298. CPathsInfo & out;
  299. STRONG_INLINE
  300. void resetTile(const int3 & tile, EPathfindingLayer layer, CGPathNode::EAccessibility accessibility);
  301. public:
  302. NodeStorage(CPathsInfo & pathsInfo, const CGHeroInstance * hero);
  303. STRONG_INLINE
  304. CGPathNode * getNode(const int3 & coord, const EPathfindingLayer layer)
  305. {
  306. return out.getNode(coord, layer);
  307. }
  308. void initialize(const PathfinderOptions & options, const CGameState * gs, const CGHeroInstance * hero) override;
  309. virtual CGPathNode * getInitialNode() override;
  310. virtual std::vector<CGPathNode *> calculateNeighbours(
  311. const PathNodeInfo & source,
  312. const PathfinderConfig * pathfinderConfig,
  313. const CPathfinderHelper * pathfinderHelper) override;
  314. virtual std::vector<CGPathNode *> calculateTeleportations(
  315. const PathNodeInfo & source,
  316. const PathfinderConfig * pathfinderConfig,
  317. const CPathfinderHelper * pathfinderHelper) override;
  318. virtual void commit(CDestinationNodeInfo & destination, const PathNodeInfo & source) override;
  319. };
  320. class DLL_LINKAGE PathfinderConfig
  321. {
  322. public:
  323. std::shared_ptr<INodeStorage> nodeStorage;
  324. std::vector<std::shared_ptr<IPathfindingRule>> rules;
  325. PathfinderOptions options;
  326. PathfinderConfig(
  327. std::shared_ptr<INodeStorage> nodeStorage,
  328. std::vector<std::shared_ptr<IPathfindingRule>> rules);
  329. };
  330. class CPathfinder : private CGameInfoCallback
  331. {
  332. public:
  333. friend class CPathfinderHelper;
  334. CPathfinder(CPathsInfo & _out, CGameState * _gs, const CGHeroInstance * _hero);
  335. CPathfinder(
  336. CGameState * _gs,
  337. const CGHeroInstance * _hero,
  338. std::shared_ptr<PathfinderConfig> config);
  339. void calculatePaths(); //calculates possible paths for hero, uses current hero position and movement left; returns pointer to newly allocated CPath or nullptr if path does not exists
  340. private:
  341. typedef EPathfindingLayer ELayer;
  342. const CGHeroInstance * hero;
  343. std::unique_ptr<CPathfinderHelper> hlp;
  344. std::shared_ptr<PathfinderConfig> config;
  345. enum EPatrolState {
  346. PATROL_NONE = 0,
  347. PATROL_LOCKED = 1,
  348. PATROL_RADIUS
  349. } patrolState;
  350. std::unordered_set<int3, ShashInt3> patrolTiles;
  351. struct NodeComparer
  352. {
  353. STRONG_INLINE
  354. bool operator()(const CGPathNode * lhs, const CGPathNode * rhs) const
  355. {
  356. return lhs->cost > rhs->cost;
  357. }
  358. };
  359. boost::heap::priority_queue<CGPathNode *, boost::heap::compare<NodeComparer> > pq;
  360. PathNodeInfo source; //current (source) path node -> we took it from the queue
  361. CDestinationNodeInfo destination; //destination node -> it's a neighbour of source that we consider
  362. bool isHeroPatrolLocked() const;
  363. bool isPatrolMovementAllowed(const int3 & dst) const;
  364. bool isLayerTransitionPossible() const;
  365. CGPathNode::ENodeAction getTeleportDestAction() const;
  366. bool isSourceInitialPosition() const;
  367. bool isSourceGuarded() const;
  368. bool isDestinationGuarded() const;
  369. bool isDestinationGuardian() const;
  370. void initializePatrol();
  371. void initializeGraph();
  372. };
  373. struct DLL_LINKAGE TurnInfo
  374. {
  375. /// This is certainly not the best design ever and certainly can be improved
  376. /// Unfortunately for pathfinder that do hundreds of thousands calls onus system add too big overhead
  377. struct BonusCache {
  378. std::vector<bool> noTerrainPenalty;
  379. bool freeShipBoarding;
  380. bool flyingMovement;
  381. int flyingMovementVal;
  382. bool waterWalking;
  383. int waterWalkingVal;
  384. BonusCache(TBonusListPtr bonusList);
  385. };
  386. std::unique_ptr<BonusCache> bonusCache;
  387. const CGHeroInstance * hero;
  388. TBonusListPtr bonuses;
  389. mutable int maxMovePointsLand;
  390. mutable int maxMovePointsWater;
  391. int nativeTerrain;
  392. TurnInfo(const CGHeroInstance * Hero, const int Turn = 0);
  393. bool isLayerAvailable(const EPathfindingLayer layer) const;
  394. bool hasBonusOfType(const Bonus::BonusType type, const int subtype = -1) const;
  395. int valOfBonuses(const Bonus::BonusType type, const int subtype = -1) const;
  396. int getMaxMovePoints(const EPathfindingLayer layer) const;
  397. };
  398. class DLL_LINKAGE CPathfinderHelper : private CGameInfoCallback
  399. {
  400. public:
  401. int turn;
  402. const CGHeroInstance * hero;
  403. std::vector<TurnInfo *> turnsInfo;
  404. const PathfinderOptions & options;
  405. CPathfinderHelper(CGameState * gs, const CGHeroInstance * Hero, const PathfinderOptions & Options);
  406. ~CPathfinderHelper();
  407. void updateTurnInfo(const int turn = 0);
  408. bool isLayerAvailable(const EPathfindingLayer layer) const;
  409. const TurnInfo * getTurnInfo() const;
  410. bool hasBonusOfType(const Bonus::BonusType type, const int subtype = -1) const;
  411. int getMaxMovePoints(const EPathfindingLayer layer) const;
  412. std::vector<int3> getCastleGates(const PathNodeInfo & source) const;
  413. bool isAllowedTeleportEntrance(const CGTeleport * obj) const;
  414. std::vector<int3> getAllowedTeleportChannelExits(TeleportChannelID channelID) const;
  415. bool addTeleportTwoWay(const CGTeleport * obj) const;
  416. bool addTeleportOneWay(const CGTeleport * obj) const;
  417. bool addTeleportOneWayRandom(const CGTeleport * obj) const;
  418. bool addTeleportWhirlpool(const CGWhirlpool * obj) const;
  419. bool canMoveBetween(const int3 & a, const int3 & b) const; //checks only for visitable objects that may make moving between tiles impossible, not other conditions (like tiles itself accessibility)
  420. std::vector<int3> getNeighbourTiles(const PathNodeInfo & source) const;
  421. std::vector<int3> getTeleportExits(const PathNodeInfo & source) const;
  422. void getNeighbours(
  423. const TerrainTile & srct,
  424. const int3 & tile,
  425. std::vector<int3> & vec,
  426. const boost::logic::tribool & onLand,
  427. const bool limitCoastSailing) const;
  428. int getMovementCost(
  429. const int3 & src,
  430. const int3 & dst,
  431. const TerrainTile * ct,
  432. const TerrainTile * dt,
  433. const int remainingMovePoints =- 1,
  434. const bool checkLast = true) const;
  435. int getMovementCost(
  436. const PathNodeInfo & src,
  437. const PathNodeInfo & dst,
  438. const int remainingMovePoints = -1,
  439. const bool checkLast = true) const
  440. {
  441. return getMovementCost(
  442. src.coord,
  443. dst.coord,
  444. src.tile,
  445. dst.tile,
  446. remainingMovePoints,
  447. checkLast
  448. );
  449. }
  450. int movementPointsAfterEmbark(int movement, int basicCost, bool disembark) const;
  451. bool passOneTurnLimitCheck(const PathNodeInfo & source) const;
  452. };