CPathfinder.cpp 19 KB

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