Nullkiller.cpp 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. /*
  2. * Nullkiller.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 "Nullkiller.h"
  12. #include "../VCAI.h"
  13. #include "../Behaviors/CaptureObjectsBehavior.h"
  14. #include "../Behaviors/RecruitHeroBehavior.h"
  15. #include "../Behaviors/BuyArmyBehavior.h"
  16. #include "../Behaviors/StartupBehavior.h"
  17. #include "../Behaviors/DefenceBehavior.h"
  18. #include "../Behaviors/BuildingBehavior.h"
  19. #include "../Behaviors/GatherArmyBehavior.h"
  20. #include "../Behaviors/ClusterBehavior.h"
  21. #include "../Goals/Invalid.h"
  22. #include "../Goals/Composition.h"
  23. extern boost::thread_specific_ptr<CCallback> cb;
  24. extern boost::thread_specific_ptr<VCAI> ai;
  25. using namespace Goals;
  26. #if AI_TRACE_LEVEL >= 1
  27. #define MAXPASS 1000000
  28. #else
  29. #define MAXPASS 30
  30. #endif
  31. Nullkiller::Nullkiller()
  32. {
  33. memory.reset(new AIMemory());
  34. }
  35. void Nullkiller::init(std::shared_ptr<CCallback> cb, PlayerColor playerID)
  36. {
  37. this->cb = cb;
  38. this->playerID = playerID;
  39. priorityEvaluator.reset(new PriorityEvaluator(this));
  40. dangerHitMap.reset(new DangerHitMapAnalyzer(this));
  41. buildAnalyzer.reset(new BuildAnalyzer(this));
  42. objectClusterizer.reset(new ObjectClusterizer(this));
  43. dangerEvaluator.reset(new FuzzyHelper(this));
  44. pathfinder.reset(new AIPathfinder(cb.get(), this));
  45. armyManager.reset(new ArmyManager(cb.get(), this));
  46. heroManager.reset(new HeroManager(cb.get(), this));
  47. decomposer.reset(new DeepDecomposer());
  48. }
  49. Goals::TTask Nullkiller::choseBestTask(Goals::TTaskVec & tasks) const
  50. {
  51. Goals::TTask bestTask = *vstd::maxElementByFun(tasks, [](Goals::TTask task) -> float{
  52. return task->priority;
  53. });
  54. return bestTask;
  55. }
  56. Goals::TTask Nullkiller::choseBestTask(Goals::TSubgoal behavior, int decompositionMaxDepth) const
  57. {
  58. logAi->debug("Checking behavior %s", behavior->toString());
  59. auto start = boost::chrono::high_resolution_clock::now();
  60. Goals::TGoalVec elementarGoals = decomposer->decompose(behavior, decompositionMaxDepth);
  61. Goals::TTaskVec tasks;
  62. boost::this_thread::interruption_point();
  63. for(auto goal : elementarGoals)
  64. {
  65. Goals::TTask task = Goals::taskptr(*goal);
  66. if(task->priority <= 0)
  67. task->priority = priorityEvaluator->evaluate(goal);
  68. tasks.push_back(task);
  69. }
  70. if(tasks.empty())
  71. {
  72. logAi->debug("Behavior %s found no tasks. Time taken %ld", behavior->toString(), timeElapsed(start));
  73. return Goals::taskptr(Goals::Invalid());
  74. }
  75. auto task = choseBestTask(tasks);
  76. logAi->debug(
  77. "Behavior %s returns %s, priority %f. Time taken %ld",
  78. behavior->toString(),
  79. task->toString(),
  80. task->priority,
  81. timeElapsed(start));
  82. return task;
  83. }
  84. void Nullkiller::resetAiState()
  85. {
  86. scanDepth = ScanDepth::SMALL;
  87. playerID = ai->playerID;
  88. lockedHeroes.clear();
  89. dangerHitMap->reset();
  90. }
  91. void Nullkiller::updateAiState(int pass)
  92. {
  93. boost::this_thread::interruption_point();
  94. auto start = boost::chrono::high_resolution_clock::now();
  95. activeHero = nullptr;
  96. memory->removeInvisibleObjects(cb.get());
  97. dangerHitMap->updateHitMap();
  98. boost::this_thread::interruption_point();
  99. heroManager->update();
  100. logAi->trace("Updating paths");
  101. std::map<const CGHeroInstance *, HeroRole> activeHeroes;
  102. for(auto hero : cb->getHeroesInfo())
  103. {
  104. if(getHeroLockedReason(hero) == HeroLockedReason::DEFENCE)
  105. continue;
  106. activeHeroes[hero] = heroManager->getHeroRole(hero);
  107. }
  108. PathfinderSettings cfg;
  109. cfg.useHeroChain = true;
  110. cfg.scoutTurnDistanceLimit = SCOUT_TURN_DISTANCE_LIMIT;
  111. if(scanDepth != ScanDepth::FULL)
  112. {
  113. cfg.mainTurnDistanceLimit = MAIN_TURN_DISTANCE_LIMIT * ((int)scanDepth + 1);
  114. }
  115. pathfinder->updatePaths(activeHeroes, cfg);
  116. armyManager->update();
  117. objectClusterizer->clusterize();
  118. buildAnalyzer->update();
  119. decomposer->reset();
  120. logAi->debug("AI state updated in %ld", timeElapsed(start));
  121. }
  122. bool Nullkiller::isHeroLocked(const CGHeroInstance * hero) const
  123. {
  124. return getHeroLockedReason(hero) != HeroLockedReason::NOT_LOCKED;
  125. }
  126. bool Nullkiller::arePathHeroesLocked(const AIPath & path) const
  127. {
  128. if(getHeroLockedReason(path.targetHero) == HeroLockedReason::STARTUP)
  129. {
  130. #if AI_TRACE_LEVEL >= 1
  131. logAi->trace("Hero %s is locked by STARTUP. Discarding %s", path.targetHero->name, path.toString());
  132. #endif
  133. return true;
  134. }
  135. for(auto & node : path.nodes)
  136. {
  137. auto lockReason = getHeroLockedReason(node.targetHero);
  138. if(lockReason != HeroLockedReason::NOT_LOCKED)
  139. {
  140. #if AI_TRACE_LEVEL >= 1
  141. logAi->trace("Hero %s is locked by STARTUP. Discarding %s", path.targetHero->name, path.toString());
  142. #endif
  143. return true;
  144. }
  145. }
  146. return false;
  147. }
  148. HeroLockedReason Nullkiller::getHeroLockedReason(const CGHeroInstance * hero) const
  149. {
  150. auto found = lockedHeroes.find(hero);
  151. return found != lockedHeroes.end() ? found->second : HeroLockedReason::NOT_LOCKED;
  152. }
  153. void Nullkiller::makeTurn()
  154. {
  155. const int MAX_DEPTH = 10;
  156. resetAiState();
  157. for(int i = 1; i <= MAXPASS; i++)
  158. {
  159. updateAiState(i);
  160. Goals::TTaskVec bestTasks = {
  161. choseBestTask(sptr(BuyArmyBehavior()), 1),
  162. choseBestTask(sptr(CaptureObjectsBehavior()), 1),
  163. choseBestTask(sptr(ClusterBehavior()), MAX_DEPTH),
  164. choseBestTask(sptr(RecruitHeroBehavior()), 1),
  165. choseBestTask(sptr(DefenceBehavior()), MAX_DEPTH),
  166. choseBestTask(sptr(BuildingBehavior()), 1),
  167. choseBestTask(sptr(GatherArmyBehavior()), MAX_DEPTH)
  168. };
  169. if(cb->getDate(Date::DAY) == 1)
  170. {
  171. bestTasks.push_back(choseBestTask(sptr(StartupBehavior()), 1));
  172. }
  173. Goals::TTask bestTask = choseBestTask(bestTasks);
  174. HeroPtr hero = bestTask->getHero();
  175. if(bestTask->priority < NEXT_SCAN_MIN_PRIORITY
  176. && hero.validAndSet()
  177. && heroManager->getHeroRole(hero) == HeroRole::MAIN
  178. && scanDepth != ScanDepth::FULL)
  179. {
  180. logAi->trace(
  181. "Goal %s has too low priority %f so increasing scan depth",
  182. bestTask->toString(),
  183. bestTask->priority);
  184. scanDepth = (ScanDepth)((int)scanDepth + 1);
  185. continue;
  186. }
  187. if(bestTask->priority < MIN_PRIORITY)
  188. {
  189. logAi->trace("Goal %s has too low priority. It is not worth doing it. Ending turn.", bestTask->toString());
  190. return;
  191. }
  192. std::string taskDescr = bestTask->toString();
  193. boost::this_thread::interruption_point();
  194. logAi->debug("Trying to realize %s (value %2.3f)", taskDescr, bestTask->priority);
  195. try
  196. {
  197. bestTask->accept(ai.get());
  198. }
  199. catch(goalFulfilledException &)
  200. {
  201. logAi->trace("Task %s completed", bestTask->toString());
  202. }
  203. catch(std::exception & e)
  204. {
  205. logAi->debug("Failed to realize subgoal of type %s, I will stop.", taskDescr);
  206. logAi->debug("The error message was: %s", e.what());
  207. return;
  208. }
  209. }
  210. }