CPathfinder.cpp 39 KB

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