CPathfinder.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  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::BLOCKED)
  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. if(isDestinationGuarded() && !isSourceGuarded())
  277. return true; // Can step into a hostile tile once
  278. break;
  279. case EPathfindingLayer::AIR:
  280. case EPathfindingLayer::WATER:
  281. return true;
  282. break;
  283. }
  284. return false;
  285. }
  286. bool CPathfinder::isSourceInitialPosition()
  287. {
  288. return cp->coord == out.hpos;
  289. }
  290. int3 CPathfinder::getSourceGuardPosition()
  291. {
  292. return gs->map->guardingCreaturePositions[cp->coord.x][cp->coord.y][cp->coord.z];
  293. }
  294. bool CPathfinder::isSourceGuarded()
  295. {
  296. //map can start with hero on guarded tile or teleport there using dimension door
  297. //so threat tile hero standing on like it's not guarded because it's should be possible to move out of here
  298. if(getSourceGuardPosition() != int3(-1, -1, -1) && !isSourceInitialPosition())
  299. {
  300. //special case -> hero embarked a boat standing on a guarded tile -> we must allow to move away from that tile
  301. if(cp->accessible != CGPathNode::VISITABLE
  302. || !cp->theNodeBefore->land
  303. || ct->topVisitableId() != Obj::BOAT)
  304. {
  305. return true;
  306. }
  307. }
  308. return false;
  309. }
  310. bool CPathfinder::isDestinationGuarded()
  311. {
  312. if(gs->map->guardingCreaturePositions[dp->coord.x][dp->coord.y][dp->coord.z].valid()
  313. && dp->accessible == CGPathNode::BLOCKVIS)
  314. {
  315. return true;
  316. }
  317. return false;
  318. }
  319. bool CPathfinder::isDestinationGuardian()
  320. {
  321. return getSourceGuardPosition() == dp->coord;
  322. }
  323. void CPathfinder::initializeGraph()
  324. {
  325. auto initializeNode = [&](int3 pos, EPathfindingLayer layer, const TerrainTile *tinfo)
  326. {
  327. auto node = out.getNode(pos, layer);
  328. node->accessible = evaluateAccessibility(pos, tinfo);
  329. node->turns = 0xff;
  330. node->moveRemains = 0;
  331. node->coord = pos;
  332. node->land = tinfo->terType != ETerrainType::WATER;
  333. node->theNodeBefore = nullptr;
  334. node->layer = layer;
  335. };
  336. int3 pos;
  337. for(pos.x=0; pos.x < out.sizes.x; ++pos.x)
  338. {
  339. for(pos.y=0; pos.y < out.sizes.y; ++pos.y)
  340. {
  341. for(pos.z=0; pos.z < out.sizes.z; ++pos.z)
  342. {
  343. const TerrainTile *tinfo = &gs->map->getTile(pos);
  344. switch (tinfo->terType)
  345. {
  346. case ETerrainType::WRONG:
  347. case ETerrainType::BORDER:
  348. case ETerrainType::ROCK:
  349. break;
  350. case ETerrainType::WATER:
  351. initializeNode(pos, EPathfindingLayer::SAIL, tinfo);
  352. if(options.useFlying)
  353. initializeNode(pos, EPathfindingLayer::AIR, tinfo);
  354. if(options.useWaterWalking)
  355. initializeNode(pos, EPathfindingLayer::WATER, tinfo);
  356. break;
  357. default:
  358. initializeNode(pos, EPathfindingLayer::LAND, tinfo);
  359. if(options.useFlying)
  360. initializeNode(pos, EPathfindingLayer::AIR, tinfo);
  361. break;
  362. }
  363. }
  364. }
  365. }
  366. }
  367. CGPathNode::EAccessibility CPathfinder::evaluateAccessibility(const int3 &pos, const TerrainTile *tinfo) const
  368. {
  369. CGPathNode::EAccessibility ret = (tinfo->blocked ? CGPathNode::BLOCKED : CGPathNode::ACCESSIBLE);
  370. if(tinfo->terType == ETerrainType::ROCK || !FoW[pos.x][pos.y][pos.z])
  371. return CGPathNode::BLOCKED;
  372. if(tinfo->visitable)
  373. {
  374. 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
  375. {
  376. return CGPathNode::BLOCKED;
  377. }
  378. else
  379. {
  380. for(const CGObjectInstance *obj : tinfo->visitableObjects)
  381. {
  382. if(obj->passableFor(hero->tempOwner))
  383. {
  384. ret = CGPathNode::ACCESSIBLE;
  385. }
  386. else if(obj->blockVisit)
  387. {
  388. return CGPathNode::BLOCKVIS;
  389. }
  390. else if(obj->ID != Obj::EVENT) //pathfinder should ignore placed events
  391. {
  392. ret = CGPathNode::VISITABLE;
  393. }
  394. }
  395. }
  396. }
  397. else if(gs->map->guardingCreaturePositions[pos.x][pos.y][pos.z].valid()
  398. && !tinfo->blocked)
  399. {
  400. // Monster close by; blocked visit for battle.
  401. return CGPathNode::BLOCKVIS;
  402. }
  403. return ret;
  404. }
  405. bool CPathfinder::canMoveBetween(const int3 &a, const int3 &b) const
  406. {
  407. return gs->checkForVisitableDir(a, b);
  408. }
  409. bool CPathfinder::addTeleportTwoWay(const CGTeleport * obj) const
  410. {
  411. return options.useTeleportTwoWay && gs->isTeleportChannelBidirectional(obj->channel, hero->tempOwner);
  412. }
  413. bool CPathfinder::addTeleportOneWay(const CGTeleport * obj) const
  414. {
  415. if(options.useTeleportOneWay && isTeleportChannelUnidirectional(obj->channel, hero->tempOwner))
  416. {
  417. auto passableExits = CGTeleport::getPassableExits(gs, hero, gs->getTeleportChannelExits(obj->channel, hero->tempOwner));
  418. if(passableExits.size() == 1)
  419. return true;
  420. }
  421. return false;
  422. }
  423. bool CPathfinder::addTeleportOneWayRandom(const CGTeleport * obj) const
  424. {
  425. if(options.useTeleportOneWayRandom && isTeleportChannelUnidirectional(obj->channel, hero->tempOwner))
  426. {
  427. auto passableExits = CGTeleport::getPassableExits(gs, hero, gs->getTeleportChannelExits(obj->channel, hero->tempOwner));
  428. if(passableExits.size() > 1)
  429. return true;
  430. }
  431. return false;
  432. }
  433. bool CPathfinder::addTeleportWhirlpool(const CGWhirlpool * obj) const
  434. {
  435. return options.useTeleportWhirlpool && obj;
  436. }
  437. bool CPathfinder::canVisitObject() const
  438. {
  439. //hero can't visit objects while walking on water or flying
  440. return cp->layer == EPathfindingLayer::LAND || cp->layer == EPathfindingLayer::SAIL;
  441. }
  442. CGPathNode::CGPathNode()
  443. :coord(-1,-1,-1)
  444. {
  445. accessible = NOT_SET;
  446. land = 0;
  447. moveRemains = 0;
  448. turns = 255;
  449. theNodeBefore = nullptr;
  450. layer = EPathfindingLayer::WRONG;
  451. }
  452. bool CGPathNode::reachable() const
  453. {
  454. return turns < 255;
  455. }
  456. int3 CGPath::startPos() const
  457. {
  458. return nodes[nodes.size()-1].coord;
  459. }
  460. int3 CGPath::endPos() const
  461. {
  462. return nodes[0].coord;
  463. }
  464. void CGPath::convert( ui8 mode )
  465. {
  466. if(mode==0)
  467. {
  468. for(auto & elem : nodes)
  469. {
  470. elem.coord = CGHeroInstance::convertPosition(elem.coord,true);
  471. }
  472. }
  473. }
  474. CPathsInfo::CPathsInfo( const int3 &Sizes )
  475. :sizes(Sizes)
  476. {
  477. hero = nullptr;
  478. nodes = new CGPathNode***[sizes.x];
  479. for(int i = 0; i < sizes.x; i++)
  480. {
  481. nodes[i] = new CGPathNode**[sizes.y];
  482. for(int j = 0; j < sizes.y; j++)
  483. {
  484. nodes[i][j] = new CGPathNode*[sizes.z];
  485. for (int z = 0; z < sizes.z; z++)
  486. {
  487. nodes[i][j][z] = new CGPathNode[EPathfindingLayer::NUM_LAYERS];
  488. }
  489. }
  490. }
  491. }
  492. CPathsInfo::~CPathsInfo()
  493. {
  494. for(int i = 0; i < sizes.x; i++)
  495. {
  496. for(int j = 0; j < sizes.y; j++)
  497. {
  498. for (int z = 0; z < sizes.z; z++)
  499. {
  500. delete [] nodes[i][j][z];
  501. }
  502. delete [] nodes[i][j];
  503. }
  504. delete [] nodes[i];
  505. }
  506. delete [] nodes;
  507. }
  508. const CGPathNode * CPathsInfo::getPathInfo(const int3 &tile, const EPathfindingLayer &layer) const
  509. {
  510. boost::unique_lock<boost::mutex> pathLock(pathMx);
  511. if(tile.x >= sizes.x || tile.y >= sizes.y || tile.z >= sizes.z || layer >= EPathfindingLayer::NUM_LAYERS)
  512. return nullptr;
  513. return getNode(tile, layer);
  514. }
  515. bool CPathsInfo::getPath(CGPath &out, const int3 &dst, const EPathfindingLayer &layer) const
  516. {
  517. boost::unique_lock<boost::mutex> pathLock(pathMx);
  518. out.nodes.clear();
  519. const CGPathNode *curnode = getNode(dst, layer);
  520. if(!curnode->theNodeBefore)
  521. return false;
  522. while(curnode)
  523. {
  524. CGPathNode cpn = *curnode;
  525. curnode = curnode->theNodeBefore;
  526. out.nodes.push_back(cpn);
  527. }
  528. return true;
  529. }
  530. int CPathsInfo::getDistance(const int3 &tile, const EPathfindingLayer &layer) const
  531. {
  532. boost::unique_lock<boost::mutex> pathLock(pathMx);
  533. CGPath ret;
  534. if(getPath(ret, tile, layer))
  535. return ret.nodes.size();
  536. else
  537. return 255;
  538. }
  539. CGPathNode *CPathsInfo::getNode(const int3 &coord, const EPathfindingLayer &layer) const
  540. {
  541. if(layer != EPathfindingLayer::AUTO)
  542. return &nodes[coord.x][coord.y][coord.z][layer];
  543. auto landNode = &nodes[coord.x][coord.y][coord.z][EPathfindingLayer::LAND];
  544. if(landNode->theNodeBefore)
  545. return landNode;
  546. else
  547. return &nodes[coord.x][coord.y][coord.z][EPathfindingLayer::SAIL];
  548. }