CPathfinder.cpp 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408
  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::AIR; 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(16);
  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 ? EPathfindingLayer::SAIL : 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 don'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 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, boost::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(Bonus::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()(Bonus::NO_TERRAIN_PENALTY).And(Selector::subtype()(terrain->getIndex())))));
  823. }
  824. freeShipBoarding = static_cast<bool>(bl->getFirst(Selector::type()(Bonus::FREE_SHIP_BOARDING)));
  825. flyingMovement = static_cast<bool>(bl->getFirst(Selector::type()(Bonus::FLYING_MOVEMENT)));
  826. flyingMovementVal = bl->valOfBonuses(Selector::type()(Bonus::FLYING_MOVEMENT));
  827. waterWalking = static_cast<bool>(bl->getFirst(Selector::type()(Bonus::WATER_WALKING)));
  828. waterWalkingVal = bl->valOfBonuses(Selector::type()(Bonus::WATER_WALKING));
  829. pathfindingVal = bl->valOfBonuses(Selector::type()(Bonus::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(!hasBonusOfType(Bonus::FLYING_MOVEMENT))
  847. return false;
  848. break;
  849. case EPathfindingLayer::WATER:
  850. if(!hasBonusOfType(Bonus::WATER_WALKING))
  851. return false;
  852. break;
  853. }
  854. return true;
  855. }
  856. bool TurnInfo::hasBonusOfType(Bonus::BonusType type, int subtype) const
  857. {
  858. switch(type)
  859. {
  860. case Bonus::FREE_SHIP_BOARDING:
  861. return bonusCache->freeShipBoarding;
  862. case Bonus::FLYING_MOVEMENT:
  863. return bonusCache->flyingMovement;
  864. case Bonus::WATER_WALKING:
  865. return bonusCache->waterWalking;
  866. case Bonus::NO_TERRAIN_PENALTY:
  867. return bonusCache->noTerrainPenalty[subtype];
  868. }
  869. return static_cast<bool>(
  870. bonuses->getFirst(Selector::type()(type).And(Selector::subtype()(subtype))));
  871. }
  872. int TurnInfo::valOfBonuses(Bonus::BonusType type, int subtype) const
  873. {
  874. switch(type)
  875. {
  876. case Bonus::FLYING_MOVEMENT:
  877. return bonusCache->flyingMovementVal;
  878. case Bonus::WATER_WALKING:
  879. return bonusCache->waterWalkingVal;
  880. case Bonus::ROUGH_TERRAIN_DISCOUNT:
  881. return bonusCache->pathfindingVal;
  882. }
  883. return bonuses->valOfBonuses(Selector::type()(type).And(Selector::subtype()(subtype)));
  884. }
  885. int TurnInfo::getMaxMovePoints(const EPathfindingLayer & layer) const
  886. {
  887. if(maxMovePointsLand == -1)
  888. maxMovePointsLand = hero->maxMovePointsCached(true, this);
  889. if(maxMovePointsWater == -1)
  890. maxMovePointsWater = hero->maxMovePointsCached(false, this);
  891. return layer == EPathfindingLayer::SAIL ? maxMovePointsWater : maxMovePointsLand;
  892. }
  893. void TurnInfo::updateHeroBonuses(Bonus::BonusType type, const CSelector& sel) const
  894. {
  895. switch(type)
  896. {
  897. case Bonus::FREE_SHIP_BOARDING:
  898. bonusCache->freeShipBoarding = static_cast<bool>(bonuses->getFirst(Selector::type()(Bonus::FREE_SHIP_BOARDING)));
  899. break;
  900. case Bonus::FLYING_MOVEMENT:
  901. bonusCache->flyingMovement = static_cast<bool>(bonuses->getFirst(Selector::type()(Bonus::FLYING_MOVEMENT)));
  902. bonusCache->flyingMovementVal = bonuses->valOfBonuses(Selector::type()(Bonus::FLYING_MOVEMENT));
  903. break;
  904. case Bonus::WATER_WALKING:
  905. bonusCache->waterWalking = static_cast<bool>(bonuses->getFirst(Selector::type()(Bonus::WATER_WALKING)));
  906. bonusCache->waterWalkingVal = bonuses->valOfBonuses(Selector::type()(Bonus::WATER_WALKING));
  907. break;
  908. case Bonus::ROUGH_TERRAIN_DISCOUNT:
  909. bonusCache->pathfindingVal = bonuses->valOfBonuses(Selector::type()(Bonus::ROUGH_TERRAIN_DISCOUNT));
  910. break;
  911. default:
  912. bonuses = hero->getAllBonuses(Selector::days(turn), Selector::all, nullptr, "");
  913. }
  914. }
  915. CPathfinderHelper::CPathfinderHelper(CGameState * gs, const CGHeroInstance * Hero, const PathfinderOptions & Options)
  916. : CGameInfoCallback(gs, boost::optional<PlayerColor>()), turn(-1), hero(Hero), options(Options), owner(Hero->tempOwner)
  917. {
  918. turnsInfo.reserve(16);
  919. updateTurnInfo();
  920. initializePatrol();
  921. }
  922. CPathfinderHelper::~CPathfinderHelper()
  923. {
  924. for(auto * ti : turnsInfo)
  925. delete ti;
  926. }
  927. void CPathfinderHelper::updateTurnInfo(const int Turn)
  928. {
  929. if(turn != Turn)
  930. {
  931. turn = Turn;
  932. if(turn >= turnsInfo.size())
  933. {
  934. auto * ti = new TurnInfo(hero, turn);
  935. turnsInfo.push_back(ti);
  936. }
  937. }
  938. }
  939. bool CPathfinderHelper::isLayerAvailable(const EPathfindingLayer & layer) const
  940. {
  941. switch(layer)
  942. {
  943. case EPathfindingLayer::AIR:
  944. if(!options.useFlying)
  945. return false;
  946. break;
  947. case EPathfindingLayer::WATER:
  948. if(!options.useWaterWalking)
  949. return false;
  950. break;
  951. }
  952. return turnsInfo[turn]->isLayerAvailable(layer);
  953. }
  954. const TurnInfo * CPathfinderHelper::getTurnInfo() const
  955. {
  956. return turnsInfo[turn];
  957. }
  958. bool CPathfinderHelper::hasBonusOfType(const Bonus::BonusType type, const int subtype) const
  959. {
  960. return turnsInfo[turn]->hasBonusOfType(type, subtype);
  961. }
  962. int CPathfinderHelper::getMaxMovePoints(const EPathfindingLayer & layer) const
  963. {
  964. return turnsInfo[turn]->getMaxMovePoints(layer);
  965. }
  966. void CPathfinderHelper::getNeighbours(
  967. const TerrainTile & srcTile,
  968. const int3 & srcCoord,
  969. std::vector<int3> & vec,
  970. const boost::logic::tribool & onLand,
  971. const bool limitCoastSailing) const
  972. {
  973. CMap * map = gs->map;
  974. static const int3 dirs[] = {
  975. int3(-1, +1, +0), int3(0, +1, +0), int3(+1, +1, +0),
  976. int3(-1, +0, +0), /* source pos */ int3(+1, +0, +0),
  977. int3(-1, -1, +0), int3(0, -1, +0), int3(+1, -1, +0)
  978. };
  979. for(const auto & dir : dirs)
  980. {
  981. const int3 destCoord = srcCoord + dir;
  982. if(!map->isInTheMap(destCoord))
  983. continue;
  984. const TerrainTile & destTile = map->getTile(destCoord);
  985. if(!destTile.terType->isPassable())
  986. continue;
  987. // //we cannot visit things from blocked tiles
  988. // if(srcTile.blocked && !srcTile.visitable && destTile.visitable && srcTile.blockingObjects.front()->ID != HEROI_TYPE)
  989. // {
  990. // continue;
  991. // }
  992. /// Following condition let us avoid diagonal movement over coast when sailing
  993. if(srcTile.terType->isWater() && limitCoastSailing && destTile.terType->isWater() && dir.x && dir.y) //diagonal move through water
  994. {
  995. const int3 horizontalNeighbour = srcCoord + int3{dir.x, 0, 0};
  996. const int3 verticalNeighbour = srcCoord + int3{0, dir.y, 0};
  997. if(map->getTile(horizontalNeighbour).terType->isLand() || map->getTile(verticalNeighbour).terType->isLand())
  998. continue;
  999. }
  1000. if(indeterminate(onLand) || onLand == destTile.terType->isLand())
  1001. {
  1002. vec.push_back(destCoord);
  1003. }
  1004. }
  1005. }
  1006. int CPathfinderHelper::getMovementCost(
  1007. const int3 & src,
  1008. const int3 & dst,
  1009. const TerrainTile * ct,
  1010. const TerrainTile * dt,
  1011. const int remainingMovePoints,
  1012. const bool checkLast) const
  1013. {
  1014. if(src == dst) //same tile
  1015. return 0;
  1016. const auto * ti = getTurnInfo();
  1017. if(ct == nullptr || dt == nullptr)
  1018. {
  1019. ct = hero->cb->getTile(src);
  1020. dt = hero->cb->getTile(dst);
  1021. }
  1022. int ret = hero->getTileCost(*dt, *ct, ti);
  1023. if(hero->boat != nullptr && dt->terType->isWater())
  1024. {
  1025. if(ct->hasFavorableWinds())
  1026. ret = static_cast<int>(ret * 2.0 / 3);
  1027. }
  1028. else if(ti->hasBonusOfType(Bonus::FLYING_MOVEMENT))
  1029. vstd::amin(ret, GameConstants::BASE_MOVEMENT_COST + ti->valOfBonuses(Bonus::FLYING_MOVEMENT));
  1030. else if(hero->boat == nullptr && dt->terType->isWater() && ti->hasBonusOfType(Bonus::WATER_WALKING))
  1031. ret = static_cast<int>(ret * (100.0 + ti->valOfBonuses(Bonus::WATER_WALKING)) / 100.0);
  1032. if(src.x != dst.x && src.y != dst.y) //it's diagonal move
  1033. {
  1034. int old = ret;
  1035. ret = static_cast<int>(ret * M_SQRT2);
  1036. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  1037. // https://heroes.thelazy.net/index.php/Movement#Diagonal_move_exception
  1038. if(ret > remainingMovePoints && remainingMovePoints >= old)
  1039. {
  1040. return remainingMovePoints;
  1041. }
  1042. }
  1043. const int left = remainingMovePoints - ret;
  1044. constexpr auto maxCostOfOneStep = static_cast<int>(175 * M_SQRT2); // diagonal move on Swamp - 247 MP
  1045. if(checkLast && left > 0 && left <= maxCostOfOneStep) //it might be the last tile - if no further move possible we take all move points
  1046. {
  1047. std::vector<int3> vec;
  1048. vec.reserve(8); //optimization
  1049. getNeighbours(*dt, dst, vec, ct->terType->isLand(), true);
  1050. for(auto & elem : vec)
  1051. {
  1052. int fcost = getMovementCost(dst, elem, nullptr, nullptr, left, false);
  1053. if(fcost <= left)
  1054. {
  1055. return ret;
  1056. }
  1057. }
  1058. ret = remainingMovePoints;
  1059. }
  1060. return ret;
  1061. }
  1062. int3 CGPath::startPos() const
  1063. {
  1064. return nodes[nodes.size()-1].coord;
  1065. }
  1066. int3 CGPath::endPos() const
  1067. {
  1068. return nodes[0].coord;
  1069. }
  1070. CPathsInfo::CPathsInfo(const int3 & Sizes, const CGHeroInstance * hero_)
  1071. : sizes(Sizes), hero(hero_)
  1072. {
  1073. nodes.resize(boost::extents[ELayer::NUM_LAYERS][sizes.z][sizes.x][sizes.y]);
  1074. }
  1075. CPathsInfo::~CPathsInfo() = default;
  1076. const CGPathNode * CPathsInfo::getPathInfo(const int3 & tile) const
  1077. {
  1078. assert(vstd::iswithin(tile.x, 0, sizes.x));
  1079. assert(vstd::iswithin(tile.y, 0, sizes.y));
  1080. assert(vstd::iswithin(tile.z, 0, sizes.z));
  1081. return getNode(tile);
  1082. }
  1083. bool CPathsInfo::getPath(CGPath & out, const int3 & dst) const
  1084. {
  1085. out.nodes.clear();
  1086. const CGPathNode * curnode = getNode(dst);
  1087. if(!curnode->theNodeBefore)
  1088. return false;
  1089. while(curnode)
  1090. {
  1091. const CGPathNode cpn = * curnode;
  1092. curnode = curnode->theNodeBefore;
  1093. out.nodes.push_back(cpn);
  1094. }
  1095. return true;
  1096. }
  1097. const CGPathNode * CPathsInfo::getNode(const int3 & coord) const
  1098. {
  1099. const auto * landNode = &nodes[ELayer::LAND][coord.z][coord.x][coord.y];
  1100. if(landNode->reachable())
  1101. return landNode;
  1102. else
  1103. return &nodes[ELayer::SAIL][coord.z][coord.x][coord.y];
  1104. }
  1105. PathNodeInfo::PathNodeInfo()
  1106. : node(nullptr), nodeObject(nullptr), tile(nullptr), coord(-1, -1, -1), guarded(false), isInitialPosition(false)
  1107. {
  1108. }
  1109. void PathNodeInfo::setNode(CGameState * gs, CGPathNode * n)
  1110. {
  1111. node = n;
  1112. if(coord != node->coord)
  1113. {
  1114. assert(node->coord.valid());
  1115. coord = node->coord;
  1116. tile = gs->getTile(coord);
  1117. nodeObject = tile->topVisitableObj();
  1118. if(nodeObject && nodeObject->ID == Obj::HERO)
  1119. {
  1120. nodeHero = dynamic_cast<const CGHeroInstance *>(nodeObject);
  1121. nodeObject = tile->topVisitableObj(true);
  1122. if(!nodeObject)
  1123. nodeObject = nodeHero;
  1124. }
  1125. else
  1126. {
  1127. nodeHero = nullptr;
  1128. }
  1129. }
  1130. guarded = false;
  1131. }
  1132. void PathNodeInfo::updateInfo(CPathfinderHelper * hlp, CGameState * gs)
  1133. {
  1134. if(gs->guardingCreaturePosition(node->coord).valid() && !isInitialPosition)
  1135. {
  1136. guarded = true;
  1137. }
  1138. if(nodeObject)
  1139. {
  1140. objectRelations = gs->getPlayerRelations(hlp->owner, nodeObject->tempOwner);
  1141. }
  1142. if(nodeHero)
  1143. {
  1144. heroRelations = gs->getPlayerRelations(hlp->owner, nodeHero->tempOwner);
  1145. }
  1146. }
  1147. CDestinationNodeInfo::CDestinationNodeInfo():
  1148. blocked(false),
  1149. action(CGPathNode::ENodeAction::UNKNOWN)
  1150. {
  1151. }
  1152. void CDestinationNodeInfo::setNode(CGameState * gs, CGPathNode * n)
  1153. {
  1154. PathNodeInfo::setNode(gs, n);
  1155. blocked = false;
  1156. action = CGPathNode::ENodeAction::UNKNOWN;
  1157. }
  1158. bool CDestinationNodeInfo::isBetterWay() const
  1159. {
  1160. if(node->turns == 0xff) //we haven't been here before
  1161. return true;
  1162. else
  1163. return cost < node->getCost(); //this route is faster
  1164. }
  1165. bool PathNodeInfo::isNodeObjectVisitable() const
  1166. {
  1167. /// Hero can't visit objects while walking on water or flying
  1168. return (node->layer == EPathfindingLayer::LAND || node->layer == EPathfindingLayer::SAIL)
  1169. && (canSeeObj(nodeObject) || canSeeObj(nodeHero));
  1170. }
  1171. VCMI_LIB_NAMESPACE_END