Nullkiller.cpp 8.7 KB

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