CPathfinder.cpp 38 KB

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