HeroManager.cpp 11 KB

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