CPathfinder.cpp 18 KB

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