CGHeroInstance.cpp 53 KB

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