CGHeroInstance.cpp 52 KB

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