CGHeroInstance.cpp 44 KB

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