CPathfinder.cpp 40 KB

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