CPathfinder.cpp 39 KB

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