CaptureObjectsBehavior.cpp 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. /*
  2. * CaptureObjectsBehavior.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 "../AIGateway.h"
  12. #include "../Engine/Nullkiller.h"
  13. #include "../Goals/Composition.h"
  14. #include "../Goals/ExecuteHeroChain.h"
  15. #include "../Goals/Invalid.h"
  16. #include "CaptureObjectsBehavior.h"
  17. #include "../AIUtility.h"
  18. namespace NKAI
  19. {
  20. using namespace Goals;
  21. template <typename T>
  22. bool vectorEquals(const std::vector<T> & v1, const std::vector<T> & v2)
  23. {
  24. return vstd::contains_if(v1, [&](T o) -> bool
  25. {
  26. return vstd::contains(v2, o);
  27. });
  28. }
  29. std::string CaptureObjectsBehavior::toString() const
  30. {
  31. return "Capture objects";
  32. }
  33. bool CaptureObjectsBehavior::operator==(const CaptureObjectsBehavior & other) const
  34. {
  35. if(specificObjects != other.specificObjects)
  36. return false;
  37. if(specificObjects)
  38. return vectorEquals(objectsToCapture, other.objectsToCapture);
  39. return vectorEquals(objectTypes, other.objectTypes)
  40. && vectorEquals(objectSubTypes, other.objectSubTypes);
  41. }
  42. Goals::TGoalVec CaptureObjectsBehavior::getVisitGoals(
  43. const std::vector<AIPath> & paths,
  44. const Nullkiller * nullkiller,
  45. const CGObjectInstance * objToVisit,
  46. bool force)
  47. {
  48. Goals::TGoalVec tasks;
  49. tasks.reserve(paths.size());
  50. std::unordered_map<HeroRole, const AIPath *> closestWaysByRole;
  51. std::vector<ExecuteHeroChain *> waysToVisitObj;
  52. for(auto & path : paths)
  53. {
  54. tasks.push_back(sptr(Goals::Invalid()));
  55. #if NKAI_TRACE_LEVEL >= 2
  56. logAi->trace("Path found %s", path.toString());
  57. #endif
  58. if(nullkiller->dangerHitMap->enemyCanKillOurHeroesAlongThePath(path))
  59. {
  60. #if NKAI_TRACE_LEVEL >= 2
  61. logAi->trace("Ignore path. Target hero can be killed by enemy. Our power %lld", path.getHeroStrength());
  62. #endif
  63. continue;
  64. }
  65. if(objToVisit && !force && !shouldVisit(nullkiller, path.targetHero, objToVisit))
  66. {
  67. #if NKAI_TRACE_LEVEL >= 2
  68. logAi->trace("Ignore path. Hero %s should not visit obj %s", path.targetHero->getNameTranslated(), objToVisit->getObjectName());
  69. #endif
  70. continue;
  71. }
  72. auto hero = path.targetHero;
  73. auto danger = path.getTotalDanger();
  74. if(nullkiller->heroManager->getHeroRole(hero) == HeroRole::SCOUT
  75. && (path.getTotalDanger() == 0 || path.turn() > 0)
  76. && path.exchangeCount > 1)
  77. {
  78. #if NKAI_TRACE_LEVEL >= 2
  79. logAi->trace("Ignore path. Hero %s is SCOUT, chain used and no danger", path.targetHero->getNameTranslated());
  80. #endif
  81. continue;
  82. }
  83. auto firstBlockedAction = path.getFirstBlockedAction();
  84. if(firstBlockedAction)
  85. {
  86. auto subGoal = firstBlockedAction->decompose(nullkiller, path.targetHero);
  87. #if NKAI_TRACE_LEVEL >= 2
  88. logAi->trace("Decomposing special action %s returns %s", firstBlockedAction->toString(), subGoal->toString());
  89. #endif
  90. if(!subGoal->invalid())
  91. {
  92. Composition composition;
  93. composition.addNext(ExecuteHeroChain(path, objToVisit));
  94. composition.addNext(subGoal);
  95. tasks[tasks.size() - 1] = sptr(composition);
  96. }
  97. continue;
  98. }
  99. auto isSafe = isSafeToVisit(hero, path.heroArmy, danger);
  100. #if NKAI_TRACE_LEVEL >= 2
  101. logAi->trace(
  102. "It is %s to visit %s by %s with army %lld, danger %lld and army loss %lld",
  103. isSafe ? "safe" : "not safe",
  104. objToVisit ? objToVisit->getObjectName() : path.targetTile().toString(),
  105. hero->getObjectName(),
  106. path.getHeroStrength(),
  107. danger,
  108. path.getTotalArmyLoss());
  109. #endif
  110. if(isSafe)
  111. {
  112. auto newWay = new ExecuteHeroChain(path, objToVisit);
  113. TSubgoal sharedPtr;
  114. sharedPtr.reset(newWay);
  115. auto heroRole = nullkiller->heroManager->getHeroRole(path.targetHero);
  116. auto & closestWay = closestWaysByRole[heroRole];
  117. if(!closestWay || closestWay->movementCost() > path.movementCost())
  118. {
  119. closestWay = &path;
  120. }
  121. if(!nullkiller->arePathHeroesLocked(path))
  122. {
  123. waysToVisitObj.push_back(newWay);
  124. tasks[tasks.size() - 1] = sharedPtr;
  125. }
  126. }
  127. }
  128. for(auto way : waysToVisitObj)
  129. {
  130. auto heroRole = nullkiller->heroManager->getHeroRole(way->getPath().targetHero);
  131. auto closestWay = closestWaysByRole[heroRole];
  132. if(closestWay)
  133. {
  134. way->closestWayRatio
  135. = closestWay->movementCost() / way->getPath().movementCost();
  136. }
  137. }
  138. return tasks;
  139. }
  140. void CaptureObjectsBehavior::decomposeObjects(
  141. Goals::TGoalVec & result,
  142. const std::vector<const CGObjectInstance *> & objs,
  143. const Nullkiller * nullkiller) const
  144. {
  145. if(objs.empty())
  146. {
  147. return;
  148. }
  149. std::mutex sync;
  150. logAi->debug("Scanning objects, count %d", objs.size());
  151. // tbb::blocked_range<size_t> r(0, objs.size());
  152. tbb::parallel_for(
  153. tbb::blocked_range<size_t>(0, objs.size()),
  154. [this, &objs, &sync, &result, nullkiller](const tbb::blocked_range<size_t> & r)
  155. {
  156. std::vector<AIPath> paths;
  157. Goals::TGoalVec tasksLocal;
  158. for(auto i = r.begin(); i != r.end(); i++)
  159. {
  160. auto objToVisit = objs[i];
  161. if(!objectMatchesFilter(objToVisit))
  162. continue;
  163. #if NKAI_TRACE_LEVEL >= 1
  164. logAi->trace("Checking object %s, %s", objToVisit->getObjectName(), objToVisit->visitablePos().toString());
  165. #endif
  166. nullkiller->pathfinder->calculatePathInfo(paths, objToVisit->visitablePos(), nullkiller->isObjectGraphAllowed());
  167. #if NKAI_TRACE_LEVEL >= 1
  168. logAi->trace("Found %d paths", paths.size());
  169. #endif
  170. vstd::concatenate(tasksLocal, getVisitGoals(paths, nullkiller, objToVisit, specificObjects));
  171. }
  172. std::lock_guard lock(sync); // FIXME: consider using tbb::parallel_reduce instead to avoid mutex overhead
  173. vstd::concatenate(result, tasksLocal);
  174. });
  175. }
  176. Goals::TGoalVec CaptureObjectsBehavior::decompose(const Nullkiller * ai) const
  177. {
  178. Goals::TGoalVec tasks;
  179. vstd::erase_if(tasks, [](TSubgoal task) -> bool
  180. {
  181. return task->invalid();
  182. });
  183. if(specificObjects)
  184. {
  185. decomposeObjects(tasks, objectsToCapture, ai);
  186. }
  187. else if(objectTypes.size())
  188. {
  189. decomposeObjects(
  190. tasks,
  191. std::vector<const CGObjectInstance *>(
  192. ai->memory->visitableObjs.begin(),
  193. ai->memory->visitableObjs.end()),
  194. ai);
  195. }
  196. else
  197. {
  198. decomposeObjects(tasks, ai->objectClusterizer->getNearbyObjects(), ai);
  199. if(tasks.empty() || ai->getScanDepth() != ScanDepth::SMALL)
  200. decomposeObjects(tasks, ai->objectClusterizer->getFarObjects(), ai);
  201. }
  202. return tasks;
  203. }
  204. bool CaptureObjectsBehavior::objectMatchesFilter(const CGObjectInstance * obj) const
  205. {
  206. if(objectTypes.size() && !vstd::contains(objectTypes, obj->ID.num))
  207. {
  208. return false;
  209. }
  210. if(objectSubTypes.size() && !vstd::contains(objectSubTypes, obj->subID))
  211. {
  212. return false;
  213. }
  214. return true;
  215. }
  216. }