CPathfinder.h 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. #pragma once
  2. #include "VCMI_Lib.h"
  3. #include "mapping/CMap.h"
  4. #include "IGameCallback.h"
  5. #include "int3.h"
  6. #include <boost/heap/priority_queue.hpp>
  7. /*
  8. * CPathfinder.h, part of VCMI engine
  9. *
  10. * Authors: listed in file AUTHORS in main folder
  11. *
  12. * License: GNU General Public License v2.0 or later
  13. * Full text of license available in license.txt file, in main folder
  14. *
  15. */
  16. class CGHeroInstance;
  17. class CGObjectInstance;
  18. struct TerrainTile;
  19. class CPathfinderHelper;
  20. struct DLL_LINKAGE CGPathNode
  21. {
  22. typedef EPathfindingLayer ELayer;
  23. enum ENodeAction : ui8
  24. {
  25. UNKNOWN = 0,
  26. EMBARK = 1,
  27. DISEMBARK,
  28. NORMAL,
  29. BATTLE,
  30. VISIT,
  31. BLOCKING_VISIT
  32. };
  33. enum EAccessibility : ui8
  34. {
  35. NOT_SET = 0,
  36. ACCESSIBLE = 1, //tile can be entered and passed
  37. VISITABLE, //tile can be entered as the last tile in path
  38. BLOCKVIS, //visitable from neighbouring tile but not passable
  39. FLYABLE, //can only be accessed in air layer
  40. BLOCKED //tile can't be entered nor visited
  41. };
  42. CGPathNode * theNodeBefore;
  43. int3 coord; //coordinates
  44. ui32 moveRemains; //remaining tiles after hero reaches the tile
  45. ui8 turns; //how many turns we have to wait before reachng the tile - 0 means current turn
  46. ELayer layer;
  47. EAccessibility accessible;
  48. ENodeAction action;
  49. bool locked;
  50. CGPathNode();
  51. void reset();
  52. void update(const int3 & Coord, const ELayer Layer, const EAccessibility Accessible);
  53. bool reachable() const;
  54. };
  55. struct DLL_LINKAGE CGPath
  56. {
  57. std::vector<CGPathNode> nodes; //just get node by node
  58. int3 startPos() const; // start point
  59. int3 endPos() const; //destination point
  60. void convert(ui8 mode); //mode=0 -> from 'manifest' to 'object'
  61. };
  62. struct DLL_LINKAGE CPathsInfo
  63. {
  64. typedef EPathfindingLayer ELayer;
  65. mutable boost::mutex pathMx;
  66. const CGHeroInstance * hero;
  67. int3 hpos;
  68. int3 sizes;
  69. boost::multi_array<CGPathNode, 4> nodes; //[w][h][level][layer]
  70. CPathsInfo(const int3 & Sizes);
  71. ~CPathsInfo();
  72. const CGPathNode * getPathInfo(const int3 & tile) const;
  73. bool getPath(CGPath & out, const int3 & dst) const;
  74. int getDistance(const int3 & tile) const;
  75. const CGPathNode * getNode(const int3 & coord) const;
  76. CGPathNode * getNode(const int3 & coord, const ELayer layer);
  77. };
  78. class CPathfinder : private CGameInfoCallback
  79. {
  80. public:
  81. friend class CPathfinderHelper;
  82. CPathfinder(CPathsInfo & _out, CGameState * _gs, const CGHeroInstance * _hero);
  83. 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
  84. private:
  85. typedef EPathfindingLayer ELayer;
  86. struct PathfinderOptions
  87. {
  88. bool useFlying;
  89. bool useWaterWalking;
  90. bool useEmbarkAndDisembark;
  91. bool useTeleportTwoWay; // Two-way monoliths and Subterranean Gate
  92. bool useTeleportOneWay; // One-way monoliths with one known exit only
  93. bool useTeleportOneWayRandom; // One-way monoliths with more than one known exit
  94. bool useTeleportWhirlpool; // Force enabled if hero protected or unaffected (have one stack of one creature)
  95. /// TODO: Find out with client and server code, merge with normal teleporters.
  96. /// Likely proper implementation would require some refactoring of CGTeleport.
  97. /// So for now this is unfinished and disabled by default.
  98. bool useCastleGate;
  99. /// If true transition into air layer only possible from initial node.
  100. /// This is drastically decrease path calculation complexity (and time).
  101. /// Downside is less MP effective paths calculation.
  102. ///
  103. /// TODO: If this option end up useful for slow devices it's can be improved:
  104. /// - Allow transition into air layer not only from initial position, but also from teleporters.
  105. /// Movement into air can be also allowed when hero disembarked.
  106. /// - Other idea is to allow transition into air within certain radius of N tiles around hero.
  107. /// Patrol support need similar functionality so it's won't be ton of useless code.
  108. /// Such limitation could be useful as it's can be scaled depend on device performance.
  109. bool lightweightFlyingMode;
  110. /// This option enable one turn limitation for flying and water walking.
  111. /// So if we're out of MP while cp is blocked or water tile we won't add dest tile to queue.
  112. ///
  113. /// Following imitation is default H3 mechanics, but someone may want to disable it in mods.
  114. /// After all this limit should benefit performance on maps with tons of water or blocked tiles.
  115. bool oneTurnSpecialLayersLimit;
  116. /// VCMI have different movement rules to solve flaws original engine has.
  117. /// If this option enabled you'll able to do following things in fly:
  118. /// - Move from blocked tiles to visitable one
  119. /// - Move from guarded tiles to blockvis tiles without being attacked
  120. /// - Move from guarded tiles to guarded visitable tiles with being attacked after
  121. /// TODO:
  122. /// - Option should also allow same tile land <-> air layer transitions.
  123. /// Current implementation only allow go into (from) air layer only to neighbour tiles.
  124. /// I find it's reasonable limitation, but it's will make some movements more expensive than in H3.
  125. bool originalMovementRules;
  126. PathfinderOptions();
  127. } options;
  128. CPathsInfo & out;
  129. const CGHeroInstance * hero;
  130. unique_ptr<CPathfinderHelper> hlp;
  131. struct NodeComparer
  132. {
  133. bool operator()(const CGPathNode * lhs, const CGPathNode * rhs) const
  134. {
  135. if(rhs->turns > lhs->turns)
  136. return false;
  137. else if(rhs->turns == lhs->turns && rhs->moveRemains < lhs->moveRemains)
  138. return false;
  139. return true;
  140. }
  141. };
  142. boost::heap::priority_queue<CGPathNode *, boost::heap::compare<NodeComparer> > pq;
  143. std::vector<int3> neighbours;
  144. CGPathNode * cp; //current (source) path node -> we took it from the queue
  145. CGPathNode * dp; //destination node -> it's a neighbour of cp that we consider
  146. const TerrainTile * ct, * dt; //tile info for both nodes
  147. const CGObjectInstance * ctObj, * dtObj;
  148. CGPathNode::ENodeAction destAction;
  149. void addNeighbours();
  150. void addTeleportExits();
  151. bool isLayerTransitionPossible() const;
  152. bool isMovementToDestPossible() const;
  153. bool isMovementAfterDestPossible() const;
  154. CGPathNode::ENodeAction getDestAction() const;
  155. bool isSourceInitialPosition() const;
  156. bool isSourceVisitableObj() const;
  157. bool isSourceGuarded() const;
  158. bool isDestVisitableObj() const;
  159. bool isDestinationGuarded(const bool ignoreAccessibility = true) const;
  160. bool isDestinationGuardian() const;
  161. void initializeGraph();
  162. CGPathNode::EAccessibility evaluateAccessibility(const int3 & pos, const TerrainTile * tinfo, const ELayer layer) const;
  163. bool isVisitableObj(const CGObjectInstance * obj, const ELayer layer) const;
  164. bool canSeeObj(const CGObjectInstance * obj) const;
  165. 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)
  166. bool isAllowedTeleportEntrance(const CGTeleport * obj) const;
  167. bool addTeleportTwoWay(const CGTeleport * obj) const;
  168. bool addTeleportOneWay(const CGTeleport * obj) const;
  169. bool addTeleportOneWayRandom(const CGTeleport * obj) const;
  170. bool addTeleportWhirlpool(const CGWhirlpool * obj) const;
  171. };
  172. struct DLL_LINKAGE TurnInfo
  173. {
  174. /// This is certainly not the best design ever and certainly can be improved
  175. /// Unfortunately for pathfinder that do hundreds of thousands calls onus system add too big overhead
  176. struct BonusCache {
  177. std::vector<bool> noTerrainPenalty;
  178. bool freeShipBoarding;
  179. bool flyingMovement;
  180. int flyingMovementVal;
  181. bool waterWalking;
  182. int waterWalkingVal;
  183. BonusCache(TBonusListPtr bonusList);
  184. };
  185. unique_ptr<BonusCache> bonusCache;
  186. const CGHeroInstance * hero;
  187. TBonusListPtr bonuses;
  188. mutable int maxMovePointsLand;
  189. mutable int maxMovePointsWater;
  190. int nativeTerrain;
  191. TurnInfo(const CGHeroInstance * Hero, const int Turn = 0);
  192. bool isLayerAvailable(const EPathfindingLayer layer) const;
  193. bool hasBonusOfType(const Bonus::BonusType type, const int subtype = -1) const;
  194. int valOfBonuses(const Bonus::BonusType type, const int subtype = -1) const;
  195. int getMaxMovePoints(const EPathfindingLayer layer) const;
  196. };
  197. class DLL_LINKAGE CPathfinderHelper
  198. {
  199. public:
  200. CPathfinderHelper(const CGHeroInstance * Hero, const CPathfinder::PathfinderOptions & Options);
  201. void updateTurnInfo(const int turn = 0);
  202. bool isLayerAvailable(const EPathfindingLayer layer) const;
  203. const TurnInfo * getTurnInfo() const;
  204. bool hasBonusOfType(const Bonus::BonusType type, const int subtype = -1) const;
  205. int getMaxMovePoints(const EPathfindingLayer layer) const;
  206. static void getNeighbours(const CMap * map, const TerrainTile & srct, const int3 & tile, std::vector<int3> & vec, const boost::logic::tribool & onLand, const bool limitCoastSailing);
  207. static int getMovementCost(const CGHeroInstance * h, const int3 & src, const int3 & dst, const TerrainTile * ct, const TerrainTile * dt, const int remainingMovePoints =- 1, const TurnInfo * ti = nullptr, const bool checkLast = true);
  208. static int getMovementCost(const CGHeroInstance * h, const int3 & dst);
  209. private:
  210. int turn;
  211. const CGHeroInstance * hero;
  212. std::vector<TurnInfo *> turnsInfo;
  213. const CPathfinder::PathfinderOptions & options;
  214. };