CPathfinder.h 17 KB

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