Nullkiller.cpp 9.7 KB

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