AIPathfinder.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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 "../../../lib/mapping/TerrainTile.h"
  14. #include <tbb/task_group.h>
  15. std::vector<std::shared_ptr<AINodeStorage>> AIPathfinder::storagePool;
  16. std::map<HeroPtr, std::shared_ptr<AINodeStorage>> AIPathfinder::storageMap;
  17. AIPathfinder::AIPathfinder(CPlayerSpecificInfoCallback * cb, VCAI * ai)
  18. :cb(cb), ai(ai)
  19. {
  20. }
  21. void AIPathfinder::init()
  22. {
  23. storagePool.clear();
  24. storageMap.clear();
  25. }
  26. bool AIPathfinder::isTileAccessible(const HeroPtr & hero, const int3 & tile) const
  27. {
  28. std::shared_ptr<const AINodeStorage> nodeStorage = getStorage(hero);
  29. return nodeStorage->isTileAccessible(tile, EPathfindingLayer::LAND)
  30. || nodeStorage->isTileAccessible(tile, EPathfindingLayer::SAIL);
  31. }
  32. std::vector<AIPath> AIPathfinder::getPathInfo(const HeroPtr & hero, const int3 & tile) const
  33. {
  34. std::shared_ptr<const AINodeStorage> nodeStorage = getStorage(hero);
  35. const TerrainTile * tileInfo = cb->getTile(tile, false);
  36. if(!tileInfo)
  37. {
  38. return std::vector<AIPath>();
  39. }
  40. return nodeStorage->getChainInfo(tile, !tileInfo->isWater());
  41. }
  42. void AIPathfinder::updatePaths(std::vector<HeroPtr> heroes)
  43. {
  44. storageMap.clear();
  45. auto calculatePaths = [&](const CGHeroInstance * hero, std::shared_ptr<AIPathfinding::AIPathfinderConfig> config)
  46. {
  47. logAi->debug("Recalculate paths for %s", hero->getNameTranslated());
  48. cb->calculatePaths(config);
  49. };
  50. tbb::task_group calculationTasks;
  51. for(HeroPtr hero : heroes)
  52. {
  53. std::shared_ptr<AINodeStorage> nodeStorage;
  54. if(storageMap.size() < storagePool.size())
  55. {
  56. nodeStorage = storagePool.at(storageMap.size());
  57. }
  58. else
  59. {
  60. nodeStorage = std::make_shared<AINodeStorage>(cb->getMapSize());
  61. storagePool.push_back(nodeStorage);
  62. }
  63. storageMap[hero] = nodeStorage;
  64. nodeStorage->setHero(hero, ai);
  65. auto config = std::make_shared<AIPathfinding::AIPathfinderConfig>(cb, ai, nodeStorage);
  66. calculationTasks.run(std::bind(calculatePaths, hero.get(), config));
  67. }
  68. calculationTasks.wait();
  69. }
  70. std::shared_ptr<const AINodeStorage> AIPathfinder::getStorage(const HeroPtr & hero) const
  71. {
  72. return storageMap.at(hero);
  73. }