ArmyManager.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  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<FactionID, uint64_t> alignmentMap;
  84. for(auto & slot : sortedSlots)
  85. {
  86. alignmentMap[slot.creature->getFaction()] += slot.power;
  87. }
  88. std::set<FactionID> allowedFactions;
  89. std::vector<SlotInfo> resultingArmy;
  90. uint64_t armyValue = 0;
  91. TemporaryArmy newArmyInstance;
  92. auto bonusModifiers = armyCarrier->getBonuses(Selector::type()(BonusType::MORALE));
  93. for(auto bonus : *bonusModifiers)
  94. {
  95. // army bonuses will change and object bonuses are temporary
  96. if(bonus->source != BonusSource::ARMY && bonus->source != BonusSource::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<FactionID, 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->getFaction()))
  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,
  195. uint8_t turn) const
  196. {
  197. ui64 aivalue = 0;
  198. auto army = getArmyAvailableToBuy(targetArmy, dwelling, availableResources);
  199. for(const creInfo & ci : army)
  200. {
  201. aivalue += ci.count * ci.cre->getAIValue();
  202. }
  203. return aivalue;
  204. }
  205. std::vector<creInfo> ArmyManager::getArmyAvailableToBuy(const CCreatureSet * hero, const CGDwelling * dwelling) const
  206. {
  207. return getArmyAvailableToBuy(hero, dwelling, ai->getFreeResources());
  208. }
  209. std::vector<creInfo> ArmyManager::getArmyAvailableToBuy(
  210. const CCreatureSet * hero,
  211. const CGDwelling * dwelling,
  212. TResources availableRes,
  213. uint8_t turn) const
  214. {
  215. std::vector<creInfo> creaturesInDwellings;
  216. int freeHeroSlots = GameConstants::ARMY_SIZE - hero->stacksCount();
  217. bool countGrowth = (cb->getDate(Date::DAY_OF_WEEK) + turn) > 7;
  218. const CGTownInstance * town = dwelling->ID == CGTownInstance::TOWN
  219. ? dynamic_cast<const CGTownInstance *>(dwelling)
  220. : nullptr;
  221. for(int i = dwelling->creatures.size() - 1; i >= 0; i--)
  222. {
  223. auto ci = infoFromDC(dwelling->creatures[i]);
  224. if(ci.creID == -1) continue;
  225. if(i < GameConstants::CREATURES_PER_TOWN && countGrowth)
  226. {
  227. ci.count += town ? town->creatureGrowth(i) : ci.cre->getGrowth();
  228. }
  229. if(!ci.count) continue;
  230. SlotID dst = hero->getSlotFor(ci.creID);
  231. if(!hero->hasStackAtSlot(dst)) //need another new slot for this stack
  232. {
  233. if(!freeHeroSlots) //no more place for stacks
  234. continue;
  235. else
  236. freeHeroSlots--; //new slot will be occupied
  237. }
  238. vstd::amin(ci.count, availableRes / ci.cre->getFullRecruitCost()); //max count we can afford
  239. if(!ci.count) continue;
  240. ci.level = i; //this is important for Dungeon Summoning Portal
  241. creaturesInDwellings.push_back(ci);
  242. availableRes -= ci.cre->getFullRecruitCost() * ci.count;
  243. }
  244. return creaturesInDwellings;
  245. }
  246. ui64 ArmyManager::howManyReinforcementsCanGet(const IBonusBearer * armyCarrier, const CCreatureSet * target, const CCreatureSet * source) const
  247. {
  248. auto bestArmy = getBestArmy(armyCarrier, target, source);
  249. uint64_t newArmy = 0;
  250. uint64_t oldArmy = target->getArmyStrength();
  251. for(auto & slot : bestArmy)
  252. {
  253. newArmy += slot.power;
  254. }
  255. return newArmy > oldArmy ? newArmy - oldArmy : 0;
  256. }
  257. uint64_t ArmyManager::evaluateStackPower(const CCreature * creature, int count) const
  258. {
  259. return creature->getAIValue() * count;
  260. }
  261. SlotInfo ArmyManager::getTotalCreaturesAvailable(CreatureID creatureID) const
  262. {
  263. auto creatureInfo = totalArmy.find(creatureID);
  264. return creatureInfo == totalArmy.end() ? SlotInfo() : creatureInfo->second;
  265. }
  266. void ArmyManager::update()
  267. {
  268. logAi->trace("Start analysing army");
  269. std::vector<const CCreatureSet *> total;
  270. auto heroes = cb->getHeroesInfo();
  271. auto towns = cb->getTownsInfo();
  272. std::copy(heroes.begin(), heroes.end(), std::back_inserter(total));
  273. std::copy(towns.begin(), towns.end(), std::back_inserter(total));
  274. totalArmy.clear();
  275. for(auto army : total)
  276. {
  277. for(auto slot : army->Slots())
  278. {
  279. totalArmy[slot.second->getCreatureID()].count += slot.second->count;
  280. }
  281. }
  282. for(auto army : totalArmy)
  283. {
  284. army.second.creature = army.first.toCreature();
  285. army.second.power = evaluateStackPower(army.second.creature, army.second.count);
  286. }
  287. }
  288. std::vector<SlotInfo> ArmyManager::convertToSlots(const CCreatureSet * army) const
  289. {
  290. std::vector<SlotInfo> result;
  291. for(auto slot : army->Slots())
  292. {
  293. SlotInfo slotInfo;
  294. slotInfo.creature = slot.second->getCreatureID().toCreature();
  295. slotInfo.count = slot.second->count;
  296. slotInfo.power = evaluateStackPower(slotInfo.creature, slotInfo.count);
  297. result.push_back(slotInfo);
  298. }
  299. return result;
  300. }
  301. std::vector<StackUpgradeInfo> ArmyManager::getHillFortUpgrades(const CCreatureSet * army) const
  302. {
  303. std::vector<StackUpgradeInfo> upgrades;
  304. for(auto creature : army->Slots())
  305. {
  306. CreatureID initial = creature.second->getCreatureID();
  307. auto possibleUpgrades = initial.toCreature()->upgrades;
  308. if(possibleUpgrades.empty())
  309. continue;
  310. CreatureID strongestUpgrade = *vstd::minElementByFun(possibleUpgrades, [](CreatureID cre) -> uint64_t
  311. {
  312. return cre.toCreature()->getAIValue();
  313. });
  314. StackUpgradeInfo upgrade = StackUpgradeInfo(initial, strongestUpgrade, creature.second->count);
  315. if(initial.toCreature()->getLevel() == 1)
  316. upgrade.cost = TResources();
  317. upgrades.push_back(upgrade);
  318. }
  319. return upgrades;
  320. }
  321. std::vector<StackUpgradeInfo> ArmyManager::getDwellingUpgrades(const CCreatureSet * army, const CGDwelling * dwelling) const
  322. {
  323. std::vector<StackUpgradeInfo> upgrades;
  324. for(auto creature : army->Slots())
  325. {
  326. CreatureID initial = creature.second->getCreatureID();
  327. auto possibleUpgrades = initial.toCreature()->upgrades;
  328. vstd::erase_if(possibleUpgrades, [&](CreatureID creID) -> bool
  329. {
  330. for(auto pair : dwelling->creatures)
  331. {
  332. if(vstd::contains(pair.second, creID))
  333. return false;
  334. }
  335. return true;
  336. });
  337. if(possibleUpgrades.empty())
  338. continue;
  339. CreatureID strongestUpgrade = *vstd::minElementByFun(possibleUpgrades, [](CreatureID cre) -> uint64_t
  340. {
  341. return cre.toCreature()->getAIValue();
  342. });
  343. StackUpgradeInfo upgrade = StackUpgradeInfo(initial, strongestUpgrade, creature.second->count);
  344. upgrades.push_back(upgrade);
  345. }
  346. return upgrades;
  347. }
  348. std::vector<StackUpgradeInfo> ArmyManager::getPossibleUpgrades(const CCreatureSet * army, const CGObjectInstance * upgrader) const
  349. {
  350. std::vector<StackUpgradeInfo> upgrades;
  351. if(upgrader->ID == Obj::HILL_FORT)
  352. {
  353. upgrades = getHillFortUpgrades(army);
  354. }
  355. else
  356. {
  357. auto dwelling = dynamic_cast<const CGDwelling *>(upgrader);
  358. if(dwelling)
  359. {
  360. upgrades = getDwellingUpgrades(army, dwelling);
  361. }
  362. }
  363. return upgrades;
  364. }
  365. ArmyUpgradeInfo ArmyManager::calculateCreaturesUpgrade(
  366. const CCreatureSet * army,
  367. const CGObjectInstance * upgrader,
  368. const TResources & availableResources) const
  369. {
  370. if(!upgrader)
  371. return ArmyUpgradeInfo();
  372. std::vector<StackUpgradeInfo> upgrades = getPossibleUpgrades(army, upgrader);
  373. vstd::erase_if(upgrades, [&](const StackUpgradeInfo & u) -> bool
  374. {
  375. return !availableResources.canAfford(u.cost);
  376. });
  377. if(upgrades.empty())
  378. return ArmyUpgradeInfo();
  379. std::sort(upgrades.begin(), upgrades.end(), [](const StackUpgradeInfo & u1, const StackUpgradeInfo & u2) -> bool
  380. {
  381. return u1.upgradeValue > u2.upgradeValue;
  382. });
  383. TResources resourcesLeft = availableResources;
  384. ArmyUpgradeInfo result;
  385. result.resultingArmy = convertToSlots(army);
  386. for(auto upgrade : upgrades)
  387. {
  388. if(resourcesLeft.canAfford(upgrade.cost))
  389. {
  390. SlotInfo upgradedArmy;
  391. upgradedArmy.creature = upgrade.upgradedCreature.toCreature();
  392. upgradedArmy.count = upgrade.count;
  393. upgradedArmy.power = evaluateStackPower(upgradedArmy.creature, upgradedArmy.count);
  394. auto slotToReplace = std::find_if(result.resultingArmy.begin(), result.resultingArmy.end(), [&](const SlotInfo & slot) -> bool {
  395. return slot.count == upgradedArmy.count && slot.creature->getId() == upgrade.initialCreature;
  396. });
  397. resourcesLeft -= upgrade.cost;
  398. result.upgradeCost += upgrade.cost;
  399. result.upgradeValue += upgrade.upgradeValue;
  400. *slotToReplace = upgradedArmy;
  401. }
  402. }
  403. return result;
  404. }
  405. }