CPathfinder.cpp 39 KB

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