HeroManager.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. /*
  2. * HeroManager.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 "../Engine/Nullkiller.h"
  12. #include "../../../lib/mapObjects/MapObjects.h"
  13. #include "../../../lib/IGameSettings.h"
  14. #include "../../../lib/spells/ISpellMechanics.h"
  15. #include "../../../lib/spells/adventure/TownPortalEffect.h"
  16. namespace NK2AI
  17. {
  18. const SecondarySkillEvaluator HeroManager::wariorSkillsScores = SecondarySkillEvaluator(
  19. {
  20. std::make_shared<SecondarySkillScoreMap>(
  21. std::map<SecondarySkill, float>
  22. {
  23. {SecondarySkill::DIPLOMACY, 2},
  24. {SecondarySkill::LOGISTICS, 2},
  25. {SecondarySkill::EARTH_MAGIC, 2},
  26. {SecondarySkill::ARMORER, 2},
  27. {SecondarySkill::OFFENCE, 2},
  28. {SecondarySkill::AIR_MAGIC, 1},
  29. {SecondarySkill::WISDOM, 1},
  30. {SecondarySkill::LEADERSHIP, 1},
  31. {SecondarySkill::INTELLIGENCE, 1},
  32. {SecondarySkill::RESISTANCE, 1},
  33. {SecondarySkill::MYSTICISM, -1},
  34. {SecondarySkill::SORCERY, -1},
  35. {SecondarySkill::ESTATES, -1},
  36. {SecondarySkill::FIRST_AID, -1},
  37. {SecondarySkill::LEARNING, -1},
  38. {SecondarySkill::SCHOLAR, -1},
  39. {SecondarySkill::EAGLE_EYE, -1},
  40. {SecondarySkill::NAVIGATION, -1}
  41. }),
  42. std::make_shared<ExistingSkillRule>(),
  43. std::make_shared<WisdomRule>(),
  44. std::make_shared<AtLeastOneMagicRule>()
  45. });
  46. const SecondarySkillEvaluator HeroManager::scountSkillsScores = SecondarySkillEvaluator(
  47. {
  48. std::make_shared<SecondarySkillScoreMap>(
  49. std::map<SecondarySkill, float>
  50. {
  51. {SecondarySkill::LOGISTICS, 2},
  52. {SecondarySkill::ESTATES, 2},
  53. {SecondarySkill::PATHFINDING, 1},
  54. {SecondarySkill::SCHOLAR, 1}
  55. }),
  56. std::make_shared<ExistingSkillRule>()
  57. });
  58. float HeroManager::evaluateSecSkill(SecondarySkill skill, const CGHeroInstance * hero) const
  59. {
  60. auto role = getHeroRole(hero);
  61. if(role == HeroRole::MAIN)
  62. return wariorSkillsScores.evaluateSecSkill(hero, skill);
  63. return scountSkillsScores.evaluateSecSkill(hero, skill);
  64. }
  65. float HeroManager::evaluateSpeciality(const CGHeroInstance * hero) const
  66. {
  67. auto heroSpecial = Selector::source(BonusSource::HERO_SPECIAL, BonusSourceID(hero->getHeroTypeID()));
  68. auto secondarySkillBonus = Selector::targetSourceType()(BonusSource::SECONDARY_SKILL);
  69. auto specialSecondarySkillBonuses = hero->getBonuses(heroSpecial.And(secondarySkillBonus), "HeroManager::evaluateSpeciality");
  70. auto secondarySkillBonuses = hero->getBonusesFrom(BonusSource::SECONDARY_SKILL);
  71. float specialityScore = 0.0f;
  72. for(auto bonus : *secondarySkillBonuses)
  73. {
  74. auto hasBonus = !!specialSecondarySkillBonuses->getFirst(Selector::typeSubtype(bonus->type, bonus->subtype));
  75. if(hasBonus)
  76. {
  77. SecondarySkill bonusSkill = bonus->sid.as<SecondarySkill>();
  78. float bonusScore = wariorSkillsScores.evaluateSecSkill(hero, bonusSkill);
  79. if(bonusScore > 0)
  80. specialityScore += bonusScore * bonusScore * bonusScore;
  81. }
  82. }
  83. return specialityScore;
  84. }
  85. float HeroManager::evaluateFightingStrength(const CGHeroInstance * hero) const
  86. {
  87. // TODO: Mircea: Shouldn't we count bonuses from artifacts when generating the fighting strength? That could make a huge difference
  88. return evaluateSpeciality(hero) + wariorSkillsScores.evaluateSecSkills(hero) + hero->getBasePrimarySkillValue(PrimarySkill::ATTACK) + hero->getBasePrimarySkillValue(PrimarySkill::DEFENSE) + hero->getBasePrimarySkillValue(PrimarySkill::SPELL_POWER) + hero->getBasePrimarySkillValue(PrimarySkill::KNOWLEDGE);
  89. }
  90. void HeroManager::update()
  91. {
  92. logAi->trace("Start analysing our heroes");
  93. std::map<const CGHeroInstance *, float> scores;
  94. auto myHeroes = cc->getHeroesInfo();
  95. for(auto & hero : myHeroes)
  96. {
  97. scores[hero] = evaluateFightingStrength(hero);
  98. knownFightingStrength[hero->id] = hero->getHeroStrength();
  99. }
  100. auto scoreSort = [&](const CGHeroInstance * h1, const CGHeroInstance * h2) -> bool
  101. {
  102. return scores.at(h1) > scores.at(h2);
  103. };
  104. int globalMainCount = std::min(((int)myHeroes.size() + 2) / 3, cc->getMapSize().x / 50 + 1);
  105. //vstd::amin(globalMainCount, 1 + (cb->getTownsInfo().size() / 3));
  106. if(cc->getTownsInfo().size() < 4 && globalMainCount > 2)
  107. {
  108. globalMainCount = 2;
  109. }
  110. std::sort(myHeroes.begin(), myHeroes.end(), scoreSort);
  111. heroToRoleMap.clear();
  112. for(auto hero : myHeroes)
  113. {
  114. if(hero->patrol.patrolling)
  115. {
  116. heroToRoleMap[HeroPtr(hero, aiNk->cc)] = HeroRole::MAIN;
  117. }
  118. else
  119. {
  120. heroToRoleMap[HeroPtr(hero, aiNk->cc)] = (globalMainCount--) > 0 ? HeroRole::MAIN : HeroRole::SCOUT;
  121. }
  122. }
  123. for(auto hero : myHeroes)
  124. {
  125. logAi->trace("Hero %s has role %s", hero->getNameTranslated(), heroToRoleMap[HeroPtr(hero, aiNk->cc)] == HeroRole::MAIN ? "main" : "scout");
  126. }
  127. }
  128. HeroRole HeroManager::getHeroRole(const CGHeroInstance * hero) const
  129. {
  130. return getHeroRole(HeroPtr(hero, aiNk->cc));
  131. }
  132. // TODO: Mircea: Do we need this map on HeroPtr or is enough just on hero?
  133. HeroRole HeroManager::getHeroRole(const HeroPtr & heroPtr) const
  134. {
  135. if(heroToRoleMap.find(heroPtr) != heroToRoleMap.end())
  136. return heroToRoleMap.at(heroPtr);
  137. return HeroRole::SCOUT;
  138. }
  139. const std::map<HeroPtr, HeroRole> & HeroManager::getHeroToRoleMap() const
  140. {
  141. return heroToRoleMap;
  142. }
  143. int HeroManager::selectBestSkill(const HeroPtr & heroPtr, const std::vector<SecondarySkill> & skills) const
  144. {
  145. auto role = getHeroRole(heroPtr);
  146. auto & evaluator = role == HeroRole::MAIN ? wariorSkillsScores : scountSkillsScores;
  147. int result = 0;
  148. float resultScore = -100;
  149. for(int i = 0; i < skills.size(); i++)
  150. {
  151. auto score = evaluator.evaluateSecSkill(heroPtr.get(), skills[i]);
  152. if(score > resultScore)
  153. {
  154. resultScore = score;
  155. result = i;
  156. }
  157. logAi->trace(
  158. "Hero %s is proposed to learn %d with score %f",
  159. heroPtr.nameOrDefault(),
  160. skills[i].toEnum(),
  161. score);
  162. }
  163. return result;
  164. }
  165. float HeroManager::evaluateHero(const CGHeroInstance * hero) const
  166. {
  167. return evaluateFightingStrength(hero);
  168. }
  169. bool HeroManager::heroCapReached(bool includeGarrisoned) const
  170. {
  171. int heroCount = cc->getHeroCount(aiNk->playerID, includeGarrisoned);
  172. int maxAllowed = aiNk->settings->getMaxRoamingHeroes();
  173. if (aiNk->settings->getMaxRoamingHeroesPerTown() > 0)
  174. {
  175. maxAllowed += cc->howManyTowns() * aiNk->settings->getMaxRoamingHeroesPerTown();
  176. }
  177. return heroCount >= maxAllowed
  178. || heroCount >= cc->getSettings().getInteger(EGameSettings::HEROES_PER_PLAYER_ON_MAP_CAP)
  179. || heroCount >= cc->getSettings().getInteger(EGameSettings::HEROES_PER_PLAYER_TOTAL_CAP);
  180. }
  181. float HeroManager::getFightingStrengthCached(const CGHeroInstance * hero) const
  182. {
  183. auto cached = knownFightingStrength.find(hero->id);
  184. //FIXME: fallback to hero->getFightingStrength() is VERY slow on higher difficulties (no object graph? map reveal?)
  185. return cached != knownFightingStrength.end() ? cached->second : hero->getHeroStrength();
  186. }
  187. float HeroManager::getMagicStrength(const CGHeroInstance * hero) const
  188. {
  189. auto manaLimit = hero->manaLimit();
  190. auto spellPower = hero->getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  191. auto score = 0.0f;
  192. // FIXME: this will not cover spells give by scrolls / tomes. Intended?
  193. for(auto spellId : hero->getSpellsInSpellbook())
  194. {
  195. auto spell = spellId.toSpell();
  196. if (!spell->isAdventure())
  197. continue;
  198. auto schoolLevel = hero->getSpellSchoolLevel(spell);
  199. auto townPortalEffect = spell->getAdventureMechanics().getEffectAs<TownPortalEffect>(hero);
  200. score += (spell->getLevel() + 1) * (schoolLevel + 1) * 0.05f;
  201. if (spell->getAdventureMechanics().givesBonus(hero, BonusType::FLYING_MOVEMENT))
  202. score += 0.3;
  203. if(townPortalEffect != nullptr && schoolLevel != 0)
  204. score += 0.6f;
  205. }
  206. vstd::amin(score, 1);
  207. score *= std::min(1.0f, spellPower / 10.0f);
  208. vstd::amin(score, 1);
  209. score *= std::min(1.0f, manaLimit / 100.0f);
  210. return std::min(score, 1.0f);
  211. }
  212. bool HeroManager::canRecruitHero(const CGTownInstance * town) const
  213. {
  214. if(!town)
  215. town = findTownWithTavern();
  216. if(!town || !townHasFreeTavern(town))
  217. return false;
  218. if(cc->getResourceAmount(EGameResID::GOLD) < GameConstants::HERO_GOLD_COST)
  219. return false;
  220. if(heroCapReached())
  221. return false;
  222. if(!cc->getAvailableHeroes(town).size())
  223. return false;
  224. return true;
  225. }
  226. const CGTownInstance * HeroManager::findTownWithTavern() const
  227. {
  228. for(const CGTownInstance * t : cc->getTownsInfo())
  229. if(townHasFreeTavern(t))
  230. return t;
  231. return nullptr;
  232. }
  233. const CGHeroInstance * HeroManager::findHeroWithGrail() const
  234. {
  235. for(const CGHeroInstance * h : cc->getHeroesInfo())
  236. {
  237. if(h->hasArt(ArtifactID::GRAIL))
  238. return h;
  239. }
  240. return nullptr;
  241. }
  242. const CGHeroInstance * HeroManager::findWeakHeroToDismiss(uint64_t armyLimit, const CGTownInstance* townToSpare) const
  243. {
  244. const CGHeroInstance * weakestHero = nullptr;
  245. auto myHeroes = aiNk->cc->getHeroesInfo();
  246. for(auto existingHero : myHeroes)
  247. {
  248. if(aiNk->getHeroLockedReason(existingHero) == HeroLockedReason::DEFENCE
  249. || existingHero->getArmyStrength() >armyLimit
  250. || getHeroRole(existingHero) == HeroRole::MAIN
  251. || existingHero->movementPointsRemaining()
  252. || (townToSpare != nullptr && existingHero->getVisitedTown() == townToSpare)
  253. || existingHero->artifactsWorn.size() > (existingHero->hasSpellbook() ? 2 : 1))
  254. {
  255. continue;
  256. }
  257. if(!weakestHero || weakestHero->getHeroStrength() > existingHero->getHeroStrength())
  258. {
  259. weakestHero = existingHero;
  260. }
  261. }
  262. return weakestHero;
  263. }
  264. SecondarySkillScoreMap::SecondarySkillScoreMap(std::map<SecondarySkill, float> scoreMap)
  265. :scoreMap(scoreMap)
  266. {
  267. }
  268. void SecondarySkillScoreMap::evaluateScore(const CGHeroInstance * hero, SecondarySkill skill, float & score) const
  269. {
  270. auto it = scoreMap.find(skill);
  271. if(it != scoreMap.end())
  272. {
  273. score = it->second;
  274. }
  275. }
  276. void ExistingSkillRule::evaluateScore(const CGHeroInstance * hero, SecondarySkill skill, float & score) const
  277. {
  278. int upgradesLeft = 0;
  279. for(auto & heroSkill : hero->secSkills)
  280. {
  281. if(heroSkill.first == skill)
  282. return;
  283. upgradesLeft += MasteryLevel::EXPERT - heroSkill.second;
  284. }
  285. if(score >= 2 || (score >= 1 && upgradesLeft <= 1))
  286. score += 1.5;
  287. }
  288. void WisdomRule::evaluateScore(const CGHeroInstance * hero, SecondarySkill skill, float & score) const
  289. {
  290. if(skill != SecondarySkill::WISDOM)
  291. return;
  292. auto wisdomLevel = hero->getSecSkillLevel(SecondarySkill::WISDOM);
  293. if(hero->level > 10 && wisdomLevel == MasteryLevel::NONE)
  294. score += 1.5;
  295. }
  296. const std::vector<SecondarySkill> AtLeastOneMagicRule::magicSchools = {
  297. SecondarySkill::AIR_MAGIC,
  298. SecondarySkill::EARTH_MAGIC,
  299. SecondarySkill::FIRE_MAGIC,
  300. SecondarySkill::WATER_MAGIC
  301. };
  302. void AtLeastOneMagicRule::evaluateScore(const CGHeroInstance * hero, SecondarySkill skill, float & score) const
  303. {
  304. if(!vstd::contains(magicSchools, skill))
  305. return;
  306. bool heroHasAnyMagic = vstd::contains_if(magicSchools, [&](SecondarySkill skill) -> bool
  307. {
  308. return hero->getSecSkillLevel(skill) > MasteryLevel::NONE;
  309. });
  310. if(!heroHasAnyMagic)
  311. score += 1;
  312. }
  313. SecondarySkillEvaluator::SecondarySkillEvaluator(std::vector<std::shared_ptr<ISecondarySkillRule>> evaluationRules)
  314. : evaluationRules(evaluationRules)
  315. {
  316. }
  317. float SecondarySkillEvaluator::evaluateSecSkills(const CGHeroInstance * hero) const
  318. {
  319. float totalScore = 0;
  320. for(auto skill : hero->secSkills)
  321. {
  322. totalScore += skill.second * evaluateSecSkill(hero, skill.first);
  323. }
  324. return totalScore;
  325. }
  326. float SecondarySkillEvaluator::evaluateSecSkill(const CGHeroInstance * hero, SecondarySkill skill) const
  327. {
  328. float score = 0;
  329. for(auto rule : evaluationRules)
  330. rule->evaluateScore(hero, skill, score);
  331. return score;
  332. }
  333. }