Nullkiller.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  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 "../Behaviors/ExplorationBehavior.h"
  23. #include "../Goals/Invalid.h"
  24. #include "../Goals/Composition.h"
  25. #include "../../../lib/CPlayerState.h"
  26. #include "../../lib/StartInfo.h"
  27. namespace NKAI
  28. {
  29. using namespace Goals;
  30. // while we play vcmieagles graph can be shared
  31. std::unique_ptr<ObjectGraph> Nullkiller::baseGraph;
  32. Nullkiller::Nullkiller()
  33. :activeHero(nullptr), scanDepth(ScanDepth::MAIN_FULL), useHeroChain(true)
  34. {
  35. memory = std::make_unique<AIMemory>();
  36. settings = std::make_unique<Settings>();
  37. useObjectGraph = settings->isObjectGraphAllowed();
  38. openMap = settings->isOpenMap() || useObjectGraph;
  39. }
  40. bool canUseOpenMap(std::shared_ptr<CCallback> cb, PlayerColor playerID)
  41. {
  42. if(!cb->getStartInfo()->extraOptionsInfo.cheatsAllowed)
  43. {
  44. return false;
  45. }
  46. const TeamState * team = cb->getPlayerTeam(playerID);
  47. auto hasHumanInTeam = vstd::contains_if(team->players, [cb](PlayerColor teamMateID) -> bool
  48. {
  49. return cb->getPlayerState(teamMateID)->isHuman();
  50. });
  51. if(hasHumanInTeam)
  52. {
  53. return false;
  54. }
  55. return cb->getStartInfo()->difficulty >= 3;
  56. }
  57. void Nullkiller::init(std::shared_ptr<CCallback> cb, AIGateway * gateway)
  58. {
  59. this->cb = cb;
  60. this->gateway = gateway;
  61. playerID = gateway->playerID;
  62. if(openMap && !canUseOpenMap(cb, playerID))
  63. {
  64. useObjectGraph = false;
  65. openMap = false;
  66. }
  67. baseGraph.reset();
  68. priorityEvaluator.reset(new PriorityEvaluator(this));
  69. priorityEvaluators.reset(
  70. new SharedPool<PriorityEvaluator>(
  71. [&]()->std::unique_ptr<PriorityEvaluator>
  72. {
  73. return std::make_unique<PriorityEvaluator>(this);
  74. }));
  75. dangerHitMap.reset(new DangerHitMapAnalyzer(this));
  76. buildAnalyzer.reset(new BuildAnalyzer(this));
  77. objectClusterizer.reset(new ObjectClusterizer(this));
  78. dangerEvaluator.reset(new FuzzyHelper(this));
  79. pathfinder.reset(new AIPathfinder(cb.get(), this));
  80. armyManager.reset(new ArmyManager(cb.get(), this));
  81. heroManager.reset(new HeroManager(cb.get(), this));
  82. decomposer.reset(new DeepDecomposer(this));
  83. armyFormation.reset(new ArmyFormation(cb, this));
  84. }
  85. TaskPlanItem::TaskPlanItem(TSubgoal task)
  86. :task(task), affectedObjects(task->asTask()->getAffectedObjects())
  87. {
  88. }
  89. Goals::TTaskVec TaskPlan::getTasks() const
  90. {
  91. Goals::TTaskVec result;
  92. for(auto & item : tasks)
  93. {
  94. result.push_back(taskptr(*item.task));
  95. }
  96. vstd::removeDuplicates(result);
  97. return result;
  98. }
  99. void TaskPlan::merge(TSubgoal task)
  100. {
  101. TGoalVec blockers;
  102. for(auto & item : tasks)
  103. {
  104. for(auto objid : item.affectedObjects)
  105. {
  106. if(task == item.task || task->asTask()->isObjectAffected(objid))
  107. {
  108. if(item.task->asTask()->priority >= task->asTask()->priority)
  109. return;
  110. blockers.push_back(item.task);
  111. break;
  112. }
  113. }
  114. }
  115. vstd::erase_if(tasks, [&](const TaskPlanItem & task)
  116. {
  117. return vstd::contains(blockers, task.task);
  118. });
  119. tasks.emplace_back(task);
  120. }
  121. Goals::TTask Nullkiller::choseBestTask(Goals::TGoalVec & tasks) const
  122. {
  123. if(tasks.empty())
  124. {
  125. return taskptr(Invalid());
  126. }
  127. for(TSubgoal & task : tasks)
  128. {
  129. if(task->asTask()->priority <= 0)
  130. task->asTask()->priority = priorityEvaluator->evaluate(task);
  131. }
  132. auto bestTask = *vstd::maxElementByFun(tasks, [](Goals::TSubgoal task) -> float
  133. {
  134. return task->asTask()->priority;
  135. });
  136. return taskptr(*bestTask);
  137. }
  138. Goals::TTaskVec Nullkiller::buildPlan(TGoalVec & tasks) const
  139. {
  140. TaskPlan taskPlan;
  141. tbb::parallel_for(tbb::blocked_range<size_t>(0, tasks.size()), [this, &tasks](const tbb::blocked_range<size_t> & r)
  142. {
  143. auto evaluator = this->priorityEvaluators->acquire();
  144. for(size_t i = r.begin(); i != r.end(); i++)
  145. {
  146. auto task = tasks[i];
  147. if(task->asTask()->priority <= 0)
  148. task->asTask()->priority = evaluator->evaluate(task);
  149. }
  150. });
  151. std::sort(tasks.begin(), tasks.end(), [](TSubgoal g1, TSubgoal g2) -> bool
  152. {
  153. return g2->asTask()->priority < g1->asTask()->priority;
  154. });
  155. for(TSubgoal & task : tasks)
  156. {
  157. taskPlan.merge(task);
  158. }
  159. return taskPlan.getTasks();
  160. }
  161. void Nullkiller::decompose(Goals::TGoalVec & result, Goals::TSubgoal behavior, int decompositionMaxDepth) const
  162. {
  163. boost::this_thread::interruption_point();
  164. logAi->debug("Checking behavior %s", behavior->toString());
  165. auto start = std::chrono::high_resolution_clock::now();
  166. decomposer->decompose(result, behavior, decompositionMaxDepth);
  167. boost::this_thread::interruption_point();
  168. logAi->debug(
  169. "Behavior %s. Time taken %ld",
  170. behavior->toString(),
  171. timeElapsed(start));
  172. }
  173. void Nullkiller::resetAiState()
  174. {
  175. std::unique_lock lockGuard(aiStateMutex);
  176. lockedResources = TResources();
  177. scanDepth = ScanDepth::MAIN_FULL;
  178. lockedHeroes.clear();
  179. dangerHitMap->reset();
  180. useHeroChain = true;
  181. objectClusterizer->reset();
  182. if(!baseGraph && isObjectGraphAllowed())
  183. {
  184. baseGraph = std::make_unique<ObjectGraph>();
  185. baseGraph->updateGraph(this);
  186. }
  187. }
  188. void Nullkiller::updateAiState(int pass, bool fast)
  189. {
  190. boost::this_thread::interruption_point();
  191. std::unique_lock lockGuard(aiStateMutex);
  192. auto start = std::chrono::high_resolution_clock::now();
  193. activeHero = nullptr;
  194. setTargetObject(-1);
  195. decomposer->reset();
  196. buildAnalyzer->update();
  197. if(!fast)
  198. {
  199. memory->removeInvisibleObjects(cb.get());
  200. dangerHitMap->updateHitMap();
  201. dangerHitMap->calculateTileOwners();
  202. boost::this_thread::interruption_point();
  203. heroManager->update();
  204. logAi->trace("Updating paths");
  205. std::map<const CGHeroInstance *, HeroRole> activeHeroes;
  206. for(auto hero : cb->getHeroesInfo())
  207. {
  208. if(getHeroLockedReason(hero) == HeroLockedReason::DEFENCE)
  209. continue;
  210. activeHeroes[hero] = heroManager->getHeroRole(hero);
  211. }
  212. PathfinderSettings cfg;
  213. cfg.useHeroChain = useHeroChain;
  214. cfg.allowBypassObjects = true;
  215. if(scanDepth == ScanDepth::SMALL || isObjectGraphAllowed())
  216. {
  217. cfg.mainTurnDistanceLimit = settings->getMainHeroTurnDistanceLimit();
  218. }
  219. if(scanDepth != ScanDepth::ALL_FULL || isObjectGraphAllowed())
  220. {
  221. cfg.scoutTurnDistanceLimit =settings->getScoutHeroTurnDistanceLimit();
  222. }
  223. boost::this_thread::interruption_point();
  224. pathfinder->updatePaths(activeHeroes, cfg);
  225. if(isObjectGraphAllowed())
  226. {
  227. pathfinder->updateGraphs(
  228. activeHeroes,
  229. scanDepth == ScanDepth::SMALL ? 255 : 10,
  230. scanDepth == ScanDepth::ALL_FULL ? 255 : 3);
  231. }
  232. boost::this_thread::interruption_point();
  233. objectClusterizer->clusterize();
  234. }
  235. armyManager->update();
  236. logAi->debug("AI state updated in %ld", timeElapsed(start));
  237. }
  238. bool Nullkiller::isHeroLocked(const CGHeroInstance * hero) const
  239. {
  240. return getHeroLockedReason(hero) != HeroLockedReason::NOT_LOCKED;
  241. }
  242. bool Nullkiller::arePathHeroesLocked(const AIPath & path) const
  243. {
  244. if(getHeroLockedReason(path.targetHero) == HeroLockedReason::STARTUP)
  245. {
  246. #if NKAI_TRACE_LEVEL >= 1
  247. logAi->trace("Hero %s is locked by STARTUP. Discarding %s", path.targetHero->getObjectName(), path.toString());
  248. #endif
  249. return true;
  250. }
  251. for(auto & node : path.nodes)
  252. {
  253. auto lockReason = getHeroLockedReason(node.targetHero);
  254. if(lockReason != HeroLockedReason::NOT_LOCKED)
  255. {
  256. #if NKAI_TRACE_LEVEL >= 1
  257. logAi->trace("Hero %s is locked by STARTUP. Discarding %s", path.targetHero->getObjectName(), path.toString());
  258. #endif
  259. return true;
  260. }
  261. }
  262. return false;
  263. }
  264. HeroLockedReason Nullkiller::getHeroLockedReason(const CGHeroInstance * hero) const
  265. {
  266. auto found = lockedHeroes.find(hero);
  267. return found != lockedHeroes.end() ? found->second : HeroLockedReason::NOT_LOCKED;
  268. }
  269. void Nullkiller::makeTurn()
  270. {
  271. boost::lock_guard<boost::mutex> sharedStorageLock(AISharedStorage::locker);
  272. const int MAX_DEPTH = 10;
  273. const float FAST_TASK_MINIMAL_PRIORITY = 0.7f;
  274. float totalHeroStrength = 0;
  275. int totalTownLevel = 0;
  276. for (auto heroInfo : cb->getHeroesInfo())
  277. {
  278. totalHeroStrength += heroInfo->getTotalStrength();
  279. }
  280. for (auto townInfo : cb->getTownsInfo())
  281. {
  282. totalTownLevel += townInfo->getTownLevel();
  283. }
  284. logAi->info("%d Turn: %d Power: %f Townlevel: %d", cb->getPlayerID()->getNum(), cb->getDate(Date::DAY), totalHeroStrength, totalTownLevel);
  285. resetAiState();
  286. Goals::TGoalVec bestTasks;
  287. for(int i = 1; i <= settings->getMaxPass() && cb->getPlayerStatus(playerID) == EPlayerStatus::INGAME; i++)
  288. {
  289. auto start = std::chrono::high_resolution_clock::now();
  290. updateAiState(i);
  291. Goals::TTask bestTask = taskptr(Goals::Invalid());
  292. for(;i <= settings->getMaxPass(); i++)
  293. {
  294. bestTasks.clear();
  295. decompose(bestTasks, sptr(BuyArmyBehavior()), 1);
  296. decompose(bestTasks, sptr(BuildingBehavior()), 1);
  297. bestTask = choseBestTask(bestTasks);
  298. if(bestTask->priority >= FAST_TASK_MINIMAL_PRIORITY)
  299. {
  300. if(!executeTask(bestTask))
  301. return;
  302. updateAiState(i, true);
  303. }
  304. else
  305. {
  306. break;
  307. }
  308. }
  309. decompose(bestTasks, sptr(RecruitHeroBehavior()), 1);
  310. decompose(bestTasks, sptr(CaptureObjectsBehavior()), 1);
  311. decompose(bestTasks, sptr(ClusterBehavior()), MAX_DEPTH);
  312. decompose(bestTasks, sptr(DefenceBehavior()), MAX_DEPTH);
  313. decompose(bestTasks, sptr(GatherArmyBehavior()), MAX_DEPTH);
  314. decompose(bestTasks, sptr(StayAtTownBehavior()), MAX_DEPTH);
  315. if(!isOpenMap())
  316. decompose(bestTasks, sptr(ExplorationBehavior()), MAX_DEPTH);
  317. if(cb->getDate(Date::DAY) == 1 || heroManager->getHeroRoles().empty())
  318. {
  319. decompose(bestTasks, sptr(StartupBehavior()), 1);
  320. }
  321. auto selectedTasks = buildPlan(bestTasks);
  322. std::sort(selectedTasks.begin(), selectedTasks.end(), [](const TTask& a, const TTask& b)
  323. {
  324. return a->priority > b->priority;
  325. });
  326. logAi->debug("Decision madel in %ld", timeElapsed(start));
  327. if(selectedTasks.empty())
  328. {
  329. selectedTasks.push_back(taskptr(Goals::Invalid()));
  330. }
  331. bool hasAnySuccess = false;
  332. for(auto bestTask : selectedTasks)
  333. {
  334. if(cb->getPlayerStatus(playerID) != EPlayerStatus::INGAME)
  335. return;
  336. if(!areAffectedObjectsPresent(bestTask))
  337. {
  338. logAi->debug("Affected object not found. Canceling task.");
  339. continue;
  340. }
  341. std::string taskDescription = bestTask->toString();
  342. HeroRole heroRole = getTaskRole(bestTask);
  343. if(heroRole != HeroRole::MAIN || bestTask->getHeroExchangeCount() <= 1)
  344. useHeroChain = false;
  345. // TODO: better to check turn distance here instead of priority
  346. if((heroRole != HeroRole::MAIN || bestTask->priority < SMALL_SCAN_MIN_PRIORITY)
  347. && scanDepth == ScanDepth::MAIN_FULL)
  348. {
  349. useHeroChain = false;
  350. scanDepth = ScanDepth::SMALL;
  351. logAi->trace(
  352. "Goal %s has low priority %f so decreasing scan depth to gain performance.",
  353. taskDescription,
  354. bestTask->priority);
  355. }
  356. if((settings->isUseFuzzy() && bestTask->priority < MIN_PRIORITY) || (!settings->isUseFuzzy() && bestTask->priority <= 0))
  357. {
  358. auto heroes = cb->getHeroesInfo();
  359. auto hasMp = vstd::contains_if(heroes, [](const CGHeroInstance * h) -> bool
  360. {
  361. return h->movementPointsRemaining() > 100;
  362. });
  363. if(hasMp && scanDepth != ScanDepth::ALL_FULL)
  364. {
  365. logAi->trace(
  366. "Goal %s has too low priority %f so increasing scan depth to full.",
  367. taskDescription,
  368. bestTask->priority);
  369. scanDepth = ScanDepth::ALL_FULL;
  370. useHeroChain = false;
  371. hasAnySuccess = true;
  372. break;
  373. }
  374. logAi->trace("Goal %s has too low priority. It is not worth doing it.", taskDescription);
  375. continue;
  376. }
  377. if (bestTask->getHero())
  378. logAi->info("Best task for %s should be %s with Prio: %f", bestTask->getHero()->getNameTranslated(), bestTask->toString(), bestTask->priority);
  379. if(!executeTask(bestTask))
  380. {
  381. if(hasAnySuccess)
  382. break;
  383. else
  384. return;
  385. }
  386. hasAnySuccess = true;
  387. }
  388. if(!hasAnySuccess)
  389. {
  390. logAi->trace("Nothing was done this turn. Ending turn.");
  391. return;
  392. }
  393. if(i == settings->getMaxPass())
  394. {
  395. logAi->warn("Maxpass exceeded. Terminating AI turn.");
  396. }
  397. }
  398. }
  399. bool Nullkiller::areAffectedObjectsPresent(Goals::TTask task) const
  400. {
  401. auto affectedObjs = task->getAffectedObjects();
  402. for(auto oid : affectedObjs)
  403. {
  404. if(!cb->getObj(oid, false))
  405. return false;
  406. }
  407. return true;
  408. }
  409. HeroRole Nullkiller::getTaskRole(Goals::TTask task) const
  410. {
  411. HeroPtr hero = task->getHero();
  412. HeroRole heroRole = HeroRole::MAIN;
  413. if(hero.validAndSet())
  414. heroRole = heroManager->getHeroRole(hero);
  415. return heroRole;
  416. }
  417. bool Nullkiller::executeTask(Goals::TTask task)
  418. {
  419. auto start = std::chrono::high_resolution_clock::now();
  420. std::string taskDescr = task->toString();
  421. boost::this_thread::interruption_point();
  422. logAi->debug("Trying to realize %s (value %2.3f)", taskDescr, task->priority);
  423. try
  424. {
  425. task->accept(gateway);
  426. logAi->trace("Task %s completed in %lld", taskDescr, timeElapsed(start));
  427. }
  428. catch(goalFulfilledException &)
  429. {
  430. logAi->trace("Task %s completed in %lld", taskDescr, timeElapsed(start));
  431. }
  432. catch(cannotFulfillGoalException & e)
  433. {
  434. logAi->error("Failed to realize subgoal of type %s, I will stop.", taskDescr);
  435. logAi->error("The error message was: %s", e.what());
  436. return false;
  437. }
  438. return true;
  439. }
  440. TResources Nullkiller::getFreeResources() const
  441. {
  442. auto freeRes = cb->getResourceAmount() - lockedResources;
  443. freeRes.positive();
  444. return freeRes;
  445. }
  446. void Nullkiller::lockResources(const TResources & res)
  447. {
  448. lockedResources += res;
  449. }
  450. }