CPathfinder.cpp 28 KB

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