ArmyManager.cpp 14 KB

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