AIPathfinder.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /*
  2. * AIPathfinder.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "AIPathfinder.h"
  12. #include "AIPathfinderConfig.h"
  13. #include "../../../CCallback.h"
  14. #include "../../../lib/mapping/CMap.h"
  15. std::shared_ptr<AINodeStorage> AIPathfinder::storage;
  16. AIPathfinder::AIPathfinder(CPlayerSpecificInfoCallback * cb, VCAI * ai)
  17. :cb(cb), ai(ai)
  18. {
  19. }
  20. void AIPathfinder::init()
  21. {
  22. storage.reset();
  23. }
  24. bool AIPathfinder::isTileAccessible(const HeroPtr & hero, const int3 & tile) const
  25. {
  26. return storage->isTileAccessible(hero, tile, EPathfindingLayer::LAND)
  27. || storage->isTileAccessible(hero, tile, EPathfindingLayer::SAIL);
  28. }
  29. std::vector<AIPath> AIPathfinder::getPathInfo(const int3 & tile) const
  30. {
  31. const TerrainTile * tileInfo = cb->getTile(tile, false);
  32. if(!tileInfo)
  33. {
  34. return std::vector<AIPath>();
  35. }
  36. return storage->getChainInfo(tile, !tileInfo->isWater());
  37. }
  38. void AIPathfinder::updatePaths(std::vector<HeroPtr> heroes, bool useHeroChain)
  39. {
  40. if(!storage)
  41. {
  42. storage = std::make_shared<AINodeStorage>(cb->getMapSize());
  43. }
  44. logAi->debug("Recalculate all paths");
  45. int pass = 0;
  46. storage->clear();
  47. storage->setHeroes(heroes, ai);
  48. if(useHeroChain)
  49. {
  50. storage->setTownsAndDwellings(cb->getTownsInfo(), ai->visitableObjs);
  51. }
  52. auto config = std::make_shared<AIPathfinding::AIPathfinderConfig>(cb, ai, storage);
  53. logAi->trace("Recalculate paths pass %d", pass++);
  54. cb->calculatePaths(config);
  55. if(!useHeroChain)
  56. return;
  57. do
  58. {
  59. storage->selectFirstActor();
  60. do
  61. {
  62. while(storage->calculateHeroChain())
  63. {
  64. logAi->trace("Recalculate paths pass %d", pass++);
  65. cb->calculatePaths(config);
  66. }
  67. logAi->trace("Select next actor");
  68. } while(storage->selectNextActor());
  69. if(storage->calculateHeroChainFinal())
  70. {
  71. logAi->trace("Recalculate paths pass final");
  72. cb->calculatePaths(config);
  73. }
  74. } while(storage->increaseHeroChainTurnLimit());
  75. }