CPathfinder.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  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 "INodeStorage.h"
  13. #include "PathfinderOptions.h"
  14. #include "PathfindingRules.h"
  15. #include "TurnInfo.h"
  16. #include "../gameState/CGameState.h"
  17. #include "../CPlayerState.h"
  18. #include "../TerrainHandler.h"
  19. #include "../mapObjects/CGHeroInstance.h"
  20. #include "../mapping/CMap.h"
  21. #include "spells/CSpellHandler.h"
  22. VCMI_LIB_NAMESPACE_BEGIN
  23. bool CPathfinderHelper::canMoveFromNode(const PathNodeInfo & source) const
  24. {
  25. // we can always make the first step, even when standing on object
  26. if(source.node->theNodeBefore == nullptr)
  27. return true;
  28. if (!source.nodeObject)
  29. return true;
  30. if (!source.isNodeObjectVisitable())
  31. return true;
  32. // we can always move from visitable object if hero has teleported here (e.g. went through monolith)
  33. if (source.node->isTeleportAction())
  34. return true;
  35. // we can go through garrisons
  36. if (source.nodeObject->ID == MapObjectID::GARRISON || source.nodeObject->ID == MapObjectID::GARRISON2)
  37. return true;
  38. // or through border gate (if we stand on it then we already have the key)
  39. if (source.nodeObject->ID == MapObjectID::BORDER_GATE)
  40. return true;
  41. // or "through" boat, but only if this is embarking
  42. if (source.nodeObject->ID == MapObjectID::BOAT && source.node->action == EPathNodeAction::EMBARK)
  43. return true;
  44. return false;
  45. }
  46. std::vector<int3> CPathfinderHelper::getNeighbourTiles(const PathNodeInfo & source) const
  47. {
  48. std::vector<int3> neighbourTiles;
  49. if (!canMoveFromNode(source))
  50. return neighbourTiles;
  51. neighbourTiles.reserve(8);
  52. getNeighbours(
  53. *source.tile,
  54. source.node->coord,
  55. neighbourTiles,
  56. boost::logic::indeterminate,
  57. source.node->layer == EPathfindingLayer::SAIL);
  58. if(source.isNodeObjectVisitable())
  59. {
  60. vstd::erase_if(neighbourTiles, [&](const int3 & tile) -> bool
  61. {
  62. return !canMoveBetween(tile, source.nodeObject->visitablePos());
  63. });
  64. }
  65. return neighbourTiles;
  66. }
  67. CPathfinder::CPathfinder(CGameState * _gs, std::shared_ptr<PathfinderConfig> config):
  68. gamestate(_gs),
  69. config(std::move(config))
  70. {
  71. initializeGraph();
  72. }
  73. void CPathfinder::push(CGPathNode * node)
  74. {
  75. if(node && !node->inPQ)
  76. {
  77. node->inPQ = true;
  78. node->pq = &this->pq;
  79. auto handle = pq.push(node);
  80. node->pqHandle = handle;
  81. }
  82. }
  83. CGPathNode * CPathfinder::topAndPop()
  84. {
  85. auto * node = pq.top();
  86. pq.pop();
  87. node->inPQ = false;
  88. node->pq = nullptr;
  89. return node;
  90. }
  91. void CPathfinder::calculatePaths()
  92. {
  93. //logGlobal->info("Calculating paths for hero %s (adress %d) of player %d", hero->name, hero , hero->tempOwner);
  94. //initial tile - set cost on 0 and add to the queue
  95. std::vector<CGPathNode *> initialNodes = config->nodeStorage->getInitialNodes();
  96. int counter = 0;
  97. for(auto * initialNode : initialNodes)
  98. {
  99. if(!gamestate->isInTheMap(initialNode->coord)/* || !gs->map->isInTheMap(dest)*/) //check input
  100. {
  101. logGlobal->error("CGameState::calculatePaths: Hero outside the gs->map? How dare you...");
  102. throw std::runtime_error("Wrong checksum");
  103. }
  104. source.setNode(gamestate, initialNode);
  105. auto * hlp = config->getOrCreatePathfinderHelper(source, gamestate);
  106. if(hlp->isHeroPatrolLocked())
  107. continue;
  108. pq.push(initialNode);
  109. }
  110. while(!pq.empty())
  111. {
  112. counter++;
  113. auto * node = topAndPop();
  114. source.setNode(gamestate, node);
  115. source.node->locked = true;
  116. int movement = source.node->moveRemains;
  117. uint8_t turn = source.node->turns;
  118. float cost = source.node->getCost();
  119. auto * hlp = config->getOrCreatePathfinderHelper(source, gamestate);
  120. hlp->updateTurnInfo(turn);
  121. if(!movement)
  122. {
  123. hlp->updateTurnInfo(++turn);
  124. movement = hlp->getMaxMovePoints(source.node->layer);
  125. if(!hlp->passOneTurnLimitCheck(source))
  126. continue;
  127. if(turn >= hlp->options.turnLimit)
  128. continue;
  129. }
  130. source.isInitialPosition = source.nodeHero == hlp->hero;
  131. source.updateInfo(hlp, gamestate);
  132. //add accessible neighbouring nodes to the queue
  133. auto neighbourNodes = config->nodeStorage->calculateNeighbours(source, config.get(), hlp);
  134. for(CGPathNode * neighbour : neighbourNodes)
  135. {
  136. if(neighbour->locked)
  137. continue;
  138. if (source.node->theNodeBefore && source.node->theNodeBefore->coord == neighbour->coord )
  139. continue; // block U-turns
  140. if(!hlp->isLayerAvailable(neighbour->layer))
  141. continue;
  142. destination.setNode(gamestate, neighbour);
  143. hlp = config->getOrCreatePathfinderHelper(destination, gamestate);
  144. if(!hlp->isPatrolMovementAllowed(neighbour->coord))
  145. continue;
  146. /// Check transition without tile accessability rules
  147. if(source.node->layer != neighbour->layer && !isLayerTransitionPossible())
  148. continue;
  149. destination.turn = turn;
  150. destination.movementLeft = movement;
  151. destination.cost = cost;
  152. destination.updateInfo(hlp, gamestate);
  153. destination.isGuardianTile = destination.guarded && isDestinationGuardian();
  154. for(const auto & rule : config->rules)
  155. {
  156. rule->process(source, destination, config.get(), hlp);
  157. if(destination.blocked)
  158. break;
  159. }
  160. if(!destination.blocked)
  161. push(destination.node);
  162. } //neighbours loop
  163. //just add all passable teleport exits
  164. hlp = config->getOrCreatePathfinderHelper(source, gamestate);
  165. /// For now we disable teleports usage for patrol movement
  166. /// VCAI not aware about patrol and may stuck while attempt to use teleport
  167. if(hlp->patrolState == CPathfinderHelper::PATROL_RADIUS)
  168. continue;
  169. auto teleportationNodes = config->nodeStorage->calculateTeleportations(source, config.get(), hlp);
  170. for(CGPathNode * teleportNode : teleportationNodes)
  171. {
  172. if(teleportNode->locked)
  173. continue;
  174. /// TODO: We may consider use invisible exits on FoW border in future
  175. /// Useful for AI when at least one tile around exit is visible and passable
  176. /// Objects are usually visible on FoW border anyway so it's not cheating.
  177. ///
  178. /// For now it's disabled as it's will cause crashes in movement code.
  179. if(teleportNode->accessible == EPathAccessibility::BLOCKED)
  180. continue;
  181. destination.setNode(gamestate, teleportNode);
  182. destination.turn = turn;
  183. destination.movementLeft = movement;
  184. destination.cost = cost;
  185. if(destination.isBetterWay())
  186. {
  187. destination.action = getTeleportDestAction();
  188. config->nodeStorage->commit(destination, source);
  189. if(destination.node->action == EPathNodeAction::TELEPORT_NORMAL)
  190. push(destination.node);
  191. }
  192. }
  193. } //queue loop
  194. logAi->trace("CPathfinder finished with %s iterations", std::to_string(counter));
  195. }
  196. std::vector<int3> CPathfinderHelper::getAllowedTeleportChannelExits(const TeleportChannelID & channelID) const
  197. {
  198. std::vector<int3> allowedExits;
  199. for(const auto & objId : getTeleportChannelExits(channelID, hero->tempOwner))
  200. {
  201. const auto * obj = getObj(objId);
  202. if(dynamic_cast<const CGWhirlpool *>(obj))
  203. {
  204. auto pos = obj->getBlockedPos();
  205. for(const auto & p : pos)
  206. {
  207. if(gs->map->getTile(p).topVisitableId() == obj->ID)
  208. allowedExits.push_back(p);
  209. }
  210. }
  211. else if(obj && CGTeleport::isExitPassable(gs, hero, obj))
  212. allowedExits.push_back(obj->visitablePos());
  213. }
  214. return allowedExits;
  215. }
  216. std::vector<int3> CPathfinderHelper::getCastleGates(const PathNodeInfo & source) const
  217. {
  218. std::vector<int3> allowedExits;
  219. auto towns = getPlayerState(hero->tempOwner)->towns;
  220. for(const auto & town : towns)
  221. {
  222. if(town->id != source.nodeObject->id && town->visitingHero == nullptr
  223. && town->hasBuilt(BuildingID::CASTLE_GATE, ETownType::INFERNO))
  224. {
  225. allowedExits.push_back(town->visitablePos());
  226. }
  227. }
  228. return allowedExits;
  229. }
  230. std::vector<int3> CPathfinderHelper::getTeleportExits(const PathNodeInfo & source) const
  231. {
  232. std::vector<int3> teleportationExits;
  233. const auto * objTeleport = dynamic_cast<const CGTeleport *>(source.nodeObject);
  234. if(isAllowedTeleportEntrance(objTeleport))
  235. {
  236. for(const auto & exit : getAllowedTeleportChannelExits(objTeleport->channel))
  237. {
  238. teleportationExits.push_back(exit);
  239. }
  240. }
  241. else if(options.useCastleGate && source.nodeObject->ID == Obj::TOWN && source.objectRelations != PlayerRelations::ENEMIES)
  242. {
  243. auto * town = dynamic_cast<const CGTownInstance *>(source.nodeObject);
  244. assert(town);
  245. if (town && town->getFaction() == FactionID::INFERNO)
  246. {
  247. /// TODO: Find way to reuse CPlayerSpecificInfoCallback::getTownsInfo
  248. /// This may be handy if we allow to use teleportation to friendly towns
  249. for(const auto & exit : getCastleGates(source))
  250. {
  251. teleportationExits.push_back(exit);
  252. }
  253. }
  254. }
  255. return teleportationExits;
  256. }
  257. bool CPathfinderHelper::isHeroPatrolLocked() const
  258. {
  259. return patrolState == PATROL_LOCKED;
  260. }
  261. bool CPathfinderHelper::isPatrolMovementAllowed(const int3 & dst) const
  262. {
  263. if(patrolState == PATROL_RADIUS)
  264. {
  265. if(!vstd::contains(patrolTiles, dst))
  266. return false;
  267. }
  268. return true;
  269. }
  270. bool CPathfinder::isLayerTransitionPossible() const
  271. {
  272. ELayer destLayer = destination.node->layer;
  273. /// No layer transition allowed when previous node action is BATTLE
  274. if(source.node->action == EPathNodeAction::BATTLE)
  275. return false;
  276. switch(source.node->layer.toEnum())
  277. {
  278. case ELayer::LAND:
  279. if(destLayer == ELayer::AIR)
  280. {
  281. if(!config->options.lightweightFlyingMode || source.isInitialPosition)
  282. return true;
  283. }
  284. else if(destLayer == ELayer::SAIL)
  285. {
  286. if(destination.tile->isWater())
  287. return true;
  288. }
  289. else
  290. return true;
  291. break;
  292. case ELayer::SAIL:
  293. if(destLayer == ELayer::LAND && !destination.tile->isWater())
  294. return true;
  295. break;
  296. case ELayer::AIR:
  297. if(destLayer == ELayer::LAND)
  298. return true;
  299. break;
  300. case ELayer::WATER:
  301. if(destLayer == ELayer::LAND)
  302. return true;
  303. break;
  304. }
  305. return false;
  306. }
  307. EPathNodeAction CPathfinder::getTeleportDestAction() const
  308. {
  309. EPathNodeAction action = EPathNodeAction::TELEPORT_NORMAL;
  310. if(destination.isNodeObjectVisitable() && destination.nodeHero)
  311. {
  312. if(destination.heroRelations == PlayerRelations::ENEMIES)
  313. action = EPathNodeAction::TELEPORT_BATTLE;
  314. else
  315. action = EPathNodeAction::TELEPORT_BLOCKING_VISIT;
  316. }
  317. return action;
  318. }
  319. bool CPathfinder::isDestinationGuardian() const
  320. {
  321. return gamestate->guardingCreaturePosition(destination.node->coord) == destination.node->coord;
  322. }
  323. void CPathfinderHelper::initializePatrol()
  324. {
  325. auto state = PATROL_NONE;
  326. if(hero->patrol.patrolling && !getPlayerState(hero->tempOwner)->human)
  327. {
  328. if(hero->patrol.patrolRadius)
  329. {
  330. state = PATROL_RADIUS;
  331. gs->getTilesInRange(patrolTiles, hero->patrol.initialPos, hero->patrol.patrolRadius, ETileVisibility::REVEALED, std::optional<PlayerColor>(), int3::DIST_MANHATTAN);
  332. }
  333. else
  334. state = PATROL_LOCKED;
  335. }
  336. patrolState = state;
  337. }
  338. void CPathfinder::initializeGraph()
  339. {
  340. INodeStorage * nodeStorage = config->nodeStorage.get();
  341. nodeStorage->initialize(config->options, gamestate);
  342. }
  343. bool CPathfinderHelper::canMoveBetween(const int3 & a, const int3 & b) const
  344. {
  345. return gs->checkForVisitableDir(a, b);
  346. }
  347. bool CPathfinderHelper::isAllowedTeleportEntrance(const CGTeleport * obj) const
  348. {
  349. if(!obj || !isTeleportEntrancePassable(obj, hero->tempOwner))
  350. return false;
  351. const auto * whirlpool = dynamic_cast<const CGWhirlpool *>(obj);
  352. if(whirlpool)
  353. {
  354. if(addTeleportWhirlpool(whirlpool))
  355. return true;
  356. }
  357. else if(addTeleportTwoWay(obj) || addTeleportOneWay(obj) || addTeleportOneWayRandom(obj))
  358. return true;
  359. return false;
  360. }
  361. bool CPathfinderHelper::addTeleportTwoWay(const CGTeleport * obj) const
  362. {
  363. return options.useTeleportTwoWay && isTeleportChannelBidirectional(obj->channel, hero->tempOwner);
  364. }
  365. bool CPathfinderHelper::addTeleportOneWay(const CGTeleport * obj) const
  366. {
  367. if(options.useTeleportOneWay && isTeleportChannelUnidirectional(obj->channel, hero->tempOwner))
  368. {
  369. auto passableExits = CGTeleport::getPassableExits(gs, hero, getTeleportChannelExits(obj->channel, hero->tempOwner));
  370. if(passableExits.size() == 1)
  371. return true;
  372. }
  373. return false;
  374. }
  375. bool CPathfinderHelper::addTeleportOneWayRandom(const CGTeleport * obj) const
  376. {
  377. if(options.useTeleportOneWayRandom && isTeleportChannelUnidirectional(obj->channel, hero->tempOwner))
  378. {
  379. auto passableExits = CGTeleport::getPassableExits(gs, hero, getTeleportChannelExits(obj->channel, hero->tempOwner));
  380. if(passableExits.size() > 1)
  381. return true;
  382. }
  383. return false;
  384. }
  385. bool CPathfinderHelper::addTeleportWhirlpool(const CGWhirlpool * obj) const
  386. {
  387. return options.useTeleportWhirlpool && hasBonusOfType(BonusType::WHIRLPOOL_PROTECTION) && obj;
  388. }
  389. int CPathfinderHelper::movementPointsAfterEmbark(int movement, int basicCost, bool disembark) const
  390. {
  391. return hero->movementPointsAfterEmbark(movement, basicCost, disembark, getTurnInfo());
  392. }
  393. bool CPathfinderHelper::passOneTurnLimitCheck(const PathNodeInfo & source) const
  394. {
  395. if(!options.oneTurnSpecialLayersLimit)
  396. return true;
  397. if(source.node->layer == EPathfindingLayer::WATER)
  398. return false;
  399. if(source.node->layer == EPathfindingLayer::AIR)
  400. {
  401. return options.originalMovementRules && source.node->accessible == EPathAccessibility::ACCESSIBLE;
  402. }
  403. return true;
  404. }
  405. int CPathfinderHelper::getGuardiansCount(int3 tile) const
  406. {
  407. return getGuardingCreatures(tile).size();
  408. }
  409. CPathfinderHelper::CPathfinderHelper(CGameState * gs, const CGHeroInstance * Hero, const PathfinderOptions & Options):
  410. CGameInfoCallback(gs),
  411. turn(-1),
  412. hero(Hero),
  413. options(Options),
  414. owner(Hero->tempOwner)
  415. {
  416. turnsInfo.reserve(16);
  417. updateTurnInfo();
  418. initializePatrol();
  419. SpellID flySpell = SpellID::FLY;
  420. canCastFly = Hero->canCastThisSpell(flySpell.toSpell());
  421. SpellID waterWalk = SpellID::WATER_WALK;
  422. canCastWaterWalk = Hero->canCastThisSpell(waterWalk.toSpell());
  423. }
  424. CPathfinderHelper::~CPathfinderHelper()
  425. {
  426. for(auto * ti : turnsInfo)
  427. delete ti;
  428. }
  429. void CPathfinderHelper::updateTurnInfo(const int Turn)
  430. {
  431. if(turn != Turn)
  432. {
  433. turn = Turn;
  434. if(turn >= turnsInfo.size())
  435. {
  436. auto * ti = new TurnInfo(hero, turn);
  437. turnsInfo.push_back(ti);
  438. }
  439. }
  440. }
  441. bool CPathfinderHelper::isLayerAvailable(const EPathfindingLayer & layer) const
  442. {
  443. switch(layer.toEnum())
  444. {
  445. case EPathfindingLayer::AIR:
  446. if(!options.useFlying)
  447. return false;
  448. if(canCastFly && options.canUseCast)
  449. return true;
  450. break;
  451. case EPathfindingLayer::WATER:
  452. if(!options.useWaterWalking)
  453. return false;
  454. if(canCastWaterWalk && options.canUseCast)
  455. return true;
  456. break;
  457. }
  458. return turnsInfo[turn]->isLayerAvailable(layer);
  459. }
  460. const TurnInfo * CPathfinderHelper::getTurnInfo() const
  461. {
  462. return turnsInfo[turn];
  463. }
  464. bool CPathfinderHelper::hasBonusOfType(const BonusType type) const
  465. {
  466. return turnsInfo[turn]->hasBonusOfType(type);
  467. }
  468. int CPathfinderHelper::getMaxMovePoints(const EPathfindingLayer & layer) const
  469. {
  470. return turnsInfo[turn]->getMaxMovePoints(layer);
  471. }
  472. void CPathfinderHelper::getNeighbours(
  473. const TerrainTile & srcTile,
  474. const int3 & srcCoord,
  475. std::vector<int3> & vec,
  476. const boost::logic::tribool & onLand,
  477. const bool limitCoastSailing) const
  478. {
  479. CMap * map = gs->map;
  480. static const int3 dirs[] = {
  481. int3(-1, +1, +0), int3(0, +1, +0), int3(+1, +1, +0),
  482. int3(-1, +0, +0), /* source pos */ int3(+1, +0, +0),
  483. int3(-1, -1, +0), int3(0, -1, +0), int3(+1, -1, +0)
  484. };
  485. for(const auto & dir : dirs)
  486. {
  487. const int3 destCoord = srcCoord + dir;
  488. if(!map->isInTheMap(destCoord))
  489. continue;
  490. const TerrainTile & destTile = map->getTile(destCoord);
  491. if(!destTile.terType->isPassable())
  492. continue;
  493. // //we cannot visit things from blocked tiles
  494. // if(srcTile.blocked && !srcTile.visitable && destTile.visitable && srcTile.blockingObjects.front()->ID != HEROI_TYPE)
  495. // {
  496. // continue;
  497. // }
  498. /// Following condition let us avoid diagonal movement over coast when sailing
  499. if(srcTile.terType->isWater() && limitCoastSailing && destTile.terType->isWater() && dir.x && dir.y) //diagonal move through water
  500. {
  501. const int3 horizontalNeighbour = srcCoord + int3{dir.x, 0, 0};
  502. const int3 verticalNeighbour = srcCoord + int3{0, dir.y, 0};
  503. if(map->getTile(horizontalNeighbour).terType->isLand() || map->getTile(verticalNeighbour).terType->isLand())
  504. continue;
  505. }
  506. if(indeterminate(onLand) || onLand == destTile.terType->isLand())
  507. {
  508. vec.push_back(destCoord);
  509. }
  510. }
  511. }
  512. int CPathfinderHelper::getMovementCost(
  513. const PathNodeInfo & src,
  514. const PathNodeInfo & dst,
  515. const int remainingMovePoints,
  516. const bool checkLast) const
  517. {
  518. return getMovementCost(
  519. src.coord,
  520. dst.coord,
  521. src.tile,
  522. dst.tile,
  523. remainingMovePoints,
  524. checkLast,
  525. dst.node->layer == EPathfindingLayer::SAIL,
  526. dst.node->layer == EPathfindingLayer::WATER
  527. );
  528. }
  529. int CPathfinderHelper::getMovementCost(
  530. const int3 & src,
  531. const int3 & dst,
  532. const TerrainTile * ct,
  533. const TerrainTile * dt,
  534. const int remainingMovePoints,
  535. const bool checkLast,
  536. boost::logic::tribool isDstSailLayer,
  537. boost::logic::tribool isDstWaterLayer) const
  538. {
  539. if(src == dst) //same tile
  540. return 0;
  541. const auto * ti = getTurnInfo();
  542. if(ct == nullptr || dt == nullptr)
  543. {
  544. ct = hero->cb->getTile(src);
  545. dt = hero->cb->getTile(dst);
  546. }
  547. bool isSailLayer;
  548. if(indeterminate(isDstSailLayer))
  549. isSailLayer = hero->boat && hero->boat->layer == EPathfindingLayer::SAIL && dt->terType->isWater();
  550. else
  551. isSailLayer = static_cast<bool>(isDstSailLayer);
  552. bool isWaterLayer;
  553. if(indeterminate(isDstWaterLayer))
  554. isWaterLayer = ((hero->boat && hero->boat->layer == EPathfindingLayer::WATER) || ti->hasBonusOfType(BonusType::WATER_WALKING)) && dt->terType->isWater();
  555. else
  556. isWaterLayer = static_cast<bool>(isDstWaterLayer);
  557. bool isAirLayer = (hero->boat && hero->boat->layer == EPathfindingLayer::AIR) || ti->hasBonusOfType(BonusType::FLYING_MOVEMENT);
  558. int ret = hero->getTileMovementCost(*dt, *ct, ti);
  559. if(isSailLayer)
  560. {
  561. if(ct->hasFavorableWinds())
  562. ret = static_cast<int>(ret * 2.0 / 3);
  563. }
  564. else if(isAirLayer)
  565. vstd::amin(ret, GameConstants::BASE_MOVEMENT_COST + ti->valOfBonuses(BonusType::FLYING_MOVEMENT));
  566. else if(isWaterLayer && ti->hasBonusOfType(BonusType::WATER_WALKING))
  567. ret = static_cast<int>(ret * (100.0 + ti->valOfBonuses(BonusType::WATER_WALKING)) / 100.0);
  568. if(src.x != dst.x && src.y != dst.y) //it's diagonal move
  569. {
  570. int old = ret;
  571. ret = static_cast<int>(ret * M_SQRT2);
  572. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  573. // https://heroes.thelazy.net/index.php/Movement#Diagonal_move_exception
  574. if(ret > remainingMovePoints && remainingMovePoints >= old)
  575. {
  576. return remainingMovePoints;
  577. }
  578. }
  579. const int left = remainingMovePoints - ret;
  580. constexpr auto maxCostOfOneStep = static_cast<int>(175 * M_SQRT2); // diagonal move on Swamp - 247 MP
  581. if(checkLast && left > 0 && left <= maxCostOfOneStep) //it might be the last tile - if no further move possible we take all move points
  582. {
  583. std::vector<int3> vec;
  584. vec.reserve(8); //optimization
  585. getNeighbours(*dt, dst, vec, ct->terType->isLand(), true);
  586. for(const auto & elem : vec)
  587. {
  588. int fcost = getMovementCost(dst, elem, nullptr, nullptr, left, false);
  589. if(fcost <= left)
  590. {
  591. return ret;
  592. }
  593. }
  594. ret = remainingMovePoints;
  595. }
  596. return ret;
  597. }
  598. VCMI_LIB_NAMESPACE_END