CPathfinder.cpp 39 KB

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