CGHeroInstance.cpp 54 KB

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