CPathfinder.cpp 28 KB

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