Nullkiller.cpp 6.5 KB

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