AIPathfinder.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. #include "../Engine/Nullkiller.h"
  16. std::shared_ptr<AINodeStorage> AIPathfinder::storage;
  17. AIPathfinder::AIPathfinder(CPlayerSpecificInfoCallback * cb, Nullkiller * ai)
  18. :cb(cb), ai(ai)
  19. {
  20. }
  21. void AIPathfinder::init()
  22. {
  23. storage.reset();
  24. }
  25. bool AIPathfinder::isTileAccessible(const HeroPtr & hero, const int3 & tile) const
  26. {
  27. return storage->isTileAccessible(hero, tile, EPathfindingLayer::LAND)
  28. || storage->isTileAccessible(hero, tile, EPathfindingLayer::SAIL);
  29. }
  30. std::vector<AIPath> AIPathfinder::getPathInfo(const int3 & tile) const
  31. {
  32. const TerrainTile * tileInfo = cb->getTile(tile, false);
  33. if(!tileInfo)
  34. {
  35. return std::vector<AIPath>();
  36. }
  37. return storage->getChainInfo(tile, !tileInfo->isWater());
  38. }
  39. void AIPathfinder::updatePaths(std::vector<const CGHeroInstance *> heroes, bool useHeroChain)
  40. {
  41. if(!storage)
  42. {
  43. storage.reset(new AINodeStorage(ai, cb->getMapSize()));
  44. }
  45. logAi->debug("Recalculate all paths");
  46. int pass = 0;
  47. storage->clear();
  48. storage->setHeroes(heroes);
  49. if(useHeroChain)
  50. {
  51. storage->setTownsAndDwellings(cb->getTownsInfo(), ai->memory->visitableObjs);
  52. }
  53. auto config = std::make_shared<AIPathfinding::AIPathfinderConfig>(cb, ai, storage);
  54. logAi->trace("Recalculate paths pass %d", pass++);
  55. cb->calculatePaths(config);
  56. if(!useHeroChain)
  57. return;
  58. do
  59. {
  60. storage->selectFirstActor();
  61. do
  62. {
  63. while(storage->calculateHeroChain())
  64. {
  65. logAi->trace("Recalculate paths pass %d", pass++);
  66. cb->calculatePaths(config);
  67. }
  68. logAi->trace("Select next actor");
  69. } while(storage->selectNextActor());
  70. if(storage->calculateHeroChainFinal())
  71. {
  72. logAi->trace("Recalculate paths pass final");
  73. cb->calculatePaths(config);
  74. }
  75. } while(storage->increaseHeroChainTurnLimit());
  76. }