CGHeroInstance.cpp 51 KB

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