Nullkiller.cpp 19 KB

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