GatherArmyBehavior.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. /*
  2. * GatherArmyBehavior.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 "../AIGateway.h"
  12. #include "../Engine/Nullkiller.h"
  13. #include "../Goals/ExecuteHeroChain.h"
  14. #include "../Goals/Composition.h"
  15. #include "../Goals/RecruitHero.h"
  16. #include "../Markers/HeroExchange.h"
  17. #include "../Markers/ArmyUpgrade.h"
  18. #include "GatherArmyBehavior.h"
  19. #include "CaptureObjectsBehavior.h"
  20. #include "../AIUtility.h"
  21. #include "../Goals/ExchangeSwapTownHeroes.h"
  22. namespace NKAI
  23. {
  24. using namespace Goals;
  25. std::string GatherArmyBehavior::toString() const
  26. {
  27. return "Gather army";
  28. }
  29. Goals::TGoalVec GatherArmyBehavior::decompose(const Nullkiller * ai) const
  30. {
  31. Goals::TGoalVec tasks;
  32. auto heroes = ai->cb->getHeroesInfo();
  33. if(heroes.empty())
  34. {
  35. return tasks;
  36. }
  37. for(const CGHeroInstance * hero : heroes)
  38. {
  39. if(ai->heroManager->getHeroRole(hero) == HeroRole::MAIN)
  40. {
  41. vstd::concatenate(tasks, deliverArmyToHero(ai, hero));
  42. }
  43. }
  44. auto towns = ai->cb->getTownsInfo();
  45. for(const CGTownInstance * town : towns)
  46. {
  47. vstd::concatenate(tasks, upgradeArmy(ai, town));
  48. }
  49. return tasks;
  50. }
  51. Goals::TGoalVec GatherArmyBehavior::deliverArmyToHero(const Nullkiller * ai, const CGHeroInstance * hero) const
  52. {
  53. Goals::TGoalVec tasks;
  54. const int3 pos = hero->visitablePos();
  55. auto targetHeroScore = ai->heroManager->evaluateHero(hero);
  56. #if NKAI_TRACE_LEVEL >= 1
  57. logAi->trace("Checking ways to gaher army for hero %s, %s", hero->getObjectName(), pos.toString());
  58. #endif
  59. auto paths = ai->pathfinder->getPathInfo(pos, ai->settings->isObjectGraphAllowed());
  60. #if NKAI_TRACE_LEVEL >= 1
  61. logAi->trace("Gather army found %d paths", paths.size());
  62. #endif
  63. for(const AIPath & path : paths)
  64. {
  65. #if NKAI_TRACE_LEVEL >= 2
  66. logAi->trace("Path found %s, %s, %lld", path.toString(), path.targetHero->getObjectName(), path.heroArmy->getArmyStrength());
  67. #endif
  68. if(path.containsHero(hero))
  69. {
  70. #if NKAI_TRACE_LEVEL >= 2
  71. logAi->trace("Selfcontaining path. Ignore");
  72. #endif
  73. continue;
  74. }
  75. if(path.turn() > 0 && ai->dangerHitMap->enemyCanKillOurHeroesAlongThePath(path))
  76. {
  77. #if NKAI_TRACE_LEVEL >= 2
  78. logAi->trace("Ignore path. Target hero can be killed by enemy. Our power %lld", path.heroArmy->getArmyStrength());
  79. #endif
  80. continue;
  81. }
  82. if(ai->arePathHeroesLocked(path))
  83. {
  84. #if NKAI_TRACE_LEVEL >= 2
  85. logAi->trace("Ignore path because of locked hero");
  86. #endif
  87. continue;
  88. }
  89. HeroExchange heroExchange(hero, path);
  90. uint64_t armyValue = heroExchange.getReinforcementArmyStrength(ai);
  91. float armyRatio = (float)armyValue / hero->getArmyStrength();
  92. // avoid transferring very small amount of army
  93. if((armyRatio < 0.1f && armyValue < 20000) || armyValue < 500)
  94. {
  95. #if NKAI_TRACE_LEVEL >= 2
  96. logAi->trace("Army value is too small.");
  97. #endif
  98. continue;
  99. }
  100. // avoid trying to move bigger army to the weaker one.
  101. bool hasOtherMainInPath = false;
  102. for(auto node : path.nodes)
  103. {
  104. if(!node.targetHero) continue;
  105. auto heroRole = ai->heroManager->getHeroRole(node.targetHero);
  106. if(heroRole == HeroRole::MAIN)
  107. {
  108. auto score = ai->heroManager->evaluateHero(node.targetHero);
  109. if(score >= targetHeroScore)
  110. {
  111. hasOtherMainInPath = true;
  112. break;
  113. }
  114. }
  115. }
  116. if(hasOtherMainInPath)
  117. {
  118. #if NKAI_TRACE_LEVEL >= 2
  119. logAi->trace("Army value is too large.");
  120. #endif
  121. continue;
  122. }
  123. auto danger = path.getTotalDanger();
  124. auto isSafe = isSafeToVisit(hero, path.heroArmy, danger);
  125. #if NKAI_TRACE_LEVEL >= 2
  126. logAi->trace(
  127. "It is %s to visit %s by %s with army %lld, danger %lld and army loss %lld",
  128. isSafe ? "safe" : "not safe",
  129. hero->getObjectName(),
  130. path.targetHero->getObjectName(),
  131. path.getHeroStrength(),
  132. danger,
  133. path.getTotalArmyLoss());
  134. #endif
  135. if(isSafe)
  136. {
  137. Composition composition;
  138. ExecuteHeroChain exchangePath(path, hero);
  139. exchangePath.closestWayRatio = 1;
  140. composition.addNext(heroExchange);
  141. if(hero->inTownGarrison && path.turn() == 0)
  142. {
  143. auto lockReason = ai->getHeroLockedReason(hero);
  144. if(path.targetHero->visitedTown == hero->visitedTown)
  145. {
  146. composition.addNextSequence({
  147. sptr(ExchangeSwapTownHeroes(hero->visitedTown, hero, lockReason))});
  148. }
  149. else
  150. {
  151. composition.addNextSequence({
  152. sptr(ExchangeSwapTownHeroes(hero->visitedTown)),
  153. sptr(exchangePath),
  154. sptr(ExchangeSwapTownHeroes(hero->visitedTown, hero, lockReason))});
  155. }
  156. }
  157. else
  158. {
  159. composition.addNext(exchangePath);
  160. }
  161. auto blockedAction = path.getFirstBlockedAction();
  162. if(blockedAction)
  163. {
  164. #if NKAI_TRACE_LEVEL >= 2
  165. logAi->trace("Action is blocked. Considering decomposition.");
  166. #endif
  167. auto subGoal = blockedAction->decompose(ai, path.targetHero);
  168. if(subGoal->invalid())
  169. {
  170. #if NKAI_TRACE_LEVEL >= 1
  171. logAi->trace("Path is invalid. Skipping");
  172. #endif
  173. continue;
  174. }
  175. composition.addNext(subGoal);
  176. }
  177. tasks.push_back(sptr(composition));
  178. }
  179. }
  180. return tasks;
  181. }
  182. Goals::TGoalVec GatherArmyBehavior::upgradeArmy(const Nullkiller * ai, const CGTownInstance * upgrader) const
  183. {
  184. Goals::TGoalVec tasks;
  185. const int3 pos = upgrader->visitablePos();
  186. TResources availableResources = ai->getFreeResources();
  187. #if NKAI_TRACE_LEVEL >= 1
  188. logAi->trace("Checking ways to upgrade army in town %s, %s", upgrader->getObjectName(), pos.toString());
  189. #endif
  190. auto paths = ai->pathfinder->getPathInfo(pos, ai->settings->isObjectGraphAllowed());
  191. auto goals = CaptureObjectsBehavior::getVisitGoals(paths, ai);
  192. std::vector<std::shared_ptr<ExecuteHeroChain>> waysToVisitObj;
  193. #if NKAI_TRACE_LEVEL >= 1
  194. logAi->trace("Found %d paths", paths.size());
  195. #endif
  196. bool hasMainAround = false;
  197. for(const AIPath & path : paths)
  198. {
  199. auto heroRole = ai->heroManager->getHeroRole(path.targetHero);
  200. if(heroRole == HeroRole::MAIN && path.turn() < ai->settings->getScoutHeroTurnDistanceLimit())
  201. hasMainAround = true;
  202. }
  203. for(int i = 0; i < paths.size(); i++)
  204. {
  205. auto & path = paths[i];
  206. auto visitGoal = goals[i];
  207. #if NKAI_TRACE_LEVEL >= 2
  208. logAi->trace("Path found %s, %s, %lld", path.toString(), path.targetHero->getObjectName(), path.heroArmy->getArmyStrength());
  209. #endif
  210. if(visitGoal->invalid())
  211. {
  212. #if NKAI_TRACE_LEVEL >= 2
  213. logAi->trace("Ignore path. Not valid way.");
  214. #endif
  215. continue;
  216. }
  217. if(upgrader->visitingHero && (upgrader->visitingHero.get() != path.targetHero || path.exchangeCount == 1))
  218. {
  219. #if NKAI_TRACE_LEVEL >= 2
  220. logAi->trace("Ignore path. Town has visiting hero.");
  221. #endif
  222. continue;
  223. }
  224. if(ai->arePathHeroesLocked(path))
  225. {
  226. #if NKAI_TRACE_LEVEL >= 2
  227. logAi->trace("Ignore path because of locked hero");
  228. #endif
  229. continue;
  230. }
  231. if(path.getFirstBlockedAction())
  232. {
  233. #if NKAI_TRACE_LEVEL >= 2
  234. // TODO: decomposition?
  235. logAi->trace("Ignore path. Action is blocked.");
  236. #endif
  237. continue;
  238. }
  239. auto heroRole = ai->heroManager->getHeroRole(path.targetHero);
  240. if(heroRole == HeroRole::SCOUT
  241. && ai->dangerHitMap->enemyCanKillOurHeroesAlongThePath(path))
  242. {
  243. #if NKAI_TRACE_LEVEL >= 2
  244. logAi->trace("Ignore path. Target hero can be killed by enemy. Our power %lld", path.heroArmy->getArmyStrength());
  245. #endif
  246. continue;
  247. }
  248. auto upgrade = ai->armyManager->calculateCreaturesUpgrade(path.heroArmy, upgrader, availableResources);
  249. if(!upgrader->garrisonHero
  250. && (
  251. hasMainAround
  252. || ai->heroManager->getHeroRole(path.targetHero) == HeroRole::MAIN))
  253. {
  254. ArmyUpgradeInfo armyToGetOrBuy;
  255. armyToGetOrBuy.addArmyToGet(
  256. ai->armyManager->getBestArmy(
  257. path.targetHero,
  258. path.heroArmy,
  259. upgrader->getUpperArmy()));
  260. armyToGetOrBuy.upgradeValue -= path.heroArmy->getArmyStrength();
  261. armyToGetOrBuy.addArmyToBuy(
  262. ai->armyManager->toSlotInfo(
  263. ai->armyManager->getArmyAvailableToBuy(
  264. path.heroArmy,
  265. upgrader,
  266. ai->getFreeResources(),
  267. path.turn())));
  268. upgrade.upgradeValue += armyToGetOrBuy.upgradeValue;
  269. upgrade.upgradeCost += armyToGetOrBuy.upgradeCost;
  270. vstd::concatenate(upgrade.resultingArmy, armyToGetOrBuy.resultingArmy);
  271. if(!upgrade.upgradeValue
  272. && armyToGetOrBuy.upgradeValue > 20000
  273. && ai->heroManager->canRecruitHero(town)
  274. && path.turn() < ai->settings->getScoutHeroTurnDistanceLimit())
  275. {
  276. for(auto hero : cb->getAvailableHeroes(town))
  277. {
  278. auto scoutReinforcement = ai->armyManager->howManyReinforcementsCanBuy(hero, town)
  279. + ai->armyManager->howManyReinforcementsCanGet(hero, town);
  280. if(scoutReinforcement >= armyToGetOrBuy.upgradeValue
  281. && ai->getFreeGold() >20000
  282. && !ai->buildAnalyzer->isGoldPreasureHigh())
  283. {
  284. Composition recruitHero;
  285. recruitHero.addNext(ArmyUpgrade(path.targetHero, town, armyToGetOrBuy)).addNext(RecruitHero(town, hero));
  286. }
  287. }
  288. }
  289. }
  290. auto armyValue = (float)upgrade.upgradeValue / path.getHeroStrength();
  291. if((armyValue < 0.25f && upgrade.upgradeValue < 40000) || upgrade.upgradeValue < 2000) // avoid small upgrades
  292. {
  293. #if NKAI_TRACE_LEVEL >= 2
  294. logAi->trace("Ignore path. Army value is too small (%f)", armyValue);
  295. #endif
  296. continue;
  297. }
  298. auto danger = path.getTotalDanger();
  299. auto isSafe = isSafeToVisit(path.targetHero, path.heroArmy, danger);
  300. #if NKAI_TRACE_LEVEL >= 2
  301. logAi->trace(
  302. "It is %s to visit %s by %s with army %lld, danger %lld and army loss %lld",
  303. isSafe ? "safe" : "not safe",
  304. upgrader->getObjectName(),
  305. path.targetHero->getObjectName(),
  306. path.getHeroStrength(),
  307. danger,
  308. path.getTotalArmyLoss());
  309. #endif
  310. if(isSafe)
  311. {
  312. tasks.push_back(sptr(Composition().addNext(ArmyUpgrade(path, upgrader, upgrade)).addNext(visitGoal)));
  313. }
  314. }
  315. return tasks;
  316. }
  317. }