CPathfinder.cpp 39 KB

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