CPathfinder.cpp 16 KB

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