CPathfinder.cpp 28 KB

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