2
0

Nullkiller.cpp 7.6 KB

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