ArmyManager.cpp 12 KB

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