CPathfinder.cpp 39 KB

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