Nullkiller.cpp 7.6 KB

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