CPathfinder.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  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 "../IGameSettings.h"
  17. #include "../CPlayerState.h"
  18. #include "../TerrainHandler.h"
  19. #include "../RoadHandler.h"
  20. #include "../callback/IGameInfoCallback.h"
  21. #include "../mapObjects/CGHeroInstance.h"
  22. #include "../mapObjects/CGTownInstance.h"
  23. #include "../mapObjects/MiscObjects.h"
  24. #include "../mapping/CMap.h"
  25. #include "spells/CSpellHandler.h"
  26. VCMI_LIB_NAMESPACE_BEGIN
  27. bool CPathfinderHelper::canMoveFromNode(const PathNodeInfo & source) const
  28. {
  29. // we can always make the first step, even when standing on object
  30. if(source.node->theNodeBefore == nullptr)
  31. return true;
  32. if (!source.nodeObject)
  33. return true;
  34. if (!source.isNodeObjectVisitable())
  35. return true;
  36. // we can always move from visitable object if hero has teleported here (e.g. went through monolith)
  37. if (source.node->isTeleportAction())
  38. return true;
  39. // 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)
  40. if (dynamic_cast<const CGTeleport*>(source.nodeObject) != nullptr)
  41. return false;
  42. return true;
  43. }
  44. void CPathfinderHelper::calculateNeighbourTiles(NeighbourTilesVector & result, const PathNodeInfo & source) const
  45. {
  46. result.clear();
  47. if (!canMoveFromNode(source))
  48. return;
  49. getNeighbours(
  50. *source.tile,
  51. source.node->coord,
  52. result,
  53. boost::logic::indeterminate,
  54. source.node->layer == EPathfindingLayer::SAIL);
  55. if(source.isNodeObjectVisitable())
  56. {
  57. vstd::erase_if(result, [&](const int3 & tile) -> bool
  58. {
  59. return !canMoveBetween(tile, source.nodeObject->visitablePos());
  60. });
  61. }
  62. }
  63. CPathfinder::CPathfinder(const IGameInfoCallback & gameInfo, std::shared_ptr<PathfinderConfig> config):
  64. gameInfo(gameInfo),
  65. config(std::move(config))
  66. {
  67. initializeGraph();
  68. }
  69. void CPathfinder::push(CGPathNode * node)
  70. {
  71. if(node && !node->inPQ())
  72. {
  73. node->pq = &this->pq;
  74. auto handle = pq.push(node);
  75. node->pqHandle = handle;
  76. }
  77. }
  78. CGPathNode * CPathfinder::topAndPop()
  79. {
  80. auto * node = pq.top();
  81. pq.pop();
  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(!gameInfo.isInTheMap(initialNode->coord)/* || !gameInfo.getMap().isInTheMap(dest)*/) //check input
  94. {
  95. logGlobal->error("CgameInfo::calculatePaths: Hero outside the gameInfo.map? How dare you...");
  96. throw std::runtime_error("Wrong checksum");
  97. }
  98. source.setNode(gameInfo, initialNode);
  99. auto * hlp = config->getOrCreatePathfinderHelper(source, gameInfo);
  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(gameInfo, 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, gameInfo);
  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, gameInfo);
  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(gameInfo, neighbour);
  138. hlp = config->getOrCreatePathfinderHelper(destination, gameInfo);
  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, gameInfo);
  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, gameInfo);
  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(gameInfo, 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 : gameInfo.getTeleportChannelExits(channelID, hero->tempOwner))
  196. {
  197. const auto * obj = gameInfo.getObj(objId);
  198. if(dynamic_cast<const CGWhirlpool *>(obj))
  199. {
  200. auto pos = obj->getBlockedPos();
  201. for(const auto & p : pos)
  202. {
  203. ObjectInstanceID topObject = gameInfo.getTile(p)->topVisitableObj();
  204. if(topObject.hasValue() && gameInfo.getObj(topObject)->ID == obj->ID)
  205. allowedExits.push_back(p);
  206. }
  207. }
  208. else if(obj && CGTeleport::isExitPassable(gameInfo, hero, obj))
  209. allowedExits.push_back(obj->visitablePos());
  210. }
  211. return allowedExits;
  212. }
  213. TeleporterTilesVector CPathfinderHelper::getCastleGates(const PathNodeInfo & source) const
  214. {
  215. TeleporterTilesVector allowedExits;
  216. for(const auto & town : gameInfo.getPlayerState(hero->tempOwner)->getTowns())
  217. {
  218. if(town->id != source.nodeObject->id && town->getVisitingHero() == nullptr
  219. && town->hasBuilt(BuildingSubID::CASTLE_GATE))
  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->getFactionID() == 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 gameInfo.guardingCreaturePosition(destination.node->coord) == destination.node->coord;
  318. }
  319. void CPathfinderHelper::initializePatrol()
  320. {
  321. auto state = PATROL_NONE;
  322. if(hero->patrol.patrolling && !gameInfo.getPlayerState(hero->tempOwner)->human)
  323. {
  324. if(hero->patrol.patrolRadius)
  325. {
  326. state = PATROL_RADIUS;
  327. gameInfo.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, gameInfo);
  338. }
  339. bool CPathfinderHelper::canMoveBetween(const int3 & a, const int3 & b) const
  340. {
  341. return gameInfo.checkForVisitableDir(a, b);
  342. }
  343. bool CPathfinderHelper::isAllowedTeleportEntrance(const CGTeleport * obj) const
  344. {
  345. if(!obj || !gameInfo.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 && gameInfo.isTeleportChannelBidirectional(obj->channel, hero->tempOwner);
  360. }
  361. bool CPathfinderHelper::addTeleportOneWay(const CGTeleport * obj) const
  362. {
  363. if(options.useTeleportOneWay && gameInfo.isTeleportChannelUnidirectional(obj->channel, hero->tempOwner))
  364. {
  365. auto passableExits = CGTeleport::getPassableExits(gameInfo, hero, gameInfo.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 && gameInfo.isTeleportChannelUnidirectional(obj->channel, hero->tempOwner))
  374. {
  375. auto passableExits = CGTeleport::getPassableExits(gameInfo, hero, gameInfo.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 && (whirlpoolProtection || options.forceUseTeleportWhirlpool) && 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 gameInfo.getGuardingCreatures(tile).size();
  404. }
  405. CPathfinderHelper::CPathfinderHelper(const IGameInfoCallback & gameInfo, const CGHeroInstance * Hero, const PathfinderOptions & Options):
  406. gameInfo(gameInfo),
  407. turn(-1),
  408. owner(Hero->tempOwner),
  409. hero(Hero),
  410. options(Options)
  411. {
  412. turnsInfo.reserve(16);
  413. updateTurnInfo();
  414. initializePatrol();
  415. whirlpoolProtection = Hero->hasBonusOfType(BonusType::WHIRLPOOL_PROTECTION);
  416. SpellID flySpell = SpellID::FLY;
  417. canCastFly = Hero->canCastThisSpell(flySpell.toSpell());
  418. SpellID waterWalk = SpellID::WATER_WALK;
  419. canCastWaterWalk = Hero->canCastThisSpell(waterWalk.toSpell());
  420. }
  421. CPathfinderHelper::~CPathfinderHelper() = default;
  422. void CPathfinderHelper::updateTurnInfo(const int Turn)
  423. {
  424. if(turn != Turn)
  425. {
  426. turn = Turn;
  427. if(turn >= turnsInfo.size())
  428. turnsInfo.push_back(hero->getTurnInfo(turn));
  429. }
  430. }
  431. bool CPathfinderHelper::isLayerAvailable(const EPathfindingLayer & layer) const
  432. {
  433. switch(layer.toEnum())
  434. {
  435. case EPathfindingLayer::AIR:
  436. if(!options.useFlying)
  437. return false;
  438. if(canCastFly && options.canUseCast)
  439. return true;
  440. break;
  441. case EPathfindingLayer::WATER:
  442. if(!options.useWaterWalking)
  443. return false;
  444. if(canCastWaterWalk && options.canUseCast)
  445. return true;
  446. break;
  447. }
  448. return turnsInfo[turn]->isLayerAvailable(layer);
  449. }
  450. const TurnInfo * CPathfinderHelper::getTurnInfo() const
  451. {
  452. return turnsInfo[turn].get();
  453. }
  454. int CPathfinderHelper::getMaxMovePoints(const EPathfindingLayer & layer) const
  455. {
  456. return turnsInfo[turn]->getMaxMovePoints(layer);
  457. }
  458. void CPathfinderHelper::getNeighbours(
  459. const TerrainTile & sourceTile,
  460. const int3 & srcCoord,
  461. NeighbourTilesVector & vec,
  462. const boost::logic::tribool & onLand,
  463. const bool limitCoastSailing) const
  464. {
  465. const TerrainType * sourceTerrain = sourceTile.getTerrain();
  466. static constexpr std::array dirs = {
  467. int3(-1, +1, +0), int3(0, +1, +0), int3(+1, +1, +0),
  468. int3(-1, +0, +0), /* source pos */ int3(+1, +0, +0),
  469. int3(-1, -1, +0), int3(0, -1, +0), int3(+1, -1, +0)
  470. };
  471. for(const auto & dir : dirs)
  472. {
  473. const int3 destCoord = srcCoord + dir;
  474. if(!gameInfo.isInTheMap(destCoord))
  475. continue;
  476. const TerrainTile * destTile = gameInfo.getTile(destCoord);
  477. const TerrainType * destTerrain = destTile->getTerrain();
  478. if(!destTerrain->isPassable())
  479. continue;
  480. /// Following condition let us avoid diagonal movement over coast when sailing
  481. if(sourceTerrain->isWater() && limitCoastSailing && destTerrain->isWater() && dir.x && dir.y) //diagonal move through water
  482. {
  483. const int3 horizontalNeighbour = srcCoord + int3{dir.x, 0, 0};
  484. const int3 verticalNeighbour = srcCoord + int3{0, dir.y, 0};
  485. if(gameInfo.getTile(horizontalNeighbour)->isLand() || gameInfo.getTile(verticalNeighbour)->isLand())
  486. continue;
  487. }
  488. if(indeterminate(onLand) || onLand == destTerrain->isLand())
  489. {
  490. vec.push_back(destCoord);
  491. }
  492. }
  493. }
  494. int CPathfinderHelper::getMovementCost(
  495. const PathNodeInfo & src,
  496. const PathNodeInfo & dst,
  497. const int remainingMovePoints,
  498. const bool checkLast) const
  499. {
  500. return getMovementCost(
  501. src.coord,
  502. dst.coord,
  503. src.tile,
  504. dst.tile,
  505. remainingMovePoints,
  506. checkLast,
  507. dst.node->layer == EPathfindingLayer::SAIL,
  508. dst.node->layer == EPathfindingLayer::WATER
  509. );
  510. }
  511. int CPathfinderHelper::getMovementCost(
  512. const int3 & src,
  513. const int3 & dst,
  514. const TerrainTile * ct,
  515. const TerrainTile * dt,
  516. const int remainingMovePoints,
  517. const bool checkLast,
  518. boost::logic::tribool isDstSailLayer,
  519. boost::logic::tribool isDstWaterLayer) const
  520. {
  521. if(src == dst) //same tile
  522. return 0;
  523. const auto * ti = getTurnInfo();
  524. if(ct == nullptr || dt == nullptr)
  525. {
  526. ct = hero->cb->getTile(src);
  527. dt = hero->cb->getTile(dst);
  528. }
  529. bool isSailLayer;
  530. if(indeterminate(isDstSailLayer))
  531. isSailLayer = hero->inBoat() && hero->getBoat()->layer == EPathfindingLayer::SAIL && dt->isWater();
  532. else
  533. isSailLayer = static_cast<bool>(isDstSailLayer);
  534. bool isWaterLayer;
  535. if(indeterminate(isDstWaterLayer))
  536. isWaterLayer = ((hero->inBoat() && hero->getBoat()->layer == EPathfindingLayer::WATER) || ti->hasWaterWalking()) && dt->isWater();
  537. else
  538. isWaterLayer = static_cast<bool>(isDstWaterLayer);
  539. bool isAirLayer = (hero->inBoat() && hero->getBoat()->layer == EPathfindingLayer::AIR) || ti->hasFlyingMovement();
  540. int movementCost = getTileMovementCost(*dt, *ct, ti);
  541. if(isSailLayer)
  542. {
  543. if(ct->hasFavorableWinds())
  544. movementCost = static_cast<int>(movementCost * 2.0 / 3);
  545. }
  546. else if(isAirLayer)
  547. {
  548. int baseCost = gameInfo.getSettings().getInteger(EGameSettings::HEROES_MOVEMENT_COST_BASE);
  549. vstd::amin(movementCost, baseCost + ti->getFlyingMovementValue());
  550. }
  551. else if(isWaterLayer && ti->hasWaterWalking())
  552. movementCost = static_cast<int>(movementCost * (100.0 + ti->getWaterWalkingValue()) / 100.0);
  553. if(src.x != dst.x && src.y != dst.y) //it's diagonal move
  554. {
  555. int old = movementCost;
  556. movementCost = static_cast<int>(movementCost * M_SQRT2);
  557. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  558. // https://heroes.thelazy.net/index.php/Movement#Diagonal_move_exception
  559. if(movementCost > remainingMovePoints && remainingMovePoints >= old)
  560. {
  561. return remainingMovePoints;
  562. }
  563. }
  564. //it might be the last tile - if no further move possible we take all move points
  565. const int pointsLeft = remainingMovePoints - movementCost;
  566. if(checkLast && pointsLeft > 0)
  567. {
  568. int minimalNextMoveCost = getTileMovementCost(*dt, *ct, ti);
  569. if (pointsLeft < minimalNextMoveCost)
  570. return remainingMovePoints;
  571. }
  572. return movementCost;
  573. }
  574. ui32 CPathfinderHelper::getTileMovementCost(const TerrainTile & dest, const TerrainTile & from, const TurnInfo * ti) const
  575. {
  576. //if there is road both on dest and src tiles - use src road movement cost
  577. if(dest.hasRoad() && from.hasRoad())
  578. return from.getRoad()->movementCost;
  579. int baseMovementCost = ti->getMovementCostBase();
  580. int terrainMoveCost = from.getTerrain()->moveCost;
  581. int terrainDiscout = ti->getRoughTerrainDiscountValue();
  582. int costWithPathfinding = std::max(baseMovementCost, terrainMoveCost - terrainDiscout);
  583. //if hero can move without penalty - either all-native army, or creatures like Nomads in army
  584. if(ti->hasNoTerrainPenalty(from.getTerrainID()))
  585. {
  586. int baseCost = gameInfo.getSettings().getInteger(EGameSettings::HEROES_MOVEMENT_COST_BASE);
  587. return std::min(baseCost, costWithPathfinding);
  588. }
  589. return costWithPathfinding;
  590. }
  591. VCMI_LIB_NAMESPACE_END