CGHeroInstance.cpp 48 KB

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