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