CPathfinder.cpp 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421
  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 "CHeroHandler.h"
  13. #include "mapping/CMap.h"
  14. #include "CGameState.h"
  15. #include "mapObjects/CGHeroInstance.h"
  16. #include "GameConstants.h"
  17. #include "CStopWatch.h"
  18. #include "CConfigHandler.h"
  19. #include "CPlayerState.h"
  20. #include "PathfinderUtil.h"
  21. bool canSeeObj(const CGObjectInstance * obj)
  22. {
  23. /// Pathfinder should ignore placed events
  24. return obj != nullptr && obj->ID != Obj::EVENT;
  25. }
  26. void NodeStorage::initialize(const PathfinderOptions & options, const CGameState * gs)
  27. {
  28. //TODO: fix this code duplication with AINodeStorage::initialize, problem is to keep `resetTile` inline
  29. int3 pos;
  30. const PlayerColor player = out.hero->tempOwner;
  31. const int3 sizes = gs->getMapSize();
  32. const auto & fow = static_cast<const CGameInfoCallback *>(gs)->getPlayerTeam(player)->fogOfWarMap;
  33. //make 200% sure that these are loop invariants (also a bit shorter code), let compiler do the rest(loop unswitching)
  34. const bool useFlying = options.useFlying;
  35. const bool useWaterWalking = options.useWaterWalking;
  36. for(pos.x=0; pos.x < sizes.x; ++pos.x)
  37. {
  38. for(pos.y=0; pos.y < sizes.y; ++pos.y)
  39. {
  40. for(pos.z=0; pos.z < sizes.z; ++pos.z)
  41. {
  42. const TerrainTile * tile = &gs->map->getTile(pos);
  43. if(tile->terType.isWater())
  44. {
  45. resetTile(pos, ELayer::SAIL, PathfinderUtil::evaluateAccessibility<ELayer::SAIL>(pos, tile, fow, player, gs));
  46. if(useFlying)
  47. resetTile(pos, ELayer::AIR, PathfinderUtil::evaluateAccessibility<ELayer::AIR>(pos, tile, fow, player, gs));
  48. if(useWaterWalking)
  49. resetTile(pos, ELayer::WATER, PathfinderUtil::evaluateAccessibility<ELayer::WATER>(pos, tile, fow, player, gs));
  50. }
  51. if(tile->terType.isLand())
  52. {
  53. resetTile(pos, ELayer::LAND, PathfinderUtil::evaluateAccessibility<ELayer::LAND>(pos, tile, fow, player, gs));
  54. if(useFlying)
  55. resetTile(pos, ELayer::AIR, PathfinderUtil::evaluateAccessibility<ELayer::AIR>(pos, tile, fow, player, gs));
  56. }
  57. }
  58. }
  59. }
  60. }
  61. std::vector<CGPathNode *> NodeStorage::calculateNeighbours(
  62. const PathNodeInfo & source,
  63. const PathfinderConfig * pathfinderConfig,
  64. const CPathfinderHelper * pathfinderHelper)
  65. {
  66. std::vector<CGPathNode *> neighbours;
  67. neighbours.reserve(16);
  68. auto accessibleNeighbourTiles = pathfinderHelper->getNeighbourTiles(source);
  69. for(auto & neighbour : accessibleNeighbourTiles)
  70. {
  71. for(EPathfindingLayer i = EPathfindingLayer::LAND; i <= EPathfindingLayer::AIR; i.advance(1))
  72. {
  73. auto node = getNode(neighbour, i);
  74. if(node->accessible == CGPathNode::NOT_SET)
  75. continue;
  76. neighbours.push_back(node);
  77. }
  78. }
  79. return neighbours;
  80. }
  81. std::vector<CGPathNode *> NodeStorage::calculateTeleportations(
  82. const PathNodeInfo & source,
  83. const PathfinderConfig * pathfinderConfig,
  84. const CPathfinderHelper * pathfinderHelper)
  85. {
  86. std::vector<CGPathNode *> neighbours;
  87. if(!source.isNodeObjectVisitable())
  88. return neighbours;
  89. auto accessibleExits = pathfinderHelper->getTeleportExits(source);
  90. for(auto & neighbour : accessibleExits)
  91. {
  92. auto node = getNode(neighbour, source.node->layer);
  93. neighbours.push_back(node);
  94. }
  95. return neighbours;
  96. }
  97. std::vector<int3> CPathfinderHelper::getNeighbourTiles(const PathNodeInfo & source) const
  98. {
  99. std::vector<int3> neighbourTiles;
  100. neighbourTiles.reserve(16);
  101. getNeighbours(
  102. *source.tile,
  103. source.node->coord,
  104. neighbourTiles,
  105. boost::logic::indeterminate,
  106. source.node->layer == EPathfindingLayer::SAIL);
  107. if(source.isNodeObjectVisitable())
  108. {
  109. vstd::erase_if(neighbourTiles, [&](int3 tile) -> bool
  110. {
  111. return !canMoveBetween(tile, source.nodeObject->visitablePos());
  112. });
  113. }
  114. return neighbourTiles;
  115. }
  116. NodeStorage::NodeStorage(CPathsInfo & pathsInfo, const CGHeroInstance * hero)
  117. :out(pathsInfo)
  118. {
  119. out.hero = hero;
  120. out.hpos = hero->getPosition(false);
  121. }
  122. void NodeStorage::resetTile(
  123. const int3 & tile,
  124. EPathfindingLayer layer,
  125. CGPathNode::EAccessibility accessibility)
  126. {
  127. getNode(tile, layer)->update(tile, layer, accessibility);
  128. }
  129. std::vector<CGPathNode *> NodeStorage::getInitialNodes()
  130. {
  131. auto initialNode = getNode(out.hpos, out.hero->boat ? EPathfindingLayer::SAIL : EPathfindingLayer::LAND);
  132. initialNode->turns = 0;
  133. initialNode->moveRemains = out.hero->movement;
  134. initialNode->setCost(0.0);
  135. if(!initialNode->coord.valid())
  136. {
  137. initialNode->coord = out.hpos;
  138. }
  139. return std::vector<CGPathNode *> { initialNode };
  140. }
  141. void NodeStorage::commit(CDestinationNodeInfo & destination, const PathNodeInfo & source)
  142. {
  143. assert(destination.node != source.node->theNodeBefore); //two tiles can't point to each other
  144. destination.node->setCost(destination.cost);
  145. destination.node->moveRemains = destination.movementLeft;
  146. destination.node->turns = destination.turn;
  147. destination.node->theNodeBefore = source.node;
  148. destination.node->action = destination.action;
  149. }
  150. PathfinderOptions::PathfinderOptions()
  151. {
  152. useFlying = settings["pathfinder"]["layers"]["flying"].Bool();
  153. useWaterWalking = settings["pathfinder"]["layers"]["waterWalking"].Bool();
  154. useEmbarkAndDisembark = settings["pathfinder"]["layers"]["sailing"].Bool();
  155. useTeleportTwoWay = settings["pathfinder"]["teleports"]["twoWay"].Bool();
  156. useTeleportOneWay = settings["pathfinder"]["teleports"]["oneWay"].Bool();
  157. useTeleportOneWayRandom = settings["pathfinder"]["teleports"]["oneWayRandom"].Bool();
  158. useTeleportWhirlpool = settings["pathfinder"]["teleports"]["whirlpool"].Bool();
  159. useCastleGate = settings["pathfinder"]["teleports"]["castleGate"].Bool();
  160. lightweightFlyingMode = settings["pathfinder"]["lightweightFlyingMode"].Bool();
  161. oneTurnSpecialLayersLimit = settings["pathfinder"]["oneTurnSpecialLayersLimit"].Bool();
  162. originalMovementRules = settings["pathfinder"]["originalMovementRules"].Bool();
  163. }
  164. void MovementCostRule::process(
  165. const PathNodeInfo & source,
  166. CDestinationNodeInfo & destination,
  167. const PathfinderConfig * pathfinderConfig,
  168. CPathfinderHelper * pathfinderHelper) const
  169. {
  170. float costAtNextTile = destination.cost;
  171. int turnAtNextTile = destination.turn;
  172. int moveAtNextTile = destination.movementLeft;
  173. int cost = pathfinderHelper->getMovementCost(source, destination, moveAtNextTile);
  174. int remains = moveAtNextTile - cost;
  175. int sourceLayerMaxMovePoints = pathfinderHelper->getMaxMovePoints(source.node->layer);
  176. if(remains < 0)
  177. {
  178. //occurs rarely, when hero with low movepoints tries to leave the road
  179. costAtNextTile += static_cast<float>(moveAtNextTile) / sourceLayerMaxMovePoints;//we spent all points of current turn
  180. pathfinderHelper->updateTurnInfo(++turnAtNextTile);
  181. int destinationLayerMaxMovePoints = pathfinderHelper->getMaxMovePoints(destination.node->layer);
  182. moveAtNextTile = destinationLayerMaxMovePoints;
  183. cost = pathfinderHelper->getMovementCost(source, destination, moveAtNextTile); //cost must be updated, movement points changed :(
  184. remains = moveAtNextTile - cost;
  185. }
  186. if(destination.action == CGPathNode::EMBARK || destination.action == CGPathNode::DISEMBARK)
  187. {
  188. /// FREE_SHIP_BOARDING bonus only remove additional penalty
  189. /// land <-> sail transition still cost movement points as normal movement
  190. remains = pathfinderHelper->movementPointsAfterEmbark(moveAtNextTile, cost, (destination.action == CGPathNode::DISEMBARK));
  191. cost = moveAtNextTile - remains;
  192. }
  193. costAtNextTile += static_cast<float>(cost) / sourceLayerMaxMovePoints;
  194. destination.cost = costAtNextTile;
  195. destination.turn = turnAtNextTile;
  196. destination.movementLeft = remains;
  197. if(destination.isBetterWay() &&
  198. ((source.node->turns == turnAtNextTile && remains) || pathfinderHelper->passOneTurnLimitCheck(source)))
  199. {
  200. pathfinderConfig->nodeStorage->commit(destination, source);
  201. return;
  202. }
  203. destination.blocked = true;
  204. }
  205. PathfinderConfig::PathfinderConfig(
  206. std::shared_ptr<INodeStorage> nodeStorage,
  207. std::vector<std::shared_ptr<IPathfindingRule>> rules)
  208. : nodeStorage(nodeStorage), rules(rules), options()
  209. {
  210. }
  211. CPathfinder::CPathfinder(
  212. CPathsInfo & _out,
  213. CGameState * _gs,
  214. const CGHeroInstance * _hero)
  215. : CPathfinder(
  216. _gs,
  217. std::make_shared<SingleHeroPathfinderConfig>(_out, _gs, _hero))
  218. {
  219. }
  220. std::vector<std::shared_ptr<IPathfindingRule>> SingleHeroPathfinderConfig::buildRuleSet()
  221. {
  222. return std::vector<std::shared_ptr<IPathfindingRule>>{
  223. std::make_shared<LayerTransitionRule>(),
  224. std::make_shared<DestinationActionRule>(),
  225. std::make_shared<MovementToDestinationRule>(),
  226. std::make_shared<MovementCostRule>(),
  227. std::make_shared<MovementAfterDestinationRule>()
  228. };
  229. }
  230. SingleHeroPathfinderConfig::SingleHeroPathfinderConfig(CPathsInfo & out, CGameState * gs, const CGHeroInstance * hero)
  231. : PathfinderConfig(std::make_shared<NodeStorage>(out, hero), buildRuleSet())
  232. {
  233. pathfinderHelper.reset(new CPathfinderHelper(gs, hero, options));
  234. }
  235. CPathfinderHelper * SingleHeroPathfinderConfig::getOrCreatePathfinderHelper(const PathNodeInfo & source, CGameState * gs)
  236. {
  237. return pathfinderHelper.get();
  238. }
  239. CPathfinder::CPathfinder(
  240. CGameState * _gs,
  241. std::shared_ptr<PathfinderConfig> config)
  242. : CGameInfoCallback(_gs, boost::optional<PlayerColor>())
  243. , config(config)
  244. , source()
  245. , destination()
  246. {
  247. initializeGraph();
  248. }
  249. void CPathfinder::push(CGPathNode * node)
  250. {
  251. if(node && !node->inPQ)
  252. {
  253. node->inPQ = true;
  254. node->pq = &this->pq;
  255. auto handle = pq.push(node);
  256. node->pqHandle = handle;
  257. }
  258. }
  259. CGPathNode * CPathfinder::topAndPop()
  260. {
  261. auto node = pq.top();
  262. pq.pop();
  263. node->inPQ = false;
  264. node->pq = nullptr;
  265. return node;
  266. }
  267. void CPathfinder::calculatePaths()
  268. {
  269. //logGlobal->info("Calculating paths for hero %s (adress %d) of player %d", hero->name, hero , hero->tempOwner);
  270. //initial tile - set cost on 0 and add to the queue
  271. std::vector<CGPathNode *> initialNodes = config->nodeStorage->getInitialNodes();
  272. int counter = 0;
  273. for(auto initialNode : initialNodes)
  274. {
  275. if(!isInTheMap(initialNode->coord)/* || !gs->map->isInTheMap(dest)*/) //check input
  276. {
  277. logGlobal->error("CGameState::calculatePaths: Hero outside the gs->map? How dare you...");
  278. throw std::runtime_error("Wrong checksum");
  279. }
  280. source.setNode(gs, initialNode);
  281. auto hlp = config->getOrCreatePathfinderHelper(source, gs);
  282. if(hlp->isHeroPatrolLocked())
  283. break;
  284. pq.push(initialNode);
  285. }
  286. while(!pq.empty())
  287. {
  288. counter++;
  289. auto node = topAndPop();
  290. source.setNode(gs, node);
  291. source.node->locked = true;
  292. int movement = source.node->moveRemains;
  293. uint8_t turn = source.node->turns;
  294. float cost = source.node->getCost();
  295. auto hlp = config->getOrCreatePathfinderHelper(source, gs);
  296. hlp->updateTurnInfo(turn);
  297. if(!movement)
  298. {
  299. hlp->updateTurnInfo(++turn);
  300. movement = hlp->getMaxMovePoints(source.node->layer);
  301. if(!hlp->passOneTurnLimitCheck(source))
  302. continue;
  303. }
  304. source.isInitialPosition = source.nodeHero == hlp->hero;
  305. source.updateInfo(hlp, gs);
  306. //add accessible neighbouring nodes to the queue
  307. auto neighbourNodes = config->nodeStorage->calculateNeighbours(source, config.get(), hlp);
  308. for(CGPathNode * neighbour : neighbourNodes)
  309. {
  310. if(neighbour->locked)
  311. continue;
  312. if(!hlp->isLayerAvailable(neighbour->layer))
  313. continue;
  314. destination.setNode(gs, neighbour);
  315. hlp = config->getOrCreatePathfinderHelper(destination, gs);
  316. if(!hlp->isPatrolMovementAllowed(neighbour->coord))
  317. continue;
  318. /// Check transition without tile accessability rules
  319. if(source.node->layer != neighbour->layer && !isLayerTransitionPossible())
  320. continue;
  321. destination.turn = turn;
  322. destination.movementLeft = movement;
  323. destination.cost = cost;
  324. destination.updateInfo(hlp, gs);
  325. destination.isGuardianTile = destination.guarded && isDestinationGuardian();
  326. for(auto rule : config->rules)
  327. {
  328. rule->process(source, destination, config.get(), hlp);
  329. if(destination.blocked)
  330. break;
  331. }
  332. if(!destination.blocked)
  333. push(destination.node);
  334. } //neighbours loop
  335. //just add all passable teleport exits
  336. hlp = config->getOrCreatePathfinderHelper(source, gs);
  337. /// For now we disable teleports usage for patrol movement
  338. /// VCAI not aware about patrol and may stuck while attempt to use teleport
  339. if(hlp->patrolState == CPathfinderHelper::PATROL_RADIUS)
  340. continue;
  341. auto teleportationNodes = config->nodeStorage->calculateTeleportations(source, config.get(), hlp);
  342. for(CGPathNode * teleportNode : teleportationNodes)
  343. {
  344. if(teleportNode->locked)
  345. continue;
  346. /// TODO: We may consider use invisible exits on FoW border in future
  347. /// Useful for AI when at least one tile around exit is visible and passable
  348. /// Objects are usually visible on FoW border anyway so it's not cheating.
  349. ///
  350. /// For now it's disabled as it's will cause crashes in movement code.
  351. if(teleportNode->accessible == CGPathNode::BLOCKED)
  352. continue;
  353. destination.setNode(gs, teleportNode);
  354. destination.turn = turn;
  355. destination.movementLeft = movement;
  356. destination.cost = cost;
  357. if(destination.isBetterWay())
  358. {
  359. destination.action = getTeleportDestAction();
  360. config->nodeStorage->commit(destination, source);
  361. if(destination.node->action == CGPathNode::TELEPORT_NORMAL)
  362. push(destination.node);
  363. }
  364. }
  365. } //queue loop
  366. logAi->trace("CPathfinder finished with %s iterations", std::to_string(counter));
  367. }
  368. std::vector<int3> CPathfinderHelper::getAllowedTeleportChannelExits(TeleportChannelID channelID) const
  369. {
  370. std::vector<int3> allowedExits;
  371. for(auto objId : getTeleportChannelExits(channelID, hero->tempOwner))
  372. {
  373. auto obj = getObj(objId);
  374. if(dynamic_cast<const CGWhirlpool *>(obj))
  375. {
  376. auto pos = obj->getBlockedPos();
  377. for(auto p : pos)
  378. {
  379. if(gs->map->getTile(p).topVisitableId() == obj->ID)
  380. allowedExits.push_back(p);
  381. }
  382. }
  383. else if(CGTeleport::isExitPassable(gs, hero, obj))
  384. allowedExits.push_back(obj->visitablePos());
  385. }
  386. return allowedExits;
  387. }
  388. std::vector<int3> CPathfinderHelper::getCastleGates(const PathNodeInfo & source) const
  389. {
  390. std::vector<int3> allowedExits;
  391. auto towns = getPlayerState(hero->tempOwner)->towns;
  392. for(const auto & town : towns)
  393. {
  394. if(town->id != source.nodeObject->id && town->visitingHero == nullptr
  395. && town->hasBuilt(BuildingID::CASTLE_GATE, ETownType::INFERNO))
  396. {
  397. allowedExits.push_back(town->visitablePos());
  398. }
  399. }
  400. return allowedExits;
  401. }
  402. std::vector<int3> CPathfinderHelper::getTeleportExits(const PathNodeInfo & source) const
  403. {
  404. std::vector<int3> teleportationExits;
  405. const CGTeleport * objTeleport = dynamic_cast<const CGTeleport *>(source.nodeObject);
  406. if(isAllowedTeleportEntrance(objTeleport))
  407. {
  408. for(auto exit : getAllowedTeleportChannelExits(objTeleport->channel))
  409. {
  410. teleportationExits.push_back(exit);
  411. }
  412. }
  413. else if(options.useCastleGate
  414. && (source.nodeObject->ID == Obj::TOWN && source.nodeObject->subID == ETownType::INFERNO
  415. && source.objectRelations != PlayerRelations::ENEMIES))
  416. {
  417. /// TODO: Find way to reuse CPlayerSpecificInfoCallback::getTownsInfo
  418. /// This may be handy if we allow to use teleportation to friendly towns
  419. for(auto exit : getCastleGates(source))
  420. {
  421. teleportationExits.push_back(exit);
  422. }
  423. }
  424. return teleportationExits;
  425. }
  426. bool CPathfinderHelper::isHeroPatrolLocked() const
  427. {
  428. return patrolState == PATROL_LOCKED;
  429. }
  430. bool CPathfinderHelper::isPatrolMovementAllowed(const int3 & dst) const
  431. {
  432. if(patrolState == PATROL_RADIUS)
  433. {
  434. if(!vstd::contains(patrolTiles, dst))
  435. return false;
  436. }
  437. return true;
  438. }
  439. bool CPathfinder::isLayerTransitionPossible() const
  440. {
  441. ELayer destLayer = destination.node->layer;
  442. /// No layer transition allowed when previous node action is BATTLE
  443. if(source.node->action == CGPathNode::BATTLE)
  444. return false;
  445. switch(source.node->layer)
  446. {
  447. case ELayer::LAND:
  448. if(destLayer == ELayer::AIR)
  449. {
  450. if(!config->options.lightweightFlyingMode || source.isInitialPosition)
  451. return true;
  452. }
  453. else if(destLayer == ELayer::SAIL)
  454. {
  455. if(destination.tile->isWater())
  456. return true;
  457. }
  458. else
  459. return true;
  460. break;
  461. case ELayer::SAIL:
  462. if(destLayer == ELayer::LAND && !destination.tile->isWater())
  463. return true;
  464. break;
  465. case ELayer::AIR:
  466. if(destLayer == ELayer::LAND)
  467. return true;
  468. break;
  469. case ELayer::WATER:
  470. if(destLayer == ELayer::LAND)
  471. return true;
  472. break;
  473. }
  474. return false;
  475. }
  476. void LayerTransitionRule::process(
  477. const PathNodeInfo & source,
  478. CDestinationNodeInfo & destination,
  479. const PathfinderConfig * pathfinderConfig,
  480. CPathfinderHelper * pathfinderHelper) const
  481. {
  482. if(source.node->layer == destination.node->layer)
  483. return;
  484. switch(source.node->layer)
  485. {
  486. case EPathfindingLayer::LAND:
  487. if(destination.node->layer == EPathfindingLayer::SAIL)
  488. {
  489. /// Cannot enter empty water tile from land -> it has to be visitable
  490. if(destination.node->accessible == CGPathNode::ACCESSIBLE)
  491. destination.blocked = true;
  492. }
  493. break;
  494. case EPathfindingLayer::SAIL:
  495. //tile must be accessible -> exception: unblocked blockvis tiles -> clear but guarded by nearby monster coast
  496. if((destination.node->accessible != CGPathNode::ACCESSIBLE && (destination.node->accessible != CGPathNode::BLOCKVIS || destination.tile->blocked))
  497. || destination.tile->visitable) //TODO: passableness problem -> town says it's passable (thus accessible) but we obviously can't disembark onto town gate
  498. {
  499. destination.blocked = true;
  500. }
  501. break;
  502. case EPathfindingLayer::AIR:
  503. if(pathfinderConfig->options.originalMovementRules)
  504. {
  505. if((source.node->accessible != CGPathNode::ACCESSIBLE &&
  506. source.node->accessible != CGPathNode::VISITABLE) &&
  507. (destination.node->accessible != CGPathNode::VISITABLE &&
  508. destination.node->accessible != CGPathNode::ACCESSIBLE))
  509. {
  510. destination.blocked = true;
  511. }
  512. }
  513. else if(source.node->accessible != CGPathNode::ACCESSIBLE && destination.node->accessible != CGPathNode::ACCESSIBLE)
  514. {
  515. /// Hero that fly can only land on accessible tiles
  516. destination.blocked = true;
  517. }
  518. break;
  519. case EPathfindingLayer::WATER:
  520. if(destination.node->accessible != CGPathNode::ACCESSIBLE && destination.node->accessible != CGPathNode::VISITABLE)
  521. {
  522. /// Hero that walking on water can transit to accessible and visitable tiles
  523. /// Though hero can't interact with blocking visit objects while standing on water
  524. destination.blocked = true;
  525. }
  526. break;
  527. }
  528. }
  529. PathfinderBlockingRule::BlockingReason MovementToDestinationRule::getBlockingReason(
  530. const PathNodeInfo & source,
  531. const CDestinationNodeInfo & destination,
  532. const PathfinderConfig * pathfinderConfig,
  533. const CPathfinderHelper * pathfinderHelper) const
  534. {
  535. if(destination.node->accessible == CGPathNode::BLOCKED)
  536. return BlockingReason::DESTINATION_BLOCKED;
  537. switch(destination.node->layer)
  538. {
  539. case EPathfindingLayer::LAND:
  540. if(!pathfinderHelper->canMoveBetween(source.coord, destination.coord))
  541. return BlockingReason::DESTINATION_BLOCKED;
  542. if(source.guarded)
  543. {
  544. if(!(pathfinderConfig->options.originalMovementRules && source.node->layer == EPathfindingLayer::AIR) &&
  545. !destination.isGuardianTile) // Can step into tile of guard
  546. {
  547. return BlockingReason::SOURCE_GUARDED;
  548. }
  549. }
  550. break;
  551. case EPathfindingLayer::SAIL:
  552. if(!pathfinderHelper->canMoveBetween(source.coord, destination.coord))
  553. return BlockingReason::DESTINATION_BLOCKED;
  554. if(source.guarded)
  555. {
  556. // Hero embarked a boat standing on a guarded tile -> we must allow to move away from that tile
  557. if(source.node->action != CGPathNode::EMBARK && !destination.isGuardianTile)
  558. return BlockingReason::SOURCE_GUARDED;
  559. }
  560. if(source.node->layer == EPathfindingLayer::LAND)
  561. {
  562. if(!destination.isNodeObjectVisitable())
  563. return BlockingReason::DESTINATION_BLOCKED;
  564. if(destination.nodeObject->ID != Obj::BOAT && !destination.nodeHero)
  565. return BlockingReason::DESTINATION_BLOCKED;
  566. }
  567. else if(destination.isNodeObjectVisitable() && destination.nodeObject->ID == Obj::BOAT)
  568. {
  569. /// Hero in boat can't visit empty boats
  570. return BlockingReason::DESTINATION_BLOCKED;
  571. }
  572. break;
  573. case EPathfindingLayer::WATER:
  574. if(!pathfinderHelper->canMoveBetween(source.coord, destination.coord)
  575. || destination.node->accessible != CGPathNode::ACCESSIBLE)
  576. {
  577. return BlockingReason::DESTINATION_BLOCKED;
  578. }
  579. if(destination.guarded)
  580. return BlockingReason::DESTINATION_BLOCKED;
  581. break;
  582. }
  583. return BlockingReason::NONE;
  584. }
  585. void MovementAfterDestinationRule::process(
  586. const PathNodeInfo & source,
  587. CDestinationNodeInfo & destination,
  588. const PathfinderConfig * config,
  589. CPathfinderHelper * pathfinderHelper) const
  590. {
  591. auto blocker = getBlockingReason(source, destination, config, pathfinderHelper);
  592. if(blocker == BlockingReason::DESTINATION_GUARDED && destination.action == CGPathNode::ENodeAction::BATTLE)
  593. {
  594. return; // allow bypass guarded tile but only in direction of guard, a bit UI related thing
  595. }
  596. destination.blocked = blocker != BlockingReason::NONE;
  597. }
  598. PathfinderBlockingRule::BlockingReason MovementAfterDestinationRule::getBlockingReason(
  599. const PathNodeInfo & source,
  600. const CDestinationNodeInfo & destination,
  601. const PathfinderConfig * config,
  602. const CPathfinderHelper * pathfinderHelper) const
  603. {
  604. switch(destination.action)
  605. {
  606. /// TODO: Investigate what kind of limitation is possible to apply on movement from visitable tiles
  607. /// Likely in many cases we don't need to add visitable tile to queue when hero don't fly
  608. case CGPathNode::VISIT:
  609. {
  610. /// For now we only add visitable tile into queue when it's teleporter that allow transit
  611. /// Movement from visitable tile when hero is standing on it is possible into any layer
  612. const CGTeleport * objTeleport = dynamic_cast<const CGTeleport *>(destination.nodeObject);
  613. if(pathfinderHelper->isAllowedTeleportEntrance(objTeleport))
  614. {
  615. /// For now we'll always allow transit over teleporters
  616. /// Transit over whirlpools only allowed when hero protected
  617. return BlockingReason::NONE;
  618. }
  619. else if(destination.nodeObject->ID == Obj::GARRISON
  620. || destination.nodeObject->ID == Obj::GARRISON2
  621. || destination.nodeObject->ID == Obj::BORDER_GATE)
  622. {
  623. /// Transit via unguarded garrisons is always possible
  624. return BlockingReason::NONE;
  625. }
  626. return BlockingReason::DESTINATION_VISIT;
  627. }
  628. case CGPathNode::BLOCKING_VISIT:
  629. return destination.guarded
  630. ? BlockingReason::DESTINATION_GUARDED
  631. : BlockingReason::DESTINATION_BLOCKVIS;
  632. case CGPathNode::NORMAL:
  633. return BlockingReason::NONE;
  634. case CGPathNode::EMBARK:
  635. if(pathfinderHelper->options.useEmbarkAndDisembark)
  636. return BlockingReason::NONE;
  637. return BlockingReason::DESTINATION_BLOCKED;
  638. case CGPathNode::DISEMBARK:
  639. if(pathfinderHelper->options.useEmbarkAndDisembark)
  640. return destination.guarded ? BlockingReason::DESTINATION_GUARDED : BlockingReason::NONE;
  641. return BlockingReason::DESTINATION_BLOCKED;
  642. case CGPathNode::BATTLE:
  643. /// Movement after BATTLE action only possible from guarded tile to guardian tile
  644. if(destination.guarded)
  645. return BlockingReason::DESTINATION_GUARDED;
  646. break;
  647. }
  648. return BlockingReason::DESTINATION_BLOCKED;
  649. }
  650. void DestinationActionRule::process(
  651. const PathNodeInfo & source,
  652. CDestinationNodeInfo & destination,
  653. const PathfinderConfig * pathfinderConfig,
  654. CPathfinderHelper * pathfinderHelper) const
  655. {
  656. if(destination.action != CGPathNode::ENodeAction::UNKNOWN)
  657. {
  658. #ifdef VCMI_TRACE_PATHFINDER
  659. logAi->trace("Accepted precalculated action at %s", destination.coord.toString());
  660. #endif
  661. return;
  662. }
  663. CGPathNode::ENodeAction action = CGPathNode::NORMAL;
  664. auto hero = pathfinderHelper->hero;
  665. switch(destination.node->layer)
  666. {
  667. case EPathfindingLayer::LAND:
  668. if(source.node->layer == EPathfindingLayer::SAIL)
  669. {
  670. // TODO: Handle dismebark into guarded areaa
  671. action = CGPathNode::DISEMBARK;
  672. break;
  673. }
  674. /// don't break - next case shared for both land and sail layers
  675. FALLTHROUGH
  676. case EPathfindingLayer::SAIL:
  677. if(destination.isNodeObjectVisitable())
  678. {
  679. auto objRel = destination.objectRelations;
  680. if(destination.nodeObject->ID == Obj::BOAT)
  681. action = CGPathNode::EMBARK;
  682. else if(destination.nodeHero)
  683. {
  684. if(destination.heroRelations == PlayerRelations::ENEMIES)
  685. action = CGPathNode::BATTLE;
  686. else
  687. action = CGPathNode::BLOCKING_VISIT;
  688. }
  689. else if(destination.nodeObject->ID == Obj::TOWN)
  690. {
  691. if(destination.nodeObject->passableFor(hero->tempOwner))
  692. action = CGPathNode::VISIT;
  693. else if(objRel == PlayerRelations::ENEMIES)
  694. action = CGPathNode::BATTLE;
  695. }
  696. else if(destination.nodeObject->ID == Obj::GARRISON || destination.nodeObject->ID == Obj::GARRISON2)
  697. {
  698. if(destination.nodeObject->passableFor(hero->tempOwner))
  699. {
  700. if(destination.guarded)
  701. action = CGPathNode::BATTLE;
  702. }
  703. else if(objRel == PlayerRelations::ENEMIES)
  704. action = CGPathNode::BATTLE;
  705. }
  706. else if(destination.nodeObject->ID == Obj::BORDER_GATE)
  707. {
  708. if(destination.nodeObject->passableFor(hero->tempOwner))
  709. {
  710. if(destination.guarded)
  711. action = CGPathNode::BATTLE;
  712. }
  713. else
  714. action = CGPathNode::BLOCKING_VISIT;
  715. }
  716. else if(destination.isGuardianTile)
  717. action = CGPathNode::BATTLE;
  718. else if(destination.nodeObject->blockVisit && !(pathfinderConfig->options.useCastleGate && destination.nodeObject->ID == Obj::TOWN))
  719. action = CGPathNode::BLOCKING_VISIT;
  720. if(action == CGPathNode::NORMAL)
  721. {
  722. if(destination.guarded)
  723. action = CGPathNode::BATTLE;
  724. else
  725. action = CGPathNode::VISIT;
  726. }
  727. }
  728. else if(destination.guarded)
  729. action = CGPathNode::BATTLE;
  730. break;
  731. }
  732. destination.action = action;
  733. }
  734. CGPathNode::ENodeAction CPathfinder::getTeleportDestAction() const
  735. {
  736. CGPathNode::ENodeAction action = CGPathNode::TELEPORT_NORMAL;
  737. if(destination.isNodeObjectVisitable() && destination.nodeHero)
  738. {
  739. if(destination.heroRelations == PlayerRelations::ENEMIES)
  740. action = CGPathNode::TELEPORT_BATTLE;
  741. else
  742. action = CGPathNode::TELEPORT_BLOCKING_VISIT;
  743. }
  744. return action;
  745. }
  746. bool CPathfinder::isDestinationGuardian() const
  747. {
  748. return gs->guardingCreaturePosition(source.node->coord) == destination.node->coord;
  749. }
  750. void CPathfinderHelper::initializePatrol()
  751. {
  752. auto state = PATROL_NONE;
  753. if(hero->patrol.patrolling && !getPlayerState(hero->tempOwner)->human)
  754. {
  755. if(hero->patrol.patrolRadius)
  756. {
  757. state = PATROL_RADIUS;
  758. gs->getTilesInRange(patrolTiles, hero->patrol.initialPos, hero->patrol.patrolRadius, boost::optional<PlayerColor>(), 0, int3::DIST_MANHATTAN);
  759. }
  760. else
  761. state = PATROL_LOCKED;
  762. }
  763. patrolState = state;
  764. }
  765. void CPathfinder::initializeGraph()
  766. {
  767. INodeStorage * nodeStorage = config->nodeStorage.get();
  768. nodeStorage->initialize(config->options, gs);
  769. }
  770. bool CPathfinderHelper::canMoveBetween(const int3 & a, const int3 & b) const
  771. {
  772. return gs->checkForVisitableDir(a, b);
  773. }
  774. bool CPathfinderHelper::isAllowedTeleportEntrance(const CGTeleport * obj) const
  775. {
  776. if(!obj || !isTeleportEntrancePassable(obj, hero->tempOwner))
  777. return false;
  778. auto whirlpool = dynamic_cast<const CGWhirlpool *>(obj);
  779. if(whirlpool)
  780. {
  781. if(addTeleportWhirlpool(whirlpool))
  782. return true;
  783. }
  784. else if(addTeleportTwoWay(obj) || addTeleportOneWay(obj) || addTeleportOneWayRandom(obj))
  785. return true;
  786. return false;
  787. }
  788. bool CPathfinderHelper::addTeleportTwoWay(const CGTeleport * obj) const
  789. {
  790. return options.useTeleportTwoWay && isTeleportChannelBidirectional(obj->channel, hero->tempOwner);
  791. }
  792. bool CPathfinderHelper::addTeleportOneWay(const CGTeleport * obj) const
  793. {
  794. if(options.useTeleportOneWay && isTeleportChannelUnidirectional(obj->channel, hero->tempOwner))
  795. {
  796. auto passableExits = CGTeleport::getPassableExits(gs, hero, getTeleportChannelExits(obj->channel, hero->tempOwner));
  797. if(passableExits.size() == 1)
  798. return true;
  799. }
  800. return false;
  801. }
  802. bool CPathfinderHelper::addTeleportOneWayRandom(const CGTeleport * obj) const
  803. {
  804. if(options.useTeleportOneWayRandom && isTeleportChannelUnidirectional(obj->channel, hero->tempOwner))
  805. {
  806. auto passableExits = CGTeleport::getPassableExits(gs, hero, getTeleportChannelExits(obj->channel, hero->tempOwner));
  807. if(passableExits.size() > 1)
  808. return true;
  809. }
  810. return false;
  811. }
  812. bool CPathfinderHelper::addTeleportWhirlpool(const CGWhirlpool * obj) const
  813. {
  814. return options.useTeleportWhirlpool && hasBonusOfType(Bonus::WHIRLPOOL_PROTECTION) && obj;
  815. }
  816. int CPathfinderHelper::movementPointsAfterEmbark(int movement, int basicCost, bool disembark) const
  817. {
  818. return hero->movementPointsAfterEmbark(movement, basicCost, disembark, getTurnInfo());
  819. }
  820. bool CPathfinderHelper::passOneTurnLimitCheck(const PathNodeInfo & source) const
  821. {
  822. if(!options.oneTurnSpecialLayersLimit)
  823. return true;
  824. if(source.node->layer == EPathfindingLayer::WATER)
  825. return false;
  826. if(source.node->layer == EPathfindingLayer::AIR)
  827. {
  828. if(options.originalMovementRules && source.node->accessible == CGPathNode::ACCESSIBLE)
  829. return true;
  830. else
  831. return false;
  832. }
  833. return true;
  834. }
  835. TurnInfo::BonusCache::BonusCache(TConstBonusListPtr bl)
  836. {
  837. for(int i = 0; i < Terrain::Manager::terrains().size(); ++i)
  838. {
  839. noTerrainPenalty.push_back(static_cast<bool>(
  840. bl->getFirst(Selector::type()(Bonus::NO_TERRAIN_PENALTY).And(Selector::subtype()(i)))));
  841. }
  842. freeShipBoarding = static_cast<bool>(bl->getFirst(Selector::type()(Bonus::FREE_SHIP_BOARDING)));
  843. flyingMovement = static_cast<bool>(bl->getFirst(Selector::type()(Bonus::FLYING_MOVEMENT)));
  844. flyingMovementVal = bl->valOfBonuses(Selector::type()(Bonus::FLYING_MOVEMENT));
  845. waterWalking = static_cast<bool>(bl->getFirst(Selector::type()(Bonus::WATER_WALKING)));
  846. waterWalkingVal = bl->valOfBonuses(Selector::type()(Bonus::WATER_WALKING));
  847. }
  848. TurnInfo::TurnInfo(const CGHeroInstance * Hero, const int turn)
  849. : hero(Hero), maxMovePointsLand(-1), maxMovePointsWater(-1)
  850. {
  851. bonuses = hero->getAllBonuses(Selector::days(turn), Selector::all, nullptr, "");
  852. bonusCache = make_unique<BonusCache>(bonuses);
  853. nativeTerrain = hero->getNativeTerrain();
  854. }
  855. bool TurnInfo::isLayerAvailable(const EPathfindingLayer layer) const
  856. {
  857. switch(layer)
  858. {
  859. case EPathfindingLayer::AIR:
  860. if(!hasBonusOfType(Bonus::FLYING_MOVEMENT))
  861. return false;
  862. break;
  863. case EPathfindingLayer::WATER:
  864. if(!hasBonusOfType(Bonus::WATER_WALKING))
  865. return false;
  866. break;
  867. }
  868. return true;
  869. }
  870. bool TurnInfo::hasBonusOfType(Bonus::BonusType type, int subtype) const
  871. {
  872. switch(type)
  873. {
  874. case Bonus::FREE_SHIP_BOARDING:
  875. return bonusCache->freeShipBoarding;
  876. case Bonus::FLYING_MOVEMENT:
  877. return bonusCache->flyingMovement;
  878. case Bonus::WATER_WALKING:
  879. return bonusCache->waterWalking;
  880. case Bonus::NO_TERRAIN_PENALTY:
  881. return bonusCache->noTerrainPenalty[subtype];
  882. }
  883. return static_cast<bool>(
  884. bonuses->getFirst(Selector::type()(type).And(Selector::subtype()(subtype))));
  885. }
  886. int TurnInfo::valOfBonuses(Bonus::BonusType type, int subtype) const
  887. {
  888. switch(type)
  889. {
  890. case Bonus::FLYING_MOVEMENT:
  891. return bonusCache->flyingMovementVal;
  892. case Bonus::WATER_WALKING:
  893. return bonusCache->waterWalkingVal;
  894. }
  895. return bonuses->valOfBonuses(Selector::type()(type).And(Selector::subtype()(subtype)));
  896. }
  897. int TurnInfo::getMaxMovePoints(const EPathfindingLayer layer) const
  898. {
  899. if(maxMovePointsLand == -1)
  900. maxMovePointsLand = hero->maxMovePointsCached(true, this);
  901. if(maxMovePointsWater == -1)
  902. maxMovePointsWater = hero->maxMovePointsCached(false, this);
  903. return layer == EPathfindingLayer::SAIL ? maxMovePointsWater : maxMovePointsLand;
  904. }
  905. CPathfinderHelper::CPathfinderHelper(CGameState * gs, const CGHeroInstance * Hero, const PathfinderOptions & Options)
  906. : CGameInfoCallback(gs, boost::optional<PlayerColor>()), turn(-1), hero(Hero), options(Options), owner(Hero->tempOwner)
  907. {
  908. turnsInfo.reserve(16);
  909. updateTurnInfo();
  910. initializePatrol();
  911. }
  912. CPathfinderHelper::~CPathfinderHelper()
  913. {
  914. for(auto ti : turnsInfo)
  915. delete ti;
  916. }
  917. void CPathfinderHelper::updateTurnInfo(const int Turn)
  918. {
  919. if(turn != Turn)
  920. {
  921. turn = Turn;
  922. if(turn >= turnsInfo.size())
  923. {
  924. auto ti = new TurnInfo(hero, turn);
  925. turnsInfo.push_back(ti);
  926. }
  927. }
  928. }
  929. bool CPathfinderHelper::isLayerAvailable(const EPathfindingLayer layer) const
  930. {
  931. switch(layer)
  932. {
  933. case EPathfindingLayer::AIR:
  934. if(!options.useFlying)
  935. return false;
  936. break;
  937. case EPathfindingLayer::WATER:
  938. if(!options.useWaterWalking)
  939. return false;
  940. break;
  941. }
  942. return turnsInfo[turn]->isLayerAvailable(layer);
  943. }
  944. const TurnInfo * CPathfinderHelper::getTurnInfo() const
  945. {
  946. return turnsInfo[turn];
  947. }
  948. bool CPathfinderHelper::hasBonusOfType(const Bonus::BonusType type, const int subtype) const
  949. {
  950. return turnsInfo[turn]->hasBonusOfType(type, subtype);
  951. }
  952. int CPathfinderHelper::getMaxMovePoints(const EPathfindingLayer layer) const
  953. {
  954. return turnsInfo[turn]->getMaxMovePoints(layer);
  955. }
  956. void CPathfinderHelper::getNeighbours(
  957. const TerrainTile & srct,
  958. const int3 & tile,
  959. std::vector<int3> & vec,
  960. const boost::logic::tribool & onLand,
  961. const bool limitCoastSailing) const
  962. {
  963. CMap * map = gs->map;
  964. static const int3 dirs[] = {
  965. int3(-1, +1, +0), int3(0, +1, +0), int3(+1, +1, +0),
  966. int3(-1, +0, +0), /* source pos */ int3(+1, +0, +0),
  967. int3(-1, -1, +0), int3(0, -1, +0), int3(+1, -1, +0)
  968. };
  969. for(auto & dir : dirs)
  970. {
  971. const int3 hlp = tile + dir;
  972. if(!map->isInTheMap(hlp))
  973. continue;
  974. const TerrainTile & hlpt = map->getTile(hlp);
  975. if(!hlpt.terType.isPassable())
  976. continue;
  977. // //we cannot visit things from blocked tiles
  978. // if(srct.blocked && !srct.visitable && hlpt.visitable && srct.blockingObjects.front()->ID != HEROI_TYPE)
  979. // {
  980. // continue;
  981. // }
  982. /// Following condition let us avoid diagonal movement over coast when sailing
  983. if(srct.terType.isWater() && limitCoastSailing && hlpt.terType.isWater() && dir.x && dir.y) //diagonal move through water
  984. {
  985. int3 hlp1 = tile,
  986. hlp2 = tile;
  987. hlp1.x += dir.x;
  988. hlp2.y += dir.y;
  989. if(map->getTile(hlp1).terType.isLand() || map->getTile(hlp2).terType.isLand())
  990. continue;
  991. }
  992. if(indeterminate(onLand) || onLand == hlpt.terType.isLand())
  993. {
  994. vec.push_back(hlp);
  995. }
  996. }
  997. }
  998. int CPathfinderHelper::getMovementCost(
  999. const int3 & src,
  1000. const int3 & dst,
  1001. const TerrainTile * ct,
  1002. const TerrainTile * dt,
  1003. const int remainingMovePoints,
  1004. const bool checkLast) const
  1005. {
  1006. if(src == dst) //same tile
  1007. return 0;
  1008. auto ti = getTurnInfo();
  1009. if(ct == nullptr || dt == nullptr)
  1010. {
  1011. ct = hero->cb->getTile(src);
  1012. dt = hero->cb->getTile(dst);
  1013. }
  1014. /// TODO: by the original game rules hero shouldn't be affected by terrain penalty while flying.
  1015. /// Also flying movement only has penalty when player moving over blocked tiles.
  1016. /// So if you only have base flying with 40% penalty you can still ignore terrain penalty while having zero flying penalty.
  1017. ui32 ret = hero->getTileCost(*dt, *ct, ti);
  1018. /// Unfortunately this can't be implemented yet as server don't know when player flying and when he's not.
  1019. /// Difference in cost calculation on client and server is much worse than incorrect cost.
  1020. /// So this one is waiting till server going to use pathfinder rules for path validation.
  1021. if(dt->blocked && ti->hasBonusOfType(Bonus::FLYING_MOVEMENT))
  1022. {
  1023. ret = static_cast<int>(ret * (100.0 + ti->valOfBonuses(Bonus::FLYING_MOVEMENT)) / 100.0);
  1024. }
  1025. else if(dt->terType.isWater())
  1026. {
  1027. if(hero->boat && ct->hasFavorableWinds() && dt->hasFavorableWinds())
  1028. ret = static_cast<int>(ret * 0.666);
  1029. else if(!hero->boat && ti->hasBonusOfType(Bonus::WATER_WALKING))
  1030. {
  1031. ret = static_cast<int>(ret * (100.0 + ti->valOfBonuses(Bonus::WATER_WALKING)) / 100.0);
  1032. }
  1033. }
  1034. if(src.x != dst.x && src.y != dst.y) //it's diagonal move
  1035. {
  1036. int old = ret;
  1037. ret = static_cast < int>(ret * 1.414213);
  1038. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  1039. if(ret > remainingMovePoints && remainingMovePoints >= old)
  1040. {
  1041. return remainingMovePoints;
  1042. }
  1043. }
  1044. /// TODO: This part need rework in order to work properly with flying and water walking
  1045. /// Currently it's only work properly for normal movement or sailing
  1046. int left = remainingMovePoints-ret;
  1047. if(checkLast && left > 0 && remainingMovePoints-ret < 250) //it might be the last tile - if no further move possible we take all move points
  1048. {
  1049. std::vector<int3> vec;
  1050. vec.reserve(8); //optimization
  1051. getNeighbours(*dt, dst, vec, ct->terType.isLand(), true);
  1052. for(auto & elem : vec)
  1053. {
  1054. int fcost = getMovementCost(dst, elem, nullptr, nullptr, left, false);
  1055. if(fcost <= left)
  1056. {
  1057. return ret;
  1058. }
  1059. }
  1060. ret = remainingMovePoints;
  1061. }
  1062. return ret;
  1063. }
  1064. int3 CGPath::startPos() const
  1065. {
  1066. return nodes[nodes.size()-1].coord;
  1067. }
  1068. int3 CGPath::endPos() const
  1069. {
  1070. return nodes[0].coord;
  1071. }
  1072. void CGPath::convert(ui8 mode)
  1073. {
  1074. if(mode==0)
  1075. {
  1076. for(auto & elem : nodes)
  1077. {
  1078. elem.coord = CGHeroInstance::convertPosition(elem.coord,true);
  1079. }
  1080. }
  1081. }
  1082. CPathsInfo::CPathsInfo(const int3 & Sizes, const CGHeroInstance * hero_)
  1083. : sizes(Sizes), hero(hero_)
  1084. {
  1085. nodes.resize(boost::extents[sizes.x][sizes.y][sizes.z][ELayer::NUM_LAYERS]);
  1086. }
  1087. CPathsInfo::~CPathsInfo() = default;
  1088. const CGPathNode * CPathsInfo::getPathInfo(const int3 & tile) const
  1089. {
  1090. assert(vstd::iswithin(tile.x, 0, sizes.x));
  1091. assert(vstd::iswithin(tile.y, 0, sizes.y));
  1092. assert(vstd::iswithin(tile.z, 0, sizes.z));
  1093. return getNode(tile);
  1094. }
  1095. bool CPathsInfo::getPath(CGPath & out, const int3 & dst) const
  1096. {
  1097. out.nodes.clear();
  1098. const CGPathNode * curnode = getNode(dst);
  1099. if(!curnode->theNodeBefore)
  1100. return false;
  1101. while(curnode)
  1102. {
  1103. const CGPathNode cpn = * curnode;
  1104. curnode = curnode->theNodeBefore;
  1105. out.nodes.push_back(cpn);
  1106. }
  1107. return true;
  1108. }
  1109. const CGPathNode * CPathsInfo::getNode(const int3 & coord) const
  1110. {
  1111. auto landNode = &nodes[coord.x][coord.y][coord.z][ELayer::LAND];
  1112. if(landNode->reachable())
  1113. return landNode;
  1114. else
  1115. return &nodes[coord.x][coord.y][coord.z][ELayer::SAIL];
  1116. }
  1117. PathNodeInfo::PathNodeInfo()
  1118. : node(nullptr), nodeObject(nullptr), tile(nullptr), coord(-1, -1, -1), guarded(false), isInitialPosition(false)
  1119. {
  1120. }
  1121. void PathNodeInfo::setNode(CGameState * gs, CGPathNode * n)
  1122. {
  1123. node = n;
  1124. if(coord != node->coord)
  1125. {
  1126. assert(node->coord.valid());
  1127. coord = node->coord;
  1128. tile = gs->getTile(coord);
  1129. nodeObject = tile->topVisitableObj();
  1130. if(nodeObject && nodeObject->ID == Obj::HERO)
  1131. {
  1132. nodeHero = dynamic_cast<const CGHeroInstance *>(nodeObject);
  1133. nodeObject = tile->topVisitableObj(true);
  1134. if(!nodeObject)
  1135. nodeObject = nodeHero;
  1136. }
  1137. else
  1138. {
  1139. nodeHero = nullptr;
  1140. }
  1141. }
  1142. guarded = false;
  1143. }
  1144. void PathNodeInfo::updateInfo(CPathfinderHelper * hlp, CGameState * gs)
  1145. {
  1146. if(gs->guardingCreaturePosition(node->coord).valid() && !isInitialPosition)
  1147. {
  1148. guarded = true;
  1149. }
  1150. if(nodeObject)
  1151. {
  1152. objectRelations = gs->getPlayerRelations(hlp->owner, nodeObject->tempOwner);
  1153. }
  1154. if(nodeHero)
  1155. {
  1156. heroRelations = gs->getPlayerRelations(hlp->owner, nodeHero->tempOwner);
  1157. }
  1158. }
  1159. CDestinationNodeInfo::CDestinationNodeInfo()
  1160. : PathNodeInfo(),
  1161. blocked(false),
  1162. action(CGPathNode::ENodeAction::UNKNOWN)
  1163. {
  1164. }
  1165. void CDestinationNodeInfo::setNode(CGameState * gs, CGPathNode * n)
  1166. {
  1167. PathNodeInfo::setNode(gs, n);
  1168. blocked = false;
  1169. action = CGPathNode::ENodeAction::UNKNOWN;
  1170. }
  1171. bool CDestinationNodeInfo::isBetterWay() const
  1172. {
  1173. if(node->turns == 0xff) //we haven't been here before
  1174. return true;
  1175. else
  1176. return cost < node->getCost(); //this route is faster
  1177. }
  1178. bool PathNodeInfo::isNodeObjectVisitable() const
  1179. {
  1180. /// Hero can't visit objects while walking on water or flying
  1181. return (node->layer == EPathfindingLayer::LAND || node->layer == EPathfindingLayer::SAIL)
  1182. && (canSeeObj(nodeObject) || canSeeObj(nodeHero));
  1183. }