CPathfinder.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032
  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(!isDestVisitableObj())
  307. return false;
  308. if(dtObj->ID != Obj::BOAT && dtObj->ID != Obj::HERO)
  309. return false;
  310. }
  311. else if(isDestVisitableObj() && 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(isDestVisitableObj())
  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. return isVisitableObj(ctObj, cp->layer);
  426. }
  427. bool CPathfinder::isSourceGuarded() const
  428. {
  429. /// Hero can move from guarded tile if movement started on that tile
  430. /// It's possible at least in these cases:
  431. /// - Map start with hero on guarded tile
  432. /// - Dimention door used
  433. /// TODO: check what happen when there is several guards
  434. if(guardingCreaturePosition(cp->coord) != int3(-1, -1, -1) && !isSourceInitialPosition())
  435. {
  436. return true;
  437. }
  438. return false;
  439. }
  440. bool CPathfinder::isDestVisitableObj() const
  441. {
  442. return isVisitableObj(dtObj, dp->layer);
  443. }
  444. bool CPathfinder::isDestinationGuarded(const bool ignoreAccessibility) const
  445. {
  446. /// isDestinationGuarded is exception needed for garrisons.
  447. /// When monster standing behind garrison it's visitable and guarded at the same time.
  448. if(guardingCreaturePosition(dp->coord).valid()
  449. && (ignoreAccessibility || dp->accessible == CGPathNode::BLOCKVIS))
  450. {
  451. return true;
  452. }
  453. return false;
  454. }
  455. bool CPathfinder::isDestinationGuardian() const
  456. {
  457. return guardingCreaturePosition(cp->coord) == dp->coord;
  458. }
  459. void CPathfinder::initializeGraph()
  460. {
  461. auto updateNode = [&](int3 pos, ELayer layer, const TerrainTile * tinfo)
  462. {
  463. auto node = out.getNode(pos, layer);
  464. auto accessibility = evaluateAccessibility(pos, tinfo, layer);
  465. node->update(pos, layer, accessibility);
  466. };
  467. int3 pos;
  468. for(pos.x=0; pos.x < out.sizes.x; ++pos.x)
  469. {
  470. for(pos.y=0; pos.y < out.sizes.y; ++pos.y)
  471. {
  472. for(pos.z=0; pos.z < out.sizes.z; ++pos.z)
  473. {
  474. const TerrainTile * tinfo = getTile(pos);
  475. switch(tinfo->terType)
  476. {
  477. case ETerrainType::ROCK:
  478. break;
  479. case ETerrainType::WATER:
  480. updateNode(pos, ELayer::SAIL, tinfo);
  481. if(options.useFlying)
  482. updateNode(pos, ELayer::AIR, tinfo);
  483. if(options.useWaterWalking)
  484. updateNode(pos, ELayer::WATER, tinfo);
  485. break;
  486. default:
  487. updateNode(pos, ELayer::LAND, tinfo);
  488. if(options.useFlying)
  489. updateNode(pos, ELayer::AIR, tinfo);
  490. break;
  491. }
  492. }
  493. }
  494. }
  495. }
  496. CGPathNode::EAccessibility CPathfinder::evaluateAccessibility(const int3 & pos, const TerrainTile * tinfo, const ELayer layer) const
  497. {
  498. if(tinfo->terType == ETerrainType::ROCK || !isVisible(pos, hero->tempOwner))
  499. return CGPathNode::BLOCKED;
  500. switch(layer)
  501. {
  502. case ELayer::LAND:
  503. case ELayer::SAIL:
  504. if(tinfo->visitable)
  505. {
  506. 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
  507. {
  508. return CGPathNode::BLOCKED;
  509. }
  510. else
  511. {
  512. for(const CGObjectInstance * obj : tinfo->visitableObjects)
  513. {
  514. if(obj->passableFor(hero->tempOwner))
  515. {
  516. return CGPathNode::ACCESSIBLE;
  517. }
  518. else if(obj->blockVisit)
  519. {
  520. return CGPathNode::BLOCKVIS;
  521. }
  522. else if(canSeeObj(obj))
  523. {
  524. return CGPathNode::VISITABLE;
  525. }
  526. }
  527. }
  528. }
  529. else if(guardingCreaturePosition(pos).valid() && !tinfo->blocked)
  530. {
  531. // Monster close by; blocked visit for battle
  532. return CGPathNode::BLOCKVIS;
  533. }
  534. else if(tinfo->blocked)
  535. return CGPathNode::BLOCKED;
  536. break;
  537. case ELayer::WATER:
  538. if(tinfo->blocked || tinfo->terType != ETerrainType::WATER)
  539. return CGPathNode::BLOCKED;
  540. break;
  541. case ELayer::AIR:
  542. if(tinfo->blocked || tinfo->terType == ETerrainType::WATER)
  543. return CGPathNode::FLYABLE;
  544. break;
  545. }
  546. return CGPathNode::ACCESSIBLE;
  547. }
  548. bool CPathfinder::isVisitableObj(const CGObjectInstance * obj, const ELayer layer) const
  549. {
  550. /// Hero can't visit objects while walking on water or flying
  551. return canSeeObj(obj) && (layer == ELayer::LAND || layer == ELayer::SAIL);
  552. }
  553. bool CPathfinder::canSeeObj(const CGObjectInstance * obj) const
  554. {
  555. /// Pathfinder should ignore placed events
  556. return obj != nullptr && obj->ID != Obj::EVENT;
  557. }
  558. bool CPathfinder::canMoveBetween(const int3 & a, const int3 & b) const
  559. {
  560. return gs->checkForVisitableDir(a, b);
  561. }
  562. bool CPathfinder::isAllowedTeleportEntrance(const CGTeleport * obj) const
  563. {
  564. if(!obj || !isTeleportEntrancePassable(obj, hero->tempOwner))
  565. return false;
  566. auto whirlpool = dynamic_cast<const CGWhirlpool *>(obj);
  567. if(whirlpool)
  568. {
  569. if(addTeleportWhirlpool(whirlpool))
  570. return true;
  571. }
  572. else if(addTeleportTwoWay(obj) || addTeleportOneWay(obj) || addTeleportOneWayRandom(obj))
  573. return true;
  574. return false;
  575. }
  576. bool CPathfinder::addTeleportTwoWay(const CGTeleport * obj) const
  577. {
  578. return options.useTeleportTwoWay && isTeleportChannelBidirectional(obj->channel, hero->tempOwner);
  579. }
  580. bool CPathfinder::addTeleportOneWay(const CGTeleport * obj) const
  581. {
  582. if(options.useTeleportOneWay && isTeleportChannelUnidirectional(obj->channel, hero->tempOwner))
  583. {
  584. auto passableExits = CGTeleport::getPassableExits(gs, hero, getTeleportChannelExits(obj->channel, hero->tempOwner));
  585. if(passableExits.size() == 1)
  586. return true;
  587. }
  588. return false;
  589. }
  590. bool CPathfinder::addTeleportOneWayRandom(const CGTeleport * obj) const
  591. {
  592. if(options.useTeleportOneWayRandom && isTeleportChannelUnidirectional(obj->channel, hero->tempOwner))
  593. {
  594. auto passableExits = CGTeleport::getPassableExits(gs, hero, getTeleportChannelExits(obj->channel, hero->tempOwner));
  595. if(passableExits.size() > 1)
  596. return true;
  597. }
  598. return false;
  599. }
  600. bool CPathfinder::addTeleportWhirlpool(const CGWhirlpool * obj) const
  601. {
  602. return options.useTeleportWhirlpool && hlp->hasBonusOfType(Bonus::WHIRLPOOL_PROTECTION) && obj;
  603. }
  604. TurnInfo::TurnInfo(const CGHeroInstance * Hero, const int turn)
  605. : hero(Hero), maxMovePointsLand(-1), maxMovePointsWater(-1)
  606. {
  607. bonuses = hero->getAllBonuses(Selector::days(turn), nullptr);
  608. }
  609. bool TurnInfo::isLayerAvailable(const EPathfindingLayer layer) const
  610. {
  611. switch(layer)
  612. {
  613. case EPathfindingLayer::AIR:
  614. if(!hasBonusOfType(Bonus::FLYING_MOVEMENT))
  615. return false;
  616. break;
  617. case EPathfindingLayer::WATER:
  618. if(!hasBonusOfType(Bonus::WATER_WALKING))
  619. return false;
  620. break;
  621. }
  622. return true;
  623. }
  624. bool TurnInfo::hasBonusOfType(Bonus::BonusType type, int subtype) const
  625. {
  626. return bonuses->getFirst(Selector::type(type).And(Selector::subtype(subtype)));
  627. }
  628. int TurnInfo::valOfBonuses(Bonus::BonusType type, int subtype) const
  629. {
  630. return bonuses->valOfBonuses(Selector::type(type).And(Selector::subtype(subtype)));
  631. }
  632. int TurnInfo::getMaxMovePoints(const EPathfindingLayer layer) const
  633. {
  634. if(maxMovePointsLand == -1)
  635. maxMovePointsLand = hero->maxMovePoints(true, this);
  636. if(maxMovePointsWater == -1)
  637. maxMovePointsWater = hero->maxMovePoints(false, this);
  638. return layer == EPathfindingLayer::SAIL ? maxMovePointsWater : maxMovePointsLand;
  639. }
  640. CPathfinderHelper::CPathfinderHelper(const CGHeroInstance * Hero, const CPathfinder::PathfinderOptions & Options)
  641. : turn(-1), hero(Hero), options(Options)
  642. {
  643. turnsInfo.reserve(16);
  644. updateTurnInfo();
  645. }
  646. void CPathfinderHelper::updateTurnInfo(const int Turn)
  647. {
  648. if(turn != Turn)
  649. {
  650. turn = Turn;
  651. if(turn >= turnsInfo.size())
  652. {
  653. auto ti = new TurnInfo(hero, turn);
  654. turnsInfo.push_back(ti);
  655. }
  656. }
  657. }
  658. bool CPathfinderHelper::isLayerAvailable(const EPathfindingLayer layer) const
  659. {
  660. switch(layer)
  661. {
  662. case EPathfindingLayer::AIR:
  663. if(!options.useFlying)
  664. return false;
  665. break;
  666. case EPathfindingLayer::WATER:
  667. if(!options.useWaterWalking)
  668. return false;
  669. break;
  670. }
  671. return turnsInfo[turn]->isLayerAvailable(layer);
  672. }
  673. const TurnInfo * CPathfinderHelper::getTurnInfo() const
  674. {
  675. return turnsInfo[turn];
  676. }
  677. bool CPathfinderHelper::hasBonusOfType(const Bonus::BonusType type, const int subtype) const
  678. {
  679. return turnsInfo[turn]->hasBonusOfType(type, subtype);
  680. }
  681. int CPathfinderHelper::getMaxMovePoints(const EPathfindingLayer layer) const
  682. {
  683. return turnsInfo[turn]->getMaxMovePoints(layer);
  684. }
  685. void CPathfinderHelper::getNeighbours(const CMap * map, const TerrainTile & srct, const int3 & tile, std::vector<int3> & vec, const boost::logic::tribool & onLand, const bool limitCoastSailing)
  686. {
  687. static const int3 dirs[] = {
  688. int3(-1, +1, +0), int3(0, +1, +0), int3(+1, +1, +0),
  689. int3(-1, +0, +0), /* source pos */ int3(+1, +0, +0),
  690. int3(-1, -1, +0), int3(0, -1, +0), int3(+1, -1, +0)
  691. };
  692. for(auto & dir : dirs)
  693. {
  694. const int3 hlp = tile + dir;
  695. if(!map->isInTheMap(hlp))
  696. continue;
  697. const TerrainTile & hlpt = map->getTile(hlp);
  698. if(hlpt.terType == ETerrainType::ROCK)
  699. continue;
  700. // //we cannot visit things from blocked tiles
  701. // if(srct.blocked && !srct.visitable && hlpt.visitable && srct.blockingObjects.front()->ID != HEROI_TYPE)
  702. // {
  703. // continue;
  704. // }
  705. /// Following condition let us avoid diagonal movement over coast when sailing
  706. if(srct.terType == ETerrainType::WATER && limitCoastSailing && hlpt.terType == ETerrainType::WATER && dir.x && dir.y) //diagonal move through water
  707. {
  708. int3 hlp1 = tile,
  709. hlp2 = tile;
  710. hlp1.x += dir.x;
  711. hlp2.y += dir.y;
  712. if(map->getTile(hlp1).terType != ETerrainType::WATER || map->getTile(hlp2).terType != ETerrainType::WATER)
  713. continue;
  714. }
  715. if(indeterminate(onLand) || onLand == (hlpt.terType != ETerrainType::WATER))
  716. {
  717. vec.push_back(hlp);
  718. }
  719. }
  720. }
  721. int CPathfinderHelper::getMovementCost(const CGHeroInstance * h, const int3 & src, const int3 & dst, const int remainingMovePoints, const TurnInfo * ti, const bool checkLast)
  722. {
  723. if(src == dst) //same tile
  724. return 0;
  725. if(!ti)
  726. ti = new TurnInfo(h);
  727. auto s = h->cb->getTile(src), d = h->cb->getTile(dst);
  728. /// TODO: by the original game rules hero shouldn't be affected by terrain penalty while flying.
  729. /// Also flying movement only has penalty when player moving over blocked tiles.
  730. /// So if you only have base flying with 40% penalty you can still ignore terrain penalty while having zero flying penalty.
  731. int ret = h->getTileCost(*d, *s, ti);
  732. /// Unfortunately this can't be implemented yet as server don't know when player flying and when he's not.
  733. /// Difference in cost calculation on client and server is much worse than incorrect cost.
  734. /// So this one is waiting till server going to use pathfinder rules for path validation.
  735. if(d->blocked && ti->hasBonusOfType(Bonus::FLYING_MOVEMENT))
  736. {
  737. ret *= (100.0 + ti->valOfBonuses(Bonus::FLYING_MOVEMENT)) / 100.0;
  738. }
  739. else if(d->terType == ETerrainType::WATER)
  740. {
  741. if(h->boat && s->hasFavourableWinds() && d->hasFavourableWinds()) //Favourable Winds
  742. ret *= 0.666;
  743. else if(!h->boat && ti->hasBonusOfType(Bonus::WATER_WALKING))
  744. {
  745. ret *= (100.0 + ti->valOfBonuses(Bonus::WATER_WALKING)) / 100.0;
  746. }
  747. }
  748. if(src.x != dst.x && src.y != dst.y) //it's diagonal move
  749. {
  750. int old = ret;
  751. ret *= 1.414213;
  752. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  753. if(ret > remainingMovePoints && remainingMovePoints >= old)
  754. return remainingMovePoints;
  755. }
  756. /// TODO: This part need rework in order to work properly with flying and water walking
  757. /// Currently it's only work properly for normal movement or sailing
  758. int left = remainingMovePoints-ret;
  759. if(checkLast && left > 0 && remainingMovePoints-ret < 250) //it might be the last tile - if no further move possible we take all move points
  760. {
  761. std::vector<int3> vec;
  762. vec.reserve(8); //optimization
  763. getNeighbours(h->cb->gameState()->map, *d, dst, vec, s->terType != ETerrainType::WATER, true);
  764. for(auto & elem : vec)
  765. {
  766. int fcost = getMovementCost(h, dst, elem, left, ti, false);
  767. if(fcost <= left)
  768. return ret;
  769. }
  770. ret = remainingMovePoints;
  771. }
  772. return ret;
  773. }
  774. int CPathfinderHelper::getMovementCost(const CGHeroInstance * h, const int3 & dst)
  775. {
  776. return getMovementCost(h, h->visitablePos(), dst, h->movement);
  777. }
  778. CGPathNode::CGPathNode()
  779. : coord(int3(-1, -1, -1)), layer(ELayer::WRONG)
  780. {
  781. reset();
  782. }
  783. void CGPathNode::reset()
  784. {
  785. locked = false;
  786. accessible = NOT_SET;
  787. moveRemains = 0;
  788. turns = 255;
  789. theNodeBefore = nullptr;
  790. action = UNKNOWN;
  791. }
  792. void CGPathNode::update(const int3 & Coord, const ELayer Layer, const EAccessibility Accessible)
  793. {
  794. if(layer == ELayer::WRONG)
  795. {
  796. coord = Coord;
  797. layer = Layer;
  798. }
  799. else
  800. reset();
  801. accessible = Accessible;
  802. }
  803. bool CGPathNode::reachable() const
  804. {
  805. return turns < 255;
  806. }
  807. int3 CGPath::startPos() const
  808. {
  809. return nodes[nodes.size()-1].coord;
  810. }
  811. int3 CGPath::endPos() const
  812. {
  813. return nodes[0].coord;
  814. }
  815. void CGPath::convert(ui8 mode)
  816. {
  817. if(mode==0)
  818. {
  819. for(auto & elem : nodes)
  820. {
  821. elem.coord = CGHeroInstance::convertPosition(elem.coord,true);
  822. }
  823. }
  824. }
  825. CPathsInfo::CPathsInfo(const int3 & Sizes)
  826. : sizes(Sizes)
  827. {
  828. hero = nullptr;
  829. nodes.resize(boost::extents[sizes.x][sizes.y][sizes.z][ELayer::NUM_LAYERS]);
  830. }
  831. CPathsInfo::~CPathsInfo()
  832. {
  833. }
  834. const CGPathNode * CPathsInfo::getPathInfo(const int3 & tile) const
  835. {
  836. assert(vstd::iswithin(tile.x, 0, sizes.x));
  837. assert(vstd::iswithin(tile.y, 0, sizes.y));
  838. assert(vstd::iswithin(tile.z, 0, sizes.z));
  839. boost::unique_lock<boost::mutex> pathLock(pathMx);
  840. return getNode(tile);
  841. }
  842. bool CPathsInfo::getPath(CGPath & out, const int3 & dst) const
  843. {
  844. boost::unique_lock<boost::mutex> pathLock(pathMx);
  845. out.nodes.clear();
  846. const CGPathNode * curnode = getNode(dst);
  847. if(!curnode->theNodeBefore)
  848. return false;
  849. while(curnode)
  850. {
  851. const CGPathNode cpn = * curnode;
  852. curnode = curnode->theNodeBefore;
  853. out.nodes.push_back(cpn);
  854. }
  855. return true;
  856. }
  857. int CPathsInfo::getDistance(const int3 & tile) const
  858. {
  859. boost::unique_lock<boost::mutex> pathLock(pathMx);
  860. CGPath ret;
  861. if(getPath(ret, tile))
  862. return ret.nodes.size();
  863. else
  864. return 255;
  865. }
  866. const CGPathNode * CPathsInfo::getNode(const int3 & coord) const
  867. {
  868. auto landNode = &nodes[coord.x][coord.y][coord.z][ELayer::LAND];
  869. if(landNode->reachable())
  870. return landNode;
  871. else
  872. return &nodes[coord.x][coord.y][coord.z][ELayer::SAIL];
  873. }
  874. CGPathNode * CPathsInfo::getNode(const int3 & coord, const ELayer layer)
  875. {
  876. return &nodes[coord.x][coord.y][coord.z][layer];
  877. }