CGHeroInstance.cpp 51 KB

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