Nullkiller.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  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 <boost/range/algorithm/sort.hpp>
  13. #include "../AIGateway.h"
  14. #include "../Behaviors/CaptureObjectsBehavior.h"
  15. #include "../Behaviors/RecruitHeroBehavior.h"
  16. #include "../Behaviors/BuyArmyBehavior.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 "../../../lib/CPlayerState.h"
  25. #include "../../lib/StartInfo.h"
  26. #include "../../lib/pathfinder/PathfinderCache.h"
  27. #include "../../lib/pathfinder/PathfinderOptions.h"
  28. namespace NK2AI
  29. {
  30. using namespace Goals;
  31. // while we play vcmieagles graph can be shared
  32. std::unique_ptr<ObjectGraph> Nullkiller::baseGraph;
  33. Nullkiller::Nullkiller()
  34. : activeHero(nullptr)
  35. , scanDepth(ScanDepth::MAIN_FULL)
  36. , useHeroChain(true)
  37. , memory(std::make_unique<AIMemory>())
  38. {
  39. }
  40. Nullkiller::~Nullkiller() = default;
  41. bool canUseOpenMap(const std::shared_ptr<CCallback>& cb, const PlayerColor playerID)
  42. {
  43. if(!cb->getStartInfo()->extraOptionsInfo.cheatsAllowed)
  44. {
  45. return false;
  46. }
  47. const TeamState * team = cb->getPlayerTeam(playerID);
  48. const auto hasHumanInTeam = vstd::contains_if(
  49. team->players,
  50. [cb](const PlayerColor teamMateID) -> bool
  51. {
  52. return cb->getPlayerState(teamMateID)->isHuman();
  53. }
  54. );
  55. return !hasHumanInTeam;
  56. }
  57. void Nullkiller::init(const std::shared_ptr<CCallback> & cbInput, AIGateway * aiGwInput)
  58. {
  59. cc = cbInput;
  60. aiGw = aiGwInput;
  61. playerID = aiGwInput->playerID;
  62. settings = std::make_unique<Settings>(cc->getStartInfo()->difficulty);
  63. PathfinderOptions pathfinderOptions(*cc);
  64. pathfinderOptions.useTeleportTwoWay = true;
  65. pathfinderOptions.useTeleportOneWay = settings->isOneWayMonolithUsageAllowed();
  66. pathfinderOptions.useTeleportOneWayRandom = settings->isOneWayMonolithUsageAllowed();
  67. pathfinderCache = std::make_unique<PathfinderCache>(cc.get(), pathfinderOptions);
  68. if(canUseOpenMap(cc, playerID))
  69. {
  70. useObjectGraph = settings->isObjectGraphAllowed();
  71. openMap = settings->isOpenMap() || useObjectGraph;
  72. }
  73. else
  74. {
  75. useObjectGraph = false;
  76. openMap = false;
  77. }
  78. baseGraph.reset();
  79. priorityEvaluator.reset(new PriorityEvaluator(this));
  80. priorityEvaluators.reset(
  81. new SharedPool<PriorityEvaluator>(
  82. [&]()->std::unique_ptr<PriorityEvaluator>
  83. {
  84. return std::make_unique<PriorityEvaluator>(this);
  85. }));
  86. dangerHitMap.reset(new DangerHitMapAnalyzer(this));
  87. buildAnalyzer.reset(new BuildAnalyzer(this));
  88. objectClusterizer.reset(new ObjectClusterizer(this));
  89. dangerEvaluator.reset(new FuzzyHelper(this));
  90. pathfinder.reset(new AIPathfinder(cc.get(), this));
  91. armyManager.reset(new ArmyManager(cc.get(), this));
  92. heroManager.reset(new HeroManager(cc.get(), this));
  93. decomposer.reset(new DeepDecomposer(this));
  94. armyFormation.reset(new ArmyFormation(cc, this));
  95. }
  96. TaskPlanItem::TaskPlanItem(const TSubgoal & task)
  97. : affectedObjects(task->asTask()->getAffectedObjects())
  98. , task(task)
  99. {
  100. }
  101. Goals::TTaskVec TaskPlan::getTasks() const
  102. {
  103. Goals::TTaskVec result;
  104. for(auto & item : tasks)
  105. {
  106. result.push_back(taskptr(*item.task));
  107. }
  108. vstd::removeDuplicates(result);
  109. return result;
  110. }
  111. void TaskPlan::merge(const TSubgoal & task)
  112. {
  113. TGoalVec blockers;
  114. if (task->asTask()->priority <= 0)
  115. return;
  116. for(auto & item : tasks)
  117. {
  118. for(auto objid : item.affectedObjects)
  119. {
  120. if(task == item.task || task->asTask()->isObjectAffected(objid) || (task->asTask()->getHero() != nullptr && task->asTask()->getHero() == item.task->asTask()->getHero()))
  121. {
  122. if(item.task->asTask()->priority >= task->asTask()->priority)
  123. return;
  124. blockers.push_back(item.task);
  125. break;
  126. }
  127. }
  128. }
  129. vstd::erase_if(tasks, [&](const TaskPlanItem & task2)
  130. {
  131. return vstd::contains(blockers, task2.task);
  132. });
  133. tasks.emplace_back(task);
  134. }
  135. Goals::TTask Nullkiller::choseBestTask(Goals::TGoalVec & tasks) const
  136. {
  137. if(tasks.empty())
  138. {
  139. return taskptr(Invalid());
  140. }
  141. for(const TSubgoal & task : tasks)
  142. {
  143. if(task->asTask()->priority <= 0)
  144. task->asTask()->priority = priorityEvaluator->evaluate(task);
  145. }
  146. auto bestTask = *vstd::maxElementByFun(tasks, [](const Goals::TSubgoal& task) -> float
  147. {
  148. return task->asTask()->priority;
  149. });
  150. return taskptr(*bestTask);
  151. }
  152. Goals::TTaskVec Nullkiller::buildPlan(TGoalVec & tasks, int priorityTier) const
  153. {
  154. TaskPlan taskPlan;
  155. tbb::parallel_for(tbb::blocked_range<size_t>(0, tasks.size()), [this, &tasks, priorityTier](const tbb::blocked_range<size_t> & r)
  156. {
  157. SET_GLOBAL_STATE_TBB(this->aiGw);
  158. auto evaluator = this->priorityEvaluators->acquire();
  159. for(size_t i = r.begin(); i != r.end(); i++)
  160. {
  161. const auto & task = tasks[i];
  162. if(task->asTask()->priority <= 0 || priorityTier != PriorityEvaluator::PriorityTier::BUILDINGS)
  163. task->asTask()->priority = evaluator->evaluate(task, priorityTier);
  164. }
  165. });
  166. boost::range::sort(tasks, [](const TSubgoal& g1, const TSubgoal& g2) -> bool
  167. {
  168. return g2->asTask()->priority < g1->asTask()->priority;
  169. });
  170. for(const TSubgoal & task : tasks)
  171. {
  172. taskPlan.merge(task);
  173. }
  174. return taskPlan.getTasks();
  175. }
  176. void Nullkiller::decompose(Goals::TGoalVec & results, const Goals::TSubgoal& behavior, int decompositionMaxDepth) const
  177. {
  178. makingTurnInterruption.interruptionPoint();
  179. logAi->debug("Decomposing behavior %s", behavior->toString());
  180. const auto start = std::chrono::high_resolution_clock::now();
  181. decomposer->decompose(results, behavior, decompositionMaxDepth);
  182. makingTurnInterruption.interruptionPoint();
  183. logAi->debug("Decomposing behavior %s done in %ld", behavior->toString(), timeElapsed(start));
  184. }
  185. void Nullkiller::resetState()
  186. {
  187. std::unique_lock lockGuard(aiStateMutex);
  188. lockedResources = TResources();
  189. scanDepth = ScanDepth::MAIN_FULL;
  190. lockedHeroes.clear();
  191. dangerHitMap->resetHitmap();
  192. useHeroChain = true;
  193. objectClusterizer->reset();
  194. if(!baseGraph && isObjectGraphAllowed())
  195. {
  196. baseGraph = std::make_unique<ObjectGraph>();
  197. baseGraph->updateGraph(this);
  198. }
  199. }
  200. void Nullkiller::invalidatePathfinderData()
  201. {
  202. pathfinderInvalidated = true;
  203. }
  204. void Nullkiller::updateState()
  205. {
  206. #if NK2AI_TRACE_LEVEL >= 1
  207. logAi->info("PERFORMANCE: AI updateState started");
  208. #endif
  209. makingTurnInterruption.interruptionPoint();
  210. std::unique_lock lockGuard(aiStateMutex);
  211. const auto start = std::chrono::high_resolution_clock::now();
  212. activeHero = nullptr;
  213. setTargetObject(-1);
  214. decomposer->reset();
  215. buildAnalyzer->update();
  216. if(!pathfinderInvalidated && dangerHitMap->isHitMapUpToDate() && dangerHitMap->isTileOwnersUpToDate())
  217. logAi->trace("Skipping full state regeneration - up to date");
  218. else
  219. {
  220. memory->removeInvisibleObjects(cc.get());
  221. dangerHitMap->updateHitMap();
  222. dangerHitMap->calculateTileOwners();
  223. makingTurnInterruption.interruptionPoint();
  224. heroManager->update();
  225. logAi->trace("Updating paths");
  226. PathfinderSettings cfg;
  227. cfg.useHeroChain = useHeroChain;
  228. cfg.allowBypassObjects = true;
  229. if(scanDepth == ScanDepth::SMALL || isObjectGraphAllowed())
  230. {
  231. cfg.mainTurnDistanceLimit = settings->getMainHeroTurnDistanceLimit();
  232. }
  233. if(scanDepth != ScanDepth::ALL_FULL || isObjectGraphAllowed())
  234. {
  235. cfg.scoutTurnDistanceLimit = settings->getScoutHeroTurnDistanceLimit();
  236. }
  237. makingTurnInterruption.interruptionPoint();
  238. const auto heroes = getHeroesForPathfinding();
  239. pathfinder->updatePaths(heroes, cfg);
  240. if(isObjectGraphAllowed())
  241. {
  242. pathfinder->updateGraphs(
  243. heroes,
  244. scanDepth == ScanDepth::SMALL ? PathfinderSettings::MaxTurnDistanceLimit : 10,
  245. scanDepth == ScanDepth::ALL_FULL ? PathfinderSettings::MaxTurnDistanceLimit : 3);
  246. }
  247. makingTurnInterruption.interruptionPoint();
  248. objectClusterizer->clusterize();
  249. pathfinderInvalidated = false;
  250. }
  251. armyManager->update();
  252. #if NK2AI_TRACE_LEVEL >= 1
  253. if(const auto timeElapsedMs = timeElapsed(start); timeElapsedMs > 499)
  254. {
  255. logAi->warn("PERFORMANCE: AI updateState took %ld ms", timeElapsedMs);
  256. }
  257. else
  258. {
  259. logAi->info("PERFORMANCE: AI updateState took %ld ms", timeElapsedMs);
  260. }
  261. #endif
  262. }
  263. bool Nullkiller::isHeroLocked(const CGHeroInstance * hero) const
  264. {
  265. return getHeroLockedReason(hero) != HeroLockedReason::NOT_LOCKED;
  266. }
  267. bool Nullkiller::arePathHeroesLocked(const AIPath & path) const
  268. {
  269. if(getHeroLockedReason(path.targetHero) == HeroLockedReason::STARTUP)
  270. {
  271. #if NK2AI_TRACE_LEVEL >= 1
  272. logAi->trace("Hero %s is locked by STARTUP. Discarding %s", path.targetHero->getObjectName(), path.toString());
  273. #endif
  274. return true;
  275. }
  276. for(const auto & node : path.nodes)
  277. {
  278. auto lockReason = getHeroLockedReason(node.targetHero);
  279. if(lockReason != HeroLockedReason::NOT_LOCKED)
  280. {
  281. #if NK2AI_TRACE_LEVEL >= 1
  282. logAi->trace("Hero %s is locked by %d. Discarding %s", path.targetHero->getObjectName(), (int)lockReason, path.toString());
  283. #endif
  284. return true;
  285. }
  286. }
  287. return false;
  288. }
  289. HeroLockedReason Nullkiller::getHeroLockedReason(const CGHeroInstance * hero) const
  290. {
  291. auto found = lockedHeroes.find(hero);
  292. return found != lockedHeroes.end() ? found->second : HeroLockedReason::NOT_LOCKED;
  293. }
  294. void Nullkiller::makeTurn()
  295. {
  296. std::lock_guard<std::mutex> sharedStorageLock(AISharedStorage::locker);
  297. const int MAX_DEPTH = 10;
  298. resetState();
  299. Goals::TGoalVec tasks;
  300. tracePlayerStatus(true);
  301. for(int i = 1; i <= settings->getMaxPass() && cc->getPlayerStatus(playerID) == EPlayerStatus::INGAME; i++)
  302. {
  303. if (!updateStateAndExecutePriorityPass(tasks, i)) return;
  304. tasks.clear();
  305. decompose(tasks, sptr(CaptureObjectsBehavior()), 1);
  306. decompose(tasks, sptr(ClusterBehavior()), MAX_DEPTH);
  307. decompose(tasks, sptr(DefenceBehavior()), MAX_DEPTH);
  308. decompose(tasks, sptr(GatherArmyBehavior()), MAX_DEPTH);
  309. decompose(tasks, sptr(StayAtTownBehavior()), MAX_DEPTH);
  310. if(!isOpenMap())
  311. decompose(tasks, sptr(ExplorationBehavior()), MAX_DEPTH);
  312. TTaskVec selectedTasks;
  313. #if NK2AI_TRACE_LEVEL >= 1
  314. int prioOfTask = 0;
  315. #endif
  316. for (int prio = PriorityEvaluator::PriorityTier::INSTAKILL; prio <= PriorityEvaluator::PriorityTier::MAX_PRIORITY_TIER; ++prio)
  317. {
  318. #if NK2AI_TRACE_LEVEL >= 1
  319. prioOfTask = prio;
  320. #endif
  321. selectedTasks = buildPlan(tasks, prio);
  322. if (!selectedTasks.empty() || settings->isUseFuzzy())
  323. break;
  324. }
  325. boost::range::sort(selectedTasks, [](const TTask& a, const TTask& b)
  326. {
  327. return a->priority > b->priority;
  328. });
  329. if(selectedTasks.empty())
  330. {
  331. selectedTasks.push_back(taskptr(Goals::Invalid()));
  332. }
  333. bool hasAnySuccess = false;
  334. for(const auto& selectedTask : selectedTasks)
  335. {
  336. if(cc->getPlayerStatus(playerID) != EPlayerStatus::INGAME)
  337. return;
  338. if(!areAffectedObjectsPresent(selectedTask))
  339. {
  340. logAi->debug("Affected object not found. Canceling task.");
  341. continue;
  342. }
  343. std::string taskDescription = selectedTask->toString();
  344. HeroRole heroRole = getTaskRole(selectedTask);
  345. if(heroRole != HeroRole::MAIN || selectedTask->getHeroExchangeCount() <= 1)
  346. useHeroChain = false;
  347. // TODO: better to check turn distance here instead of priority
  348. if((heroRole != HeroRole::MAIN || selectedTask->priority < SMALL_SCAN_MIN_PRIORITY)
  349. && scanDepth == ScanDepth::MAIN_FULL)
  350. {
  351. useHeroChain = false;
  352. scanDepth = ScanDepth::SMALL;
  353. logAi->trace(
  354. "Goal %s has low priority %f so decreasing scan depth to gain performance.",
  355. taskDescription,
  356. selectedTask->priority);
  357. }
  358. if((settings->isUseFuzzy() && selectedTask->priority < MIN_PRIORITY) || (!settings->isUseFuzzy() && selectedTask->priority <= 0))
  359. {
  360. auto heroes = cc->getHeroesInfo();
  361. const auto hasMp = vstd::contains_if(heroes, [](const CGHeroInstance * h) -> bool
  362. {
  363. return h->movementPointsRemaining() > 100;
  364. });
  365. if(hasMp && scanDepth != ScanDepth::ALL_FULL)
  366. {
  367. logAi->trace(
  368. "Goal %s has too low priority %f so increasing scan depth to full.",
  369. taskDescription,
  370. selectedTask->priority);
  371. scanDepth = ScanDepth::ALL_FULL;
  372. useHeroChain = false;
  373. hasAnySuccess = true;
  374. break;
  375. }
  376. logAi->trace("Goal %s has too low priority. It is not worth doing it.", taskDescription);
  377. continue;
  378. }
  379. #if NK2AI_TRACE_LEVEL >= 1
  380. logAi->info("Pass %d: Performing prio %d task %s with prio: %d", i, prioOfTask, selectedTask->toString(), selectedTask->priority);
  381. #endif
  382. if(!executeTask(selectedTask))
  383. {
  384. if(hasAnySuccess)
  385. break;
  386. return;
  387. }
  388. hasAnySuccess = true;
  389. }
  390. hasAnySuccess |= handleTrading();
  391. if(!hasAnySuccess)
  392. {
  393. logAi->trace("Nothing was done this turn. Ending turn.");
  394. tracePlayerStatus(false);
  395. return;
  396. }
  397. for (const auto *heroInfo : cc->getHeroesInfo())
  398. AIGateway::pickBestArtifacts(cc, heroInfo);
  399. if(i == settings->getMaxPass())
  400. {
  401. logAi->warn("MaxPass reached. Terminating AI turn.");
  402. }
  403. }
  404. }
  405. bool Nullkiller::updateStateAndExecutePriorityPass(Goals::TGoalVec & tempResults, const int passIndex)
  406. {
  407. updateState();
  408. Goals::TTask bestPrioPassTask = taskptr(Goals::Invalid());
  409. for(int i = 1; i <= settings->getMaxPriorityPass() && cc->getPlayerStatus(playerID) == EPlayerStatus::INGAME; i++)
  410. {
  411. tempResults.clear();
  412. decompose(tempResults, sptr(RecruitHeroBehavior()), 1);
  413. decompose(tempResults, sptr(BuyArmyBehavior()), 1);
  414. decompose(tempResults, sptr(BuildingBehavior()), 1);
  415. bestPrioPassTask = choseBestTask(tempResults);
  416. if(bestPrioPassTask->priority > 0)
  417. {
  418. logAi->info("Pass %d: Performing priorityPass %d task %s with prio: %d", passIndex, i, bestPrioPassTask->toString(), bestPrioPassTask->priority);
  419. if(!executeTask(bestPrioPassTask))
  420. {
  421. logAi->warn("Task failed to execute");
  422. return false;
  423. }
  424. // TODO: Mircea: Might want to consider calling it before executeTask just in case
  425. updateState();
  426. }
  427. else
  428. {
  429. break;
  430. }
  431. if(i == settings->getMaxPriorityPass())
  432. {
  433. logAi->warn("MaxPriorityPass reached. Terminating priorityPass loop.");
  434. }
  435. }
  436. return true;
  437. }
  438. bool Nullkiller::areAffectedObjectsPresent(const Goals::TTask & task) const
  439. {
  440. auto affectedObjs = task->getAffectedObjects();
  441. for(auto oid : affectedObjs)
  442. {
  443. if(!cc->getObj(oid, false))
  444. return false;
  445. }
  446. return true;
  447. }
  448. HeroRole Nullkiller::getTaskRole(const Goals::TTask & task) const
  449. {
  450. HeroPtr heroPtr(task->getHero(), cc);
  451. HeroRole heroRole = HeroRole::MAIN;
  452. if(heroPtr.isVerified())
  453. heroRole = heroManager->getHeroRoleOrDefault(heroPtr);
  454. return heroRole;
  455. }
  456. bool Nullkiller::executeTask(const Goals::TTask & task)
  457. {
  458. auto start = std::chrono::high_resolution_clock::now();
  459. std::string taskDescr = task->toString();
  460. makingTurnInterruption.interruptionPoint();
  461. logAi->debug("Trying to realize %s (value %2.3f)", taskDescr, task->priority);
  462. try
  463. {
  464. task->accept(aiGw);
  465. logAi->trace("Task %s completed in %lld", taskDescr, timeElapsed(start));
  466. }
  467. catch(goalFulfilledException &)
  468. {
  469. logAi->trace("Task %s completed in %lld", taskDescr, timeElapsed(start));
  470. }
  471. catch(cannotFulfillGoalException & e)
  472. {
  473. logAi->error("Failed to realize subgoal of type %s, I will stop.", taskDescr);
  474. logAi->error("The error message was: %s", e.what());
  475. return false;
  476. }
  477. return true;
  478. }
  479. TResources Nullkiller::getFreeResources() const
  480. {
  481. auto freeRes = cc->getResourceAmount() - lockedResources;
  482. freeRes.positive();
  483. return freeRes;
  484. }
  485. void Nullkiller::lockResources(const TResources & res)
  486. {
  487. lockedResources += res;
  488. }
  489. bool Nullkiller::handleTrading()
  490. {
  491. bool haveTraded = false;
  492. bool shouldTryToTrade = true;
  493. ObjectInstanceID marketId;
  494. for (const auto town : cc->getTownsInfo())
  495. {
  496. if (town->hasBuiltSomeTradeBuilding())
  497. {
  498. marketId = town->id;
  499. }
  500. }
  501. if (!marketId.hasValue())
  502. return false;
  503. if (const CGObjectInstance* obj = cc->getObj(marketId, false))
  504. {
  505. if (const auto* m = dynamic_cast<const IMarket*>(obj))
  506. {
  507. while (shouldTryToTrade)
  508. {
  509. shouldTryToTrade = false;
  510. buildAnalyzer->update();
  511. TResources required = buildAnalyzer->getTotalResourcesRequired();
  512. TResources income = buildAnalyzer->getDailyIncome();
  513. TResources available = cc->getResourceAmount();
  514. #if NK2AI_TRACE_LEVEL >= 2
  515. logAi->debug("Available %s", available.toString());
  516. logAi->debug("Required %s", required.toString());
  517. #endif
  518. int mostWanted = -1;
  519. int mostExpendable = -1;
  520. float minRatio = std::numeric_limits<float>::max();
  521. float maxRatio = std::numeric_limits<float>::min();
  522. for (int i = 0; i < required.size(); ++i)
  523. {
  524. if (required[i] <= 0)
  525. continue;
  526. float ratio = static_cast<float>(available[i]) / required[i];
  527. if (ratio < minRatio) {
  528. minRatio = ratio;
  529. mostWanted = i;
  530. }
  531. }
  532. for (int i = 0; i < required.size(); ++i)
  533. {
  534. float ratio;
  535. if (required[i] > 0)
  536. ratio = static_cast<float>(available[i]) / required[i];
  537. else
  538. ratio = available[i];
  539. bool okToSell = false;
  540. if (i == GameResID::GOLD)
  541. {
  542. if (income[i] > 0 && !buildAnalyzer->isGoldPressureOverMax())
  543. okToSell = true;
  544. }
  545. else
  546. {
  547. if (required[i] <= 0 && income[i] > 0)
  548. okToSell = true;
  549. }
  550. if (ratio > maxRatio && okToSell) {
  551. maxRatio = ratio;
  552. mostExpendable = i;
  553. }
  554. }
  555. #if NK2AI_TRACE_LEVEL >= 2
  556. logAi->debug("mostExpendable: %d mostWanted: %d", mostExpendable, mostWanted);
  557. #endif
  558. if (mostExpendable == mostWanted || mostWanted == -1 || mostExpendable == -1)
  559. return false;
  560. int toGive;
  561. int toGet;
  562. m->getOffer(mostExpendable, mostWanted, toGive, toGet, EMarketMode::RESOURCE_RESOURCE);
  563. //logAi->info("Offer is: I get %d of %s for %d of %s at %s", toGet, mostWanted, toGive, mostExpendable, obj->getObjectName());
  564. //TODO trade only as much as needed
  565. if (toGive && toGive <= available[mostExpendable]) //don't try to sell 0 resources
  566. {
  567. cc->trade(m->getObjInstanceID(), EMarketMode::RESOURCE_RESOURCE, GameResID(mostExpendable), GameResID(mostWanted), toGive);
  568. #if NK2AI_TRACE_LEVEL >= 2
  569. logAi->info("Traded %d of %s for %d of %s at %s", toGive, mostExpendable, toGet, mostWanted, obj->getObjectName());
  570. #endif
  571. haveTraded = true;
  572. shouldTryToTrade = true;
  573. }
  574. }
  575. }
  576. }
  577. return haveTraded;
  578. }
  579. std::shared_ptr<const CPathsInfo> Nullkiller::getPathsInfo(const CGHeroInstance * h) const
  580. {
  581. return pathfinderCache->getPathsInfo(h);
  582. }
  583. void Nullkiller::invalidatePaths()
  584. {
  585. pathfinderCache->invalidatePaths();
  586. }
  587. void Nullkiller::tracePlayerStatus(bool beginning) const
  588. {
  589. #if NK2AI_TRACE_LEVEL >= 1
  590. float totalHeroesStrength = 0;
  591. int totalTownsLevel = 0;
  592. for (const auto *heroInfo : cc->getHeroesInfo())
  593. {
  594. totalHeroesStrength += heroInfo->getTotalStrength();
  595. }
  596. for (const auto *townInfo : cc->getTownsInfo())
  597. {
  598. totalTownsLevel += townInfo->getTownLevel();
  599. }
  600. const auto *firstWord = beginning ? "Beginning:" : "End:";
  601. logAi->info("%s totalHeroesStrength: %f, totalTownsLevel: %d, resources: %s", firstWord, totalHeroesStrength, totalTownsLevel, cc->getResourceAmount().toString());
  602. #endif
  603. }
  604. std::map<const CGHeroInstance *, HeroRole> Nullkiller::getHeroesForPathfinding() const
  605. {
  606. std::map<const CGHeroInstance *, HeroRole> activeHeroes;
  607. for(auto hero : cc->getHeroesInfo())
  608. {
  609. if(getHeroLockedReason(hero) == HeroLockedReason::DEFENCE)
  610. continue;
  611. activeHeroes[hero] = heroManager->getHeroRoleOrDefaultInefficient(hero);
  612. }
  613. return activeHeroes;
  614. }
  615. }