GatherArmyBehavior.cpp 9.6 KB

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