Nullkiller.cpp 8.1 KB

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