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