CPathfinder.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377
  1. /*
  2. * CPathfinder.cpp, 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. #include "StdInc.h"
  11. #include "CPathfinder.h"
  12. #include "CHeroHandler.h"
  13. #include "mapping/CMap.h"
  14. #include "CGameState.h"
  15. #include "mapObjects/CGHeroInstance.h"
  16. #include "GameConstants.h"
  17. #include "CStopWatch.h"
  18. #include "CConfigHandler.h"
  19. #include "CPlayerState.h"
  20. #include "PathfinderUtil.h"
  21. bool canSeeObj(const CGObjectInstance * obj)
  22. {
  23. /// Pathfinder should ignore placed events
  24. return obj != nullptr && obj->ID != Obj::EVENT;
  25. }
  26. void NodeStorage::initialize(const PathfinderOptions & options, const CGameState * gs, const CGHeroInstance * hero)
  27. {
  28. //TODO: fix this code duplication with AINodeStorage::initialize, problem is to keep `resetTile` inline
  29. int3 pos;
  30. const int3 sizes = gs->getMapSize();
  31. const auto & fow = static_cast<const CGameInfoCallback *>(gs)->getPlayerTeam(hero->tempOwner)->fogOfWarMap;
  32. const PlayerColor player = hero->tempOwner;
  33. //make 200% sure that these are loop invariants (also a bit shorter code), let compiler do the rest(loop unswitching)
  34. const bool useFlying = options.useFlying;
  35. const bool useWaterWalking = options.useWaterWalking;
  36. for(pos.x=0; pos.x < sizes.x; ++pos.x)
  37. {
  38. for(pos.y=0; pos.y < sizes.y; ++pos.y)
  39. {
  40. for(pos.z=0; pos.z < sizes.z; ++pos.z)
  41. {
  42. const TerrainTile * tile = &gs->map->getTile(pos);
  43. switch(tile->terType)
  44. {
  45. case ETerrainType::ROCK:
  46. break;
  47. case ETerrainType::WATER:
  48. resetTile(pos, ELayer::SAIL, PathfinderUtil::evaluateAccessibility<ELayer::SAIL>(pos, tile, fow, player, gs));
  49. if(useFlying)
  50. resetTile(pos, ELayer::AIR, PathfinderUtil::evaluateAccessibility<ELayer::AIR>(pos, tile, fow, player, gs));
  51. if(useWaterWalking)
  52. resetTile(pos, ELayer::WATER, PathfinderUtil::evaluateAccessibility<ELayer::WATER>(pos, tile, fow, player, gs));
  53. break;
  54. default:
  55. resetTile(pos, ELayer::LAND, PathfinderUtil::evaluateAccessibility<ELayer::LAND>(pos, tile, fow, player, gs));
  56. if(useFlying)
  57. resetTile(pos, ELayer::AIR, PathfinderUtil::evaluateAccessibility<ELayer::AIR>(pos, tile, fow, player, gs));
  58. break;
  59. }
  60. }
  61. }
  62. }
  63. }
  64. std::vector<CGPathNode *> NodeStorage::calculateNeighbours(
  65. const PathNodeInfo & source,
  66. const PathfinderConfig * pathfinderConfig,
  67. const CPathfinderHelper * pathfinderHelper)
  68. {
  69. std::vector<CGPathNode *> neighbours;
  70. neighbours.reserve(16);
  71. auto accessibleNeighbourTiles = pathfinderHelper->getNeighbourTiles(source);
  72. for(auto & neighbour : accessibleNeighbourTiles)
  73. {
  74. for(EPathfindingLayer i = EPathfindingLayer::LAND; i <= EPathfindingLayer::AIR; i.advance(1))
  75. {
  76. auto node = getNode(neighbour, i);
  77. if(node->accessible == CGPathNode::NOT_SET)
  78. continue;
  79. neighbours.push_back(node);
  80. }
  81. }
  82. return neighbours;
  83. }
  84. std::vector<CGPathNode *> NodeStorage::calculateTeleportations(
  85. const PathNodeInfo & source,
  86. const PathfinderConfig * pathfinderConfig,
  87. const CPathfinderHelper * pathfinderHelper)
  88. {
  89. std::vector<CGPathNode *> neighbours;
  90. if(!source.isNodeObjectVisitable())
  91. return neighbours;
  92. auto accessibleExits = pathfinderHelper->getTeleportExits(source);
  93. for(auto & neighbour : accessibleExits)
  94. {
  95. auto node = getNode(neighbour, source.node->layer);
  96. neighbours.push_back(node);
  97. }
  98. return neighbours;
  99. }
  100. std::vector<int3> CPathfinderHelper::getNeighbourTiles(const PathNodeInfo & source) const
  101. {
  102. std::vector<int3> neighbourTiles;
  103. neighbourTiles.reserve(16);
  104. getNeighbours(
  105. *source.tile,
  106. source.node->coord,
  107. neighbourTiles,
  108. boost::logic::indeterminate,
  109. source.node->layer == EPathfindingLayer::SAIL);
  110. if(source.isNodeObjectVisitable())
  111. {
  112. vstd::erase_if(neighbourTiles, [&](int3 tile) -> bool
  113. {
  114. return !canMoveBetween(tile, source.nodeObject->visitablePos());
  115. });
  116. }
  117. return neighbourTiles;
  118. }
  119. NodeStorage::NodeStorage(CPathsInfo & pathsInfo, const CGHeroInstance * hero)
  120. :out(pathsInfo)
  121. {
  122. out.hero = hero;
  123. out.hpos = hero->getPosition(false);
  124. }
  125. void NodeStorage::resetTile(
  126. const int3 & tile,
  127. EPathfindingLayer layer,
  128. CGPathNode::EAccessibility accessibility)
  129. {
  130. getNode(tile, layer)->update(tile, layer, accessibility);
  131. }
  132. CGPathNode * NodeStorage::getInitialNode()
  133. {
  134. auto initialNode = getNode(out.hpos, out.hero->boat ? EPathfindingLayer::SAIL : EPathfindingLayer::LAND);
  135. initialNode->turns = 0;
  136. initialNode->moveRemains = out.hero->movement;
  137. initialNode->cost = 0.0;
  138. return initialNode;
  139. }
  140. void NodeStorage::commit(CDestinationNodeInfo & destination, const PathNodeInfo & source)
  141. {
  142. assert(destination.node != source.node->theNodeBefore); //two tiles can't point to each other
  143. destination.node->cost = destination.cost;
  144. destination.node->moveRemains = destination.movementLeft;
  145. destination.node->turns = destination.turn;
  146. destination.node->theNodeBefore = source.node;
  147. destination.node->action = destination.action;
  148. }
  149. PathfinderOptions::PathfinderOptions()
  150. {
  151. useFlying = settings["pathfinder"]["layers"]["flying"].Bool();
  152. useWaterWalking = settings["pathfinder"]["layers"]["waterWalking"].Bool();
  153. useEmbarkAndDisembark = settings["pathfinder"]["layers"]["sailing"].Bool();
  154. useTeleportTwoWay = settings["pathfinder"]["teleports"]["twoWay"].Bool();
  155. useTeleportOneWay = settings["pathfinder"]["teleports"]["oneWay"].Bool();
  156. useTeleportOneWayRandom = settings["pathfinder"]["teleports"]["oneWayRandom"].Bool();
  157. useTeleportWhirlpool = settings["pathfinder"]["teleports"]["whirlpool"].Bool();
  158. useCastleGate = settings["pathfinder"]["teleports"]["castleGate"].Bool();
  159. lightweightFlyingMode = settings["pathfinder"]["lightweightFlyingMode"].Bool();
  160. oneTurnSpecialLayersLimit = settings["pathfinder"]["oneTurnSpecialLayersLimit"].Bool();
  161. originalMovementRules = settings["pathfinder"]["originalMovementRules"].Bool();
  162. }
  163. void MovementCostRule::process(
  164. const PathNodeInfo & source,
  165. CDestinationNodeInfo & destination,
  166. const PathfinderConfig * pathfinderConfig,
  167. CPathfinderHelper * pathfinderHelper) const
  168. {
  169. float costAtNextTile = destination.cost;
  170. int turnAtNextTile = destination.turn;
  171. int moveAtNextTile = destination.movementLeft;
  172. int cost = pathfinderHelper->getMovementCost(source, destination, moveAtNextTile);
  173. int remains = moveAtNextTile - cost;
  174. int maxMovePoints = pathfinderHelper->getMaxMovePoints(destination.node->layer);
  175. if(remains < 0)
  176. {
  177. //occurs rarely, when hero with low movepoints tries to leave the road
  178. costAtNextTile += static_cast<float>(moveAtNextTile) / maxMovePoints;//we spent all points of current turn
  179. pathfinderHelper->updateTurnInfo(++turnAtNextTile);
  180. maxMovePoints = pathfinderHelper->getMaxMovePoints(destination.node->layer);
  181. moveAtNextTile = maxMovePoints;
  182. cost = pathfinderHelper->getMovementCost(source, destination, moveAtNextTile); //cost must be updated, movement points changed :(
  183. remains = moveAtNextTile - cost;
  184. }
  185. if(destination.action == CGPathNode::EMBARK || destination.action == CGPathNode::DISEMBARK)
  186. {
  187. /// FREE_SHIP_BOARDING bonus only remove additional penalty
  188. /// land <-> sail transition still cost movement points as normal movement
  189. remains = pathfinderHelper->movementPointsAfterEmbark(moveAtNextTile, cost, (destination.action == CGPathNode::DISEMBARK));
  190. cost = moveAtNextTile - remains;
  191. }
  192. costAtNextTile += static_cast<float>(cost) / maxMovePoints;
  193. destination.cost = costAtNextTile;
  194. destination.turn = turnAtNextTile;
  195. destination.movementLeft = remains;
  196. if(destination.isBetterWay() &&
  197. ((source.node->turns == turnAtNextTile && remains) || pathfinderHelper->passOneTurnLimitCheck(source)))
  198. {
  199. pathfinderConfig->nodeStorage->commit(destination, source);
  200. return;
  201. }
  202. destination.blocked = true;
  203. }
  204. PathfinderConfig::PathfinderConfig(
  205. std::shared_ptr<INodeStorage> nodeStorage,
  206. std::vector<std::shared_ptr<IPathfindingRule>> rules)
  207. : nodeStorage(nodeStorage), rules(rules), options()
  208. {
  209. }
  210. CPathfinder::CPathfinder(
  211. CPathsInfo & _out,
  212. CGameState * _gs,
  213. const CGHeroInstance * _hero)
  214. : CPathfinder(
  215. _gs,
  216. _hero,
  217. std::make_shared<PathfinderConfig>(
  218. std::make_shared<NodeStorage>(_out, _hero),
  219. std::vector<std::shared_ptr<IPathfindingRule>>{
  220. std::make_shared<LayerTransitionRule>(),
  221. std::make_shared<DestinationActionRule>(),
  222. std::make_shared<MovementToDestinationRule>(),
  223. std::make_shared<MovementCostRule>(),
  224. std::make_shared<MovementAfterDestinationRule>()
  225. }))
  226. {
  227. }
  228. CPathfinder::CPathfinder(
  229. CGameState * _gs,
  230. const CGHeroInstance * _hero,
  231. std::shared_ptr<PathfinderConfig> config)
  232. : CGameInfoCallback(_gs, boost::optional<PlayerColor>())
  233. , hero(_hero)
  234. , patrolTiles({})
  235. , config(config)
  236. , source()
  237. , destination()
  238. {
  239. assert(hero);
  240. assert(hero == getHero(hero->id));
  241. hlp = make_unique<CPathfinderHelper>(_gs, hero, config->options);
  242. initializePatrol();
  243. initializeGraph();
  244. }
  245. void CPathfinder::calculatePaths()
  246. {
  247. //logGlobal->info("Calculating paths for hero %s (adress %d) of player %d", hero->name, hero , hero->tempOwner);
  248. //initial tile - set cost on 0 and add to the queue
  249. CGPathNode * initialNode = config->nodeStorage->getInitialNode();
  250. if(!isInTheMap(initialNode->coord)/* || !gs->map->isInTheMap(dest)*/) //check input
  251. {
  252. logGlobal->error("CGameState::calculatePaths: Hero outside the gs->map? How dare you...");
  253. throw std::runtime_error("Wrong checksum");
  254. }
  255. if(isHeroPatrolLocked())
  256. return;
  257. pq.push(initialNode);
  258. while(!pq.empty())
  259. {
  260. auto node = pq.top();
  261. auto excludeOurHero = node->coord == initialNode->coord;
  262. source.setNode(gs, node, excludeOurHero);
  263. pq.pop();
  264. source.node->locked = true;
  265. int movement = source.node->moveRemains;
  266. uint8_t turn = source.node->turns;
  267. float cost = source.node->cost;
  268. hlp->updateTurnInfo(turn);
  269. if(!movement)
  270. {
  271. hlp->updateTurnInfo(++turn);
  272. movement = hlp->getMaxMovePoints(source.node->layer);
  273. if(!hlp->passOneTurnLimitCheck(source))
  274. continue;
  275. }
  276. source.guarded = isSourceGuarded();
  277. if(source.nodeObject)
  278. source.objectRelations = gs->getPlayerRelations(hero->tempOwner, source.nodeObject->tempOwner);
  279. //add accessible neighbouring nodes to the queue
  280. auto neighbourNodes = config->nodeStorage->calculateNeighbours(source, config.get(), hlp.get());
  281. for(CGPathNode * neighbour : neighbourNodes)
  282. {
  283. if(neighbour->locked)
  284. continue;
  285. if(!isPatrolMovementAllowed(neighbour->coord))
  286. continue;
  287. if(!hlp->isLayerAvailable(neighbour->layer))
  288. continue;
  289. destination.setNode(gs, neighbour);
  290. /// Check transition without tile accessability rules
  291. if(source.node->layer != neighbour->layer && !isLayerTransitionPossible())
  292. continue;
  293. destination.turn = turn;
  294. destination.movementLeft = movement;
  295. destination.cost = cost;
  296. destination.guarded = isDestinationGuarded();
  297. destination.isGuardianTile = destination.guarded && isDestinationGuardian();
  298. if(destination.nodeObject)
  299. destination.objectRelations = gs->getPlayerRelations(hero->tempOwner, destination.nodeObject->tempOwner);
  300. for(auto rule : config->rules)
  301. {
  302. rule->process(source, destination, config.get(), hlp.get());
  303. if(destination.blocked)
  304. break;
  305. }
  306. if(!destination.blocked)
  307. pq.push(destination.node);
  308. } //neighbours loop
  309. //just add all passable teleport exits
  310. /// For now we disable teleports usage for patrol movement
  311. /// VCAI not aware about patrol and may stuck while attempt to use teleport
  312. if(patrolState == PATROL_RADIUS)
  313. continue;
  314. auto teleportationNodes = config->nodeStorage->calculateTeleportations(source, config.get(), hlp.get());
  315. for(CGPathNode * teleportNode : teleportationNodes)
  316. {
  317. if(teleportNode->locked)
  318. continue;
  319. /// TODO: We may consider use invisible exits on FoW border in future
  320. /// Useful for AI when at least one tile around exit is visible and passable
  321. /// Objects are usually visible on FoW border anyway so it's not cheating.
  322. ///
  323. /// For now it's disabled as it's will cause crashes in movement code.
  324. if(teleportNode->accessible == CGPathNode::BLOCKED)
  325. continue;
  326. destination.setNode(gs, teleportNode);
  327. destination.turn = turn;
  328. destination.movementLeft = movement;
  329. destination.cost = cost;
  330. if(destination.isBetterWay())
  331. {
  332. destination.action = getTeleportDestAction();
  333. config->nodeStorage->commit(destination, source);
  334. if(destination.node->action == CGPathNode::TELEPORT_NORMAL)
  335. pq.push(destination.node);
  336. }
  337. }
  338. } //queue loop
  339. }
  340. std::vector<int3> CPathfinderHelper::getAllowedTeleportChannelExits(TeleportChannelID channelID) const
  341. {
  342. std::vector<int3> allowedExits;
  343. for(auto objId : getTeleportChannelExits(channelID, hero->tempOwner))
  344. {
  345. auto obj = getObj(objId);
  346. if(dynamic_cast<const CGWhirlpool *>(obj))
  347. {
  348. auto pos = obj->getBlockedPos();
  349. for(auto p : pos)
  350. {
  351. if(gs->map->getTile(p).topVisitableId() == obj->ID)
  352. allowedExits.push_back(p);
  353. }
  354. }
  355. else if(CGTeleport::isExitPassable(gs, hero, obj))
  356. allowedExits.push_back(obj->visitablePos());
  357. }
  358. return allowedExits;
  359. }
  360. std::vector<int3> CPathfinderHelper::getCastleGates(const PathNodeInfo & source) const
  361. {
  362. std::vector<int3> allowedExits;
  363. auto towns = getPlayer(hero->tempOwner)->towns;
  364. for(const auto & town : towns)
  365. {
  366. if(town->id != source.nodeObject->id && town->visitingHero == nullptr
  367. && town->hasBuilt(BuildingID::CASTLE_GATE, ETownType::INFERNO))
  368. {
  369. allowedExits.push_back(town->visitablePos());
  370. }
  371. }
  372. return allowedExits;
  373. }
  374. std::vector<int3> CPathfinderHelper::getTeleportExits(const PathNodeInfo & source) const
  375. {
  376. std::vector<int3> teleportationExits;
  377. const CGTeleport * objTeleport = dynamic_cast<const CGTeleport *>(source.nodeObject);
  378. if(isAllowedTeleportEntrance(objTeleport))
  379. {
  380. for(auto exit : getAllowedTeleportChannelExits(objTeleport->channel))
  381. {
  382. teleportationExits.push_back(exit);
  383. }
  384. }
  385. else if(options.useCastleGate
  386. && (source.nodeObject->ID == Obj::TOWN && source.nodeObject->subID == ETownType::INFERNO
  387. && source.objectRelations != PlayerRelations::ENEMIES))
  388. {
  389. /// TODO: Find way to reuse CPlayerSpecificInfoCallback::getTownsInfo
  390. /// This may be handy if we allow to use teleportation to friendly towns
  391. for(auto exit : getCastleGates(source))
  392. {
  393. teleportationExits.push_back(exit);
  394. }
  395. }
  396. return teleportationExits;
  397. }
  398. bool CPathfinder::isHeroPatrolLocked() const
  399. {
  400. return patrolState == PATROL_LOCKED;
  401. }
  402. bool CPathfinder::isPatrolMovementAllowed(const int3 & dst) const
  403. {
  404. if(patrolState == PATROL_RADIUS)
  405. {
  406. if(!vstd::contains(patrolTiles, dst))
  407. return false;
  408. }
  409. return true;
  410. }
  411. bool CPathfinder::isLayerTransitionPossible() const
  412. {
  413. ELayer destLayer = destination.node->layer;
  414. /// No layer transition allowed when previous node action is BATTLE
  415. if(source.node->action == CGPathNode::BATTLE)
  416. return false;
  417. switch(source.node->layer)
  418. {
  419. case ELayer::LAND:
  420. if(destLayer == ELayer::AIR)
  421. {
  422. if(!config->options.lightweightFlyingMode || isSourceInitialPosition())
  423. return true;
  424. }
  425. else if(destLayer == ELayer::SAIL)
  426. {
  427. if(destination.tile->isWater())
  428. return true;
  429. }
  430. else
  431. return true;
  432. break;
  433. case ELayer::SAIL:
  434. if(destLayer == ELayer::LAND && !destination.tile->isWater())
  435. return true;
  436. break;
  437. case ELayer::AIR:
  438. if(destLayer == ELayer::LAND)
  439. return true;
  440. break;
  441. case ELayer::WATER:
  442. if(destLayer == ELayer::LAND)
  443. return true;
  444. break;
  445. }
  446. return false;
  447. }
  448. void LayerTransitionRule::process(
  449. const PathNodeInfo & source,
  450. CDestinationNodeInfo & destination,
  451. const PathfinderConfig * pathfinderConfig,
  452. CPathfinderHelper * pathfinderHelper) const
  453. {
  454. if(source.node->layer == destination.node->layer)
  455. return;
  456. switch(source.node->layer)
  457. {
  458. case EPathfindingLayer::LAND:
  459. if(destination.node->layer == EPathfindingLayer::SAIL)
  460. {
  461. /// Cannot enter empty water tile from land -> it has to be visitable
  462. if(destination.node->accessible == CGPathNode::ACCESSIBLE)
  463. destination.blocked = true;
  464. }
  465. break;
  466. case EPathfindingLayer::SAIL:
  467. //tile must be accessible -> exception: unblocked blockvis tiles -> clear but guarded by nearby monster coast
  468. if((destination.node->accessible != CGPathNode::ACCESSIBLE && (destination.node->accessible != CGPathNode::BLOCKVIS || destination.tile->blocked))
  469. || destination.tile->visitable) //TODO: passableness problem -> town says it's passable (thus accessible) but we obviously can't disembark onto town gate
  470. {
  471. destination.blocked = true;
  472. }
  473. break;
  474. case EPathfindingLayer::AIR:
  475. if(pathfinderConfig->options.originalMovementRules)
  476. {
  477. if((source.node->accessible != CGPathNode::ACCESSIBLE &&
  478. source.node->accessible != CGPathNode::VISITABLE) &&
  479. (destination.node->accessible != CGPathNode::VISITABLE &&
  480. destination.node->accessible != CGPathNode::ACCESSIBLE))
  481. {
  482. destination.blocked = true;
  483. }
  484. }
  485. else if(source.node->accessible != CGPathNode::ACCESSIBLE && destination.node->accessible != CGPathNode::ACCESSIBLE)
  486. {
  487. /// Hero that fly can only land on accessible tiles
  488. destination.blocked = true;
  489. }
  490. break;
  491. case EPathfindingLayer::WATER:
  492. if(destination.node->accessible != CGPathNode::ACCESSIBLE && destination.node->accessible != CGPathNode::VISITABLE)
  493. {
  494. /// Hero that walking on water can transit to accessible and visitable tiles
  495. /// Though hero can't interact with blocking visit objects while standing on water
  496. destination.blocked = true;
  497. }
  498. break;
  499. }
  500. }
  501. PathfinderBlockingRule::BlockingReason MovementToDestinationRule::getBlockingReason(
  502. const PathNodeInfo & source,
  503. const CDestinationNodeInfo & destination,
  504. const PathfinderConfig * pathfinderConfig,
  505. const CPathfinderHelper * pathfinderHelper) const
  506. {
  507. if(destination.node->accessible == CGPathNode::BLOCKED)
  508. return BlockingReason::DESTINATION_BLOCKED;
  509. switch(destination.node->layer)
  510. {
  511. case EPathfindingLayer::LAND:
  512. if(!pathfinderHelper->canMoveBetween(source.coord, destination.coord))
  513. return BlockingReason::DESTINATION_BLOCKED;
  514. if(source.guarded)
  515. {
  516. if(!(pathfinderConfig->options.originalMovementRules && source.node->layer == EPathfindingLayer::AIR) &&
  517. !destination.isGuardianTile) // Can step into tile of guard
  518. {
  519. return BlockingReason::SOURCE_GUARDED;
  520. }
  521. }
  522. break;
  523. case EPathfindingLayer::SAIL:
  524. if(!pathfinderHelper->canMoveBetween(source.coord, destination.coord))
  525. return BlockingReason::DESTINATION_BLOCKED;
  526. if(source.guarded)
  527. {
  528. // Hero embarked a boat standing on a guarded tile -> we must allow to move away from that tile
  529. if(source.node->action != CGPathNode::EMBARK && !destination.isGuardianTile)
  530. return BlockingReason::SOURCE_GUARDED;
  531. }
  532. if(source.node->layer == EPathfindingLayer::LAND)
  533. {
  534. if(!destination.isNodeObjectVisitable())
  535. return BlockingReason::DESTINATION_BLOCKED;
  536. if(destination.nodeObject->ID != Obj::BOAT && destination.nodeObject->ID != Obj::HERO)
  537. return BlockingReason::DESTINATION_BLOCKED;
  538. }
  539. else if(destination.isNodeObjectVisitable() && destination.nodeObject->ID == Obj::BOAT)
  540. {
  541. /// Hero in boat can't visit empty boats
  542. return BlockingReason::DESTINATION_BLOCKED;
  543. }
  544. break;
  545. case EPathfindingLayer::WATER:
  546. if(!pathfinderHelper->canMoveBetween(source.coord, destination.coord)
  547. || destination.node->accessible != CGPathNode::ACCESSIBLE)
  548. {
  549. return BlockingReason::DESTINATION_BLOCKED;
  550. }
  551. if(destination.guarded)
  552. return BlockingReason::DESTINATION_BLOCKED;
  553. break;
  554. }
  555. return BlockingReason::NONE;
  556. }
  557. void MovementAfterDestinationRule::process(
  558. const PathNodeInfo & source,
  559. CDestinationNodeInfo & destination,
  560. const PathfinderConfig * config,
  561. CPathfinderHelper * pathfinderHelper) const
  562. {
  563. auto blocker = getBlockingReason(source, destination, config, pathfinderHelper);
  564. if(blocker == BlockingReason::DESTINATION_GUARDED && destination.action == CGPathNode::ENodeAction::BATTLE)
  565. {
  566. return; // allow bypass guarded tile but only in direction of guard, a bit UI related thing
  567. }
  568. destination.blocked = blocker != BlockingReason::NONE;
  569. }
  570. PathfinderBlockingRule::BlockingReason MovementAfterDestinationRule::getBlockingReason(
  571. const PathNodeInfo & source,
  572. const CDestinationNodeInfo & destination,
  573. const PathfinderConfig * config,
  574. const CPathfinderHelper * pathfinderHelper) const
  575. {
  576. switch(destination.action)
  577. {
  578. /// TODO: Investigate what kind of limitation is possible to apply on movement from visitable tiles
  579. /// Likely in many cases we don't need to add visitable tile to queue when hero don't fly
  580. case CGPathNode::VISIT:
  581. {
  582. /// For now we only add visitable tile into queue when it's teleporter that allow transit
  583. /// Movement from visitable tile when hero is standing on it is possible into any layer
  584. const CGTeleport * objTeleport = dynamic_cast<const CGTeleport *>(destination.nodeObject);
  585. if(pathfinderHelper->isAllowedTeleportEntrance(objTeleport))
  586. {
  587. /// For now we'll always allow transit over teleporters
  588. /// Transit over whirlpools only allowed when hero protected
  589. return BlockingReason::NONE;
  590. }
  591. else if(destination.nodeObject->ID == Obj::GARRISON
  592. || destination.nodeObject->ID == Obj::GARRISON2
  593. || destination.nodeObject->ID == Obj::BORDER_GATE)
  594. {
  595. /// Transit via unguarded garrisons is always possible
  596. return BlockingReason::NONE;
  597. }
  598. return BlockingReason::DESTINATION_VISIT;
  599. }
  600. case CGPathNode::BLOCKING_VISIT:
  601. return destination.guarded
  602. ? BlockingReason::DESTINATION_GUARDED
  603. : BlockingReason::DESTINATION_BLOCKVIS;
  604. case CGPathNode::NORMAL:
  605. return BlockingReason::NONE;
  606. case CGPathNode::EMBARK:
  607. if(pathfinderHelper->options.useEmbarkAndDisembark)
  608. return BlockingReason::NONE;
  609. return BlockingReason::DESTINATION_BLOCKED;
  610. case CGPathNode::DISEMBARK:
  611. if(pathfinderHelper->options.useEmbarkAndDisembark)
  612. return destination.guarded ? BlockingReason::DESTINATION_GUARDED : BlockingReason::NONE;
  613. return BlockingReason::DESTINATION_BLOCKED;
  614. case CGPathNode::BATTLE:
  615. /// Movement after BATTLE action only possible from guarded tile to guardian tile
  616. if(destination.guarded)
  617. return BlockingReason::DESTINATION_GUARDED;
  618. break;
  619. }
  620. return BlockingReason::DESTINATION_BLOCKED;
  621. }
  622. void DestinationActionRule::process(
  623. const PathNodeInfo & source,
  624. CDestinationNodeInfo & destination,
  625. const PathfinderConfig * pathfinderConfig,
  626. CPathfinderHelper * pathfinderHelper) const
  627. {
  628. if(destination.action != CGPathNode::ENodeAction::UNKNOWN)
  629. {
  630. #ifdef VCMI_TRACE_PATHFINDER
  631. logAi->trace("Accepted precalculated action at %s", destination.coord.toString());
  632. #endif
  633. return;
  634. }
  635. CGPathNode::ENodeAction action = CGPathNode::NORMAL;
  636. auto hero = pathfinderHelper->hero;
  637. switch(destination.node->layer)
  638. {
  639. case EPathfindingLayer::LAND:
  640. if(source.node->layer == EPathfindingLayer::SAIL)
  641. {
  642. // TODO: Handle dismebark into guarded areaa
  643. action = CGPathNode::DISEMBARK;
  644. break;
  645. }
  646. /// don't break - next case shared for both land and sail layers
  647. FALLTHROUGH
  648. case EPathfindingLayer::SAIL:
  649. if(destination.isNodeObjectVisitable())
  650. {
  651. auto objRel = destination.objectRelations;
  652. if(destination.nodeObject->ID == Obj::BOAT)
  653. action = CGPathNode::EMBARK;
  654. else if(destination.nodeObject->ID == Obj::HERO)
  655. {
  656. if(objRel == PlayerRelations::ENEMIES)
  657. action = CGPathNode::BATTLE;
  658. else
  659. action = CGPathNode::BLOCKING_VISIT;
  660. }
  661. else if(destination.nodeObject->ID == Obj::TOWN)
  662. {
  663. if(destination.nodeObject->passableFor(hero->tempOwner))
  664. action = CGPathNode::VISIT;
  665. else if(objRel == PlayerRelations::ENEMIES)
  666. action = CGPathNode::BATTLE;
  667. }
  668. else if(destination.nodeObject->ID == Obj::GARRISON || destination.nodeObject->ID == Obj::GARRISON2)
  669. {
  670. if(destination.nodeObject->passableFor(hero->tempOwner))
  671. {
  672. if(destination.guarded)
  673. action = CGPathNode::BATTLE;
  674. }
  675. else if(objRel == PlayerRelations::ENEMIES)
  676. action = CGPathNode::BATTLE;
  677. }
  678. else if(destination.nodeObject->ID == Obj::BORDER_GATE)
  679. {
  680. if(destination.nodeObject->passableFor(hero->tempOwner))
  681. {
  682. if(destination.guarded)
  683. action = CGPathNode::BATTLE;
  684. }
  685. else
  686. action = CGPathNode::BLOCKING_VISIT;
  687. }
  688. else if(destination.isGuardianTile)
  689. action = CGPathNode::BATTLE;
  690. else if(destination.nodeObject->blockVisit && !(pathfinderConfig->options.useCastleGate && destination.nodeObject->ID == Obj::TOWN))
  691. action = CGPathNode::BLOCKING_VISIT;
  692. if(action == CGPathNode::NORMAL)
  693. {
  694. if(destination.guarded)
  695. action = CGPathNode::BATTLE;
  696. else
  697. action = CGPathNode::VISIT;
  698. }
  699. }
  700. else if(destination.guarded)
  701. action = CGPathNode::BATTLE;
  702. break;
  703. }
  704. destination.action = action;
  705. }
  706. CGPathNode::ENodeAction CPathfinder::getTeleportDestAction() const
  707. {
  708. CGPathNode::ENodeAction action = CGPathNode::TELEPORT_NORMAL;
  709. if(destination.isNodeObjectVisitable() && destination.nodeObject->ID == Obj::HERO)
  710. {
  711. auto objRel = getPlayerRelations(destination.nodeObject->tempOwner, hero->tempOwner);
  712. if(objRel == PlayerRelations::ENEMIES)
  713. action = CGPathNode::TELEPORT_BATTLE;
  714. else
  715. action = CGPathNode::TELEPORT_BLOCKING_VISIT;
  716. }
  717. return action;
  718. }
  719. bool CPathfinder::isSourceInitialPosition() const
  720. {
  721. return source.node->coord == config->nodeStorage->getInitialNode()->coord;
  722. }
  723. bool CPathfinder::isSourceGuarded() const
  724. {
  725. /// Hero can move from guarded tile if movement started on that tile
  726. /// It's possible at least in these cases:
  727. /// - Map start with hero on guarded tile
  728. /// - Dimention door used
  729. /// TODO: check what happen when there is several guards
  730. if(gs->guardingCreaturePosition(source.node->coord).valid() && !isSourceInitialPosition())
  731. {
  732. return true;
  733. }
  734. return false;
  735. }
  736. bool CPathfinder::isDestinationGuarded() const
  737. {
  738. /// isDestinationGuarded is exception needed for garrisons.
  739. /// When monster standing behind garrison it's visitable and guarded at the same time.
  740. return gs->guardingCreaturePosition(destination.node->coord).valid();
  741. }
  742. bool CPathfinder::isDestinationGuardian() const
  743. {
  744. return gs->guardingCreaturePosition(source.node->coord) == destination.node->coord;
  745. }
  746. void CPathfinder::initializePatrol()
  747. {
  748. auto state = PATROL_NONE;
  749. if(hero->patrol.patrolling && !getPlayer(hero->tempOwner)->human)
  750. {
  751. if(hero->patrol.patrolRadius)
  752. {
  753. state = PATROL_RADIUS;
  754. gs->getTilesInRange(patrolTiles, hero->patrol.initialPos, hero->patrol.patrolRadius, boost::optional<PlayerColor>(), 0, int3::DIST_MANHATTAN);
  755. }
  756. else
  757. state = PATROL_LOCKED;
  758. }
  759. patrolState = state;
  760. }
  761. void CPathfinder::initializeGraph()
  762. {
  763. INodeStorage * nodeStorage = config->nodeStorage.get();
  764. nodeStorage->initialize(config->options, gs, hero);
  765. }
  766. bool CPathfinderHelper::canMoveBetween(const int3 & a, const int3 & b) const
  767. {
  768. return gs->checkForVisitableDir(a, b);
  769. }
  770. bool CPathfinderHelper::isAllowedTeleportEntrance(const CGTeleport * obj) const
  771. {
  772. if(!obj || !isTeleportEntrancePassable(obj, hero->tempOwner))
  773. return false;
  774. auto whirlpool = dynamic_cast<const CGWhirlpool *>(obj);
  775. if(whirlpool)
  776. {
  777. if(addTeleportWhirlpool(whirlpool))
  778. return true;
  779. }
  780. else if(addTeleportTwoWay(obj) || addTeleportOneWay(obj) || addTeleportOneWayRandom(obj))
  781. return true;
  782. return false;
  783. }
  784. bool CPathfinderHelper::addTeleportTwoWay(const CGTeleport * obj) const
  785. {
  786. return options.useTeleportTwoWay && isTeleportChannelBidirectional(obj->channel, hero->tempOwner);
  787. }
  788. bool CPathfinderHelper::addTeleportOneWay(const CGTeleport * obj) const
  789. {
  790. if(options.useTeleportOneWay && isTeleportChannelUnidirectional(obj->channel, hero->tempOwner))
  791. {
  792. auto passableExits = CGTeleport::getPassableExits(gs, hero, getTeleportChannelExits(obj->channel, hero->tempOwner));
  793. if(passableExits.size() == 1)
  794. return true;
  795. }
  796. return false;
  797. }
  798. bool CPathfinderHelper::addTeleportOneWayRandom(const CGTeleport * obj) const
  799. {
  800. if(options.useTeleportOneWayRandom && isTeleportChannelUnidirectional(obj->channel, hero->tempOwner))
  801. {
  802. auto passableExits = CGTeleport::getPassableExits(gs, hero, getTeleportChannelExits(obj->channel, hero->tempOwner));
  803. if(passableExits.size() > 1)
  804. return true;
  805. }
  806. return false;
  807. }
  808. bool CPathfinderHelper::addTeleportWhirlpool(const CGWhirlpool * obj) const
  809. {
  810. return options.useTeleportWhirlpool && hasBonusOfType(Bonus::WHIRLPOOL_PROTECTION) && obj;
  811. }
  812. int CPathfinderHelper::movementPointsAfterEmbark(int movement, int basicCost, bool disembark) const
  813. {
  814. return hero->movementPointsAfterEmbark(movement, basicCost, disembark, getTurnInfo());
  815. }
  816. bool CPathfinderHelper::passOneTurnLimitCheck(const PathNodeInfo & source) const
  817. {
  818. if(!options.oneTurnSpecialLayersLimit)
  819. return true;
  820. if(source.node->layer == EPathfindingLayer::WATER)
  821. return false;
  822. if(source.node->layer == EPathfindingLayer::AIR)
  823. {
  824. if(options.originalMovementRules && source.node->accessible == CGPathNode::ACCESSIBLE)
  825. return true;
  826. else
  827. return false;
  828. }
  829. return true;
  830. }
  831. TurnInfo::BonusCache::BonusCache(TBonusListPtr bl)
  832. {
  833. noTerrainPenalty.reserve(ETerrainType::ROCK);
  834. for(int i = 0; i < ETerrainType::ROCK; i++)
  835. {
  836. noTerrainPenalty.push_back(static_cast<bool>(
  837. bl->getFirst(Selector::type(Bonus::NO_TERRAIN_PENALTY).And(Selector::subtype(i)))));
  838. }
  839. freeShipBoarding = static_cast<bool>(bl->getFirst(Selector::type(Bonus::FREE_SHIP_BOARDING)));
  840. flyingMovement = static_cast<bool>(bl->getFirst(Selector::type(Bonus::FLYING_MOVEMENT)));
  841. flyingMovementVal = bl->valOfBonuses(Selector::type(Bonus::FLYING_MOVEMENT));
  842. waterWalking = static_cast<bool>(bl->getFirst(Selector::type(Bonus::WATER_WALKING)));
  843. waterWalkingVal = bl->valOfBonuses(Selector::type(Bonus::WATER_WALKING));
  844. }
  845. TurnInfo::TurnInfo(const CGHeroInstance * Hero, const int turn)
  846. : hero(Hero), maxMovePointsLand(-1), maxMovePointsWater(-1)
  847. {
  848. bonuses = hero->getAllBonuses(Selector::days(turn), Selector::all, nullptr, "");
  849. bonusCache = make_unique<BonusCache>(bonuses);
  850. nativeTerrain = hero->getNativeTerrain();
  851. }
  852. bool TurnInfo::isLayerAvailable(const EPathfindingLayer layer) const
  853. {
  854. switch(layer)
  855. {
  856. case EPathfindingLayer::AIR:
  857. if(!hasBonusOfType(Bonus::FLYING_MOVEMENT))
  858. return false;
  859. break;
  860. case EPathfindingLayer::WATER:
  861. if(!hasBonusOfType(Bonus::WATER_WALKING))
  862. return false;
  863. break;
  864. }
  865. return true;
  866. }
  867. bool TurnInfo::hasBonusOfType(Bonus::BonusType type, int subtype) const
  868. {
  869. switch(type)
  870. {
  871. case Bonus::FREE_SHIP_BOARDING:
  872. return bonusCache->freeShipBoarding;
  873. case Bonus::FLYING_MOVEMENT:
  874. return bonusCache->flyingMovement;
  875. case Bonus::WATER_WALKING:
  876. return bonusCache->waterWalking;
  877. case Bonus::NO_TERRAIN_PENALTY:
  878. return bonusCache->noTerrainPenalty[subtype];
  879. }
  880. return static_cast<bool>(
  881. bonuses->getFirst(Selector::type(type).And(Selector::subtype(subtype))));
  882. }
  883. int TurnInfo::valOfBonuses(Bonus::BonusType type, int subtype) const
  884. {
  885. switch(type)
  886. {
  887. case Bonus::FLYING_MOVEMENT:
  888. return bonusCache->flyingMovementVal;
  889. case Bonus::WATER_WALKING:
  890. return bonusCache->waterWalkingVal;
  891. }
  892. return bonuses->valOfBonuses(Selector::type(type).And(Selector::subtype(subtype)));
  893. }
  894. int TurnInfo::getMaxMovePoints(const EPathfindingLayer layer) const
  895. {
  896. if(maxMovePointsLand == -1)
  897. maxMovePointsLand = hero->maxMovePointsCached(true, this);
  898. if(maxMovePointsWater == -1)
  899. maxMovePointsWater = hero->maxMovePointsCached(false, this);
  900. return layer == EPathfindingLayer::SAIL ? maxMovePointsWater : maxMovePointsLand;
  901. }
  902. CPathfinderHelper::CPathfinderHelper(CGameState * gs, const CGHeroInstance * Hero, const PathfinderOptions & Options)
  903. : CGameInfoCallback(gs, boost::optional<PlayerColor>()), turn(-1), hero(Hero), options(Options)
  904. {
  905. turnsInfo.reserve(16);
  906. updateTurnInfo();
  907. }
  908. CPathfinderHelper::~CPathfinderHelper()
  909. {
  910. for(auto ti : turnsInfo)
  911. delete ti;
  912. }
  913. void CPathfinderHelper::updateTurnInfo(const int Turn)
  914. {
  915. if(turn != Turn)
  916. {
  917. turn = Turn;
  918. if(turn >= turnsInfo.size())
  919. {
  920. auto ti = new TurnInfo(hero, turn);
  921. turnsInfo.push_back(ti);
  922. }
  923. }
  924. }
  925. bool CPathfinderHelper::isLayerAvailable(const EPathfindingLayer layer) const
  926. {
  927. switch(layer)
  928. {
  929. case EPathfindingLayer::AIR:
  930. if(!options.useFlying)
  931. return false;
  932. break;
  933. case EPathfindingLayer::WATER:
  934. if(!options.useWaterWalking)
  935. return false;
  936. break;
  937. }
  938. return turnsInfo[turn]->isLayerAvailable(layer);
  939. }
  940. const TurnInfo * CPathfinderHelper::getTurnInfo() const
  941. {
  942. return turnsInfo[turn];
  943. }
  944. bool CPathfinderHelper::hasBonusOfType(const Bonus::BonusType type, const int subtype) const
  945. {
  946. return turnsInfo[turn]->hasBonusOfType(type, subtype);
  947. }
  948. int CPathfinderHelper::getMaxMovePoints(const EPathfindingLayer layer) const
  949. {
  950. return turnsInfo[turn]->getMaxMovePoints(layer);
  951. }
  952. void CPathfinderHelper::getNeighbours(
  953. const TerrainTile & srct,
  954. const int3 & tile,
  955. std::vector<int3> & vec,
  956. const boost::logic::tribool & onLand,
  957. const bool limitCoastSailing) const
  958. {
  959. CMap * map = gs->map;
  960. static const int3 dirs[] = {
  961. int3(-1, +1, +0), int3(0, +1, +0), int3(+1, +1, +0),
  962. int3(-1, +0, +0), /* source pos */ int3(+1, +0, +0),
  963. int3(-1, -1, +0), int3(0, -1, +0), int3(+1, -1, +0)
  964. };
  965. for(auto & dir : dirs)
  966. {
  967. const int3 hlp = tile + dir;
  968. if(!map->isInTheMap(hlp))
  969. continue;
  970. const TerrainTile & hlpt = map->getTile(hlp);
  971. if(hlpt.terType == ETerrainType::ROCK)
  972. continue;
  973. // //we cannot visit things from blocked tiles
  974. // if(srct.blocked && !srct.visitable && hlpt.visitable && srct.blockingObjects.front()->ID != HEROI_TYPE)
  975. // {
  976. // continue;
  977. // }
  978. /// Following condition let us avoid diagonal movement over coast when sailing
  979. if(srct.terType == ETerrainType::WATER && limitCoastSailing && hlpt.terType == ETerrainType::WATER && dir.x && dir.y) //diagonal move through water
  980. {
  981. int3 hlp1 = tile,
  982. hlp2 = tile;
  983. hlp1.x += dir.x;
  984. hlp2.y += dir.y;
  985. if(map->getTile(hlp1).terType != ETerrainType::WATER || map->getTile(hlp2).terType != ETerrainType::WATER)
  986. continue;
  987. }
  988. if(indeterminate(onLand) || onLand == (hlpt.terType != ETerrainType::WATER))
  989. {
  990. vec.push_back(hlp);
  991. }
  992. }
  993. }
  994. int CPathfinderHelper::getMovementCost(
  995. const int3 & src,
  996. const int3 & dst,
  997. const TerrainTile * ct,
  998. const TerrainTile * dt,
  999. const int remainingMovePoints,
  1000. const bool checkLast) const
  1001. {
  1002. if(src == dst) //same tile
  1003. return 0;
  1004. auto ti = getTurnInfo();
  1005. if(ct == nullptr || dt == nullptr)
  1006. {
  1007. ct = hero->cb->getTile(src);
  1008. dt = hero->cb->getTile(dst);
  1009. }
  1010. /// TODO: by the original game rules hero shouldn't be affected by terrain penalty while flying.
  1011. /// Also flying movement only has penalty when player moving over blocked tiles.
  1012. /// So if you only have base flying with 40% penalty you can still ignore terrain penalty while having zero flying penalty.
  1013. int ret = hero->getTileCost(*dt, *ct, ti);
  1014. /// Unfortunately this can't be implemented yet as server don't know when player flying and when he's not.
  1015. /// Difference in cost calculation on client and server is much worse than incorrect cost.
  1016. /// So this one is waiting till server going to use pathfinder rules for path validation.
  1017. if(dt->blocked && ti->hasBonusOfType(Bonus::FLYING_MOVEMENT))
  1018. {
  1019. ret *= (100.0 + ti->valOfBonuses(Bonus::FLYING_MOVEMENT)) / 100.0;
  1020. }
  1021. else if(dt->terType == ETerrainType::WATER)
  1022. {
  1023. if(hero->boat && ct->hasFavorableWinds() && dt->hasFavorableWinds())
  1024. ret *= 0.666;
  1025. else if(!hero->boat && ti->hasBonusOfType(Bonus::WATER_WALKING))
  1026. {
  1027. ret *= (100.0 + ti->valOfBonuses(Bonus::WATER_WALKING)) / 100.0;
  1028. }
  1029. }
  1030. if(src.x != dst.x && src.y != dst.y) //it's diagonal move
  1031. {
  1032. int old = ret;
  1033. ret *= 1.414213;
  1034. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  1035. if(ret > remainingMovePoints && remainingMovePoints >= old)
  1036. {
  1037. return remainingMovePoints;
  1038. }
  1039. }
  1040. /// TODO: This part need rework in order to work properly with flying and water walking
  1041. /// Currently it's only work properly for normal movement or sailing
  1042. int left = remainingMovePoints-ret;
  1043. if(checkLast && left > 0 && remainingMovePoints-ret < 250) //it might be the last tile - if no further move possible we take all move points
  1044. {
  1045. std::vector<int3> vec;
  1046. vec.reserve(8); //optimization
  1047. getNeighbours(*dt, dst, vec, ct->terType != ETerrainType::WATER, true);
  1048. for(auto & elem : vec)
  1049. {
  1050. int fcost = getMovementCost(dst, elem, nullptr, nullptr, left, false);
  1051. if(fcost <= left)
  1052. {
  1053. return ret;
  1054. }
  1055. }
  1056. ret = remainingMovePoints;
  1057. }
  1058. return ret;
  1059. }
  1060. int3 CGPath::startPos() const
  1061. {
  1062. return nodes[nodes.size()-1].coord;
  1063. }
  1064. int3 CGPath::endPos() const
  1065. {
  1066. return nodes[0].coord;
  1067. }
  1068. void CGPath::convert(ui8 mode)
  1069. {
  1070. if(mode==0)
  1071. {
  1072. for(auto & elem : nodes)
  1073. {
  1074. elem.coord = CGHeroInstance::convertPosition(elem.coord,true);
  1075. }
  1076. }
  1077. }
  1078. CPathsInfo::CPathsInfo(const int3 & Sizes, const CGHeroInstance * hero_)
  1079. : sizes(Sizes), hero(hero_)
  1080. {
  1081. nodes.resize(boost::extents[sizes.x][sizes.y][sizes.z][ELayer::NUM_LAYERS]);
  1082. }
  1083. CPathsInfo::~CPathsInfo() = default;
  1084. const CGPathNode * CPathsInfo::getPathInfo(const int3 & tile) const
  1085. {
  1086. assert(vstd::iswithin(tile.x, 0, sizes.x));
  1087. assert(vstd::iswithin(tile.y, 0, sizes.y));
  1088. assert(vstd::iswithin(tile.z, 0, sizes.z));
  1089. return getNode(tile);
  1090. }
  1091. bool CPathsInfo::getPath(CGPath & out, const int3 & dst) const
  1092. {
  1093. out.nodes.clear();
  1094. const CGPathNode * curnode = getNode(dst);
  1095. if(!curnode->theNodeBefore)
  1096. return false;
  1097. while(curnode)
  1098. {
  1099. const CGPathNode cpn = * curnode;
  1100. curnode = curnode->theNodeBefore;
  1101. out.nodes.push_back(cpn);
  1102. }
  1103. return true;
  1104. }
  1105. const CGPathNode * CPathsInfo::getNode(const int3 & coord) const
  1106. {
  1107. auto landNode = &nodes[coord.x][coord.y][coord.z][ELayer::LAND];
  1108. if(landNode->reachable())
  1109. return landNode;
  1110. else
  1111. return &nodes[coord.x][coord.y][coord.z][ELayer::SAIL];
  1112. }
  1113. PathNodeInfo::PathNodeInfo()
  1114. : node(nullptr), nodeObject(nullptr), tile(nullptr), coord(-1, -1, -1), guarded(false)
  1115. {
  1116. }
  1117. void PathNodeInfo::setNode(CGameState * gs, CGPathNode * n, bool excludeTopObject)
  1118. {
  1119. node = n;
  1120. if(coord != node->coord)
  1121. {
  1122. assert(node->coord.valid());
  1123. coord = node->coord;
  1124. tile = gs->getTile(coord);
  1125. nodeObject = tile->topVisitableObj(excludeTopObject);
  1126. }
  1127. guarded = false;
  1128. }
  1129. CDestinationNodeInfo::CDestinationNodeInfo()
  1130. : PathNodeInfo(),
  1131. blocked(false),
  1132. action(CGPathNode::ENodeAction::UNKNOWN)
  1133. {
  1134. }
  1135. void CDestinationNodeInfo::setNode(CGameState * gs, CGPathNode * n, bool excludeTopObject)
  1136. {
  1137. PathNodeInfo::setNode(gs, n, excludeTopObject);
  1138. blocked = false;
  1139. action = CGPathNode::ENodeAction::UNKNOWN;
  1140. }
  1141. bool CDestinationNodeInfo::isBetterWay() const
  1142. {
  1143. if(node->turns == 0xff) //we haven't been here before
  1144. return true;
  1145. else
  1146. return cost < node->cost; //this route is faster
  1147. }
  1148. bool PathNodeInfo::isNodeObjectVisitable() const
  1149. {
  1150. /// Hero can't visit objects while walking on water or flying
  1151. return canSeeObj(nodeObject) && (node->layer == EPathfindingLayer::LAND || node->layer == EPathfindingLayer::SAIL);
  1152. }