CPathfinder.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  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. #include "spells/ISpellMechanics.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(const IGameInfoCallback & gameInfo, std::shared_ptr<PathfinderConfig> config):
  65. gameInfo(gameInfo),
  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(!gameInfo.isInTheMap(initialNode->coord)/* || !gameInfo.getMap().isInTheMap(dest)*/) //check input
  95. {
  96. logGlobal->error("CgameInfo::calculatePaths: Hero outside the gameInfo.map? How dare you...");
  97. throw std::runtime_error("Wrong checksum");
  98. }
  99. source.setNode(gameInfo, initialNode);
  100. auto * hlp = config->getOrCreatePathfinderHelper(source, gameInfo);
  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(gameInfo, 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, gameInfo);
  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, gameInfo);
  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(gameInfo, neighbour);
  139. hlp = config->getOrCreatePathfinderHelper(destination, gameInfo);
  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, gameInfo);
  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, gameInfo);
  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(gameInfo, 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 : gameInfo.getTeleportChannelExits(channelID, hero->tempOwner))
  197. {
  198. const auto * obj = gameInfo.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 = gameInfo.getTile(p)->topVisitableObj();
  205. if(topObject.hasValue() && gameInfo.getObj(topObject)->ID == obj->ID)
  206. allowedExits.push_back(p);
  207. }
  208. }
  209. else if(obj && CGTeleport::isExitPassable(gameInfo, 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 : gameInfo.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 gameInfo.guardingCreaturePosition(destination.node->coord) == destination.node->coord;
  319. }
  320. void CPathfinderHelper::initializePatrol()
  321. {
  322. auto state = PATROL_NONE;
  323. if(hero->patrol.patrolling && !gameInfo.getPlayerState(hero->tempOwner)->human)
  324. {
  325. if(hero->patrol.patrolRadius)
  326. {
  327. state = PATROL_RADIUS;
  328. gameInfo.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, gameInfo);
  339. }
  340. bool CPathfinderHelper::canMoveBetween(const int3 & a, const int3 & b) const
  341. {
  342. return gameInfo.checkForVisitableDir(a, b);
  343. }
  344. bool CPathfinderHelper::isAllowedTeleportEntrance(const CGTeleport * obj) const
  345. {
  346. if(!obj || !gameInfo.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 && gameInfo.isTeleportChannelBidirectional(obj->channel, hero->tempOwner);
  361. }
  362. bool CPathfinderHelper::addTeleportOneWay(const CGTeleport * obj) const
  363. {
  364. if(options.useTeleportOneWay && gameInfo.isTeleportChannelUnidirectional(obj->channel, hero->tempOwner))
  365. {
  366. auto passableExits = CGTeleport::getPassableExits(gameInfo, hero, gameInfo.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 && gameInfo.isTeleportChannelUnidirectional(obj->channel, hero->tempOwner))
  375. {
  376. auto passableExits = CGTeleport::getPassableExits(gameInfo, hero, gameInfo.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 gameInfo.getGuardingCreatures(tile).size();
  405. }
  406. CPathfinderHelper::CPathfinderHelper(const IGameInfoCallback & gameInfo, const CGHeroInstance * Hero, const PathfinderOptions & Options):
  407. gameInfo(gameInfo),
  408. turn(-1),
  409. owner(Hero->tempOwner),
  410. hero(Hero),
  411. options(Options),
  412. canCastFly(false),
  413. canCastWaterWalk(false)
  414. {
  415. turnsInfo.reserve(16);
  416. updateTurnInfo();
  417. initializePatrol();
  418. whirlpoolProtection = Hero->hasBonusOfType(BonusType::WHIRLPOOL_PROTECTION);
  419. if (options.canUseCast)
  420. {
  421. for (const auto & spell : LIBRARY->spellh->objects)
  422. {
  423. if (!spell || !spell->isAdventure())
  424. continue;
  425. if(spell->getAdventureMechanics().givesBonus(hero, BonusType::WATER_WALKING) && hero->canCastThisSpell(spell.get()) && hero->mana >= hero->getSpellCost(spell.get()))
  426. canCastWaterWalk = true;
  427. if(spell->getAdventureMechanics().givesBonus(hero, BonusType::FLYING_MOVEMENT) && hero->canCastThisSpell(spell.get()) && hero->mana >= hero->getSpellCost(spell.get()))
  428. canCastFly = true;
  429. }
  430. }
  431. }
  432. CPathfinderHelper::~CPathfinderHelper() = default;
  433. void CPathfinderHelper::updateTurnInfo(const int Turn)
  434. {
  435. if(turn != Turn)
  436. {
  437. turn = Turn;
  438. if(turn >= turnsInfo.size())
  439. turnsInfo.push_back(hero->getTurnInfo(turn));
  440. }
  441. }
  442. bool CPathfinderHelper::isLayerAvailable(const EPathfindingLayer & layer) const
  443. {
  444. switch(layer.toEnum())
  445. {
  446. case EPathfindingLayer::AIR:
  447. if(!options.useFlying)
  448. return false;
  449. if(canCastFly && options.canUseCast)
  450. return true;
  451. break;
  452. case EPathfindingLayer::WATER:
  453. if(!options.useWaterWalking)
  454. return false;
  455. if(canCastWaterWalk && options.canUseCast)
  456. return true;
  457. break;
  458. }
  459. return turnsInfo[turn]->isLayerAvailable(layer);
  460. }
  461. const TurnInfo * CPathfinderHelper::getTurnInfo() const
  462. {
  463. return turnsInfo[turn].get();
  464. }
  465. int CPathfinderHelper::getMaxMovePoints(const EPathfindingLayer & layer) const
  466. {
  467. return turnsInfo[turn]->getMaxMovePoints(layer);
  468. }
  469. void CPathfinderHelper::getNeighbours(
  470. const TerrainTile & sourceTile,
  471. const int3 & srcCoord,
  472. NeighbourTilesVector & vec,
  473. const boost::logic::tribool & onLand,
  474. const bool limitCoastSailing) const
  475. {
  476. const TerrainType * sourceTerrain = sourceTile.getTerrain();
  477. static constexpr std::array dirs = {
  478. int3(-1, +1, +0), int3(0, +1, +0), int3(+1, +1, +0),
  479. int3(-1, +0, +0), /* source pos */ int3(+1, +0, +0),
  480. int3(-1, -1, +0), int3(0, -1, +0), int3(+1, -1, +0)
  481. };
  482. for(const auto & dir : dirs)
  483. {
  484. const int3 destCoord = srcCoord + dir;
  485. if(!gameInfo.isInTheMap(destCoord))
  486. continue;
  487. const TerrainTile * destTile = gameInfo.getTile(destCoord);
  488. const TerrainType * destTerrain = destTile->getTerrain();
  489. if(!destTerrain->isPassable())
  490. continue;
  491. /// Following condition let us avoid diagonal movement over coast when sailing
  492. if(sourceTerrain->isWater() && limitCoastSailing && destTerrain->isWater() && dir.x && dir.y) //diagonal move through water
  493. {
  494. const int3 horizontalNeighbour = srcCoord + int3{dir.x, 0, 0};
  495. const int3 verticalNeighbour = srcCoord + int3{0, dir.y, 0};
  496. if(gameInfo.getTile(horizontalNeighbour)->isLand() || gameInfo.getTile(verticalNeighbour)->isLand())
  497. continue;
  498. }
  499. if(indeterminate(onLand) || onLand == destTerrain->isLand())
  500. {
  501. vec.push_back(destCoord);
  502. }
  503. }
  504. }
  505. int CPathfinderHelper::getMovementCost(
  506. const PathNodeInfo & src,
  507. const PathNodeInfo & dst,
  508. const int remainingMovePoints,
  509. const bool checkLast) const
  510. {
  511. return getMovementCost(
  512. src.coord,
  513. dst.coord,
  514. src.tile,
  515. dst.tile,
  516. remainingMovePoints,
  517. checkLast,
  518. dst.node->layer == EPathfindingLayer::SAIL,
  519. dst.node->layer == EPathfindingLayer::WATER
  520. );
  521. }
  522. int CPathfinderHelper::getMovementCost(
  523. const int3 & src,
  524. const int3 & dst,
  525. const TerrainTile * ct,
  526. const TerrainTile * dt,
  527. const int remainingMovePoints,
  528. const bool checkLast,
  529. boost::logic::tribool isDstSailLayer,
  530. boost::logic::tribool isDstWaterLayer) const
  531. {
  532. if(src == dst) //same tile
  533. return 0;
  534. const auto * ti = getTurnInfo();
  535. if(ct == nullptr || dt == nullptr)
  536. {
  537. ct = hero->cb->getTile(src);
  538. dt = hero->cb->getTile(dst);
  539. }
  540. bool isSailLayer;
  541. if(indeterminate(isDstSailLayer))
  542. isSailLayer = hero->inBoat() && hero->getBoat()->layer == EPathfindingLayer::SAIL && dt->isWater();
  543. else
  544. isSailLayer = static_cast<bool>(isDstSailLayer);
  545. bool isWaterLayer;
  546. if(indeterminate(isDstWaterLayer))
  547. isWaterLayer = ((hero->inBoat() && hero->getBoat()->layer == EPathfindingLayer::WATER) || ti->hasWaterWalking()) && dt->isWater();
  548. else
  549. isWaterLayer = static_cast<bool>(isDstWaterLayer);
  550. bool isAirLayer = (hero->inBoat() && hero->getBoat()->layer == EPathfindingLayer::AIR) || ti->hasFlyingMovement();
  551. int movementCost = getTileMovementCost(*dt, *ct, ti);
  552. if(isSailLayer)
  553. {
  554. if(ct->hasFavorableWinds())
  555. movementCost = static_cast<int>(movementCost * 2.0 / 3);
  556. }
  557. else if(isAirLayer)
  558. {
  559. int baseCost = gameInfo.getSettings().getInteger(EGameSettings::HEROES_MOVEMENT_COST_BASE);
  560. vstd::amin(movementCost, baseCost + ti->getFlyingMovementValue());
  561. }
  562. else if(isWaterLayer && ti->hasWaterWalking())
  563. movementCost = static_cast<int>(movementCost * (100.0 + ti->getWaterWalkingValue()) / 100.0);
  564. if(src.x != dst.x && src.y != dst.y) //it's diagonal move
  565. {
  566. int old = movementCost;
  567. movementCost = static_cast<int>(movementCost * 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(movementCost > remainingMovePoints && remainingMovePoints >= old)
  571. {
  572. return remainingMovePoints;
  573. }
  574. }
  575. //it might be the last tile - if no further move possible we take all move points
  576. const int pointsLeft = remainingMovePoints - movementCost;
  577. if(checkLast && pointsLeft > 0)
  578. {
  579. int minimalNextMoveCost = getTileMovementCost(*dt, *ct, ti);
  580. if (pointsLeft < minimalNextMoveCost)
  581. return remainingMovePoints;
  582. }
  583. return movementCost;
  584. }
  585. ui32 CPathfinderHelper::getTileMovementCost(const TerrainTile & dest, const TerrainTile & from, const TurnInfo * ti) const
  586. {
  587. //if there is road both on dest and src tiles - use src road movement cost
  588. if(dest.hasRoad() && from.hasRoad())
  589. return from.getRoad()->movementCost;
  590. int baseMovementCost = ti->getMovementCostBase();
  591. int terrainMoveCost = from.getTerrain()->moveCost;
  592. int terrainDiscout = ti->getRoughTerrainDiscountValue();
  593. int costWithPathfinding = std::max(baseMovementCost, terrainMoveCost - terrainDiscout);
  594. //if hero can move without penalty - either all-native army, or creatures like Nomads in army
  595. if(ti->hasNoTerrainPenalty(from.getTerrainID()))
  596. {
  597. int baseCost = gameInfo.getSettings().getInteger(EGameSettings::HEROES_MOVEMENT_COST_BASE);
  598. return std::min(baseCost, costWithPathfinding);
  599. }
  600. return costWithPathfinding;
  601. }
  602. VCMI_LIB_NAMESPACE_END