CaptureObjectsBehavior.cpp 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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(objToVisit && !force && !shouldVisit(nullkiller, path.targetHero, objToVisit))
  59. {
  60. #if NKAI_TRACE_LEVEL >= 2
  61. logAi->trace("Ignore path. Hero %s should not visit obj %s", path.targetHero->getNameTranslated(), objToVisit->getObjectName());
  62. #endif
  63. continue;
  64. }
  65. auto hero = path.targetHero;
  66. auto danger = path.getTotalDanger();
  67. if (hero->getOwner() != nullkiller->playerID)
  68. continue;
  69. if(nullkiller->heroManager->getHeroRole(hero) == HeroRole::SCOUT
  70. && (path.getTotalDanger() == 0 || path.turn() > 0)
  71. && path.exchangeCount > 1)
  72. {
  73. #if NKAI_TRACE_LEVEL >= 2
  74. logAi->trace("Ignore path. Hero %s is SCOUT, chain used and no danger", path.targetHero->getNameTranslated());
  75. #endif
  76. continue;
  77. }
  78. auto firstBlockedAction = path.getFirstBlockedAction();
  79. if(firstBlockedAction)
  80. {
  81. auto subGoal = firstBlockedAction->decompose(nullkiller, path.targetHero);
  82. #if NKAI_TRACE_LEVEL >= 2
  83. logAi->trace("Decomposing special action %s returns %s", firstBlockedAction->toString(), subGoal->toString());
  84. #endif
  85. if(!subGoal->invalid())
  86. {
  87. Composition composition;
  88. composition.addNext(ExecuteHeroChain(path, objToVisit));
  89. composition.addNext(subGoal);
  90. tasks[tasks.size() - 1] = sptr(composition);
  91. }
  92. continue;
  93. }
  94. auto isSafe = isSafeToVisit(hero, path.heroArmy, danger, nullkiller->settings->getSafeAttackRatio());
  95. #if NKAI_TRACE_LEVEL >= 2
  96. logAi->trace(
  97. "It is %s to visit %s by %s with army %lld, danger %lld and army loss %lld",
  98. isSafe ? "safe" : "not safe",
  99. objToVisit ? objToVisit->getObjectName() : path.targetTile().toString(),
  100. hero->getObjectName(),
  101. path.getHeroStrength(),
  102. danger,
  103. path.getTotalArmyLoss());
  104. #endif
  105. if(isSafe)
  106. {
  107. auto newWay = new ExecuteHeroChain(path, objToVisit);
  108. TSubgoal sharedPtr;
  109. sharedPtr.reset(newWay);
  110. auto heroRole = nullkiller->heroManager->getHeroRole(path.targetHero);
  111. auto & closestWay = closestWaysByRole[heroRole];
  112. if(!closestWay || closestWay->movementCost() > path.movementCost())
  113. {
  114. closestWay = &path;
  115. }
  116. if(!nullkiller->arePathHeroesLocked(path))
  117. {
  118. waysToVisitObj.push_back(newWay);
  119. tasks[tasks.size() - 1] = sharedPtr;
  120. }
  121. }
  122. }
  123. for(auto way : waysToVisitObj)
  124. {
  125. auto heroRole = nullkiller->heroManager->getHeroRole(way->getPath().targetHero);
  126. auto closestWay = closestWaysByRole[heroRole];
  127. if(closestWay)
  128. {
  129. way->closestWayRatio
  130. = closestWay->movementCost() / way->getPath().movementCost();
  131. }
  132. }
  133. return tasks;
  134. }
  135. void CaptureObjectsBehavior::decomposeObjects(
  136. Goals::TGoalVec & result,
  137. const std::vector<const CGObjectInstance *> & objs,
  138. const Nullkiller * nullkiller) const
  139. {
  140. if(objs.empty())
  141. {
  142. return;
  143. }
  144. std::mutex sync;
  145. logAi->debug("Scanning objects, count %d", objs.size());
  146. // tbb::blocked_range<size_t> r(0, objs.size());
  147. tbb::parallel_for(
  148. tbb::blocked_range<size_t>(0, objs.size()),
  149. [this, &objs, &sync, &result, nullkiller](const tbb::blocked_range<size_t> & r)
  150. {
  151. std::vector<AIPath> paths;
  152. Goals::TGoalVec tasksLocal;
  153. for(auto i = r.begin(); i != r.end(); i++)
  154. {
  155. auto objToVisit = objs[i];
  156. if(!objectMatchesFilter(objToVisit))
  157. continue;
  158. #if NKAI_TRACE_LEVEL >= 1
  159. logAi->trace("Checking object %s, %s", objToVisit->getObjectName(), objToVisit->visitablePos().toString());
  160. #endif
  161. nullkiller->pathfinder->calculatePathInfo(paths, objToVisit->visitablePos(), nullkiller->isObjectGraphAllowed());
  162. #if NKAI_TRACE_LEVEL >= 1
  163. logAi->trace("Found %d paths", paths.size());
  164. #endif
  165. vstd::concatenate(tasksLocal, getVisitGoals(paths, nullkiller, objToVisit, specificObjects));
  166. }
  167. std::lock_guard lock(sync); // FIXME: consider using tbb::parallel_reduce instead to avoid mutex overhead
  168. vstd::concatenate(result, tasksLocal);
  169. });
  170. }
  171. Goals::TGoalVec CaptureObjectsBehavior::decompose(const Nullkiller * ai) const
  172. {
  173. Goals::TGoalVec tasks;
  174. vstd::erase_if(tasks, [](TSubgoal task) -> bool
  175. {
  176. return task->invalid();
  177. });
  178. if(specificObjects)
  179. {
  180. decomposeObjects(tasks, objectsToCapture, ai);
  181. }
  182. else if(objectTypes.size())
  183. {
  184. decomposeObjects(
  185. tasks,
  186. std::vector<const CGObjectInstance *>(
  187. ai->memory->visitableObjs.begin(),
  188. ai->memory->visitableObjs.end()),
  189. ai);
  190. }
  191. else
  192. {
  193. decomposeObjects(tasks, ai->objectClusterizer->getNearbyObjects(), ai);
  194. if(tasks.empty() || ai->getScanDepth() != ScanDepth::SMALL)
  195. decomposeObjects(tasks, ai->objectClusterizer->getFarObjects(), ai);
  196. }
  197. return tasks;
  198. }
  199. bool CaptureObjectsBehavior::objectMatchesFilter(const CGObjectInstance * obj) const
  200. {
  201. if(objectTypes.size() && !vstd::contains(objectTypes, obj->ID.num))
  202. {
  203. return false;
  204. }
  205. if(objectSubTypes.size() && !vstd::contains(objectSubTypes, obj->subID))
  206. {
  207. return false;
  208. }
  209. return true;
  210. }
  211. }