CPathfinder.cpp 16 KB

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