CGHeroInstance.cpp 52 KB

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