ArmyManager.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. /*
  2. * BuildingManager.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 "ArmyManager.h"
  12. #include "../Engine/Nullkiller.h"
  13. #include "../../../CCallback.h"
  14. #include "../../../lib/mapObjects/MapObjects.h"
  15. namespace NKAI
  16. {
  17. class StackUpgradeInfo
  18. {
  19. public:
  20. CreatureID initialCreature;
  21. CreatureID upgradedCreature;
  22. TResources cost;
  23. int count;
  24. uint64_t upgradeValue;
  25. StackUpgradeInfo(CreatureID initial, CreatureID upgraded, int count)
  26. :initialCreature(initial), upgradedCreature(upgraded), count(count)
  27. {
  28. cost = (upgradedCreature.toCreature()->getFullRecruitCost() - initialCreature.toCreature()->getFullRecruitCost()) * count;
  29. upgradeValue = (upgradedCreature.toCreature()->getAIValue() - initialCreature.toCreature()->getAIValue()) * count;
  30. }
  31. };
  32. uint64_t ArmyManager::howManyReinforcementsCanGet(const CGHeroInstance * hero, const CCreatureSet * source) const
  33. {
  34. return howManyReinforcementsCanGet(hero, hero, source);
  35. }
  36. std::vector<SlotInfo> ArmyManager::getSortedSlots(const CCreatureSet * target, const CCreatureSet * source) const
  37. {
  38. const CCreatureSet * armies[] = { target, source };
  39. //we calculate total strength for each creature type available in armies
  40. std::map<const CCreature *, SlotInfo> creToPower;
  41. std::vector<SlotInfo> resultingArmy;
  42. for(auto armyPtr : armies)
  43. {
  44. for(auto & i : armyPtr->Slots())
  45. {
  46. auto cre = dynamic_cast<const CCreature*>(i.second->type);
  47. auto & slotInfp = creToPower[cre];
  48. slotInfp.creature = cre;
  49. slotInfp.power += i.second->getPower();
  50. slotInfp.count += i.second->count;
  51. }
  52. }
  53. for(auto & pair : creToPower)
  54. resultingArmy.push_back(pair.second);
  55. boost::sort(resultingArmy, [](const SlotInfo & left, const SlotInfo & right) -> bool
  56. {
  57. return left.power > right.power;
  58. });
  59. return resultingArmy;
  60. }
  61. std::vector<SlotInfo>::iterator ArmyManager::getWeakestCreature(std::vector<SlotInfo> & army) const
  62. {
  63. auto weakest = boost::min_element(army, [](const SlotInfo & left, const SlotInfo & right) -> bool
  64. {
  65. if(left.creature->getLevel() != right.creature->getLevel())
  66. return left.creature->getLevel() < right.creature->getLevel();
  67. return left.creature->Speed() > right.creature->Speed();
  68. });
  69. return weakest;
  70. }
  71. class TemporaryArmy : public CArmedInstance
  72. {
  73. public:
  74. void armyChanged() override {}
  75. TemporaryArmy()
  76. :CArmedInstance(true)
  77. {
  78. }
  79. };
  80. std::vector<SlotInfo> ArmyManager::getBestArmy(const IBonusBearer * armyCarrier, const CCreatureSet * target, const CCreatureSet * source) const
  81. {
  82. auto sortedSlots = getSortedSlots(target, source);
  83. std::map<TFaction, uint64_t> alignmentMap;
  84. for(auto & slot : sortedSlots)
  85. {
  86. alignmentMap[slot.creature->getFactionIndex()] += slot.power;
  87. }
  88. std::set<TFaction> allowedFactions;
  89. std::vector<SlotInfo> resultingArmy;
  90. uint64_t armyValue = 0;
  91. TemporaryArmy newArmyInstance;
  92. auto bonusModifiers = armyCarrier->getBonuses(Selector::type()(Bonus::MORALE));
  93. for(auto bonus : *bonusModifiers)
  94. {
  95. // army bonuses will change and object bonuses are temporary
  96. if(bonus->source != Bonus::ARMY && bonus->source != Bonus::OBJECT)
  97. {
  98. newArmyInstance.addNewBonus(std::make_shared<Bonus>(*bonus));
  99. }
  100. }
  101. while(allowedFactions.size() < alignmentMap.size())
  102. {
  103. auto strongestAlignment = vstd::maxElementByFun(alignmentMap, [&](std::pair<TFaction, uint64_t> pair) -> uint64_t
  104. {
  105. return vstd::contains(allowedFactions, pair.first) ? 0 : pair.second;
  106. });
  107. allowedFactions.insert(strongestAlignment->first);
  108. std::vector<SlotInfo> newArmy;
  109. uint64_t newValue = 0;
  110. newArmyInstance.clear();
  111. for(auto & slot : sortedSlots)
  112. {
  113. if(vstd::contains(allowedFactions, slot.creature->getFactionIndex()))
  114. {
  115. auto slotID = newArmyInstance.getSlotFor(slot.creature);
  116. if(slotID.validSlot())
  117. {
  118. newArmyInstance.setCreature(slotID, slot.creature->getId(), slot.count);
  119. newArmy.push_back(slot);
  120. }
  121. }
  122. }
  123. newArmyInstance.updateMoraleBonusFromArmy();
  124. for(auto & slot : newArmyInstance.Slots())
  125. {
  126. auto morale = slot.second->MoraleVal();
  127. auto multiplier = 1.0f;
  128. const float BadMoraleChance = 0.083f;
  129. const float HighMoraleChance = 0.04f;
  130. if(morale < 0)
  131. {
  132. multiplier += morale * BadMoraleChance;
  133. }
  134. else if(morale > 0)
  135. {
  136. multiplier += morale * HighMoraleChance;
  137. }
  138. newValue += multiplier * slot.second->getPower();
  139. }
  140. if(armyValue >= newValue)
  141. {
  142. break;
  143. }
  144. resultingArmy = newArmy;
  145. armyValue = newValue;
  146. }
  147. if(resultingArmy.size() <= GameConstants::ARMY_SIZE
  148. && allowedFactions.size() == alignmentMap.size()
  149. && source->needsLastStack())
  150. {
  151. auto weakest = getWeakestCreature(resultingArmy);
  152. if(weakest->count == 1)
  153. {
  154. assert(resultingArmy.size() > 1);
  155. resultingArmy.erase(weakest);
  156. }
  157. else
  158. {
  159. weakest->power -= weakest->power / weakest->count;
  160. weakest->count--;
  161. }
  162. }
  163. return resultingArmy;
  164. }
  165. ui64 ArmyManager::howManyReinforcementsCanBuy(const CCreatureSet * h, const CGDwelling * t) const
  166. {
  167. return howManyReinforcementsCanBuy(h, t, ai->getFreeResources());
  168. }
  169. std::shared_ptr<CCreatureSet> ArmyManager::getArmyAvailableToBuyAsCCreatureSet(
  170. const CGDwelling * dwelling,
  171. TResources availableRes) const
  172. {
  173. std::vector<creInfo> creaturesInDwellings;
  174. auto army = std::make_shared<TemporaryArmy>();
  175. for(int i = dwelling->creatures.size() - 1; i >= 0; i--)
  176. {
  177. auto ci = infoFromDC(dwelling->creatures[i]);
  178. if(!ci.count || ci.creID == -1)
  179. continue;
  180. vstd::amin(ci.count, availableRes / ci.cre->getFullRecruitCost()); //max count we can afford
  181. if(!ci.count)
  182. continue;
  183. SlotID dst = army->getFreeSlot();
  184. if(!dst.validSlot())
  185. break;
  186. army->setCreature(dst, ci.creID, ci.count);
  187. availableRes -= ci.cre->getFullRecruitCost() * ci.count;
  188. }
  189. return army;
  190. }
  191. ui64 ArmyManager::howManyReinforcementsCanBuy(
  192. const CCreatureSet * targetArmy,
  193. const CGDwelling * dwelling,
  194. const TResources & availableResources) const
  195. {
  196. ui64 aivalue = 0;
  197. auto army = getArmyAvailableToBuy(targetArmy, dwelling, availableResources);
  198. for(const creInfo & ci : army)
  199. {
  200. aivalue += ci.count * ci.cre->getAIValue();
  201. }
  202. return aivalue;
  203. }
  204. std::vector<creInfo> ArmyManager::getArmyAvailableToBuy(const CCreatureSet * hero, const CGDwelling * dwelling) const
  205. {
  206. return getArmyAvailableToBuy(hero, dwelling, ai->getFreeResources());
  207. }
  208. std::vector<creInfo> ArmyManager::getArmyAvailableToBuy(
  209. const CCreatureSet * hero,
  210. const CGDwelling * dwelling,
  211. TResources availableRes) const
  212. {
  213. std::vector<creInfo> creaturesInDwellings;
  214. int freeHeroSlots = GameConstants::ARMY_SIZE - hero->stacksCount();
  215. for(int i = dwelling->creatures.size() - 1; i >= 0; i--)
  216. {
  217. auto ci = infoFromDC(dwelling->creatures[i]);
  218. if(!ci.count || ci.creID == -1)
  219. continue;
  220. SlotID dst = hero->getSlotFor(ci.creID);
  221. if(!hero->hasStackAtSlot(dst)) //need another new slot for this stack
  222. {
  223. if(!freeHeroSlots) //no more place for stacks
  224. continue;
  225. else
  226. freeHeroSlots--; //new slot will be occupied
  227. }
  228. vstd::amin(ci.count, availableRes / ci.cre->getFullRecruitCost()); //max count we can afford
  229. if(!ci.count)
  230. continue;
  231. ci.level = i; //this is important for Dungeon Summoning Portal
  232. creaturesInDwellings.push_back(ci);
  233. availableRes -= ci.cre->getFullRecruitCost() * ci.count;
  234. }
  235. return creaturesInDwellings;
  236. }
  237. ui64 ArmyManager::howManyReinforcementsCanGet(const IBonusBearer * armyCarrier, const CCreatureSet * target, const CCreatureSet * source) const
  238. {
  239. auto bestArmy = getBestArmy(armyCarrier, target, source);
  240. uint64_t newArmy = 0;
  241. uint64_t oldArmy = target->getArmyStrength();
  242. for(auto & slot : bestArmy)
  243. {
  244. newArmy += slot.power;
  245. }
  246. return newArmy > oldArmy ? newArmy - oldArmy : 0;
  247. }
  248. uint64_t ArmyManager::evaluateStackPower(const CCreature * creature, int count) const
  249. {
  250. return creature->getAIValue() * count;
  251. }
  252. SlotInfo ArmyManager::getTotalCreaturesAvailable(CreatureID creatureID) const
  253. {
  254. auto creatureInfo = totalArmy.find(creatureID);
  255. return creatureInfo == totalArmy.end() ? SlotInfo() : creatureInfo->second;
  256. }
  257. void ArmyManager::update()
  258. {
  259. logAi->trace("Start analysing army");
  260. std::vector<const CCreatureSet *> total;
  261. auto heroes = cb->getHeroesInfo();
  262. auto towns = cb->getTownsInfo();
  263. std::copy(heroes.begin(), heroes.end(), std::back_inserter(total));
  264. std::copy(towns.begin(), towns.end(), std::back_inserter(total));
  265. totalArmy.clear();
  266. for(auto army : total)
  267. {
  268. for(auto slot : army->Slots())
  269. {
  270. totalArmy[slot.second->getCreatureID()].count += slot.second->count;
  271. }
  272. }
  273. for(auto army : totalArmy)
  274. {
  275. army.second.creature = army.first.toCreature();
  276. army.second.power = evaluateStackPower(army.second.creature, army.second.count);
  277. }
  278. }
  279. std::vector<SlotInfo> ArmyManager::convertToSlots(const CCreatureSet * army) const
  280. {
  281. std::vector<SlotInfo> result;
  282. for(auto slot : army->Slots())
  283. {
  284. SlotInfo slotInfo;
  285. slotInfo.creature = slot.second->getCreatureID().toCreature();
  286. slotInfo.count = slot.second->count;
  287. slotInfo.power = evaluateStackPower(slotInfo.creature, slotInfo.count);
  288. result.push_back(slotInfo);
  289. }
  290. return result;
  291. }
  292. std::vector<StackUpgradeInfo> ArmyManager::getHillFortUpgrades(const CCreatureSet * army) const
  293. {
  294. std::vector<StackUpgradeInfo> upgrades;
  295. for(auto creature : army->Slots())
  296. {
  297. CreatureID initial = creature.second->getCreatureID();
  298. auto possibleUpgrades = initial.toCreature()->upgrades;
  299. if(possibleUpgrades.empty())
  300. continue;
  301. CreatureID strongestUpgrade = *vstd::minElementByFun(possibleUpgrades, [](CreatureID cre) -> uint64_t
  302. {
  303. return cre.toCreature()->getAIValue();
  304. });
  305. StackUpgradeInfo upgrade = StackUpgradeInfo(initial, strongestUpgrade, creature.second->count);
  306. if(initial.toCreature()->getLevel() == 1)
  307. upgrade.cost = TResources();
  308. upgrades.push_back(upgrade);
  309. }
  310. return upgrades;
  311. }
  312. std::vector<StackUpgradeInfo> ArmyManager::getDwellingUpgrades(const CCreatureSet * army, const CGDwelling * dwelling) const
  313. {
  314. std::vector<StackUpgradeInfo> upgrades;
  315. for(auto creature : army->Slots())
  316. {
  317. CreatureID initial = creature.second->getCreatureID();
  318. auto possibleUpgrades = initial.toCreature()->upgrades;
  319. vstd::erase_if(possibleUpgrades, [&](CreatureID creID) -> bool
  320. {
  321. for(auto pair : dwelling->creatures)
  322. {
  323. if(vstd::contains(pair.second, creID))
  324. return false;
  325. }
  326. return true;
  327. });
  328. if(possibleUpgrades.empty())
  329. continue;
  330. CreatureID strongestUpgrade = *vstd::minElementByFun(possibleUpgrades, [](CreatureID cre) -> uint64_t
  331. {
  332. return cre.toCreature()->getAIValue();
  333. });
  334. StackUpgradeInfo upgrade = StackUpgradeInfo(initial, strongestUpgrade, creature.second->count);
  335. upgrades.push_back(upgrade);
  336. }
  337. return upgrades;
  338. }
  339. std::vector<StackUpgradeInfo> ArmyManager::getPossibleUpgrades(const CCreatureSet * army, const CGObjectInstance * upgrader) const
  340. {
  341. std::vector<StackUpgradeInfo> upgrades;
  342. if(upgrader->ID == Obj::HILL_FORT)
  343. {
  344. upgrades = getHillFortUpgrades(army);
  345. }
  346. else
  347. {
  348. auto dwelling = dynamic_cast<const CGDwelling *>(upgrader);
  349. if(dwelling)
  350. {
  351. upgrades = getDwellingUpgrades(army, dwelling);
  352. }
  353. }
  354. return upgrades;
  355. }
  356. ArmyUpgradeInfo ArmyManager::calculateCreaturesUpgrade(
  357. const CCreatureSet * army,
  358. const CGObjectInstance * upgrader,
  359. const TResources & availableResources) const
  360. {
  361. if(!upgrader)
  362. return ArmyUpgradeInfo();
  363. std::vector<StackUpgradeInfo> upgrades = getPossibleUpgrades(army, upgrader);
  364. vstd::erase_if(upgrades, [&](const StackUpgradeInfo & u) -> bool
  365. {
  366. return !availableResources.canAfford(u.cost);
  367. });
  368. if(upgrades.empty())
  369. return ArmyUpgradeInfo();
  370. std::sort(upgrades.begin(), upgrades.end(), [](const StackUpgradeInfo & u1, const StackUpgradeInfo & u2) -> bool
  371. {
  372. return u1.upgradeValue > u2.upgradeValue;
  373. });
  374. TResources resourcesLeft = availableResources;
  375. ArmyUpgradeInfo result;
  376. result.resultingArmy = convertToSlots(army);
  377. for(auto upgrade : upgrades)
  378. {
  379. if(resourcesLeft.canAfford(upgrade.cost))
  380. {
  381. SlotInfo upgradedArmy;
  382. upgradedArmy.creature = upgrade.upgradedCreature.toCreature();
  383. upgradedArmy.count = upgrade.count;
  384. upgradedArmy.power = evaluateStackPower(upgradedArmy.creature, upgradedArmy.count);
  385. auto slotToReplace = std::find_if(result.resultingArmy.begin(), result.resultingArmy.end(), [&](const SlotInfo & slot) -> bool {
  386. return slot.count == upgradedArmy.count && slot.creature->getId() == upgrade.initialCreature;
  387. });
  388. resourcesLeft -= upgrade.cost;
  389. result.upgradeCost += upgrade.cost;
  390. result.upgradeValue += upgrade.upgradeValue;
  391. *slotToReplace = upgradedArmy;
  392. }
  393. }
  394. return result;
  395. }
  396. }