CPathfinder.cpp 25 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  1. #include "StdInc.h"
  2. #include "CPathfinder.h"
  3. #include "CHeroHandler.h"
  4. #include "mapping/CMap.h"
  5. #include "CGameState.h"
  6. #include "mapObjects/CGHeroInstance.h"
  7. #include "GameConstants.h"
  8. #include "CStopWatch.h"
  9. /*
  10. * CPathfinder.cpp, part of VCMI engine
  11. *
  12. * Authors: listed in file AUTHORS in main folder
  13. *
  14. * License: GNU General Public License v2.0 or later
  15. * Full text of license available in license.txt file, in main folder
  16. *
  17. */
  18. CPathfinder::PathfinderOptions::PathfinderOptions()
  19. {
  20. useFlying = true;
  21. useWaterWalking = true;
  22. useEmbarkAndDisembark = true;
  23. useTeleportTwoWay = true;
  24. useTeleportOneWay = true;
  25. useTeleportOneWayRandom = false;
  26. useTeleportWhirlpool = true;
  27. useCastleGate = false;
  28. lightweightFlyingMode = false;
  29. oneTurnSpecialLayersLimit = true;
  30. originalMovementRules = true;
  31. }
  32. CPathfinder::CPathfinder(CPathsInfo & _out, CGameState * _gs, const CGHeroInstance * _hero)
  33. : CGameInfoCallback(_gs, boost::optional<PlayerColor>()), out(_out), hero(_hero)
  34. {
  35. assert(hero);
  36. assert(hero == getHero(hero->id));
  37. out.hero = hero;
  38. out.hpos = hero->getPosition(false);
  39. if(!isInTheMap(out.hpos)/* || !gs->map->isInTheMap(dest)*/) //check input
  40. {
  41. logGlobal->errorStream() << "CGameState::calculatePaths: Hero outside the gs->map? How dare you...";
  42. throw std::runtime_error("Wrong checksum");
  43. }
  44. hlp = make_unique<CPathfinderHelper>(hero, options);
  45. initializeGraph();
  46. neighbours.reserve(16);
  47. }
  48. void CPathfinder::calculatePaths()
  49. {
  50. auto passOneTurnLimitCheck = [&](bool shouldCheck) -> bool
  51. {
  52. if(options.oneTurnSpecialLayersLimit && shouldCheck)
  53. {
  54. if((cp->layer == ELayer::AIR || cp->layer == ELayer::WATER)
  55. && cp->accessible != CGPathNode::ACCESSIBLE)
  56. {
  57. return false;
  58. }
  59. }
  60. return true;
  61. };
  62. auto isBetterWay = [&](int remains, int turn) -> bool
  63. {
  64. if(dp->turns == 0xff) //we haven't been here before
  65. return true;
  66. else if(dp->turns > turn)
  67. return true;
  68. else if(dp->turns >= turn && dp->moveRemains < remains) //this route is faster
  69. return true;
  70. return false;
  71. };
  72. //logGlobal->infoStream() << boost::format("Calculating paths for hero %s (adress %d) of player %d") % hero->name % hero % hero->tempOwner;
  73. //initial tile - set cost on 0 and add to the queue
  74. CGPathNode * initialNode = out.getNode(out.hpos, hero->boat ? ELayer::SAIL : ELayer::LAND);
  75. initialNode->turns = 0;
  76. initialNode->moveRemains = hero->movement;
  77. pq.push(initialNode);
  78. while(!pq.empty())
  79. {
  80. cp = pq.top();
  81. pq.pop();
  82. cp->locked = true;
  83. ct = getTile(cp->coord);
  84. ctObj = ct->topVisitableObj(isSourceInitialPosition());
  85. int movement = cp->moveRemains, turn = cp->turns;
  86. hlp->updateTurnInfo(turn);
  87. if(!movement)
  88. {
  89. hlp->updateTurnInfo(++turn);
  90. movement = hlp->getMaxMovePoints(cp->layer);
  91. }
  92. //add accessible neighbouring nodes to the queue
  93. addNeighbours();
  94. for(auto & neighbour : neighbours)
  95. {
  96. dt = getTile(neighbour);
  97. dtObj = dt->topVisitableObj();
  98. for(ELayer i = ELayer::LAND; i <= ELayer::AIR; i.advance(1))
  99. {
  100. dp = out.getNode(neighbour, i);
  101. if(dp->accessible == CGPathNode::NOT_SET)
  102. continue;
  103. if(dp->locked)
  104. continue;
  105. if(!passOneTurnLimitCheck(cp->turns != turn))
  106. continue;
  107. if(!hlp->isLayerAvailable(i))
  108. continue;
  109. if(cp->layer != i && !isLayerTransitionPossible())
  110. continue;
  111. if(!isMovementToDestPossible())
  112. continue;
  113. destAction = getDestAction();
  114. int cost = CPathfinderHelper::getMovementCost(hero, cp->coord, dp->coord, movement, hlp->getTurnInfo());
  115. int remains = movement - cost;
  116. if(destAction == CGPathNode::EMBARK || destAction == CGPathNode::DISEMBARK)
  117. {
  118. remains = hero->movementPointsAfterEmbark(movement, cost, destAction - 1, hlp->getTurnInfo());
  119. cost = movement - remains;
  120. }
  121. int turnAtNextTile = turn;
  122. if(remains < 0)
  123. {
  124. //occurs rarely, when hero with low movepoints tries to leave the road
  125. hlp->updateTurnInfo(++turnAtNextTile);
  126. int moveAtNextTile = hlp->getMaxMovePoints(i);
  127. cost = CPathfinderHelper::getMovementCost(hero, cp->coord, dp->coord, moveAtNextTile, hlp->getTurnInfo()); //cost must be updated, movement points changed :(
  128. remains = moveAtNextTile - cost;
  129. }
  130. if(isBetterWay(remains, turnAtNextTile)
  131. && passOneTurnLimitCheck(cp->turns != turnAtNextTile || !remains))
  132. {
  133. assert(dp != cp->theNodeBefore); //two tiles can't point to each other
  134. dp->moveRemains = remains;
  135. dp->turns = turnAtNextTile;
  136. dp->theNodeBefore = cp;
  137. dp->action = destAction;
  138. if(isMovementAfterDestPossible())
  139. pq.push(dp);
  140. }
  141. }
  142. } //neighbours loop
  143. //just add all passable teleport exits
  144. addTeleportExits();
  145. for(auto & neighbour : neighbours)
  146. {
  147. dp = out.getNode(neighbour, cp->layer);
  148. if(dp->locked)
  149. continue;
  150. if(isBetterWay(movement, turn))
  151. {
  152. dp->moveRemains = movement;
  153. dp->turns = turn;
  154. dp->theNodeBefore = cp;
  155. dp->action = CGPathNode::NORMAL;
  156. pq.push(dp);
  157. }
  158. }
  159. } //queue loop
  160. }
  161. void CPathfinder::addNeighbours()
  162. {
  163. neighbours.clear();
  164. std::vector<int3> tiles;
  165. tiles.reserve(8);
  166. CPathfinderHelper::getNeighbours(gs->map, *ct, cp->coord, tiles, boost::logic::indeterminate, cp->layer == ELayer::SAIL);
  167. if(isSourceVisitableObj())
  168. {
  169. for(int3 tile: tiles)
  170. {
  171. if(canMoveBetween(tile, ctObj->visitablePos()))
  172. neighbours.push_back(tile);
  173. }
  174. }
  175. else
  176. vstd::concatenate(neighbours, tiles);
  177. }
  178. void CPathfinder::addTeleportExits()
  179. {
  180. neighbours.clear();
  181. if(!isSourceVisitableObj())
  182. return;
  183. const CGTeleport * objTeleport = dynamic_cast<const CGTeleport *>(ctObj);
  184. if(isAllowedTeleportEntrance(objTeleport))
  185. {
  186. for(auto objId : getTeleportChannelExits(objTeleport->channel, hero->tempOwner))
  187. {
  188. auto obj = getObj(objId);
  189. if(dynamic_cast<const CGWhirlpool *>(obj))
  190. {
  191. auto pos = obj->getBlockedPos();
  192. for(auto p : pos)
  193. {
  194. if(getTile(p)->topVisitableId() == obj->ID)
  195. neighbours.push_back(p);
  196. }
  197. }
  198. else if(CGTeleport::isExitPassable(gs, hero, obj))
  199. neighbours.push_back(obj->visitablePos());
  200. }
  201. }
  202. if(options.useCastleGate
  203. && (ctObj->ID == Obj::TOWN && ctObj->subID == ETownType::INFERNO
  204. && getPlayerRelations(hero->tempOwner, ctObj->tempOwner) != PlayerRelations::ENEMIES))
  205. {
  206. /// TODO: Find way to reuse CPlayerSpecificInfoCallback::getTownsInfo
  207. /// This may be handy if we allow to use teleportation to friendly towns
  208. auto towns = getPlayer(hero->tempOwner)->towns;
  209. for(const auto & town : towns)
  210. {
  211. if(town->id != ctObj->id && town->visitingHero == nullptr
  212. && town->hasBuilt(BuildingID::CASTLE_GATE, ETownType::INFERNO))
  213. {
  214. neighbours.push_back(town->visitablePos());
  215. }
  216. }
  217. }
  218. }
  219. bool CPathfinder::isLayerTransitionPossible() const
  220. {
  221. /// No layer transition allowed when previous node action is BATTLE
  222. if(cp->action == CGPathNode::BATTLE)
  223. return false;
  224. switch(cp->layer)
  225. {
  226. case ELayer::LAND:
  227. if(options.lightweightFlyingMode && dp->layer == ELayer::AIR)
  228. {
  229. if(!isSourceInitialPosition())
  230. return false;
  231. }
  232. else if(dp->layer == ELayer::SAIL)
  233. {
  234. /// Cannot enter empty water tile from land -> it has to be visitable
  235. if(dp->accessible == CGPathNode::ACCESSIBLE)
  236. return false;
  237. }
  238. break;
  239. case ELayer::SAIL:
  240. if(dp->layer != ELayer::LAND)
  241. return false;
  242. if(!dt->isCoastal())
  243. return false;
  244. //tile must be accessible -> exception: unblocked blockvis tiles -> clear but guarded by nearby monster coast
  245. if((dp->accessible != CGPathNode::ACCESSIBLE && (dp->accessible != CGPathNode::BLOCKVIS || dt->blocked))
  246. || dt->visitable) //TODO: passableness problem -> town says it's passable (thus accessible) but we obviously can't disembark onto town gate
  247. {
  248. return false;
  249. }
  250. break;
  251. case ELayer::AIR:
  252. if(dp->layer != ELayer::LAND)
  253. return false;
  254. if(options.originalMovementRules)
  255. {
  256. if((cp->accessible != CGPathNode::ACCESSIBLE &&
  257. cp->accessible != CGPathNode::VISITABLE) &&
  258. (dp->accessible != CGPathNode::VISITABLE &&
  259. dp->accessible != CGPathNode::ACCESSIBLE))
  260. {
  261. return false;
  262. }
  263. }
  264. else if(cp->accessible != CGPathNode::ACCESSIBLE && dp->accessible != CGPathNode::ACCESSIBLE)
  265. {
  266. /// Hero that fly can only land on accessible tiles
  267. return false;
  268. }
  269. break;
  270. case ELayer::WATER:
  271. if(dp->layer != ELayer::LAND)
  272. return false;
  273. break;
  274. }
  275. return true;
  276. }
  277. bool CPathfinder::isMovementToDestPossible() const
  278. {
  279. if(dp->accessible == CGPathNode::BLOCKED)
  280. return false;
  281. switch(dp->layer)
  282. {
  283. case ELayer::LAND:
  284. if(!canMoveBetween(cp->coord, dp->coord))
  285. return false;
  286. if(isSourceGuarded())
  287. {
  288. if(!(options.originalMovementRules && cp->layer == ELayer::AIR) &&
  289. !isDestinationGuardian()) // Can step into tile of guard
  290. {
  291. return false;
  292. }
  293. }
  294. break;
  295. case ELayer::SAIL:
  296. if(!canMoveBetween(cp->coord, dp->coord))
  297. return false;
  298. if(isSourceGuarded())
  299. {
  300. // Hero embarked a boat standing on a guarded tile -> we must allow to move away from that tile
  301. if(cp->action != CGPathNode::EMBARK && !isDestinationGuardian())
  302. return false;
  303. }
  304. if(cp->layer == ELayer::LAND)
  305. {
  306. if(!dtObj)
  307. return false;
  308. if(dtObj->ID != Obj::BOAT && dtObj->ID != Obj::HERO)
  309. return false;
  310. }
  311. else if(dtObj && dtObj->ID == Obj::BOAT)
  312. {
  313. /// Hero in boat can't visit empty boats
  314. return false;
  315. }
  316. break;
  317. case ELayer::WATER:
  318. if(!canMoveBetween(cp->coord, dp->coord) || dp->accessible != CGPathNode::ACCESSIBLE)
  319. return false;
  320. if(isDestinationGuarded())
  321. return false;
  322. break;
  323. }
  324. return true;
  325. }
  326. bool CPathfinder::isMovementAfterDestPossible() const
  327. {
  328. switch(destAction)
  329. {
  330. /// TODO: Investigate what kind of limitation is possible to apply on movement from visitable tiles
  331. /// Likely in many cases we don't need to add visitable tile to queue when hero don't fly
  332. case CGPathNode::VISIT:
  333. {
  334. /// For now we only add visitable tile into queue when it's teleporter that allow transit
  335. /// Movement from visitable tile when hero is standing on it is possible into any layer
  336. const CGTeleport * objTeleport = dynamic_cast<const CGTeleport *>(dtObj);
  337. if(isAllowedTeleportEntrance(objTeleport))
  338. {
  339. /// For now we'll always allow transit over teleporters
  340. /// Transit over whirlpools only allowed when hero protected
  341. return true;
  342. }
  343. break;
  344. }
  345. case CGPathNode::NORMAL:
  346. return true;
  347. case CGPathNode::EMBARK:
  348. if(options.useEmbarkAndDisembark)
  349. return true;
  350. break;
  351. case CGPathNode::DISEMBARK:
  352. if(options.useEmbarkAndDisembark && !isDestinationGuarded())
  353. return true;
  354. break;
  355. case CGPathNode::BATTLE:
  356. /// Movement after BATTLE action only possible from guarded tile to guardian tile
  357. if(isDestinationGuarded())
  358. return true;
  359. break;
  360. }
  361. return false;
  362. }
  363. CGPathNode::ENodeAction CPathfinder::getDestAction() const
  364. {
  365. CGPathNode::ENodeAction action = CGPathNode::NORMAL;
  366. switch(dp->layer)
  367. {
  368. case ELayer::LAND:
  369. if(cp->layer == ELayer::SAIL)
  370. {
  371. // TODO: Handle dismebark into guarded areaa
  372. action = CGPathNode::DISEMBARK;
  373. break;
  374. }
  375. /// don't break - next case shared for both land and sail layers
  376. case ELayer::SAIL:
  377. if(dtObj)
  378. {
  379. auto objRel = getPlayerRelations(dtObj->tempOwner, hero->tempOwner);
  380. if(dtObj->ID == Obj::BOAT)
  381. action = CGPathNode::EMBARK;
  382. else if(dtObj->ID == Obj::HERO)
  383. {
  384. if(objRel == PlayerRelations::ENEMIES)
  385. action = CGPathNode::BATTLE;
  386. else
  387. action = CGPathNode::BLOCKING_VISIT;
  388. }
  389. else if(dtObj->ID == Obj::TOWN && objRel == PlayerRelations::ENEMIES)
  390. {
  391. const CGTownInstance * townObj = dynamic_cast<const CGTownInstance *>(dtObj);
  392. if(townObj->armedGarrison())
  393. action = CGPathNode::BATTLE;
  394. }
  395. else if(dtObj->ID == Obj::GARRISON || dtObj->ID == Obj::GARRISON2)
  396. {
  397. const CGGarrison * garrisonObj = dynamic_cast<const CGGarrison *>(dtObj);
  398. if((garrisonObj->stacksCount() && objRel == PlayerRelations::ENEMIES) || isDestinationGuarded(true))
  399. action = CGPathNode::BATTLE;
  400. }
  401. else if(isDestinationGuardian())
  402. action = CGPathNode::BATTLE;
  403. else if(dtObj->blockVisit && !(options.useCastleGate && dtObj->ID == Obj::TOWN))
  404. action = CGPathNode::BLOCKING_VISIT;
  405. if(action == CGPathNode::NORMAL)
  406. {
  407. if(options.originalMovementRules && isDestinationGuarded())
  408. action = CGPathNode::BATTLE;
  409. else
  410. action = CGPathNode::VISIT;
  411. }
  412. }
  413. else if(isDestinationGuarded())
  414. action = CGPathNode::BATTLE;
  415. break;
  416. }
  417. return action;
  418. }
  419. bool CPathfinder::isSourceInitialPosition() const
  420. {
  421. return cp->coord == out.hpos;
  422. }
  423. bool CPathfinder::isSourceVisitableObj() const
  424. {
  425. /// Hero can't visit objects while walking on water or flying
  426. return ctObj != nullptr && (cp->layer == ELayer::LAND || cp->layer == ELayer::SAIL);
  427. }
  428. bool CPathfinder::isSourceGuarded() const
  429. {
  430. /// Hero can move from guarded tile if movement started on that tile
  431. /// It's possible at least in these cases:
  432. /// - Map start with hero on guarded tile
  433. /// - Dimention door used
  434. /// TODO: check what happen when there is several guards
  435. if(guardingCreaturePosition(cp->coord) != int3(-1, -1, -1) && !isSourceInitialPosition())
  436. {
  437. return true;
  438. }
  439. return false;
  440. }
  441. bool CPathfinder::isDestinationGuarded(const bool ignoreAccessibility) const
  442. {
  443. /// isDestinationGuarded is exception needed for garrisons.
  444. /// When monster standing behind garrison it's visitable and guarded at the same time.
  445. if(guardingCreaturePosition(dp->coord).valid()
  446. && (ignoreAccessibility || dp->accessible == CGPathNode::BLOCKVIS))
  447. {
  448. return true;
  449. }
  450. return false;
  451. }
  452. bool CPathfinder::isDestinationGuardian() const
  453. {
  454. return guardingCreaturePosition(cp->coord) == dp->coord;
  455. }
  456. void CPathfinder::initializeGraph()
  457. {
  458. auto updateNode = [&](int3 pos, ELayer layer, const TerrainTile * tinfo)
  459. {
  460. auto node = out.getNode(pos, layer);
  461. auto accessibility = evaluateAccessibility(pos, tinfo, layer);
  462. node->update(pos, layer, accessibility);
  463. };
  464. int3 pos;
  465. for(pos.x=0; pos.x < out.sizes.x; ++pos.x)
  466. {
  467. for(pos.y=0; pos.y < out.sizes.y; ++pos.y)
  468. {
  469. for(pos.z=0; pos.z < out.sizes.z; ++pos.z)
  470. {
  471. const TerrainTile * tinfo = getTile(pos);
  472. switch(tinfo->terType)
  473. {
  474. case ETerrainType::ROCK:
  475. break;
  476. case ETerrainType::WATER:
  477. updateNode(pos, ELayer::SAIL, tinfo);
  478. if(options.useFlying)
  479. updateNode(pos, ELayer::AIR, tinfo);
  480. if(options.useWaterWalking)
  481. updateNode(pos, ELayer::WATER, tinfo);
  482. break;
  483. default:
  484. updateNode(pos, ELayer::LAND, tinfo);
  485. if(options.useFlying)
  486. updateNode(pos, ELayer::AIR, tinfo);
  487. break;
  488. }
  489. }
  490. }
  491. }
  492. }
  493. CGPathNode::EAccessibility CPathfinder::evaluateAccessibility(const int3 & pos, const TerrainTile * tinfo, const ELayer layer) const
  494. {
  495. if(tinfo->terType == ETerrainType::ROCK || !isVisible(pos, hero->tempOwner))
  496. return CGPathNode::BLOCKED;
  497. switch(layer)
  498. {
  499. case ELayer::LAND:
  500. case ELayer::SAIL:
  501. if(tinfo->visitable)
  502. {
  503. if(tinfo->visitableObjects.front()->ID == Obj::SANCTUARY && tinfo->visitableObjects.back()->ID == Obj::HERO && tinfo->visitableObjects.back()->tempOwner != hero->tempOwner) //non-owned hero stands on Sanctuary
  504. {
  505. return CGPathNode::BLOCKED;
  506. }
  507. else
  508. {
  509. for(const CGObjectInstance * obj : tinfo->visitableObjects)
  510. {
  511. if(obj->passableFor(hero->tempOwner))
  512. {
  513. return CGPathNode::ACCESSIBLE;
  514. }
  515. else if(obj->blockVisit)
  516. {
  517. return CGPathNode::BLOCKVIS;
  518. }
  519. else if(obj->ID != Obj::EVENT) //pathfinder should ignore placed events
  520. {
  521. return CGPathNode::VISITABLE;
  522. }
  523. }
  524. }
  525. }
  526. else if(guardingCreaturePosition(pos).valid() && !tinfo->blocked)
  527. {
  528. // Monster close by; blocked visit for battle
  529. return CGPathNode::BLOCKVIS;
  530. }
  531. else if(tinfo->blocked)
  532. return CGPathNode::BLOCKED;
  533. break;
  534. case ELayer::WATER:
  535. if(tinfo->blocked || tinfo->terType != ETerrainType::WATER)
  536. return CGPathNode::BLOCKED;
  537. break;
  538. case ELayer::AIR:
  539. if(tinfo->blocked || tinfo->terType == ETerrainType::WATER)
  540. return CGPathNode::FLYABLE;
  541. break;
  542. }
  543. return CGPathNode::ACCESSIBLE;
  544. }
  545. bool CPathfinder::canMoveBetween(const int3 & a, const int3 & b) const
  546. {
  547. return gs->checkForVisitableDir(a, b);
  548. }
  549. bool CPathfinder::isAllowedTeleportEntrance(const CGTeleport * obj) const
  550. {
  551. if(!obj || !isTeleportEntrancePassable(obj, hero->tempOwner))
  552. return false;
  553. auto whirlpool = dynamic_cast<const CGWhirlpool *>(obj);
  554. if(whirlpool)
  555. {
  556. if(addTeleportWhirlpool(whirlpool))
  557. return true;
  558. }
  559. else if(addTeleportTwoWay(obj) || addTeleportOneWay(obj) || addTeleportOneWayRandom(obj))
  560. return true;
  561. return false;
  562. }
  563. bool CPathfinder::addTeleportTwoWay(const CGTeleport * obj) const
  564. {
  565. return options.useTeleportTwoWay && isTeleportChannelBidirectional(obj->channel, hero->tempOwner);
  566. }
  567. bool CPathfinder::addTeleportOneWay(const CGTeleport * obj) const
  568. {
  569. if(options.useTeleportOneWay && isTeleportChannelUnidirectional(obj->channel, hero->tempOwner))
  570. {
  571. auto passableExits = CGTeleport::getPassableExits(gs, hero, getTeleportChannelExits(obj->channel, hero->tempOwner));
  572. if(passableExits.size() == 1)
  573. return true;
  574. }
  575. return false;
  576. }
  577. bool CPathfinder::addTeleportOneWayRandom(const CGTeleport * obj) const
  578. {
  579. if(options.useTeleportOneWayRandom && isTeleportChannelUnidirectional(obj->channel, hero->tempOwner))
  580. {
  581. auto passableExits = CGTeleport::getPassableExits(gs, hero, getTeleportChannelExits(obj->channel, hero->tempOwner));
  582. if(passableExits.size() > 1)
  583. return true;
  584. }
  585. return false;
  586. }
  587. bool CPathfinder::addTeleportWhirlpool(const CGWhirlpool * obj) const
  588. {
  589. return options.useTeleportWhirlpool && hlp->hasBonusOfType(Bonus::WHIRLPOOL_PROTECTION) && obj;
  590. }
  591. TurnInfo::TurnInfo(const CGHeroInstance * Hero, const int turn)
  592. : hero(Hero), maxMovePointsLand(-1), maxMovePointsWater(-1)
  593. {
  594. bonuses = hero->getAllBonuses(Selector::days(turn), nullptr);
  595. }
  596. bool TurnInfo::isLayerAvailable(const EPathfindingLayer layer) const
  597. {
  598. switch(layer)
  599. {
  600. case EPathfindingLayer::AIR:
  601. if(!hasBonusOfType(Bonus::FLYING_MOVEMENT))
  602. return false;
  603. break;
  604. case EPathfindingLayer::WATER:
  605. if(!hasBonusOfType(Bonus::WATER_WALKING))
  606. return false;
  607. break;
  608. }
  609. return true;
  610. }
  611. bool TurnInfo::hasBonusOfType(Bonus::BonusType type, int subtype) const
  612. {
  613. return bonuses->getFirst(Selector::type(type).And(Selector::subtype(subtype)));
  614. }
  615. int TurnInfo::valOfBonuses(Bonus::BonusType type, int subtype) const
  616. {
  617. return bonuses->valOfBonuses(Selector::type(type).And(Selector::subtype(subtype)));
  618. }
  619. int TurnInfo::getMaxMovePoints(const EPathfindingLayer layer) const
  620. {
  621. if(maxMovePointsLand == -1)
  622. maxMovePointsLand = hero->maxMovePoints(true, this);
  623. if(maxMovePointsWater == -1)
  624. maxMovePointsWater = hero->maxMovePoints(false, this);
  625. return layer == EPathfindingLayer::SAIL ? maxMovePointsWater : maxMovePointsLand;
  626. }
  627. CPathfinderHelper::CPathfinderHelper(const CGHeroInstance * Hero, const CPathfinder::PathfinderOptions & Options)
  628. : turn(-1), hero(Hero), options(Options)
  629. {
  630. turnsInfo.reserve(16);
  631. updateTurnInfo();
  632. }
  633. void CPathfinderHelper::updateTurnInfo(const int Turn)
  634. {
  635. if(turn != Turn)
  636. {
  637. turn = Turn;
  638. if(turn >= turnsInfo.size())
  639. {
  640. auto ti = new TurnInfo(hero, turn);
  641. turnsInfo.push_back(ti);
  642. }
  643. }
  644. }
  645. bool CPathfinderHelper::isLayerAvailable(const EPathfindingLayer layer) const
  646. {
  647. switch(layer)
  648. {
  649. case EPathfindingLayer::AIR:
  650. if(!options.useFlying)
  651. return false;
  652. break;
  653. case EPathfindingLayer::WATER:
  654. if(!options.useWaterWalking)
  655. return false;
  656. break;
  657. }
  658. return turnsInfo[turn]->isLayerAvailable(layer);
  659. }
  660. const TurnInfo * CPathfinderHelper::getTurnInfo() const
  661. {
  662. return turnsInfo[turn];
  663. }
  664. bool CPathfinderHelper::hasBonusOfType(const Bonus::BonusType type, const int subtype) const
  665. {
  666. return turnsInfo[turn]->hasBonusOfType(type, subtype);
  667. }
  668. int CPathfinderHelper::getMaxMovePoints(const EPathfindingLayer layer) const
  669. {
  670. return turnsInfo[turn]->getMaxMovePoints(layer);
  671. }
  672. void CPathfinderHelper::getNeighbours(const CMap * map, const TerrainTile & srct, const int3 & tile, std::vector<int3> & vec, const boost::logic::tribool & onLand, const bool limitCoastSailing)
  673. {
  674. static const int3 dirs[] = {
  675. int3(-1, +1, +0), int3(0, +1, +0), int3(+1, +1, +0),
  676. int3(-1, +0, +0), /* source pos */ int3(+1, +0, +0),
  677. int3(-1, -1, +0), int3(0, -1, +0), int3(+1, -1, +0)
  678. };
  679. for(auto & dir : dirs)
  680. {
  681. const int3 hlp = tile + dir;
  682. if(!map->isInTheMap(hlp))
  683. continue;
  684. const TerrainTile & hlpt = map->getTile(hlp);
  685. if(hlpt.terType == ETerrainType::ROCK)
  686. continue;
  687. // //we cannot visit things from blocked tiles
  688. // if(srct.blocked && !srct.visitable && hlpt.visitable && srct.blockingObjects.front()->ID != HEROI_TYPE)
  689. // {
  690. // continue;
  691. // }
  692. /// Following condition let us avoid diagonal movement over coast when sailing
  693. if(srct.terType == ETerrainType::WATER && limitCoastSailing && hlpt.terType == ETerrainType::WATER && dir.x && dir.y) //diagonal move through water
  694. {
  695. int3 hlp1 = tile,
  696. hlp2 = tile;
  697. hlp1.x += dir.x;
  698. hlp2.y += dir.y;
  699. if(map->getTile(hlp1).terType != ETerrainType::WATER || map->getTile(hlp2).terType != ETerrainType::WATER)
  700. continue;
  701. }
  702. if(indeterminate(onLand) || onLand == (hlpt.terType != ETerrainType::WATER))
  703. {
  704. vec.push_back(hlp);
  705. }
  706. }
  707. }
  708. int CPathfinderHelper::getMovementCost(const CGHeroInstance * h, const int3 & src, const int3 & dst, const int remainingMovePoints, const TurnInfo * ti, const bool checkLast)
  709. {
  710. if(src == dst) //same tile
  711. return 0;
  712. if(!ti)
  713. ti = new TurnInfo(h);
  714. auto s = h->cb->getTile(src), d = h->cb->getTile(dst);
  715. /// TODO: by the original game rules hero shouldn't be affected by terrain penalty while flying.
  716. /// Also flying movement only has penalty when player moving over blocked tiles.
  717. /// So if you only have base flying with 40% penalty you can still ignore terrain penalty while having zero flying penalty.
  718. int ret = h->getTileCost(*d, *s, ti);
  719. /// Unfortunately this can't be implemented yet as server don't know when player flying and when he's not.
  720. /// Difference in cost calculation on client and server is much worse than incorrect cost.
  721. /// So this one is waiting till server going to use pathfinder rules for path validation.
  722. if(d->blocked && ti->hasBonusOfType(Bonus::FLYING_MOVEMENT))
  723. {
  724. ret *= (100.0 + ti->valOfBonuses(Bonus::FLYING_MOVEMENT)) / 100.0;
  725. }
  726. else if(d->terType == ETerrainType::WATER)
  727. {
  728. if(h->boat && s->hasFavourableWinds() && d->hasFavourableWinds()) //Favourable Winds
  729. ret *= 0.666;
  730. else if(!h->boat && ti->hasBonusOfType(Bonus::WATER_WALKING))
  731. {
  732. ret *= (100.0 + ti->valOfBonuses(Bonus::WATER_WALKING)) / 100.0;
  733. }
  734. }
  735. if(src.x != dst.x && src.y != dst.y) //it's diagonal move
  736. {
  737. int old = ret;
  738. ret *= 1.414213;
  739. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  740. if(ret > remainingMovePoints && remainingMovePoints >= old)
  741. return remainingMovePoints;
  742. }
  743. /// TODO: This part need rework in order to work properly with flying and water walking
  744. /// Currently it's only work properly for normal movement or sailing
  745. int left = remainingMovePoints-ret;
  746. if(checkLast && left > 0 && remainingMovePoints-ret < 250) //it might be the last tile - if no further move possible we take all move points
  747. {
  748. std::vector<int3> vec;
  749. vec.reserve(8); //optimization
  750. getNeighbours(h->cb->gameState()->map, *d, dst, vec, s->terType != ETerrainType::WATER, true);
  751. for(auto & elem : vec)
  752. {
  753. int fcost = getMovementCost(h, dst, elem, left, ti, false);
  754. if(fcost <= left)
  755. return ret;
  756. }
  757. ret = remainingMovePoints;
  758. }
  759. return ret;
  760. }
  761. int CPathfinderHelper::getMovementCost(const CGHeroInstance * h, const int3 & dst)
  762. {
  763. return getMovementCost(h, h->visitablePos(), dst, h->movement);
  764. }
  765. CGPathNode::CGPathNode()
  766. : coord(int3(-1, -1, -1)), layer(ELayer::WRONG)
  767. {
  768. reset();
  769. }
  770. void CGPathNode::reset()
  771. {
  772. locked = false;
  773. accessible = NOT_SET;
  774. moveRemains = 0;
  775. turns = 255;
  776. theNodeBefore = nullptr;
  777. action = UNKNOWN;
  778. }
  779. void CGPathNode::update(const int3 & Coord, const ELayer Layer, const EAccessibility Accessible)
  780. {
  781. if(layer == ELayer::WRONG)
  782. {
  783. coord = Coord;
  784. layer = Layer;
  785. }
  786. else
  787. reset();
  788. accessible = Accessible;
  789. }
  790. bool CGPathNode::reachable() const
  791. {
  792. return turns < 255;
  793. }
  794. int3 CGPath::startPos() const
  795. {
  796. return nodes[nodes.size()-1].coord;
  797. }
  798. int3 CGPath::endPos() const
  799. {
  800. return nodes[0].coord;
  801. }
  802. void CGPath::convert(ui8 mode)
  803. {
  804. if(mode==0)
  805. {
  806. for(auto & elem : nodes)
  807. {
  808. elem.coord = CGHeroInstance::convertPosition(elem.coord,true);
  809. }
  810. }
  811. }
  812. CPathsInfo::CPathsInfo(const int3 & Sizes)
  813. : sizes(Sizes)
  814. {
  815. hero = nullptr;
  816. nodes.resize(boost::extents[sizes.x][sizes.y][sizes.z][ELayer::NUM_LAYERS]);
  817. }
  818. CPathsInfo::~CPathsInfo()
  819. {
  820. }
  821. const CGPathNode * CPathsInfo::getPathInfo(const int3 & tile) const
  822. {
  823. assert(vstd::iswithin(tile.x, 0, sizes.x));
  824. assert(vstd::iswithin(tile.y, 0, sizes.y));
  825. assert(vstd::iswithin(tile.z, 0, sizes.z));
  826. boost::unique_lock<boost::mutex> pathLock(pathMx);
  827. return getNode(tile);
  828. }
  829. bool CPathsInfo::getPath(CGPath & out, const int3 & dst) const
  830. {
  831. boost::unique_lock<boost::mutex> pathLock(pathMx);
  832. out.nodes.clear();
  833. const CGPathNode * curnode = getNode(dst);
  834. if(!curnode->theNodeBefore)
  835. return false;
  836. while(curnode)
  837. {
  838. const CGPathNode cpn = * curnode;
  839. curnode = curnode->theNodeBefore;
  840. out.nodes.push_back(cpn);
  841. }
  842. return true;
  843. }
  844. int CPathsInfo::getDistance(const int3 & tile) const
  845. {
  846. boost::unique_lock<boost::mutex> pathLock(pathMx);
  847. CGPath ret;
  848. if(getPath(ret, tile))
  849. return ret.nodes.size();
  850. else
  851. return 255;
  852. }
  853. const CGPathNode * CPathsInfo::getNode(const int3 & coord) const
  854. {
  855. auto landNode = &nodes[coord.x][coord.y][coord.z][ELayer::LAND];
  856. if(landNode->reachable())
  857. return landNode;
  858. else
  859. return &nodes[coord.x][coord.y][coord.z][ELayer::SAIL];
  860. }
  861. CGPathNode * CPathsInfo::getNode(const int3 & coord, const ELayer layer)
  862. {
  863. return &nodes[coord.x][coord.y][coord.z][layer];
  864. }