Nullkiller.cpp 7.8 KB

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