CGHeroInstance.cpp 54 KB

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