CGHeroInstance.cpp 54 KB

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