Nullkiller.cpp 18 KB

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