CPathfinder.cpp 19 KB

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