2
0

CGHeroInstance.cpp 53 KB

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