Nullkiller.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  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 true;
  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. if (task->asTask()->priority <= 0)
  103. return;
  104. for(auto & item : tasks)
  105. {
  106. for(auto objid : item.affectedObjects)
  107. {
  108. if(task == item.task || task->asTask()->isObjectAffected(objid) || task->asTask()->getHero() == item.task->asTask()->getHero())
  109. {
  110. if(item.task->asTask()->priority >= task->asTask()->priority)
  111. return;
  112. blockers.push_back(item.task);
  113. break;
  114. }
  115. }
  116. }
  117. vstd::erase_if(tasks, [&](const TaskPlanItem & task)
  118. {
  119. return vstd::contains(blockers, task.task);
  120. });
  121. tasks.emplace_back(task);
  122. }
  123. Goals::TTask Nullkiller::choseBestTask(Goals::TGoalVec & tasks) const
  124. {
  125. if(tasks.empty())
  126. {
  127. return taskptr(Invalid());
  128. }
  129. for(TSubgoal & task : tasks)
  130. {
  131. if(task->asTask()->priority <= 0)
  132. task->asTask()->priority = priorityEvaluator->evaluate(task);
  133. }
  134. auto bestTask = *vstd::maxElementByFun(tasks, [](Goals::TSubgoal task) -> float
  135. {
  136. return task->asTask()->priority;
  137. });
  138. return taskptr(*bestTask);
  139. }
  140. Goals::TTaskVec Nullkiller::buildPlan(TGoalVec & tasks, int priorityTier) const
  141. {
  142. TaskPlan taskPlan;
  143. tbb::parallel_for(tbb::blocked_range<size_t>(0, tasks.size()), [this, &tasks, priorityTier](const tbb::blocked_range<size_t> & r)
  144. {
  145. auto evaluator = this->priorityEvaluators->acquire();
  146. for(size_t i = r.begin(); i != r.end(); i++)
  147. {
  148. auto task = tasks[i];
  149. if (task->asTask()->priority <= 0 || priorityTier != 3)
  150. task->asTask()->priority = evaluator->evaluate(task, priorityTier);
  151. }
  152. });
  153. std::sort(tasks.begin(), tasks.end(), [](TSubgoal g1, TSubgoal g2) -> bool
  154. {
  155. return g2->asTask()->priority < g1->asTask()->priority;
  156. });
  157. for(TSubgoal & task : tasks)
  158. {
  159. taskPlan.merge(task);
  160. }
  161. return taskPlan.getTasks();
  162. }
  163. void Nullkiller::decompose(Goals::TGoalVec & result, Goals::TSubgoal behavior, int decompositionMaxDepth) const
  164. {
  165. boost::this_thread::interruption_point();
  166. logAi->debug("Checking behavior %s", behavior->toString());
  167. auto start = std::chrono::high_resolution_clock::now();
  168. decomposer->decompose(result, behavior, decompositionMaxDepth);
  169. boost::this_thread::interruption_point();
  170. logAi->debug(
  171. "Behavior %s. Time taken %ld",
  172. behavior->toString(),
  173. timeElapsed(start));
  174. }
  175. void Nullkiller::resetAiState()
  176. {
  177. std::unique_lock lockGuard(aiStateMutex);
  178. lockedResources = TResources();
  179. scanDepth = ScanDepth::MAIN_FULL;
  180. lockedHeroes.clear();
  181. dangerHitMap->reset();
  182. useHeroChain = true;
  183. objectClusterizer->reset();
  184. if(!baseGraph && isObjectGraphAllowed())
  185. {
  186. baseGraph = std::make_unique<ObjectGraph>();
  187. baseGraph->updateGraph(this);
  188. }
  189. }
  190. void Nullkiller::updateAiState(int pass, bool fast)
  191. {
  192. boost::this_thread::interruption_point();
  193. std::unique_lock lockGuard(aiStateMutex);
  194. auto start = std::chrono::high_resolution_clock::now();
  195. activeHero = nullptr;
  196. setTargetObject(-1);
  197. decomposer->reset();
  198. buildAnalyzer->update();
  199. if(!fast)
  200. {
  201. memory->removeInvisibleObjects(cb.get());
  202. dangerHitMap->updateHitMap();
  203. dangerHitMap->calculateTileOwners();
  204. boost::this_thread::interruption_point();
  205. heroManager->update();
  206. logAi->trace("Updating paths");
  207. std::map<const CGHeroInstance *, HeroRole> activeHeroes;
  208. for(auto hero : cb->getHeroesInfo())
  209. {
  210. if(getHeroLockedReason(hero) == HeroLockedReason::DEFENCE)
  211. continue;
  212. activeHeroes[hero] = heroManager->getHeroRole(hero);
  213. }
  214. PathfinderSettings cfg;
  215. cfg.useHeroChain = useHeroChain;
  216. cfg.allowBypassObjects = true;
  217. if(scanDepth == ScanDepth::SMALL || isObjectGraphAllowed())
  218. {
  219. cfg.mainTurnDistanceLimit = settings->getMainHeroTurnDistanceLimit();
  220. }
  221. if(scanDepth != ScanDepth::ALL_FULL || isObjectGraphAllowed())
  222. {
  223. cfg.scoutTurnDistanceLimit =settings->getScoutHeroTurnDistanceLimit();
  224. }
  225. boost::this_thread::interruption_point();
  226. pathfinder->updatePaths(activeHeroes, cfg);
  227. if(isObjectGraphAllowed())
  228. {
  229. pathfinder->updateGraphs(
  230. activeHeroes,
  231. scanDepth == ScanDepth::SMALL ? 255 : 10,
  232. scanDepth == ScanDepth::ALL_FULL ? 255 : 3);
  233. }
  234. boost::this_thread::interruption_point();
  235. objectClusterizer->clusterize();
  236. }
  237. armyManager->update();
  238. logAi->debug("AI state updated in %ld", timeElapsed(start));
  239. }
  240. bool Nullkiller::isHeroLocked(const CGHeroInstance * hero) const
  241. {
  242. return getHeroLockedReason(hero) != HeroLockedReason::NOT_LOCKED;
  243. }
  244. bool Nullkiller::arePathHeroesLocked(const AIPath & path) const
  245. {
  246. if(getHeroLockedReason(path.targetHero) == HeroLockedReason::STARTUP)
  247. {
  248. #if NKAI_TRACE_LEVEL >= 1
  249. logAi->trace("Hero %s is locked by STARTUP. Discarding %s", path.targetHero->getObjectName(), path.toString());
  250. #endif
  251. return true;
  252. }
  253. for(auto & node : path.nodes)
  254. {
  255. auto lockReason = getHeroLockedReason(node.targetHero);
  256. if(lockReason != HeroLockedReason::NOT_LOCKED)
  257. {
  258. #if NKAI_TRACE_LEVEL >= 1
  259. logAi->trace("Hero %s is locked by %d. Discarding %s", path.targetHero->getObjectName(), (int)lockReason, path.toString());
  260. #endif
  261. return true;
  262. }
  263. }
  264. return false;
  265. }
  266. HeroLockedReason Nullkiller::getHeroLockedReason(const CGHeroInstance * hero) const
  267. {
  268. auto found = lockedHeroes.find(hero);
  269. return found != lockedHeroes.end() ? found->second : HeroLockedReason::NOT_LOCKED;
  270. }
  271. void Nullkiller::makeTurn()
  272. {
  273. boost::lock_guard<boost::mutex> sharedStorageLock(AISharedStorage::locker);
  274. const int MAX_DEPTH = 10;
  275. const float FAST_TASK_MINIMAL_PRIORITY = 0.7f;
  276. float totalHeroStrength = 0;
  277. int totalTownLevel = 0;
  278. for (auto heroInfo : cb->getHeroesInfo())
  279. {
  280. totalHeroStrength += heroInfo->getTotalStrength();
  281. }
  282. for (auto townInfo : cb->getTownsInfo())
  283. {
  284. totalTownLevel += townInfo->getTownLevel();
  285. }
  286. resetAiState();
  287. Goals::TGoalVec bestTasks;
  288. for(int i = 1; i <= settings->getMaxPass() && cb->getPlayerStatus(playerID) == EPlayerStatus::INGAME; i++)
  289. {
  290. logAi->info("Strength: %f Townlevel: %d Resources: %s", totalHeroStrength, totalTownLevel, cb->getResourceAmount().toString());
  291. auto start = std::chrono::high_resolution_clock::now();
  292. updateAiState(i);
  293. Goals::TTask bestTask = taskptr(Goals::Invalid());
  294. for(;i <= settings->getMaxPass(); i++)
  295. {
  296. bestTasks.clear();
  297. decompose(bestTasks, sptr(RecruitHeroBehavior()), 1);
  298. decompose(bestTasks, sptr(BuyArmyBehavior()), 1);
  299. decompose(bestTasks, sptr(BuildingBehavior()), 1);
  300. bestTask = choseBestTask(bestTasks);
  301. if(bestTask->priority > 0)
  302. {
  303. logAi->info("Performing task %s with prio: %d", bestTask->toString(), bestTask->priority);
  304. if(!executeTask(bestTask))
  305. return;
  306. updateAiState(i, true);
  307. }
  308. else
  309. {
  310. break;
  311. }
  312. }
  313. decompose(bestTasks, sptr(CaptureObjectsBehavior()), 1);
  314. decompose(bestTasks, sptr(ClusterBehavior()), MAX_DEPTH);
  315. decompose(bestTasks, sptr(DefenceBehavior()), MAX_DEPTH);
  316. decompose(bestTasks, sptr(GatherArmyBehavior()), MAX_DEPTH);
  317. decompose(bestTasks, sptr(StayAtTownBehavior()), MAX_DEPTH);
  318. if(!isOpenMap())
  319. decompose(bestTasks, sptr(ExplorationBehavior()), MAX_DEPTH);
  320. TTaskVec selectedTasks;
  321. int prioOfTask = 0;
  322. for (int prio = 0; prio <= 2; ++prio)
  323. {
  324. prioOfTask = prio;
  325. selectedTasks = buildPlan(bestTasks, prio);
  326. if (!selectedTasks.empty() || settings->isUseFuzzy())
  327. break;
  328. }
  329. std::sort(selectedTasks.begin(), selectedTasks.end(), [](const TTask& a, const TTask& b)
  330. {
  331. return a->priority > b->priority;
  332. });
  333. logAi->debug("Decision madel in %ld", timeElapsed(start));
  334. if(selectedTasks.empty())
  335. {
  336. selectedTasks.push_back(taskptr(Goals::Invalid()));
  337. }
  338. bool hasAnySuccess = false;
  339. for(auto bestTask : selectedTasks)
  340. {
  341. if(cb->getPlayerStatus(playerID) != EPlayerStatus::INGAME)
  342. return;
  343. if(!areAffectedObjectsPresent(bestTask))
  344. {
  345. logAi->debug("Affected object not found. Canceling task.");
  346. continue;
  347. }
  348. std::string taskDescription = bestTask->toString();
  349. HeroRole heroRole = getTaskRole(bestTask);
  350. if(heroRole != HeroRole::MAIN || bestTask->getHeroExchangeCount() <= 1)
  351. useHeroChain = false;
  352. // TODO: better to check turn distance here instead of priority
  353. if((heroRole != HeroRole::MAIN || bestTask->priority < SMALL_SCAN_MIN_PRIORITY)
  354. && scanDepth == ScanDepth::MAIN_FULL)
  355. {
  356. useHeroChain = false;
  357. scanDepth = ScanDepth::SMALL;
  358. logAi->trace(
  359. "Goal %s has low priority %f so decreasing scan depth to gain performance.",
  360. taskDescription,
  361. bestTask->priority);
  362. }
  363. if((settings->isUseFuzzy() && bestTask->priority < MIN_PRIORITY) || (!settings->isUseFuzzy() && bestTask->priority <= 0))
  364. {
  365. auto heroes = cb->getHeroesInfo();
  366. auto hasMp = vstd::contains_if(heroes, [](const CGHeroInstance * h) -> bool
  367. {
  368. return h->movementPointsRemaining() > 100;
  369. });
  370. if(hasMp && scanDepth != ScanDepth::ALL_FULL)
  371. {
  372. logAi->trace(
  373. "Goal %s has too low priority %f so increasing scan depth to full.",
  374. taskDescription,
  375. bestTask->priority);
  376. scanDepth = ScanDepth::ALL_FULL;
  377. useHeroChain = false;
  378. hasAnySuccess = true;
  379. break;
  380. }
  381. logAi->trace("Goal %s has too low priority. It is not worth doing it.", taskDescription);
  382. continue;
  383. }
  384. logAi->info("Performing prio %d task %s with prio: %d", prioOfTask, bestTask->toString(), bestTask->priority);
  385. if(!executeTask(bestTask))
  386. {
  387. if(hasAnySuccess)
  388. break;
  389. else
  390. return;
  391. }
  392. hasAnySuccess = true;
  393. }
  394. hasAnySuccess |= handleTrading();
  395. if(!hasAnySuccess)
  396. {
  397. logAi->trace("Nothing was done this turn. Ending turn.");
  398. return;
  399. }
  400. if(i == settings->getMaxPass())
  401. {
  402. logAi->warn("Maxpass exceeded. Terminating AI turn.");
  403. }
  404. }
  405. }
  406. bool Nullkiller::areAffectedObjectsPresent(Goals::TTask task) const
  407. {
  408. auto affectedObjs = task->getAffectedObjects();
  409. for(auto oid : affectedObjs)
  410. {
  411. if(!cb->getObj(oid, false))
  412. return false;
  413. }
  414. return true;
  415. }
  416. HeroRole Nullkiller::getTaskRole(Goals::TTask task) const
  417. {
  418. HeroPtr hero = task->getHero();
  419. HeroRole heroRole = HeroRole::MAIN;
  420. if(hero.validAndSet())
  421. heroRole = heroManager->getHeroRole(hero);
  422. return heroRole;
  423. }
  424. bool Nullkiller::executeTask(Goals::TTask task)
  425. {
  426. auto start = std::chrono::high_resolution_clock::now();
  427. std::string taskDescr = task->toString();
  428. boost::this_thread::interruption_point();
  429. logAi->debug("Trying to realize %s (value %2.3f)", taskDescr, task->priority);
  430. try
  431. {
  432. task->accept(gateway);
  433. logAi->trace("Task %s completed in %lld", taskDescr, timeElapsed(start));
  434. }
  435. catch(goalFulfilledException &)
  436. {
  437. logAi->trace("Task %s completed in %lld", taskDescr, timeElapsed(start));
  438. }
  439. catch(cannotFulfillGoalException & e)
  440. {
  441. logAi->error("Failed to realize subgoal of type %s, I will stop.", taskDescr);
  442. logAi->error("The error message was: %s", e.what());
  443. return false;
  444. }
  445. return true;
  446. }
  447. TResources Nullkiller::getFreeResources() const
  448. {
  449. auto freeRes = cb->getResourceAmount() - lockedResources;
  450. freeRes.positive();
  451. return freeRes;
  452. }
  453. void Nullkiller::lockResources(const TResources & res)
  454. {
  455. lockedResources += res;
  456. }
  457. bool Nullkiller::handleTrading()
  458. {
  459. bool haveTraded = false;
  460. bool shouldTryToTrade = true;
  461. int marketId = -1;
  462. for (auto town : cb->getTownsInfo())
  463. {
  464. if (town->hasBuiltSomeTradeBuilding())
  465. {
  466. marketId = town->id;
  467. }
  468. }
  469. if (marketId == -1)
  470. return false;
  471. if (const CGObjectInstance* obj = cb->getObj(ObjectInstanceID(marketId), false))
  472. {
  473. if (const auto* m = dynamic_cast<const IMarket*>(obj))
  474. {
  475. while (shouldTryToTrade)
  476. {
  477. shouldTryToTrade = false;
  478. buildAnalyzer->update();
  479. TResources required = buildAnalyzer->getTotalResourcesRequired();
  480. TResources income = buildAnalyzer->getDailyIncome();
  481. TResources available = getFreeResources();
  482. int mostWanted = -1;
  483. int mostExpendable = -1;
  484. float minRatio = std::numeric_limits<float>::max();
  485. float maxRatio = std::numeric_limits<float>::min();
  486. for (int i = 0; i < required.size(); ++i)
  487. {
  488. if (required[i] == 0)
  489. continue;
  490. float ratio = static_cast<float>(available[i]) / required[i];
  491. if (ratio < minRatio) {
  492. minRatio = ratio;
  493. mostWanted = i;
  494. }
  495. }
  496. for (int i = 0; i < required.size(); ++i)
  497. {
  498. float ratio = available[i];
  499. if (required[i] > 0)
  500. ratio = static_cast<float>(available[i]) / required[i];
  501. bool okToSell = false;
  502. if (i == 6)
  503. {
  504. if (income[i] > 0)
  505. okToSell = true;
  506. }
  507. else
  508. {
  509. if (available[i] > required[i])
  510. okToSell = true;
  511. }
  512. if (ratio > maxRatio && okToSell) {
  513. maxRatio = ratio;
  514. mostExpendable = i;
  515. }
  516. }
  517. //logAi->info("mostExpendable: %d mostWanted: %d", mostExpendable, mostWanted);
  518. if (mostExpendable == mostWanted || mostWanted == -1 || mostExpendable == -1)
  519. return false;
  520. int toGive;
  521. int toGet;
  522. m->getOffer(mostExpendable, mostWanted, toGive, toGet, EMarketMode::RESOURCE_RESOURCE);
  523. //logAi->info("Offer is: I get %d of %s for %d of %s at %s", toGet, mostWanted, toGive, mostExpendable, obj->getObjectName());
  524. //TODO trade only as much as needed
  525. if (toGive && toGive <= available[mostExpendable]) //don't try to sell 0 resources
  526. {
  527. cb->trade(m, EMarketMode::RESOURCE_RESOURCE, GameResID(mostExpendable), GameResID(mostWanted), toGive);
  528. logAi->info("Traded %d of %s for %d of %s at %s", toGive, mostExpendable, toGet, mostWanted, obj->getObjectName());
  529. haveTraded = true;
  530. shouldTryToTrade = true;
  531. }
  532. }
  533. }
  534. }
  535. return haveTraded;
  536. }
  537. }