CPathfinder.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. #include "StdInc.h"
  2. #include "CPathfinder.h"
  3. #include "CHeroHandler.h"
  4. #include "mapping/CMap.h"
  5. #include "CGameState.h"
  6. #include "mapObjects/CGHeroInstance.h"
  7. #include "GameConstants.h"
  8. #include "CStopWatch.h"
  9. /*
  10. * CPathfinder.cpp, part of VCMI engine
  11. *
  12. * Authors: listed in file AUTHORS in main folder
  13. *
  14. * License: GNU General Public License v2.0 or later
  15. * Full text of license available in license.txt file, in main folder
  16. *
  17. */
  18. CPathfinder::PathfinderOptions::PathfinderOptions()
  19. {
  20. useFlying = false;
  21. useWaterWalking = false;
  22. useEmbarkAndDisembark = true;
  23. useTeleportTwoWay = true;
  24. useTeleportOneWay = true;
  25. useTeleportOneWayRandom = false;
  26. useTeleportWhirlpool = false;
  27. lightweightFlyingMode = false;
  28. }
  29. CPathfinder::CPathfinder(CPathsInfo &_out, CGameState *_gs, const CGHeroInstance *_hero) : CGameInfoCallback(_gs, boost::optional<PlayerColor>()), out(_out), hero(_hero), FoW(getPlayerTeam(hero->tempOwner)->fogOfWarMap)
  30. {
  31. assert(hero);
  32. assert(hero == getHero(hero->id));
  33. out.hero = hero;
  34. out.hpos = hero->getPosition(false);
  35. if(!gs->map->isInTheMap(out.hpos)/* || !gs->map->isInTheMap(dest)*/) //check input
  36. {
  37. logGlobal->errorStream() << "CGameState::calculatePaths: Hero outside the gs->map? How dare you...";
  38. throw std::runtime_error("Wrong checksum");
  39. }
  40. if(hero->canFly())
  41. options.useFlying = true;
  42. if(hero->canWalkOnSea())
  43. options.useWaterWalking = true;
  44. if(CGWhirlpool::isProtected(hero))
  45. options.useTeleportWhirlpool = true;
  46. initializeGraph();
  47. neighbours.reserve(16);
  48. }
  49. void CPathfinder::calculatePaths()
  50. {
  51. int maxMovePointsLand = hero->maxMovePoints(true);
  52. int maxMovePointsWater = hero->maxMovePoints(false);
  53. auto maxMovePoints = [&](CGPathNode *cp) -> int
  54. {
  55. return cp->land ? maxMovePointsLand : maxMovePointsWater;
  56. };
  57. auto isBetterWay = [&](int remains, int turn) -> bool
  58. {
  59. if(dp->turns == 0xff) //we haven't been here before
  60. return true;
  61. else if(dp->turns > turn)
  62. return true;
  63. else if(dp->turns >= turn && dp->moveRemains < remains) //this route is faster
  64. return true;
  65. return false;
  66. };
  67. //logGlobal->infoStream() << boost::format("Calculating paths for hero %s (adress %d) of player %d") % hero->name % hero % hero->tempOwner;
  68. //initial tile - set cost on 0 and add to the queue
  69. CGPathNode *initialNode = out.getNode(out.hpos, hero->boat ? EPathfindingLayer::SAIL : EPathfindingLayer::LAND);
  70. initialNode->turns = 0;
  71. initialNode->moveRemains = hero->movement;
  72. mq.push_back(initialNode);
  73. while(!mq.empty())
  74. {
  75. cp = mq.front();
  76. mq.pop_front();
  77. int movement = cp->moveRemains, turn = cp->turns;
  78. if(!movement)
  79. {
  80. movement = maxMovePoints(cp);
  81. turn++;
  82. }
  83. //add accessible neighbouring nodes to the queue
  84. addNeighbours(cp->coord);
  85. for(auto & neighbour : neighbours)
  86. {
  87. dt = &gs->map->getTile(neighbour);
  88. for(EPathfindingLayer i = EPathfindingLayer::LAND; i <= EPathfindingLayer::AIR; i.advance(1))
  89. {
  90. useEmbarkCost = 0; //0 - usual movement; 1 - embark; 2 - disembark
  91. dp = out.getNode(neighbour, i);
  92. if(dp->accessible == CGPathNode::NOT_SET)
  93. continue;
  94. if(cp->layer != i && !isLayerTransitionPossible())
  95. continue;
  96. if(!isMovementToDestPossible())
  97. continue;
  98. int cost = gs->getMovementCost(hero, cp->coord, dp->coord, movement);
  99. int remains = movement - cost;
  100. if(useEmbarkCost)
  101. {
  102. remains = hero->movementPointsAfterEmbark(movement, cost, useEmbarkCost - 1);
  103. cost = movement - remains;
  104. }
  105. int turnAtNextTile = turn;
  106. if(remains < 0)
  107. {
  108. //occurs rarely, when hero with low movepoints tries to leave the road
  109. turnAtNextTile++;
  110. int moveAtNextTile = maxMovePoints(cp);
  111. cost = gs->getMovementCost(hero, cp->coord, dp->coord, moveAtNextTile); //cost must be updated, movement points changed :(
  112. remains = moveAtNextTile - cost;
  113. }
  114. if(isBetterWay(remains, turnAtNextTile))
  115. {
  116. assert(dp != cp->theNodeBefore); //two tiles can't point to each other
  117. dp->moveRemains = remains;
  118. dp->turns = turnAtNextTile;
  119. dp->theNodeBefore = cp;
  120. if(isMovementAfterDestPossible())
  121. mq.push_back(dp);
  122. }
  123. }
  124. } //neighbours loop
  125. //just add all passable teleport exits
  126. if(sTileObj && canVisitObject())
  127. {
  128. addTeleportExits();
  129. for(auto & neighbour : neighbours)
  130. {
  131. dp = out.getNode(neighbour, cp->layer);
  132. if(isBetterWay(movement, turn))
  133. {
  134. dp->moveRemains = movement;
  135. dp->turns = turn;
  136. dp->theNodeBefore = cp;
  137. mq.push_back(dp);
  138. }
  139. }
  140. }
  141. } //queue loop
  142. }
  143. void CPathfinder::addNeighbours(const int3 &coord)
  144. {
  145. neighbours.clear();
  146. ct = &gs->map->getTile(coord);
  147. std::vector<int3> tiles;
  148. gs->getNeighbours(*ct, coord, tiles, boost::logic::indeterminate, !cp->land);
  149. sTileObj = ct->topVisitableObj(coord == out.hpos);
  150. if(canVisitObject())
  151. {
  152. if(sTileObj)
  153. {
  154. for(int3 tile: tiles)
  155. {
  156. if(canMoveBetween(tile, sTileObj->visitablePos()))
  157. neighbours.push_back(tile);
  158. }
  159. }
  160. else
  161. vstd::concatenate(neighbours, tiles);
  162. }
  163. else
  164. vstd::concatenate(neighbours, tiles);
  165. }
  166. void CPathfinder::addTeleportExits(bool noTeleportExcludes)
  167. {
  168. assert(sTileObj);
  169. neighbours.clear();
  170. auto isAllowedTeleportEntrance = [&](const CGTeleport * obj) -> bool
  171. {
  172. if(!gs->isTeleportEntrancePassable(obj, hero->tempOwner))
  173. return false;
  174. if(noTeleportExcludes)
  175. return true;
  176. auto whirlpool = dynamic_cast<const CGWhirlpool *>(obj);
  177. if(whirlpool)
  178. {
  179. if(addTeleportWhirlpool(whirlpool))
  180. return true;
  181. }
  182. else if(addTeleportTwoWay(obj) || addTeleportOneWay(obj) || addTeleportOneWayRandom(obj))
  183. return true;
  184. return false;
  185. };
  186. const CGTeleport *sTileTeleport = dynamic_cast<const CGTeleport *>(sTileObj);
  187. if(isAllowedTeleportEntrance(sTileTeleport))
  188. {
  189. for(auto objId : gs->getTeleportChannelExits(sTileTeleport->channel, hero->tempOwner))
  190. {
  191. auto obj = getObj(objId);
  192. if(CGTeleport::isExitPassable(gs, hero, obj))
  193. neighbours.push_back(obj->visitablePos());
  194. }
  195. }
  196. }
  197. bool CPathfinder::isLayerTransitionPossible()
  198. {
  199. if((cp->layer == EPathfindingLayer::AIR || cp->layer == EPathfindingLayer::WATER)
  200. && dp->layer != EPathfindingLayer::LAND)
  201. {
  202. return false;
  203. }
  204. else if(cp->layer == EPathfindingLayer::LAND && dp->layer == EPathfindingLayer::AIR)
  205. {
  206. if(options.lightweightFlyingMode && !isSourceInitialPosition())
  207. return false;
  208. }
  209. else if(cp->layer == EPathfindingLayer::SAIL && dp->layer != EPathfindingLayer::LAND)
  210. return false;
  211. else if(cp->layer == EPathfindingLayer::SAIL && dp->layer == EPathfindingLayer::LAND)
  212. {
  213. if(!dt->isCoastal())
  214. return false;
  215. //tile must be accessible -> exception: unblocked blockvis tiles -> clear but guarded by nearby monster coast
  216. if((dp->accessible != CGPathNode::ACCESSIBLE && (dp->accessible != CGPathNode::BLOCKVIS || dt->blocked))
  217. || dt->visitable) //TODO: passableness problem -> town says it's passable (thus accessible) but we obviously can't disembark onto town gate
  218. return false;
  219. useEmbarkCost = 2;
  220. }
  221. else if(cp->layer == EPathfindingLayer::LAND && dp->layer == EPathfindingLayer::SAIL)
  222. {
  223. Obj destTopVisObjID = dt->topVisitableId();
  224. if(dp->accessible == CGPathNode::ACCESSIBLE || destTopVisObjID < 0) //cannot enter empty water tile from land -> it has to be visitable
  225. return false;
  226. if(destTopVisObjID != Obj::HERO && destTopVisObjID != Obj::BOAT) //only boat or hero can be accessed from land
  227. return false;
  228. if(destTopVisObjID == Obj::BOAT)
  229. useEmbarkCost = 1;
  230. }
  231. return true;
  232. }
  233. bool CPathfinder::isMovementToDestPossible()
  234. {
  235. switch (dp->layer)
  236. {
  237. case EPathfindingLayer::LAND:
  238. if(!canMoveBetween(cp->coord, dp->coord) || dp->accessible == CGPathNode::BLOCKED)
  239. return false;
  240. if(isSourceGuarded() && !isDestinationGuardian()) // Can step into tile of guard
  241. return false;
  242. break;
  243. case EPathfindingLayer::SAIL:
  244. if(!canMoveBetween(cp->coord, dp->coord) || dp->accessible == CGPathNode::BLOCKED)
  245. return false;
  246. if(isSourceGuarded() && !isDestinationGuardian()) // Can step into tile of guard
  247. return false;
  248. break;
  249. case EPathfindingLayer::AIR:
  250. //if(!canMoveBetween(cp->coord, dp->coord))
  251. // return false;
  252. break;
  253. case EPathfindingLayer::WATER:
  254. if(!canMoveBetween(cp->coord, dp->coord) || dp->accessible != CGPathNode::ACCESSIBLE)
  255. return false;
  256. if(isDestinationGuarded())
  257. return false;
  258. break;
  259. }
  260. return true;
  261. }
  262. bool CPathfinder::isMovementAfterDestPossible()
  263. {
  264. switch (dp->layer)
  265. {
  266. case EPathfindingLayer::LAND:
  267. case EPathfindingLayer::SAIL:
  268. if(dp->accessible == CGPathNode::ACCESSIBLE)
  269. return true;
  270. if(dp->coord == out.hpos)
  271. return true; // This one is tricky, we can ignore fact that tile is not ACCESSIBLE in case if it's our hero block it. Though this need investigation
  272. if(dp->accessible == CGPathNode::VISITABLE && CGTeleport::isTeleport(dt->topVisitableObj()))
  273. return true; // For now we'll always allow transit for teleporters
  274. if(useEmbarkCost && options.useEmbarkAndDisembark)
  275. return true;
  276. break;
  277. case EPathfindingLayer::AIR:
  278. case EPathfindingLayer::WATER:
  279. return true;
  280. break;
  281. }
  282. return false;
  283. }
  284. bool CPathfinder::isSourceInitialPosition()
  285. {
  286. return cp->coord == out.hpos;
  287. }
  288. int3 CPathfinder::getSourceGuardPosition()
  289. {
  290. return gs->map->guardingCreaturePositions[cp->coord.x][cp->coord.y][cp->coord.z];
  291. }
  292. bool CPathfinder::isSourceGuarded()
  293. {
  294. //map can start with hero on guarded tile or teleport there using dimension door
  295. //so threat tile hero standing on like it's not guarded because it's should be possible to move out of here
  296. if(getSourceGuardPosition() != int3(-1, -1, -1) && !isSourceInitialPosition())
  297. {
  298. //special case -> hero embarked a boat standing on a guarded tile -> we must allow to move away from that tile
  299. if(cp->accessible != CGPathNode::VISITABLE
  300. || !cp->theNodeBefore->land
  301. || ct->topVisitableId() != Obj::BOAT)
  302. {
  303. return true;
  304. }
  305. }
  306. return false;
  307. }
  308. bool CPathfinder::isDestinationGuarded()
  309. {
  310. if(gs->map->guardingCreaturePositions[dp->coord.x][dp->coord.y][dp->coord.z].valid()
  311. && dp->accessible == CGPathNode::BLOCKVIS)
  312. {
  313. return true;
  314. }
  315. return false;
  316. }
  317. bool CPathfinder::isDestinationGuardian()
  318. {
  319. return getSourceGuardPosition() == dp->coord;
  320. }
  321. void CPathfinder::initializeGraph()
  322. {
  323. auto initializeNode = [&](int3 pos, EPathfindingLayer layer, const TerrainTile *tinfo)
  324. {
  325. auto node = out.getNode(pos, layer);
  326. node->accessible = evaluateAccessibility(pos, tinfo);
  327. node->turns = 0xff;
  328. node->moveRemains = 0;
  329. node->coord = pos;
  330. node->land = tinfo->terType != ETerrainType::WATER;
  331. node->theNodeBefore = nullptr;
  332. node->layer = layer;
  333. };
  334. int3 pos;
  335. for(pos.x=0; pos.x < out.sizes.x; ++pos.x)
  336. {
  337. for(pos.y=0; pos.y < out.sizes.y; ++pos.y)
  338. {
  339. for(pos.z=0; pos.z < out.sizes.z; ++pos.z)
  340. {
  341. const TerrainTile *tinfo = &gs->map->getTile(pos);
  342. switch (tinfo->terType)
  343. {
  344. case ETerrainType::WRONG:
  345. case ETerrainType::BORDER:
  346. case ETerrainType::ROCK:
  347. break;
  348. case ETerrainType::WATER:
  349. initializeNode(pos, EPathfindingLayer::SAIL, tinfo);
  350. if(options.useFlying)
  351. initializeNode(pos, EPathfindingLayer::AIR, tinfo);
  352. if(options.useWaterWalking)
  353. initializeNode(pos, EPathfindingLayer::WATER, tinfo);
  354. break;
  355. default:
  356. initializeNode(pos, EPathfindingLayer::LAND, tinfo);
  357. if(options.useFlying)
  358. initializeNode(pos, EPathfindingLayer::AIR, tinfo);
  359. break;
  360. }
  361. }
  362. }
  363. }
  364. }
  365. CGPathNode::EAccessibility CPathfinder::evaluateAccessibility(const int3 &pos, const TerrainTile *tinfo) const
  366. {
  367. CGPathNode::EAccessibility ret = (tinfo->blocked ? CGPathNode::BLOCKED : CGPathNode::ACCESSIBLE);
  368. if(tinfo->terType == ETerrainType::ROCK || !FoW[pos.x][pos.y][pos.z])
  369. return CGPathNode::BLOCKED;
  370. if(tinfo->visitable)
  371. {
  372. 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
  373. {
  374. return CGPathNode::BLOCKED;
  375. }
  376. else
  377. {
  378. for(const CGObjectInstance *obj : tinfo->visitableObjects)
  379. {
  380. if(obj->passableFor(hero->tempOwner))
  381. {
  382. ret = CGPathNode::ACCESSIBLE;
  383. }
  384. else if(obj->blockVisit)
  385. {
  386. return CGPathNode::BLOCKVIS;
  387. }
  388. else if(obj->ID != Obj::EVENT) //pathfinder should ignore placed events
  389. {
  390. ret = CGPathNode::VISITABLE;
  391. }
  392. }
  393. }
  394. }
  395. else if(gs->map->guardingCreaturePositions[pos.x][pos.y][pos.z].valid()
  396. && !tinfo->blocked)
  397. {
  398. // Monster close by; blocked visit for battle.
  399. return CGPathNode::BLOCKVIS;
  400. }
  401. return ret;
  402. }
  403. bool CPathfinder::canMoveBetween(const int3 &a, const int3 &b) const
  404. {
  405. return gs->checkForVisitableDir(a, b);
  406. }
  407. bool CPathfinder::addTeleportTwoWay(const CGTeleport * obj) const
  408. {
  409. return options.useTeleportTwoWay && gs->isTeleportChannelBidirectional(obj->channel, hero->tempOwner);
  410. }
  411. bool CPathfinder::addTeleportOneWay(const CGTeleport * obj) const
  412. {
  413. if(options.useTeleportOneWay && isTeleportChannelUnidirectional(obj->channel, hero->tempOwner))
  414. {
  415. auto passableExits = CGTeleport::getPassableExits(gs, hero, gs->getTeleportChannelExits(obj->channel, hero->tempOwner));
  416. if(passableExits.size() == 1)
  417. return true;
  418. }
  419. return false;
  420. }
  421. bool CPathfinder::addTeleportOneWayRandom(const CGTeleport * obj) const
  422. {
  423. if(options.useTeleportOneWayRandom && isTeleportChannelUnidirectional(obj->channel, hero->tempOwner))
  424. {
  425. auto passableExits = CGTeleport::getPassableExits(gs, hero, gs->getTeleportChannelExits(obj->channel, hero->tempOwner));
  426. if(passableExits.size() > 1)
  427. return true;
  428. }
  429. return false;
  430. }
  431. bool CPathfinder::addTeleportWhirlpool(const CGWhirlpool * obj) const
  432. {
  433. return options.useTeleportWhirlpool && obj;
  434. }
  435. bool CPathfinder::canVisitObject() const
  436. {
  437. //hero can't visit objects while walking on water or flying
  438. return cp->layer == EPathfindingLayer::LAND || cp->layer == EPathfindingLayer::SAIL;
  439. }
  440. CGPathNode::CGPathNode()
  441. :coord(-1,-1,-1)
  442. {
  443. accessible = NOT_SET;
  444. land = 0;
  445. moveRemains = 0;
  446. turns = 255;
  447. theNodeBefore = nullptr;
  448. layer = EPathfindingLayer::WRONG;
  449. }
  450. bool CGPathNode::reachable() const
  451. {
  452. return turns < 255;
  453. }
  454. int3 CGPath::startPos() const
  455. {
  456. return nodes[nodes.size()-1].coord;
  457. }
  458. int3 CGPath::endPos() const
  459. {
  460. return nodes[0].coord;
  461. }
  462. void CGPath::convert( ui8 mode )
  463. {
  464. if(mode==0)
  465. {
  466. for(auto & elem : nodes)
  467. {
  468. elem.coord = CGHeroInstance::convertPosition(elem.coord,true);
  469. }
  470. }
  471. }
  472. CPathsInfo::CPathsInfo( const int3 &Sizes )
  473. :sizes(Sizes)
  474. {
  475. hero = nullptr;
  476. nodes = new CGPathNode***[sizes.x];
  477. for(int i = 0; i < sizes.x; i++)
  478. {
  479. nodes[i] = new CGPathNode**[sizes.y];
  480. for(int j = 0; j < sizes.y; j++)
  481. {
  482. nodes[i][j] = new CGPathNode*[sizes.z];
  483. for (int z = 0; z < sizes.z; z++)
  484. {
  485. nodes[i][j][z] = new CGPathNode[EPathfindingLayer::NUM_LAYERS];
  486. }
  487. }
  488. }
  489. }
  490. CPathsInfo::~CPathsInfo()
  491. {
  492. for(int i = 0; i < sizes.x; i++)
  493. {
  494. for(int j = 0; j < sizes.y; j++)
  495. {
  496. for (int z = 0; z < sizes.z; z++)
  497. {
  498. delete [] nodes[i][j][z];
  499. }
  500. delete [] nodes[i][j];
  501. }
  502. delete [] nodes[i];
  503. }
  504. delete [] nodes;
  505. }
  506. const CGPathNode * CPathsInfo::getPathInfo(const int3 &tile, const EPathfindingLayer &layer) const
  507. {
  508. boost::unique_lock<boost::mutex> pathLock(pathMx);
  509. if(tile.x >= sizes.x || tile.y >= sizes.y || tile.z >= sizes.z || layer >= EPathfindingLayer::NUM_LAYERS)
  510. return nullptr;
  511. return getNode(tile, layer);
  512. }
  513. bool CPathsInfo::getPath(CGPath &out, const int3 &dst, const EPathfindingLayer &layer) const
  514. {
  515. boost::unique_lock<boost::mutex> pathLock(pathMx);
  516. out.nodes.clear();
  517. const CGPathNode *curnode = getNode(dst, layer);
  518. if(!curnode->theNodeBefore)
  519. return false;
  520. while(curnode)
  521. {
  522. CGPathNode cpn = *curnode;
  523. curnode = curnode->theNodeBefore;
  524. out.nodes.push_back(cpn);
  525. }
  526. return true;
  527. }
  528. int CPathsInfo::getDistance(const int3 &tile, const EPathfindingLayer &layer) const
  529. {
  530. boost::unique_lock<boost::mutex> pathLock(pathMx);
  531. CGPath ret;
  532. if(getPath(ret, tile, layer))
  533. return ret.nodes.size();
  534. else
  535. return 255;
  536. }
  537. CGPathNode *CPathsInfo::getNode(const int3 &coord, const EPathfindingLayer &layer) const
  538. {
  539. if(layer != EPathfindingLayer::AUTO)
  540. return &nodes[coord.x][coord.y][coord.z][layer];
  541. auto landNode = &nodes[coord.x][coord.y][coord.z][EPathfindingLayer::LAND];
  542. if(landNode->theNodeBefore)
  543. return landNode;
  544. else
  545. return &nodes[coord.x][coord.y][coord.z][EPathfindingLayer::SAIL];
  546. }