CPathfinder.h 16 KB

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