CGHeroInstance.cpp 47 KB

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