CPathfinder.cpp 19 KB

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