CGHeroInstance.cpp 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844
  1. /*
  2. * CGHeroInstance.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 "CGHeroInstance.h"
  12. #include <vcmi/ServerCallback.h>
  13. #include <vcmi/spells/Spell.h>
  14. #include <vstd/RNG.h>
  15. #include "../callback/IGameInfoCallback.h"
  16. #include "../callback/IGameEventCallback.h"
  17. #include "../callback/IGameRandomizer.h"
  18. #include "../texts/CGeneralTextHandler.h"
  19. #include "../TerrainHandler.h"
  20. #include "../RoadHandler.h"
  21. #include "../IGameSettings.h"
  22. #include "../CSoundBase.h"
  23. #include "../spells/CSpellHandler.h"
  24. #include "../CSkillHandler.h"
  25. #include "../gameState/CGameState.h"
  26. #include "../gameState/UpgradeInfo.h"
  27. #include "../CCreatureHandler.h"
  28. #include "../mapping/CMap.h"
  29. #include "../StartInfo.h"
  30. #include "CGTownInstance.h"
  31. #include "../entities/artifact/ArtifactUtils.h"
  32. #include "../entities/artifact/CArtifact.h"
  33. #include "../entities/faction/CTownHandler.h"
  34. #include "../entities/hero/CHeroHandler.h"
  35. #include "../entities/hero/CHeroClass.h"
  36. #include "../battle/CBattleInfoEssentials.h"
  37. #include "../campaign/CampaignState.h"
  38. #include "../json/JsonBonus.h"
  39. #include "../pathfinder/TurnInfo.h"
  40. #include "../serializer/JsonSerializeFormat.h"
  41. #include "../mapObjectConstructors/AObjectTypeHandler.h"
  42. #include "../mapObjectConstructors/CObjectClassesHandler.h"
  43. #include "../mapObjects/MiscObjects.h"
  44. #include "../modding/ModScope.h"
  45. #include "../networkPacks/PacksForClient.h"
  46. #include "../networkPacks/PacksForClientBattle.h"
  47. #include "../constants/StringConstants.h"
  48. #include "../battle/Unit.h"
  49. #include "CConfigHandler.h"
  50. VCMI_LIB_NAMESPACE_BEGIN
  51. const ui32 CGHeroInstance::NO_PATROLLING = std::numeric_limits<ui32>::max();
  52. void CGHeroPlaceholder::serializeJsonOptions(JsonSerializeFormat & handler)
  53. {
  54. serializeJsonOwner(handler);
  55. bool isHeroType = heroType.has_value();
  56. handler.serializeBool("placeholderType", isHeroType, false);
  57. if(!handler.saving)
  58. {
  59. if(isHeroType)
  60. heroType = HeroTypeID::NONE;
  61. else
  62. powerRank = 0;
  63. }
  64. if(isHeroType)
  65. handler.serializeId("heroType", heroType.value(), HeroTypeID::NONE);
  66. else
  67. handler.serializeInt("powerRank", powerRank.value());
  68. }
  69. FactionID CGHeroInstance::getFactionID() const
  70. {
  71. return getHeroClass()->faction;
  72. }
  73. const IBonusBearer* CGHeroInstance::getBonusBearer() const
  74. {
  75. return this;
  76. }
  77. TerrainId CGHeroInstance::getNativeTerrain() const
  78. {
  79. // NOTE: in H3 neutral stacks will ignore terrain penalty only if placed as topmost stack(s) in hero army.
  80. // This is clearly bug in H3 however intended behaviour is not clear.
  81. // Current VCMI behaviour will ignore neutrals in calculations so army in VCMI
  82. // will always have best penalty without any influence from player-defined stacks order
  83. // and army that consist solely from neutral will always be considered to be on native terrain
  84. TerrainId nativeTerrain = ETerrainId::ANY_TERRAIN;
  85. for(const auto & stack : stacks)
  86. {
  87. TerrainId stackNativeTerrain = stack.second->getNativeTerrain(); //consider terrain bonuses e.g. Lodestar.
  88. if(stackNativeTerrain == ETerrainId::NONE)
  89. continue;
  90. if(nativeTerrain == ETerrainId::ANY_TERRAIN)
  91. nativeTerrain = stackNativeTerrain;
  92. else if(nativeTerrain != stackNativeTerrain)
  93. return ETerrainId::NONE;
  94. }
  95. return nativeTerrain;
  96. }
  97. bool CGHeroInstance::isCoastVisitable() const
  98. {
  99. return true;
  100. }
  101. bool CGHeroInstance::isBlockedVisitable() const
  102. {
  103. return true;
  104. }
  105. BattleField CGHeroInstance::getBattlefield() const
  106. {
  107. return BattleField::NONE;
  108. }
  109. ui8 CGHeroInstance::getSecSkillLevel(const SecondarySkill & skill) const
  110. {
  111. for(const auto & elem : secSkills)
  112. if(elem.first == skill)
  113. return elem.second;
  114. return 0;
  115. }
  116. void CGHeroInstance::setSecSkillLevel(const SecondarySkill & which, int val, ChangeValueMode mode)
  117. {
  118. int currentLevel = getSecSkillLevel(which);
  119. int newLevel = mode == ChangeValueMode::ABSOLUTE ? val : currentLevel + val;
  120. int newLevelClamped = std::clamp<int>(newLevel, MasteryLevel::NONE, MasteryLevel::EXPERT);
  121. if (currentLevel == newLevelClamped)
  122. return; // no change
  123. if (newLevelClamped == 0) // skill removal
  124. {
  125. vstd::erase_if(secSkills, [which](const std::pair<SecondarySkill, ui8>& pair) { return pair.first == which; });
  126. }
  127. else if(currentLevel == 0) // gained new skill
  128. {
  129. secSkills.emplace_back(which, newLevelClamped);
  130. }
  131. else
  132. {
  133. for (auto & elem : secSkills)
  134. {
  135. if(elem.first == which)
  136. elem.second = newLevelClamped;
  137. }
  138. }
  139. updateSkillBonus(which, newLevelClamped);
  140. }
  141. int3 CGHeroInstance::convertToVisitablePos(const int3 & position) const
  142. {
  143. return position - getVisitableOffset();
  144. }
  145. int3 CGHeroInstance::convertFromVisitablePos(const int3 & position) const
  146. {
  147. return position + getVisitableOffset();
  148. }
  149. bool CGHeroInstance::canLearnSkill() const
  150. {
  151. return secSkills.size() < GameConstants::SKILL_PER_HERO;
  152. }
  153. bool CGHeroInstance::canLearnSkill(const SecondarySkill & which) const
  154. {
  155. if ( !canLearnSkill())
  156. return false;
  157. if (!cb->isAllowed(which))
  158. return false;
  159. if (getSecSkillLevel(which) > 0)
  160. return false;
  161. if (getHeroClass()->secSkillProbability.count(which) == 0)
  162. return false;
  163. if (getHeroClass()->secSkillProbability.at(which) == 0)
  164. return false;
  165. return true;
  166. }
  167. int CGHeroInstance::movementPointsRemaining() const
  168. {
  169. return movement;
  170. }
  171. void CGHeroInstance::setMovementPoints(int points)
  172. {
  173. if(getBonusBearer()->hasBonusOfType(BonusType::UNLIMITED_MOVEMENT))
  174. movement = 1000000;
  175. else
  176. movement = std::max(0, points);
  177. }
  178. int CGHeroInstance::movementPointsLimit(bool onLand) const
  179. {
  180. auto ti = getTurnInfo(0);
  181. return onLand ? ti->getMovePointsLimitLand() : ti->getMovePointsLimitWater();
  182. }
  183. int CGHeroInstance::getLowestCreatureSpeed() const
  184. {
  185. if(stacksCount() != 0)
  186. {
  187. int minimalSpeed = std::numeric_limits<int>::max();
  188. //TODO? should speed modifiers (eg from artifacts) affect hero movement?
  189. for(const auto & slot : Slots())
  190. minimalSpeed = std::min(minimalSpeed, slot.second->getInitiative());
  191. return minimalSpeed;
  192. }
  193. else
  194. {
  195. if(commander && commander->alive)
  196. return commander->getInitiative();
  197. }
  198. return 10;
  199. }
  200. std::unique_ptr<TurnInfo> CGHeroInstance::getTurnInfo(int days) const
  201. {
  202. return std::make_unique<TurnInfo>(turnInfoCache.get(), this, days);
  203. }
  204. int CGHeroInstance::movementPointsLimitCached(bool onLand, const TurnInfo * ti) const
  205. {
  206. if (onLand)
  207. return ti->getMovePointsLimitLand();
  208. else
  209. return ti->getMovePointsLimitWater();
  210. }
  211. CGHeroInstance::CGHeroInstance(IGameInfoCallback * cb)
  212. : CArmedInstance(cb),
  213. CArtifactSet(cb),
  214. tacticFormationEnabled(false),
  215. inTownGarrison(false),
  216. moveDir(4),
  217. mana(UNINITIALIZED_MANA),
  218. movement(UNINITIALIZED_MOVEMENT),
  219. level(1),
  220. exp(UNINITIALIZED_EXPERIENCE),
  221. gender(EHeroGender::DEFAULT),
  222. primarySkills(this),
  223. magicSchoolMastery(this),
  224. turnInfoCache(std::make_unique<TurnInfoCache>(this)),
  225. manaPerKnowledgeCached(this, Selector::type()(BonusType::MANA_PER_KNOWLEDGE_PERCENTAGE))
  226. {
  227. setNodeType(HERO);
  228. ID = Obj::HERO;
  229. secSkills.emplace_back(SecondarySkill::NONE, -1);
  230. }
  231. PlayerColor CGHeroInstance::getOwner() const
  232. {
  233. return tempOwner;
  234. }
  235. const CHeroClass * CGHeroInstance::getHeroClass() const
  236. {
  237. return getHeroType()->heroClass;
  238. }
  239. HeroClassID CGHeroInstance::getHeroClassID() const
  240. {
  241. auto heroType = getHeroTypeID();
  242. if (heroType.hasValue())
  243. return getHeroType()->heroClass->getId();
  244. else
  245. return HeroClassID();
  246. }
  247. const CHero * CGHeroInstance::getHeroType() const
  248. {
  249. return getHeroTypeID().toHeroType();
  250. }
  251. HeroTypeID CGHeroInstance::getHeroTypeID() const
  252. {
  253. if (ID == Obj::RANDOM_HERO)
  254. return HeroTypeID::NONE;
  255. return HeroTypeID(getObjTypeIndex().getNum());
  256. }
  257. void CGHeroInstance::setHeroType(HeroTypeID heroType)
  258. {
  259. subID = heroType;
  260. }
  261. bool CGHeroInstance::isGarrisoned() const
  262. {
  263. return inTownGarrison;
  264. }
  265. const CGTownInstance * CGHeroInstance::getVisitedTown() const
  266. {
  267. if (!visitedTown.hasValue())
  268. return nullptr;
  269. return cb->getTown(visitedTown);
  270. }
  271. CGTownInstance * CGHeroInstance::getVisitedTown()
  272. {
  273. if (!visitedTown.hasValue())
  274. return nullptr;
  275. return dynamic_cast<CGTownInstance*>(cb->gameState().getObjInstance(visitedTown));
  276. }
  277. void CGHeroInstance::setVisitedTown(const CGTownInstance * town, bool garrisoned)
  278. {
  279. if (town)
  280. visitedTown = town->id;
  281. else
  282. visitedTown = {};
  283. inTownGarrison = garrisoned;
  284. }
  285. const CCommanderInstance * CGHeroInstance::getCommander() const
  286. {
  287. return commander.get();
  288. }
  289. CCommanderInstance * CGHeroInstance::getCommander()
  290. {
  291. return commander.get();
  292. }
  293. void CGHeroInstance::initObj(IGameRandomizer & gameRandomizer)
  294. {
  295. if (ID == Obj::HERO)
  296. updateAppearance();
  297. }
  298. void CGHeroInstance::initHero(IGameRandomizer & gameRandomizer, const HeroTypeID & SUBID)
  299. {
  300. subID = SUBID.getNum();
  301. initHero(gameRandomizer);
  302. }
  303. TObjectTypeHandler CGHeroInstance::getObjectHandler() const
  304. {
  305. if (ID == Obj::HERO)
  306. return LIBRARY->objtypeh->getHandlerFor(ID, getHeroClass()->getIndex());
  307. else // prison or random hero
  308. return LIBRARY->objtypeh->getHandlerFor(ID, 0);
  309. }
  310. void CGHeroInstance::updateAppearance()
  311. {
  312. auto handler = LIBRARY->objtypeh->getHandlerFor(Obj::HERO, getHeroClass()->getIndex());
  313. auto terrain = cb->getTile(visitablePos())->getTerrainID();
  314. auto app = handler->getOverride(terrain, this);
  315. if (app)
  316. appearance = app;
  317. }
  318. void CGHeroInstance::initHero(IGameRandomizer & gameRandomizer)
  319. {
  320. assert(validTypes(true));
  321. if (gender == EHeroGender::DEFAULT)
  322. gender = getHeroType()->gender;
  323. if (ID == Obj::HERO)
  324. {
  325. auto handler = LIBRARY->objtypeh->getHandlerFor(Obj::HERO, getHeroClass()->getIndex());
  326. appearance = handler->getTemplates().front();
  327. }
  328. if(!vstd::contains(spells, SpellID::PRESET))
  329. {
  330. // hero starts with default spells
  331. for(const auto & spellID : getHeroType()->spells)
  332. spells.insert(spellID);
  333. }
  334. else //remove placeholder
  335. spells -= SpellID::PRESET;
  336. if(!vstd::contains(spells, SpellID::SPELLBOOK_PRESET))
  337. {
  338. // hero starts with default spellbook presence status
  339. if(!getArt(ArtifactPosition::SPELLBOOK) && getHeroType()->haveSpellBook)
  340. {
  341. auto artifact = cb->gameState().createArtifact(ArtifactID::SPELLBOOK);
  342. putArtifact(ArtifactPosition::SPELLBOOK, artifact);
  343. }
  344. }
  345. else
  346. spells -= SpellID::SPELLBOOK_PRESET;
  347. if(!getArt(ArtifactPosition::MACH4))
  348. {
  349. auto artifact = cb->gameState().createArtifact(ArtifactID::CATAPULT);
  350. putArtifact(ArtifactPosition::MACH4, artifact); //everyone has a catapult
  351. }
  352. if(!hasBonusFrom(BonusSource::HERO_BASE_SKILL))
  353. {
  354. for(int g=0; g<GameConstants::PRIMARY_SKILLS; ++g)
  355. {
  356. pushPrimSkill(static_cast<PrimarySkill>(g), getHeroClass()->primarySkillInitial[g]);
  357. }
  358. }
  359. if(secSkills.size() == 1 && secSkills[0] == std::pair<SecondarySkill,ui8>(SecondarySkill::NONE, -1)) //set secondary skills to default
  360. secSkills = getHeroType()->secSkillsInit;
  361. setFormation(EArmyFormation::LOOSE);
  362. if (!stacksCount()) //standard army//initial army
  363. {
  364. initArmy(gameRandomizer.getDefault());
  365. }
  366. assert(validTypes());
  367. if (patrol.patrolling)
  368. patrol.initialPos = visitablePos();
  369. if(exp == UNINITIALIZED_EXPERIENCE)
  370. {
  371. initExp(gameRandomizer.getDefault());
  372. }
  373. else
  374. {
  375. levelUpAutomatically(gameRandomizer);
  376. }
  377. // load base hero bonuses, TODO: per-map loading of base hero bonuses
  378. // must be done separately from global bonuses since recruitable heroes in taverns
  379. // are not attached to global bonus node but need access to some global bonuses
  380. // e.g. MANA_PER_KNOWLEDGE_PERCENTAGE for correct preview and initial state after recruit for(const auto & ob : LIBRARY->modh->heroBaseBonuses)
  381. // or MOVEMENT to compute initial movement before recruiting is finished
  382. const JsonNode & baseBonuses = cb->getSettings().getValue(EGameSettings::BONUSES_PER_HERO);
  383. for(const auto & b : baseBonuses.Struct())
  384. {
  385. auto bonus = JsonUtils::parseBonus(b.second);
  386. bonus->source = BonusSource::HERO_BASE_SKILL;
  387. bonus->sid = BonusSourceID(id);
  388. bonus->duration = BonusDuration::PERMANENT;
  389. addNewBonus(bonus);
  390. }
  391. if (cb->getSettings().getBoolean(EGameSettings::MODULE_COMMANDERS) && !commander && getHeroClass()->commander.hasValue())
  392. {
  393. commander = std::make_unique<CCommanderInstance>(cb, getHeroClass()->commander);
  394. commander->setArmy(getArmy()); //TODO: separate function for setting commanders
  395. commander->giveTotalStackExperience(exp); //after our exp is set
  396. }
  397. //copy active (probably growing) bonuses from hero prototype to hero object
  398. for(const std::shared_ptr<Bonus> & b : getHeroType()->specialty)
  399. addNewBonus(b);
  400. //initialize bonuses
  401. recreateSecondarySkillsBonuses();
  402. movement = movementPointsLimit(true);
  403. mana = manaLimit(); //after all bonuses are taken into account, make sure this line is the last one
  404. }
  405. void CGHeroInstance::initArmy(vstd::RNG & rand, IArmyDescriptor * dst)
  406. {
  407. if(!dst)
  408. dst = this;
  409. int warMachinesGiven = 0;
  410. auto stacksCountChances = cb->getSettings().getVector(EGameSettings::HEROES_STARTING_STACKS_CHANCES);
  411. int stacksCountInitRandomNumber = rand.nextInt(1, 100);
  412. size_t maxStacksCount = std::min(stacksCountChances.size(), getHeroType()->initialArmy.size());
  413. for(int stackNo=0; stackNo < maxStacksCount; stackNo++)
  414. {
  415. if (stacksCountInitRandomNumber > stacksCountChances[stackNo])
  416. continue;
  417. auto & stack = getHeroType()->initialArmy[stackNo];
  418. int count = rand.nextInt(stack.minAmount, stack.maxAmount);
  419. if(stack.creature == CreatureID::NONE)
  420. {
  421. logGlobal->error("Hero %s has invalid creature in initial army", getNameTranslated());
  422. continue;
  423. }
  424. const CCreature * creature = stack.creature.toCreature();
  425. if(creature->warMachine != ArtifactID::NONE) //war machine
  426. {
  427. warMachinesGiven++;
  428. if(dst != this)
  429. continue;
  430. ArtifactID aid = creature->warMachine;
  431. const CArtifact * art = aid.toArtifact();
  432. if(art != nullptr && !art->getPossibleSlots().at(ArtBearer::HERO).empty())
  433. {
  434. //TODO: should we try another possible slots?
  435. ArtifactPosition slot = art->getPossibleSlots().at(ArtBearer::HERO).front();
  436. if(!getArt(slot))
  437. {
  438. auto artifact = cb->gameState().createArtifact(aid);
  439. putArtifact(slot, artifact);
  440. }
  441. else
  442. logGlobal->warn("Hero %s already has artifact at %d, omitting giving artifact %d", getNameTranslated(), slot.toEnum(), aid.toEnum());
  443. }
  444. else
  445. {
  446. logGlobal->error("Hero %s has invalid war machine in initial army", getNameTranslated());
  447. }
  448. }
  449. else
  450. {
  451. dst->setCreature(SlotID(stackNo-warMachinesGiven), stack.creature, count);
  452. }
  453. }
  454. }
  455. CGHeroInstance::~CGHeroInstance() = default;
  456. bool CGHeroInstance::needsLastStack() const
  457. {
  458. return true;
  459. }
  460. void CGHeroInstance::onHeroVisit(IGameEventCallback & gameEvents, const CGHeroInstance * h) const
  461. {
  462. if(h == this) return; //exclude potential self-visiting
  463. if (ID == Obj::HERO)
  464. {
  465. if( cb->getPlayerRelations(tempOwner, h->tempOwner) != PlayerRelations::ENEMIES)
  466. {
  467. //exchange
  468. gameEvents.heroExchange(h->id, id);
  469. }
  470. else //battle
  471. {
  472. if(getVisitedTown()) //we're in town
  473. getVisitedTown()->onHeroVisit(gameEvents, h); //town will handle attacking
  474. else
  475. gameEvents.startBattle(h, this);
  476. }
  477. }
  478. else if(ID == Obj::PRISON)
  479. {
  480. if (cb->getHeroCount(h->tempOwner, false) < cb->getSettings().getInteger(EGameSettings::HEROES_PER_PLAYER_ON_MAP_CAP))//free hero slot
  481. {
  482. //update hero parameters
  483. SetMovePoints smp;
  484. smp.hid = id;
  485. gameEvents.setManaPoints(id, manaLimit());
  486. ObjectInstanceID boatId;
  487. const auto boatPos = visitablePos();
  488. if (cb->getTile(boatPos)->isWater())
  489. {
  490. smp.val = movementPointsLimit(false);
  491. if (!inBoat())
  492. {
  493. //Create a new boat for hero
  494. gameEvents.createBoat(boatPos, getBoatType(), h->getOwner());
  495. boatId = cb->getTopObj(boatPos)->id;
  496. }
  497. }
  498. else
  499. {
  500. smp.val = movementPointsLimit(true);
  501. }
  502. gameEvents.giveHero(id, h->tempOwner, boatId); //recreates def and adds hero to player
  503. gameEvents.setObjPropertyID(id, ObjProperty::ID, Obj(Obj::HERO)); //set ID to 34 AFTER hero gets correct flag color
  504. gameEvents.setMovePoints (&smp);
  505. h->showInfoDialog(gameEvents, 102);
  506. }
  507. else //already 8 wandering heroes
  508. {
  509. h->showInfoDialog(gameEvents, 103);
  510. }
  511. }
  512. }
  513. std::string CGHeroInstance::getObjectName() const
  514. {
  515. if(ID != Obj::PRISON)
  516. {
  517. std::string hoverName = LIBRARY->generaltexth->allTexts[15];
  518. boost::algorithm::replace_first(hoverName,"%s",getNameTranslated());
  519. boost::algorithm::replace_first(hoverName,"%s", getClassNameTranslated());
  520. return hoverName;
  521. }
  522. else
  523. return LIBRARY->objtypeh->getObjectName(ID, 0);
  524. }
  525. std::string CGHeroInstance::getHoverText(PlayerColor player) const
  526. {
  527. std::string hoverText = CArmedInstance::getHoverText(player) + getMovementPointsTextIfOwner(player);
  528. return hoverText;
  529. }
  530. std::string CGHeroInstance::getMovementPointsTextIfOwner(PlayerColor player) const
  531. {
  532. std::string output = "";
  533. if(player == getOwner())
  534. {
  535. output += " " + LIBRARY->generaltexth->translate("vcmi.adventureMap.movementPointsHeroInfo");
  536. boost::replace_first(output, "%POINTS", std::to_string(movementPointsLimit(!inBoat())));
  537. boost::replace_first(output, "%REMAINING", std::to_string(movementPointsRemaining()));
  538. }
  539. return output;
  540. }
  541. ui8 CGHeroInstance::maxlevelsToMagicSchool() const
  542. {
  543. return getHeroClass()->isMagicHero() ? 3 : 4;
  544. }
  545. ui8 CGHeroInstance::maxlevelsToWisdom() const
  546. {
  547. return getHeroClass()->isMagicHero() ? 3 : 6;
  548. }
  549. void CGHeroInstance::pickRandomObject(IGameRandomizer & gameRandomizer)
  550. {
  551. assert(ID == Obj::HERO || ID == Obj::PRISON || ID == Obj::RANDOM_HERO);
  552. if (ID == Obj::RANDOM_HERO)
  553. {
  554. auto selectedHero = cb->gameState().pickNextHeroType(gameRandomizer.getDefault(), getOwner());
  555. ID = Obj::HERO;
  556. subID = selectedHero;
  557. randomizeArmy(getHeroClass()->faction);
  558. }
  559. auto oldSubID = subID;
  560. // to find object handler we must use heroClass->id
  561. // after setType subID used to store unique hero identify id. Check issue 2277 for details
  562. // exclude prisons which should use appearance as set in map, via map editor or RMG
  563. if (ID != Obj::PRISON)
  564. setType(ID, getHeroClass()->getIndex());
  565. this->subID = oldSubID;
  566. }
  567. void CGHeroInstance::recreateSecondarySkillsBonuses()
  568. {
  569. auto secondarySkillsBonuses = getBonusesFrom(BonusSource::SECONDARY_SKILL);
  570. for(const auto & bonus : *secondarySkillsBonuses)
  571. removeBonus(bonus);
  572. for(const auto & skill_info : secSkills)
  573. if(skill_info.second > 0)
  574. updateSkillBonus(SecondarySkill(skill_info.first), skill_info.second);
  575. }
  576. void CGHeroInstance::updateSkillBonus(const SecondarySkill & which, int val)
  577. {
  578. removeBonuses(Selector::source(BonusSource::SECONDARY_SKILL, BonusSourceID(which)));
  579. if(val > 0)
  580. {
  581. auto skillBonus = (*LIBRARY->skillh)[which]->at(val).effects;
  582. for(const auto& b : skillBonus)
  583. addNewBonus(std::make_shared<Bonus>(*b));
  584. }
  585. }
  586. void CGHeroInstance::setPropertyDer(ObjProperty what, ObjPropertyID identifier)
  587. {
  588. if(what == ObjProperty::PRIMARY_STACK_COUNT)
  589. setStackCount(SlotID(0), identifier.getNum());
  590. }
  591. int CGHeroInstance::getPrimSkillLevel(PrimarySkill id) const
  592. {
  593. return primarySkills.getSkill(id);
  594. }
  595. double CGHeroInstance::getFightingStrength() const
  596. {
  597. const auto & skillValues = primarySkills.getSkills();
  598. return sqrt((1.0 + 0.05*skillValues[PrimarySkill::ATTACK.getNum()]) * (1.0 + 0.05*skillValues[PrimarySkill::DEFENSE.getNum()]));
  599. }
  600. double CGHeroInstance::getMagicStrength() const
  601. {
  602. const auto & skillValues = primarySkills.getSkills();
  603. if (!hasSpellbook())
  604. return 1;
  605. bool atLeastOneCombatSpell = false;
  606. for (auto spell : spells)
  607. {
  608. if (spell.toSpell()->isCombat())
  609. {
  610. atLeastOneCombatSpell = true;
  611. break;
  612. }
  613. }
  614. if (!atLeastOneCombatSpell)
  615. return 1;
  616. return sqrt((1.0 + 0.05*skillValues[PrimarySkill::KNOWLEDGE.getNum()] * mana / manaLimit()) * (1.0 + 0.05*skillValues[PrimarySkill::SPELL_POWER.getNum()] * mana / manaLimit()));
  617. }
  618. double CGHeroInstance::getHeroStrength() const
  619. {
  620. return getFightingStrength() * getMagicStrength();
  621. }
  622. uint64_t CGHeroInstance::getValueForDiplomacy() const
  623. {
  624. // H3 formula for hero strength when considering diplomacy skill
  625. uint64_t armyStrength = getArmyStrength();
  626. double heroStrength = sqrt(
  627. (1.0 + 0.05 * getPrimSkillLevel(PrimarySkill::ATTACK)) *
  628. (1.0 + 0.05 * getPrimSkillLevel(PrimarySkill::DEFENSE))
  629. );
  630. return heroStrength * armyStrength;
  631. }
  632. uint32_t CGHeroInstance::getValueForCampaign() const
  633. {
  634. // Determined by testing H3: hero is preferred for transfer in campaigns if total sum of his primary skills and his secondary skill levels is greatest
  635. // Additional info from wiki: https://heroes.thelazy.net/index.php/Power_rating
  636. uint32_t score = level;
  637. score += getPrimSkillLevel(PrimarySkill::ATTACK);
  638. score += getPrimSkillLevel(PrimarySkill::DEFENSE);
  639. score += getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  640. score += getPrimSkillLevel(PrimarySkill::DEFENSE);
  641. return score;
  642. }
  643. ui64 CGHeroInstance::getTotalStrength() const
  644. {
  645. double ret = getHeroStrength() * getArmyStrength();
  646. return static_cast<ui64>(ret);
  647. }
  648. TExpType CGHeroInstance::calculateXp(TExpType exp) const
  649. {
  650. return static_cast<TExpType>(exp * (valOfBonuses(BonusType::HERO_EXPERIENCE_GAIN_PERCENT)) / 100.0);
  651. }
  652. int32_t CGHeroInstance::getCasterUnitId() const
  653. {
  654. return id.getNum();
  655. }
  656. int32_t CGHeroInstance::getSpellSchoolLevel(const spells::Spell * spell, SpellSchool * outSelectedSchool) const
  657. {
  658. int32_t skill = -1; //skill level
  659. spell->forEachSchool([&, this](const SpellSchool & cnf, bool & stop)
  660. {
  661. int32_t thisSchool = magicSchoolMastery.getMastery(cnf); //FIXME: Bonus shouldn't be additive (Witchking Artifacts : Crown of Skies)
  662. if(thisSchool > skill)
  663. {
  664. skill = thisSchool;
  665. if(outSelectedSchool)
  666. *outSelectedSchool = cnf;
  667. }
  668. });
  669. vstd::amax(skill, magicSchoolMastery.getMastery(SpellSchool::ANY)); //any school bonus
  670. vstd::amax(skill, valOfBonuses(BonusType::SPELL, BonusSubtypeID(spell->getId()))); //given by artifact or other effect
  671. vstd::amax(skill, 0); //in case we don't know any school
  672. vstd::amin(skill, 3);
  673. return skill;
  674. }
  675. int64_t CGHeroInstance::getSpellBonus(const spells::Spell * spell, int64_t base, const battle::Unit * affectedStack) const
  676. {
  677. //applying sorcery secondary skill
  678. if(spell->isMagical())
  679. base = static_cast<int64_t>(base * (valOfBonuses(BonusType::SPELL_DAMAGE, BonusSubtypeID(SpellSchool::ANY))) / 100.0);
  680. base = static_cast<int64_t>(base * (100 + valOfBonuses(BonusType::SPECIFIC_SPELL_DAMAGE, BonusSubtypeID(spell->getId()))) / 100.0);
  681. int maxSchoolBonus = 0;
  682. spell->forEachSchool([&maxSchoolBonus, this](const SpellSchool & cnf, bool & stop)
  683. {
  684. vstd::amax(maxSchoolBonus, valOfBonuses(BonusType::SPELL_DAMAGE, BonusSubtypeID(cnf)));
  685. });
  686. base = static_cast<int64_t>(base * (100 + maxSchoolBonus) / 100.0);
  687. if(affectedStack && affectedStack->creatureLevel() > 0) //Hero specials like Solmyr, Deemer
  688. base = static_cast<int64_t>(base * static_cast<double>(100 + valOfBonuses(BonusType::SPECIAL_SPELL_LEV, BonusSubtypeID(spell->getId())) / affectedStack->creatureLevel()) / 100.0);
  689. return base;
  690. }
  691. int64_t CGHeroInstance::getSpecificSpellBonus(const spells::Spell * spell, int64_t base) const
  692. {
  693. base = static_cast<int64_t>(base * (100 + valOfBonuses(BonusType::SPECIFIC_SPELL_DAMAGE, BonusSubtypeID(spell->getId()))) / 100.0);
  694. return base;
  695. }
  696. int32_t CGHeroInstance::getEffectLevel(const spells::Spell * spell) const
  697. {
  698. return getSpellSchoolLevel(spell);
  699. }
  700. int32_t CGHeroInstance::getEffectPower(const spells::Spell * spell) const
  701. {
  702. return getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  703. }
  704. int32_t CGHeroInstance::getEnchantPower(const spells::Spell * spell) const
  705. {
  706. int32_t spellpower = getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  707. int32_t durationCommon = valOfBonuses(BonusType::SPELL_DURATION, BonusSubtypeID());
  708. int32_t durationSpecific = valOfBonuses(BonusType::SPELL_DURATION, BonusSubtypeID(spell->getId()));
  709. return spellpower + durationCommon + durationSpecific;
  710. }
  711. int64_t CGHeroInstance::getEffectValue(const spells::Spell * spell) const
  712. {
  713. return 0;
  714. }
  715. PlayerColor CGHeroInstance::getCasterOwner() const
  716. {
  717. return tempOwner;
  718. }
  719. void CGHeroInstance::getCasterName(MetaString & text) const
  720. {
  721. //FIXME: use local name, MetaString need access to gamestate as hero name is part of map object
  722. text.replaceRawString(getNameTranslated());
  723. }
  724. void CGHeroInstance::getCastDescription(const spells::Spell * spell, const battle::Units & attacked, MetaString & text) const
  725. {
  726. const bool singleTarget = attacked.size() == 1;
  727. const int textIndex = singleTarget ? 195 : 196;
  728. text.appendLocalString(EMetaText::GENERAL_TXT, textIndex);
  729. getCasterName(text);
  730. text.replaceName(spell->getId());
  731. if(singleTarget)
  732. attacked.at(0)->addNameReplacement(text, true);
  733. }
  734. const CGHeroInstance * CGHeroInstance::getHeroCaster() const
  735. {
  736. return this;
  737. }
  738. void CGHeroInstance::spendMana(ServerCallback * server, const int spellCost) const
  739. {
  740. if(spellCost != 0)
  741. {
  742. SetMana sm;
  743. sm.mode = ChangeValueMode::RELATIVE;
  744. sm.hid = id;
  745. sm.val = -spellCost;
  746. server->apply(sm);
  747. }
  748. }
  749. bool CGHeroInstance::canCastThisSpell(const spells::Spell * spell) const
  750. {
  751. const bool isAllowed = cb->isAllowed(spell->getId());
  752. const bool inSpellBook = vstd::contains(spells, spell->getId()) && hasSpellbook();
  753. const bool specificBonus = hasBonusOfType(BonusType::SPELL, BonusSubtypeID(spell->getId()));
  754. bool schoolBonus = false;
  755. spell->forEachSchool([this, &schoolBonus](const SpellSchool & cnf, bool & stop)
  756. {
  757. if(hasBonusOfType(BonusType::SPELLS_OF_SCHOOL, BonusSubtypeID(cnf)))
  758. {
  759. schoolBonus = stop = true;
  760. }
  761. });
  762. const bool levelBonus = hasBonusOfType(BonusType::SPELLS_OF_LEVEL, BonusCustomSubtype::spellLevel(spell->getLevel()));
  763. if(spell->isSpecial())
  764. {
  765. if(inSpellBook)
  766. {//hero has this spell in spellbook
  767. logGlobal->error("Special spell %s in spellbook.", spell->getNameTranslated());
  768. }
  769. return specificBonus;
  770. }
  771. else if(!isAllowed)
  772. {
  773. if(inSpellBook)
  774. {
  775. //hero has this spell in spellbook
  776. //it is normal if set in map editor, but trace it to possible debug of magic guild
  777. logGlobal->trace("Banned spell %s in spellbook.", spell->getNameTranslated());
  778. }
  779. return inSpellBook || specificBonus || schoolBonus || levelBonus;
  780. }
  781. else
  782. {
  783. return inSpellBook || schoolBonus || specificBonus || levelBonus;
  784. }
  785. }
  786. bool CGHeroInstance::canLearnSpell(const spells::Spell * spell, bool allowBanned) const
  787. {
  788. if(!hasSpellbook())
  789. return false;
  790. if(spell->getLevel() > maxSpellLevel()) //not enough wisdom
  791. return false;
  792. if(vstd::contains(spells, spell->getId()))//already known
  793. return false;
  794. if(spell->isSpecial())
  795. {
  796. logGlobal->warn("Hero %s try to learn special spell %s", nodeName(), spell->getNameTranslated());
  797. return false;//special spells can not be learned
  798. }
  799. if(spell->isCreatureAbility())
  800. {
  801. logGlobal->warn("Hero %s try to learn creature spell %s", nodeName(), spell->getNameTranslated());
  802. return false;//creature abilities can not be learned
  803. }
  804. if(!allowBanned && !cb->isAllowed(spell->getId()))
  805. {
  806. logGlobal->warn("Hero %s try to learn banned spell %s", nodeName(), spell->getNameTranslated());
  807. return false;//banned spells should not be learned
  808. }
  809. return true;
  810. }
  811. /**
  812. * Calculates what creatures and how many to be raised from a battle.
  813. * @param battleResult The results of the battle.
  814. * @return Returns a pair with the first value indicating the ID of the creature
  815. * type and second value the amount. Both values are returned as -1 if necromancy
  816. * could not be applied.
  817. */
  818. CStackBasicDescriptor CGHeroInstance::calculateNecromancy (const BattleResult &battleResult) const
  819. {
  820. TConstBonusListPtr improvedNecromancy = getBonusesOfType(BonusType::IMPROVED_NECROMANCY);
  821. // need skill or cloak of undead king - lesser artifacts don't work without skill
  822. if (improvedNecromancy->empty())
  823. return CStackBasicDescriptor();
  824. int raisedUnitsPercentage = std::clamp(valOfBonuses(BonusType::UNDEAD_RAISE_PERCENTAGE), 0, 100);
  825. if (raisedUnitsPercentage == 0)
  826. return CStackBasicDescriptor();
  827. const std::map<CreatureID,si32> &casualties = battleResult.casualties[CBattleInfoEssentials::otherSide(battleResult.winner)];
  828. if(casualties.empty())
  829. return CStackBasicDescriptor();
  830. // figure out what to raise - pick strongest creature meeting requirements
  831. CreatureID bestCreature = CreatureID::NONE;
  832. int necromancerPower = improvedNecromancy->totalValue();
  833. // pick best bonus available
  834. for(const std::shared_ptr<Bonus> & newPick : *improvedNecromancy)
  835. {
  836. // addInfo[0] = required necromancy skill
  837. if(newPick->additionalInfo[0] > necromancerPower)
  838. continue;
  839. CreatureID newCreature = newPick->subtype.as<CreatureID>();;
  840. if(!bestCreature.hasValue())
  841. {
  842. bestCreature = newCreature;
  843. }
  844. else
  845. {
  846. auto quality = [](CreatureID pick) -> std::tuple<int, int>
  847. {
  848. const auto * c = pick.toCreature();
  849. return std::tuple<int, int> {c->getLevel(), static_cast<int>(c->getFullRecruitCost().marketValue())};
  850. };
  851. if(quality(bestCreature) < quality(newCreature))
  852. bestCreature = newCreature;
  853. }
  854. }
  855. assert(bestCreature != CreatureID::NONE);
  856. CreatureID selectedCreature = bestCreature;
  857. // raise upgraded creature (at 2/3 rate) if no space available otherwise
  858. if(getSlotFor(selectedCreature) == SlotID())
  859. {
  860. for (const auto & slot : Slots())
  861. {
  862. if (selectedCreature.toCreature()->isMyDirectOrIndirectUpgrade(slot.second->getCreature()))
  863. {
  864. selectedCreature = slot.second->getCreatureID();
  865. break;
  866. }
  867. }
  868. }
  869. // calculate number of creatures raised - low level units contribute at 50% rate
  870. const double raisedUnitHealth = selectedCreature.toCreature()->getMaxHealth();
  871. double raisedUnits = 0;
  872. for(const auto & casualty : casualties)
  873. {
  874. const CCreature * c = casualty.first.toCreature();
  875. double raisedFromCasualty = std::min(c->getMaxHealth() / raisedUnitHealth, 1.0) * casualty.second * raisedUnitsPercentage;
  876. if (bestCreature != selectedCreature)
  877. raisedUnits += raisedFromCasualty * 2 / 3 / 100;
  878. else
  879. raisedUnits += raisedFromCasualty / 100;
  880. }
  881. return CStackBasicDescriptor(selectedCreature, std::max(static_cast<int>(raisedUnits), 1));
  882. }
  883. int CGHeroInstance::getSightRadius() const
  884. {
  885. int baseValue = LIBRARY->engineSettings()->getInteger(EGameSettings::HEROES_BASE_SCOUNTING_RANGE);
  886. return applyBonuses(BonusType::SIGHT_RADIUS, baseValue);
  887. }
  888. si32 CGHeroInstance::manaRegain() const
  889. {
  890. int percentageRegeneration = valOfBonuses(BonusType::MANA_PERCENTAGE_REGENERATION);
  891. int regeneratedByPercentage = manaLimit() * percentageRegeneration / 100;
  892. int regeneratedByValue = valOfBonuses(BonusType::MANA_REGENERATION);
  893. return std::max(regeneratedByValue, regeneratedByPercentage);
  894. }
  895. si32 CGHeroInstance::getManaNewTurn() const
  896. {
  897. if(getVisitedTown() && getVisitedTown()->hasBuilt(BuildingID::MAGES_GUILD_1))
  898. {
  899. //if hero starts turn in town with mage guild - restore all mana
  900. return std::max(mana, manaLimit());
  901. }
  902. si32 res = mana + manaRegain();
  903. res = std::min(res, manaLimit());
  904. res = std::max(res, mana);
  905. res = std::max(res, 0);
  906. return res;
  907. }
  908. // /**
  909. // * Places an artifact in hero's backpack. If it's a big artifact equips it
  910. // * or discards it if it cannot be equipped.
  911. // */
  912. // void CGHeroInstance::giveArtifact (ui32 aid) //use only for fixed artifacts
  913. // {
  914. // CArtifact * const artifact = LIBRARY->arth->objects[aid]; //pointer to constant object
  915. // CArtifactInstance *ai = CArtifactInstance::createNewArtifactInstance(artifact);
  916. // ai->putAt(this, ai->firstAvailableSlot(this));
  917. // }
  918. BoatId CGHeroInstance::getBoatType() const
  919. {
  920. return BoatId(LIBRARY->townh->getById(getHeroClass()->faction)->getBoatType());
  921. }
  922. void CGHeroInstance::getOutOffsets(std::vector<int3> &offsets) const
  923. {
  924. offsets = {
  925. {0, -1, 0},
  926. {+1, -1, 0},
  927. {+1, 0, 0},
  928. {+1, +1, 0},
  929. {0, +1, 0},
  930. {-1, +1, 0},
  931. {-1, 0, 0},
  932. {-1, -1, 0},
  933. };
  934. }
  935. const IObjectInterface * CGHeroInstance::getObject() const
  936. {
  937. return this;
  938. }
  939. int32_t CGHeroInstance::getSpellCost(const spells::Spell * sp) const
  940. {
  941. return sp->getCost(getSpellSchoolLevel(sp));
  942. }
  943. void CGHeroInstance::pushPrimSkill( PrimarySkill which, int val )
  944. {
  945. auto sel = Selector::typeSubtype(BonusType::PRIMARY_SKILL, BonusSubtypeID(which))
  946. .And(Selector::sourceType()(BonusSource::HERO_BASE_SKILL));
  947. removeBonuses(sel);
  948. addNewBonus(std::make_shared<Bonus>(BonusDuration::PERMANENT, BonusType::PRIMARY_SKILL, BonusSource::HERO_BASE_SKILL, val, BonusSourceID(id), BonusSubtypeID(which)));
  949. }
  950. EAlignment CGHeroInstance::getAlignment() const
  951. {
  952. return getHeroClass()->getAlignment();
  953. }
  954. void CGHeroInstance::initExp(vstd::RNG & rand)
  955. {
  956. exp = rand.nextInt(40, 89);
  957. }
  958. std::string CGHeroInstance::nodeName() const
  959. {
  960. return "Hero " + getNameTextID();
  961. }
  962. si32 CGHeroInstance::manaLimit() const
  963. {
  964. return getPrimSkillLevel(PrimarySkill::KNOWLEDGE) * manaPerKnowledgeCached.getValue() / 100;
  965. }
  966. HeroTypeID CGHeroInstance::getPortraitSource() const
  967. {
  968. if (customPortraitSource.isValid())
  969. return customPortraitSource;
  970. else
  971. return getHeroTypeID();
  972. }
  973. int32_t CGHeroInstance::getIconIndex() const
  974. {
  975. return getPortraitSource().toEntity(LIBRARY)->getIconIndex();
  976. }
  977. std::string CGHeroInstance::getNameTranslated() const
  978. {
  979. return LIBRARY->generaltexth->translate(getNameTextID());
  980. }
  981. std::string CGHeroInstance::getClassNameTranslated() const
  982. {
  983. return LIBRARY->generaltexth->translate(getClassNameTextID());
  984. }
  985. std::string CGHeroInstance::getClassNameTextID() const
  986. {
  987. if (isCampaignGem())
  988. return "core.genrltxt.735";
  989. return getHeroClass()->getNameTextID();
  990. }
  991. std::string CGHeroInstance::getNameTextID() const
  992. {
  993. if (!nameCustomTextId.empty())
  994. return nameCustomTextId;
  995. if (getHeroTypeID().hasValue())
  996. return getHeroType()->getNameTextID();
  997. // FIXME: called by logging from some specialties (mods?) before type is set on deserialization
  998. // assert(0);
  999. return "";
  1000. }
  1001. std::string CGHeroInstance::getBiographyTranslated() const
  1002. {
  1003. return LIBRARY->generaltexth->translate(getBiographyTextID());
  1004. }
  1005. std::string CGHeroInstance::getBiographyTextID() const
  1006. {
  1007. if (!biographyCustomTextId.empty())
  1008. return biographyCustomTextId;
  1009. if (getHeroTypeID().hasValue())
  1010. return getHeroType()->getBiographyTextID();
  1011. return ""; //for random hero
  1012. }
  1013. CGHeroInstance::ArtPlacementMap CGHeroInstance::putArtifact(const ArtifactPosition & pos, const CArtifactInstance * art)
  1014. {
  1015. assert(art->canBePutAt(this, pos));
  1016. if(ArtifactUtils::isSlotEquipment(pos))
  1017. attachToSource(*art);
  1018. return CArtifactSet::putArtifact(pos, art);
  1019. }
  1020. void CGHeroInstance::removeArtifact(const ArtifactPosition & pos)
  1021. {
  1022. auto art = getArt(pos);
  1023. assert(art);
  1024. CArtifactSet::removeArtifact(pos);
  1025. if(ArtifactUtils::isSlotEquipment(pos))
  1026. detachFromSource(*art);
  1027. }
  1028. bool CGHeroInstance::hasSpellbook() const
  1029. {
  1030. return getArt(ArtifactPosition::SPELLBOOK);
  1031. }
  1032. void CGHeroInstance::addSpellToSpellbook(const SpellID & spell)
  1033. {
  1034. spells.insert(spell);
  1035. }
  1036. void CGHeroInstance::removeSpellFromSpellbook(const SpellID & spell)
  1037. {
  1038. spells.erase(spell);
  1039. }
  1040. bool CGHeroInstance::spellbookContainsSpell(const SpellID & spell) const
  1041. {
  1042. return vstd::contains(spells, spell);
  1043. }
  1044. void CGHeroInstance::removeSpellbook()
  1045. {
  1046. spells.clear();
  1047. if(hasSpellbook())
  1048. {
  1049. cb->gameState().getMap().removeArtifactInstance(*this, ArtifactPosition::SPELLBOOK);
  1050. }
  1051. }
  1052. const std::set<SpellID> & CGHeroInstance::getSpellsInSpellbook() const
  1053. {
  1054. return spells;
  1055. }
  1056. int CGHeroInstance::maxSpellLevel() const
  1057. {
  1058. return std::min(GameConstants::SPELL_LEVELS, valOfBonuses(BonusType::MAX_LEARNABLE_SPELL_LEVEL));
  1059. }
  1060. bool CGHeroInstance::inBoat() const
  1061. {
  1062. return boardedBoat.hasValue();
  1063. }
  1064. const CGBoat * CGHeroInstance::getBoat() const
  1065. {
  1066. if (boardedBoat.hasValue())
  1067. return dynamic_cast<const CGBoat*>(cb->getObjInstance(boardedBoat));
  1068. return nullptr;
  1069. }
  1070. CGBoat * CGHeroInstance::getBoat()
  1071. {
  1072. if (boardedBoat.hasValue())
  1073. return dynamic_cast<CGBoat*>(cb->gameState().getObjInstance(boardedBoat));
  1074. return nullptr;
  1075. }
  1076. void CGHeroInstance::setBoat(CGBoat* newBoat)
  1077. {
  1078. if (newBoat)
  1079. {
  1080. boardedBoat = newBoat->id;
  1081. attachTo(*newBoat);
  1082. newBoat->setBoardedHero(this);
  1083. }
  1084. else if (boardedBoat.hasValue())
  1085. {
  1086. auto oldBoat = getBoat();
  1087. boardedBoat = {};
  1088. detachFrom(*oldBoat);
  1089. oldBoat->setBoardedHero(nullptr);
  1090. }
  1091. }
  1092. void CGHeroInstance::restoreBonusSystem(CGameState & gs)
  1093. {
  1094. CArmedInstance::restoreBonusSystem(gs);
  1095. artDeserializationFix(gs, this);
  1096. if (commander)
  1097. commander->artDeserializationFix(gs, this->commander.get());
  1098. if (boardedBoat.hasValue())
  1099. {
  1100. auto boat = gs.getObjInstance(boardedBoat);
  1101. if (boat)
  1102. attachTo(dynamic_cast<CGBoat&>(*boat));
  1103. }
  1104. }
  1105. void CGHeroInstance::attachToBonusSystem(CGameState & gs)
  1106. {
  1107. CArmedInstance::attachToBonusSystem(gs);
  1108. if (boardedBoat.hasValue())
  1109. {
  1110. auto boat = gs.getObjInstance(boardedBoat);
  1111. if (boat)
  1112. attachTo(dynamic_cast<CGBoat&>(*boat));
  1113. }
  1114. }
  1115. void CGHeroInstance::detachFromBonusSystem(CGameState & gs)
  1116. {
  1117. CArmedInstance::detachFromBonusSystem(gs);
  1118. if (boardedBoat.hasValue())
  1119. {
  1120. auto boat = gs.getObjInstance(boardedBoat);
  1121. if (boat)
  1122. detachFrom(dynamic_cast<CGBoat&>(*boat));
  1123. }
  1124. }
  1125. CBonusSystemNode * CGHeroInstance::whereShouldBeAttachedOnSiege(const bool isBattleOutsideTown) const
  1126. {
  1127. if(!getVisitedTown())
  1128. return nullptr;
  1129. if (isBattleOutsideTown)
  1130. return const_cast<CTownAndVisitingHero *>(&getVisitedTown()->townAndVis);
  1131. return const_cast<CGTownInstance*>(getVisitedTown());
  1132. }
  1133. CBonusSystemNode * CGHeroInstance::whereShouldBeAttachedOnSiege(CGameState & gs)
  1134. {
  1135. if(getVisitedTown())
  1136. return whereShouldBeAttachedOnSiege(getVisitedTown()->isBattleOutsideTown(this));
  1137. return &CArmedInstance::whereShouldBeAttached(gs);
  1138. }
  1139. CBonusSystemNode & CGHeroInstance::whereShouldBeAttached(CGameState & gs)
  1140. {
  1141. if(visitedTown.hasValue())
  1142. {
  1143. auto town = gs.getTown(visitedTown);
  1144. if(isGarrisoned())
  1145. return *town;
  1146. else
  1147. return town->townAndVis;
  1148. }
  1149. else
  1150. return CArmedInstance::whereShouldBeAttached(gs);
  1151. }
  1152. int CGHeroInstance::movementPointsAfterEmbark(int MPsBefore, int basicCost, bool disembark, const TurnInfo * ti) const
  1153. {
  1154. if(!ti->hasFreeShipBoarding())
  1155. return 0; // take all MPs by default
  1156. auto boatLayer = inBoat() ? getBoat()->layer : EPathfindingLayer::SAIL;
  1157. int mp1 = ti->getMaxMovePoints(disembark ? EPathfindingLayer::LAND : boatLayer);
  1158. int mp2 = ti->getMaxMovePoints(disembark ? boatLayer : EPathfindingLayer::LAND);
  1159. int ret = static_cast<int>((MPsBefore - basicCost) * static_cast<double>(mp1) / mp2);
  1160. return ret;
  1161. }
  1162. EDiggingStatus CGHeroInstance::diggingStatus() const
  1163. {
  1164. if(static_cast<int>(movement) < movementPointsLimit(true))
  1165. return EDiggingStatus::LACK_OF_MOVEMENT;
  1166. if(!ArtifactID(ArtifactID::GRAIL).toArtifact()->canBePutAt(this))
  1167. return EDiggingStatus::BACKPACK_IS_FULL;
  1168. return cb->getTileDigStatus(visitablePos());
  1169. }
  1170. ArtBearer CGHeroInstance::bearerType() const
  1171. {
  1172. return ArtBearer::HERO;
  1173. }
  1174. std::vector<SecondarySkill> CGHeroInstance::getLevelupSkillCandidates(IGameRandomizer & gameRandomizer) const
  1175. {
  1176. std::set<SecondarySkill> basicAndAdv;
  1177. std::set<SecondarySkill> none;
  1178. std::vector<SecondarySkill> skills;
  1179. if (canLearnSkill())
  1180. {
  1181. for(int i = 0; i < LIBRARY->skillh->size(); i++)
  1182. if (canLearnSkill(SecondarySkill(i)))
  1183. none.insert(SecondarySkill(i));
  1184. }
  1185. for(const auto & elem : secSkills)
  1186. {
  1187. if(elem.second < MasteryLevel::EXPERT)
  1188. basicAndAdv.insert(elem.first);
  1189. none.erase(elem.first);
  1190. }
  1191. if (!basicAndAdv.empty())
  1192. {
  1193. skills.push_back(gameRandomizer.rollSecondarySkillForLevelup(this, basicAndAdv));
  1194. basicAndAdv.erase(skills.back());
  1195. }
  1196. if (!none.empty())
  1197. {
  1198. skills.push_back(gameRandomizer.rollSecondarySkillForLevelup(this, none));
  1199. none.erase(skills.back());
  1200. }
  1201. if (!basicAndAdv.empty() && skills.size() < 2)
  1202. {
  1203. skills.push_back(gameRandomizer.rollSecondarySkillForLevelup(this, basicAndAdv));
  1204. basicAndAdv.erase(skills.back());
  1205. }
  1206. if (!none.empty() && skills.size() < 2)
  1207. {
  1208. skills.push_back(gameRandomizer.rollSecondarySkillForLevelup(this, none));
  1209. none.erase(skills.back());
  1210. }
  1211. return skills;
  1212. }
  1213. void CGHeroInstance::setPrimarySkill(PrimarySkill primarySkill, si64 value, ChangeValueMode mode)
  1214. {
  1215. auto skill = getLocalBonus(Selector::type()(BonusType::PRIMARY_SKILL)
  1216. .And(Selector::subtype()(BonusSubtypeID(primarySkill)))
  1217. .And(Selector::sourceType()(BonusSource::HERO_BASE_SKILL)));
  1218. assert(skill);
  1219. if(mode == ChangeValueMode::ABSOLUTE)
  1220. {
  1221. skill->val = static_cast<si32>(value);
  1222. }
  1223. else
  1224. {
  1225. skill->val += static_cast<si32>(value);
  1226. }
  1227. nodeHasChanged();
  1228. }
  1229. void CGHeroInstance::setExperience(si64 value, ChangeValueMode mode)
  1230. {
  1231. if(mode == ChangeValueMode::ABSOLUTE)
  1232. {
  1233. exp = value;
  1234. }
  1235. else
  1236. {
  1237. exp += value;
  1238. }
  1239. }
  1240. bool CGHeroInstance::gainsLevel() const
  1241. {
  1242. return level < LIBRARY->heroh->maxSupportedLevel() && exp >= static_cast<TExpType>(LIBRARY->heroh->reqExp(level+1));
  1243. }
  1244. void CGHeroInstance::levelUp()
  1245. {
  1246. ++level;
  1247. //update specialty and other bonuses that scale with level
  1248. nodeHasChanged();
  1249. }
  1250. void CGHeroInstance::attachCommanderToArmy()
  1251. {
  1252. if (commander)
  1253. commander->setArmy(this);
  1254. }
  1255. void CGHeroInstance::levelUpAutomatically(IGameRandomizer & gameRandomizer)
  1256. {
  1257. while(gainsLevel())
  1258. {
  1259. const auto primarySkill = gameRandomizer.rollPrimarySkillForLevelup(this);
  1260. const auto proposedSecondarySkills = getLevelupSkillCandidates(gameRandomizer);
  1261. setPrimarySkill(primarySkill, 1, ChangeValueMode::RELATIVE);
  1262. if(!proposedSecondarySkills.empty())
  1263. setSecSkillLevel(proposedSecondarySkills.front(), 1, ChangeValueMode::RELATIVE);
  1264. levelUp();
  1265. }
  1266. }
  1267. bool CGHeroInstance::hasVisions(const CGObjectInstance * target, BonusSubtypeID subtype) const
  1268. {
  1269. //VISIONS spell support
  1270. const int visionsMultiplier = valOfBonuses(BonusType::VISIONS, subtype);
  1271. int visionsRange = visionsMultiplier * getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  1272. if (visionsMultiplier > 0)
  1273. vstd::amax(visionsRange, 3); //minimum range is 3 tiles, but only if VISIONS bonus present
  1274. const int distance = static_cast<int>(target->anchorPos().dist2d(visitablePos()));
  1275. //logGlobal->debug(boost::str(boost::format("Visions: dist %d, mult %d, range %d") % distance % visionsMultiplier % visionsRange));
  1276. return (distance < visionsRange) && (target->anchorPos().z == anchorPos().z);
  1277. }
  1278. std::string CGHeroInstance::getHeroTypeName() const
  1279. {
  1280. if(ID == Obj::HERO || ID == Obj::PRISON)
  1281. return getHeroType()->getJsonKey();
  1282. return "";
  1283. }
  1284. void CGHeroInstance::afterAddToMap(CMap * map)
  1285. {
  1286. map->heroAddedToMap(this);
  1287. }
  1288. void CGHeroInstance::afterRemoveFromMap(CMap* map)
  1289. {
  1290. map->heroRemovedFromMap(this);
  1291. }
  1292. void CGHeroInstance::setHeroTypeName(const std::string & identifier)
  1293. {
  1294. if(ID == Obj::HERO || ID == Obj::PRISON)
  1295. {
  1296. auto rawId = LIBRARY->identifiers()->getIdentifier(ModScope::scopeMap(), "hero", identifier);
  1297. if(rawId)
  1298. subID = rawId.value();
  1299. else
  1300. {
  1301. throw std::runtime_error("Couldn't resolve hero identifier " + identifier);
  1302. }
  1303. }
  1304. }
  1305. void CGHeroInstance::updateFrom(const JsonNode & data)
  1306. {
  1307. CGObjectInstance::updateFrom(data);
  1308. }
  1309. void CGHeroInstance::serializeCommonOptions(JsonSerializeFormat & handler)
  1310. {
  1311. handler.serializeString("biography", biographyCustomTextId);
  1312. handler.serializeInt("experience", exp, 0);
  1313. if(!handler.saving && exp != UNINITIALIZED_EXPERIENCE) //do not gain levels if experience is not initialized
  1314. {
  1315. while (gainsLevel())
  1316. {
  1317. ++level;
  1318. }
  1319. }
  1320. handler.serializeString("name", nameCustomTextId);
  1321. handler.serializeInt("gender", gender, 0);
  1322. handler.serializeId("portrait", customPortraitSource, HeroTypeID::NONE);
  1323. //primary skills
  1324. if(handler.saving)
  1325. {
  1326. const bool haveSkills = hasBonus(Selector::type()(BonusType::PRIMARY_SKILL).And(Selector::sourceType()(BonusSource::HERO_BASE_SKILL)));
  1327. if(haveSkills)
  1328. {
  1329. auto primarySkills = handler.enterStruct("primarySkills");
  1330. for(auto skill : PrimarySkill::ALL_SKILLS())
  1331. {
  1332. int value = valOfBonuses(Selector::typeSubtype(BonusType::PRIMARY_SKILL, BonusSubtypeID(skill)).And(Selector::sourceType()(BonusSource::HERO_BASE_SKILL)));
  1333. handler.serializeInt(NPrimarySkill::names[skill.getNum()], value, 0);
  1334. }
  1335. }
  1336. }
  1337. else
  1338. {
  1339. auto primarySkills = handler.enterStruct("primarySkills");
  1340. if(handler.getCurrent().getType() == JsonNode::JsonType::DATA_STRUCT)
  1341. {
  1342. for(int i = 0; i < GameConstants::PRIMARY_SKILLS; ++i)
  1343. {
  1344. int value = 0;
  1345. handler.serializeInt(NPrimarySkill::names[i], value, 0);
  1346. pushPrimSkill(static_cast<PrimarySkill>(i), value);
  1347. }
  1348. }
  1349. }
  1350. //secondary skills
  1351. if(handler.saving)
  1352. {
  1353. //does hero have default skills?
  1354. bool defaultSkills = false;
  1355. bool normalSkills = false;
  1356. for(const auto & p : secSkills)
  1357. {
  1358. if(p.first == SecondarySkill(SecondarySkill::NONE))
  1359. defaultSkills = true;
  1360. else
  1361. normalSkills = true;
  1362. }
  1363. if(defaultSkills && normalSkills)
  1364. logGlobal->error("Mixed default and normal secondary skills");
  1365. //in json default skills means no field/null
  1366. if(!defaultSkills)
  1367. {
  1368. //enter array here as handler initialize it
  1369. auto secondarySkills = handler.enterArray("secondarySkills");
  1370. secondarySkills.syncSize(secSkills, JsonNode::JsonType::DATA_VECTOR);
  1371. for(size_t skillIndex = 0; skillIndex < secondarySkills.size(); ++skillIndex)
  1372. {
  1373. JsonArraySerializer inner = secondarySkills.enterArray(skillIndex);
  1374. SecondarySkill skillId = secSkills.at(skillIndex).first;
  1375. handler.serializeId("skill", skillId);
  1376. std::string skillLevel = NSecondarySkill::levels.at(secSkills.at(skillIndex).second);
  1377. handler.serializeString("level", skillLevel);
  1378. }
  1379. }
  1380. }
  1381. else
  1382. {
  1383. auto secondarySkills = handler.getCurrent()["secondarySkills"];
  1384. secSkills.clear();
  1385. if(secondarySkills.getType() == JsonNode::JsonType::DATA_NULL)
  1386. {
  1387. secSkills.emplace_back(SecondarySkill::NONE, -1);
  1388. }
  1389. else
  1390. {
  1391. auto addSkill = [this](const std::string & skillId, const std::string & levelId)
  1392. {
  1393. const int rawId = SecondarySkill::decode(skillId);
  1394. if(rawId < 0)
  1395. {
  1396. logGlobal->error("Invalid secondary skill %s", skillId);
  1397. return;
  1398. }
  1399. const int level = vstd::find_pos(NSecondarySkill::levels, levelId);
  1400. if(level < 0)
  1401. {
  1402. logGlobal->error("Invalid secondary skill level%s", levelId);
  1403. return;
  1404. }
  1405. secSkills.emplace_back(SecondarySkill(rawId), level);
  1406. };
  1407. if(secondarySkills.getType() == JsonNode::JsonType::DATA_VECTOR)
  1408. {
  1409. for(const auto & p : secondarySkills.Vector())
  1410. {
  1411. auto skillMap = p.Struct();
  1412. addSkill(skillMap["skill"].String(), skillMap["level"].String());
  1413. }
  1414. }
  1415. else if(secondarySkills.getType() == JsonNode::JsonType::DATA_STRUCT)
  1416. {
  1417. for(const auto & p : secondarySkills.Struct())
  1418. {
  1419. addSkill(p.first, p.second.String());
  1420. };
  1421. }
  1422. }
  1423. }
  1424. handler.serializeIdArray("spellBook", spells);
  1425. if(handler.saving)
  1426. CArtifactSet::serializeJsonArtifacts(handler, "artifacts", &cb->gameState().getMap());
  1427. }
  1428. void CGHeroInstance::serializeJsonOptions(JsonSerializeFormat & handler)
  1429. {
  1430. serializeCommonOptions(handler);
  1431. serializeJsonOwner(handler);
  1432. if(ID == Obj::HERO || ID == Obj::PRISON)
  1433. {
  1434. std::string typeName;
  1435. if(handler.saving)
  1436. typeName = getHeroTypeName();
  1437. handler.serializeString("type", typeName);
  1438. if(!handler.saving)
  1439. setHeroTypeName(typeName);
  1440. }
  1441. if(!handler.saving)
  1442. {
  1443. if(!appearance)
  1444. {
  1445. // crossoverDeserialize
  1446. appearance = LIBRARY->objtypeh->getHandlerFor(Obj::HERO, getHeroClassID())->getTemplates().front();
  1447. }
  1448. }
  1449. CArmedInstance::serializeJsonOptions(handler);
  1450. {
  1451. ui32 rawPatrolRadius = NO_PATROLLING;
  1452. if(handler.saving)
  1453. {
  1454. rawPatrolRadius = patrol.patrolling ? patrol.patrolRadius : NO_PATROLLING;
  1455. }
  1456. handler.serializeInt("patrolRadius", rawPatrolRadius, NO_PATROLLING);
  1457. if(!handler.saving)
  1458. {
  1459. patrol.patrolling = (rawPatrolRadius != NO_PATROLLING);
  1460. patrol.initialPos = visitablePos();
  1461. patrol.patrolRadius = patrol.patrolling ? rawPatrolRadius : 0;
  1462. }
  1463. }
  1464. }
  1465. void CGHeroInstance::serializeJsonDefinition(JsonSerializeFormat & handler)
  1466. {
  1467. serializeCommonOptions(handler);
  1468. }
  1469. bool CGHeroInstance::isMissionCritical() const
  1470. {
  1471. for(const TriggeredEvent & event : cb->getMapHeader()->triggeredEvents)
  1472. {
  1473. if (event.effect.type != EventEffect::DEFEAT)
  1474. continue;
  1475. auto const & testFunctor = [&](const EventCondition & condition)
  1476. {
  1477. if ((condition.condition == EventCondition::CONTROL) && condition.objectID != ObjectInstanceID::NONE)
  1478. return (id != condition.objectID);
  1479. if (condition.condition == EventCondition::HAVE_ARTIFACT)
  1480. {
  1481. if(hasArt(condition.objectType.as<ArtifactID>()))
  1482. return true;
  1483. }
  1484. if(condition.condition == EventCondition::IS_HUMAN)
  1485. return true;
  1486. return false;
  1487. };
  1488. if(event.trigger.test(testFunctor))
  1489. return true;
  1490. }
  1491. return false;
  1492. }
  1493. void CGHeroInstance::fillUpgradeInfo(UpgradeInfo & info, const CStackInstance & stack) const
  1494. {
  1495. TConstBonusListPtr lista = stack.getBonusesOfType(BonusType::SPECIAL_UPGRADE, BonusSubtypeID(stack.getId()));
  1496. for(const auto & it : *lista)
  1497. {
  1498. auto nid = CreatureID(it->additionalInfo[0]);
  1499. if (nid != stack.getId()) //in very specific case the upgrade is available by default (?)
  1500. {
  1501. info.addUpgrade(nid, stack.getType());
  1502. }
  1503. }
  1504. }
  1505. bool CGHeroInstance::isCampaignYog() const
  1506. {
  1507. const StartInfo *si = cb->getStartInfo();
  1508. return si && si->campState &&si->campState->getYogWizardID() == getHeroTypeID();
  1509. }
  1510. bool CGHeroInstance::isCampaignGem() const
  1511. {
  1512. const StartInfo *si = cb->getStartInfo();
  1513. return si && si->campState &&si->campState->getGemSorceressID() == getHeroTypeID();
  1514. }
  1515. ResourceSet CGHeroInstance::dailyIncome() const
  1516. {
  1517. ResourceSet income;
  1518. for (GameResID k : GameResID::ALL_RESOURCES())
  1519. income[k] += valOfBonuses(BonusType::GENERATE_RESOURCE, BonusSubtypeID(k));
  1520. const auto & playerSettings = cb->getPlayerSettings(getOwner());
  1521. income.applyHandicap(playerSettings->handicap.percentIncome);
  1522. return income;
  1523. }
  1524. std::vector<CreatureID> CGHeroInstance::providedCreatures() const
  1525. {
  1526. return {};
  1527. }
  1528. const IOwnableObject * CGHeroInstance::asOwnable() const
  1529. {
  1530. return this;
  1531. }
  1532. int CGHeroInstance::getBasePrimarySkillValue(PrimarySkill which) const
  1533. {
  1534. std::string cachingStr = "CGHeroInstance::getBasePrimarySkillValue" + std::to_string(which.getNum());
  1535. auto selector = Selector::typeSubtype(BonusType::PRIMARY_SKILL, BonusSubtypeID(which)).And(Selector::sourceType()(BonusSource::HERO_BASE_SKILL));
  1536. auto minSkillValue = LIBRARY->engineSettings()->getVectorValue(EGameSettings::HEROES_MINIMAL_PRIMARY_SKILLS, which.getNum());
  1537. return std::max(valOfBonuses(selector, cachingStr), minSkillValue);
  1538. }
  1539. VCMI_LIB_NAMESPACE_END