Nullkiller.cpp 8.7 KB

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