CGHeroInstance.cpp 52 KB

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