CGHeroInstance.cpp 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379
  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 "../CSpellHandler.h"
  18. #include "CObjectClassesHandler.h"
  19. #include "../IGameCallback.h"
  20. #include "../CGameState.h"
  21. #include "../CCreatureHandler.h"
  22. ///helpers
  23. static void showInfoDialog(const PlayerColor playerID, const ui32 txtID, const ui16 soundID)
  24. {
  25. InfoWindow iw;
  26. iw.soundID = soundID;
  27. iw.player = playerID;
  28. iw.text.addTxt(MetaString::ADVOB_TXT,txtID);
  29. IObjectInterface::cb->sendAndApply(&iw);
  30. }
  31. static void showInfoDialog(const CGHeroInstance* h, const ui32 txtID, const ui16 soundID)
  32. {
  33. const PlayerColor playerID = h->getOwner();
  34. showInfoDialog(playerID,txtID,soundID);
  35. }
  36. static int lowestSpeed(const CGHeroInstance * chi)
  37. {
  38. if(!chi->Slots().size())
  39. {
  40. logGlobal->errorStream() << "Error! Hero " << chi->id.getNum() << " ("<<chi->name<<") has no army!";
  41. return 20;
  42. }
  43. auto i = chi->Slots().begin();
  44. //TODO? should speed modifiers (eg from artifacts) affect hero movement?
  45. int ret = (i++)->second->valOfBonuses(Bonus::STACKS_SPEED);
  46. for (;i!=chi->Slots().end();i++)
  47. {
  48. ret = std::min(ret, i->second->valOfBonuses(Bonus::STACKS_SPEED));
  49. }
  50. return ret;
  51. }
  52. ui32 CGHeroInstance::getTileCost(const TerrainTile &dest, const TerrainTile &from) const
  53. {
  54. //base move cost
  55. unsigned ret = 100;
  56. //if there is road both on dest and src tiles - use road movement cost
  57. if(dest.roadType != ERoadType::NO_ROAD && from.roadType != ERoadType::NO_ROAD)
  58. {
  59. int road = std::min(dest.roadType,from.roadType); //used road ID
  60. switch(road)
  61. {
  62. case ERoadType::DIRT_ROAD:
  63. ret = 75;
  64. break;
  65. case ERoadType::GRAVEL_ROAD:
  66. ret = 65;
  67. break;
  68. case ERoadType::COBBLESTONE_ROAD:
  69. ret = 50;
  70. break;
  71. default:
  72. logGlobal->errorStream() << "Unknown road type: " << road << "... Something wrong!";
  73. break;
  74. }
  75. }
  76. else
  77. {
  78. //FIXME: in H3 presence of Nomad in army will remove terrain penalty for sand. Bonus not implemented in VCMI
  79. // NOTE: in H3 neutral stacks will ignore terrain penalty only if placed as topmost stack(s) in hero army.
  80. // This is clearly bug in H3 however intended behaviour is not clear.
  81. // Current VCMI behaviour will ignore neutrals in calculations so army in VCMI
  82. // will always have best penalty without any influence from player-defined stacks order
  83. bool nativeArmy = true;
  84. for(auto stack : stacks)
  85. {
  86. int nativeTerrain = VLC->townh->factions[stack.second->type->faction]->nativeTerrain;
  87. if (nativeTerrain != -1 && nativeTerrain != from.terType)
  88. {
  89. nativeArmy = false;
  90. break;
  91. }
  92. }
  93. if (!nativeArmy)
  94. ret = VLC->heroh->terrCosts[from.terType];
  95. }
  96. return ret;
  97. }
  98. int3 CGHeroInstance::convertPosition(int3 src, bool toh3m) //toh3m=true: manifest->h3m; toh3m=false: h3m->manifest
  99. {
  100. if (toh3m)
  101. {
  102. src.x+=1;
  103. return src;
  104. }
  105. else
  106. {
  107. src.x-=1;
  108. return src;
  109. }
  110. }
  111. int3 CGHeroInstance::getPosition(bool h3m) const //h3m=true - returns position of hero object; h3m=false - returns position of hero 'manifestation'
  112. {
  113. if (h3m)
  114. {
  115. return pos;
  116. }
  117. else
  118. {
  119. return convertPosition(pos,false);
  120. }
  121. }
  122. bool CGHeroInstance::canWalkOnSea() const
  123. {
  124. return hasBonusOfType(Bonus::FLYING_MOVEMENT) || hasBonusOfType(Bonus::WATER_WALKING);
  125. }
  126. ui8 CGHeroInstance::getSecSkillLevel(SecondarySkill skill) const
  127. {
  128. for(auto & elem : secSkills)
  129. if(elem.first == skill)
  130. return elem.second;
  131. return 0;
  132. }
  133. void CGHeroInstance::setSecSkillLevel(SecondarySkill which, int val, bool abs)
  134. {
  135. if(getSecSkillLevel(which) == 0)
  136. {
  137. secSkills.push_back(std::pair<SecondarySkill,ui8>(which, val));
  138. updateSkill(which, val);
  139. }
  140. else
  141. {
  142. for (auto & elem : secSkills)
  143. {
  144. if(elem.first == which)
  145. {
  146. if(abs)
  147. elem.second = val;
  148. else
  149. elem.second += val;
  150. if(elem.second > 3) //workaround to avoid crashes when same sec skill is given more than once
  151. {
  152. logGlobal->warnStream() << "Warning: Skill " << which << " increased over limit! Decreasing to Expert.";
  153. elem.second = 3;
  154. }
  155. updateSkill(which, elem.second); //when we know final value
  156. }
  157. }
  158. }
  159. }
  160. bool CGHeroInstance::canLearnSkill() const
  161. {
  162. return secSkills.size() < GameConstants::SKILL_PER_HERO;
  163. }
  164. int CGHeroInstance::maxMovePoints(bool onLand) const
  165. {
  166. int base;
  167. if(onLand)
  168. {
  169. // used function is f(x) = 66.6x + 1300, rounded to second digit, where x is lowest speed in army
  170. static const int baseSpeed = 1300; // base speed from creature with 0 speed
  171. int armySpeed = lowestSpeed(this) * 20 / 3;
  172. base = armySpeed * 10 + baseSpeed; // separate *10 is intentional to receive same rounding as in h3
  173. vstd::abetween(base, 1500, 2000); // base speed is limited by these values
  174. }
  175. else
  176. {
  177. base = 1500; //on water base movement is always 1500 (speed of army doesn't matter)
  178. }
  179. const Bonus::BonusType bt = onLand ? Bonus::LAND_MOVEMENT : Bonus::SEA_MOVEMENT;
  180. const int bonus = valOfBonuses(Bonus::MOVEMENT) + valOfBonuses(bt);
  181. const int subtype = onLand ? SecondarySkill::LOGISTICS : SecondarySkill::NAVIGATION;
  182. const double modifier = valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, subtype) / 100.0;
  183. return int(base* (1+modifier)) + bonus;
  184. }
  185. CGHeroInstance::CGHeroInstance()
  186. : IBoatGenerator(this)
  187. {
  188. setNodeType(HERO);
  189. ID = Obj::HERO;
  190. tacticFormationEnabled = inTownGarrison = false;
  191. mana = movement = portrait = level = -1;
  192. isStanding = true;
  193. moveDir = 4;
  194. exp = 0xffffffff;
  195. visitedTown = nullptr;
  196. type = nullptr;
  197. boat = nullptr;
  198. commander = nullptr;
  199. sex = 0xff;
  200. secSkills.push_back(std::make_pair(SecondarySkill::DEFAULT, -1));
  201. }
  202. void CGHeroInstance::initHero(HeroTypeID SUBID)
  203. {
  204. subID = SUBID.getNum();
  205. initHero();
  206. }
  207. void CGHeroInstance::setType(si32 ID, si32 subID)
  208. {
  209. assert(ID == Obj::HERO); // just in case
  210. type = VLC->heroh->heroes[subID];
  211. portrait = type->imageIndex;
  212. CGObjectInstance::setType(ID, type->heroClass->id);
  213. randomizeArmy(type->heroClass->faction);
  214. }
  215. void CGHeroInstance::initHero()
  216. {
  217. assert(validTypes(true));
  218. if(!type)
  219. type = VLC->heroh->heroes[subID];
  220. if (ID == Obj::HERO)
  221. appearance = VLC->objtypeh->getHandlerFor(Obj::HERO, type->heroClass->id)->getTemplates().front();
  222. if(!vstd::contains(spells, SpellID::PRESET)) //hero starts with a spell
  223. {
  224. for(auto spellID : type->spells)
  225. spells.insert(spellID);
  226. }
  227. else //remove placeholder
  228. spells -= SpellID::PRESET;
  229. if(!getArt(ArtifactPosition::MACH4) && !getArt(ArtifactPosition::SPELLBOOK) && type->haveSpellBook) //no catapult means we haven't read pre-existent set -> use default rules for spellbook
  230. putArtifact(ArtifactPosition::SPELLBOOK, CArtifactInstance::createNewArtifactInstance(0));
  231. if(!getArt(ArtifactPosition::MACH4))
  232. putArtifact(ArtifactPosition::MACH4, CArtifactInstance::createNewArtifactInstance(3)); //everyone has a catapult
  233. if(portrait < 0 || portrait == 255)
  234. portrait = type->imageIndex;
  235. if(!hasBonus(Selector::sourceType(Bonus::HERO_BASE_SKILL)))
  236. {
  237. for(int g=0; g<GameConstants::PRIMARY_SKILLS; ++g)
  238. {
  239. pushPrimSkill(static_cast<PrimarySkill::PrimarySkill>(g), type->heroClass->primarySkillInitial[g]);
  240. }
  241. }
  242. if(secSkills.size() == 1 && secSkills[0] == std::pair<SecondarySkill,ui8>(SecondarySkill::DEFAULT, -1)) //set secondary skills to default
  243. secSkills = type->secSkillsInit;
  244. if (!name.length())
  245. name = type->name;
  246. if (sex == 0xFF)//sex is default
  247. sex = type->sex;
  248. setFormation(false);
  249. if (!stacksCount()) //standard army//initial army
  250. {
  251. initArmy();
  252. }
  253. assert(validTypes());
  254. level = 1;
  255. if(exp == 0xffffffff)
  256. {
  257. initExp();
  258. }
  259. else
  260. {
  261. levelUpAutomatically();
  262. }
  263. if (VLC->modh->modules.COMMANDERS && !commander)
  264. {
  265. commander = new CCommanderInstance(type->heroClass->commander->idNumber);
  266. commander->setArmyObj (castToArmyObj()); //TODO: separate function for setting commanders
  267. commander->giveStackExp (exp); //after our exp is set
  268. }
  269. if (mana < 0)
  270. mana = manaLimit();
  271. }
  272. void CGHeroInstance::initArmy(IArmyDescriptor *dst /*= nullptr*/)
  273. {
  274. if(!dst)
  275. dst = this;
  276. int howManyStacks = 0; //how many stacks will hero receives <1 - 3>
  277. int pom = cb->gameState()->getRandomGenerator().nextInt(99);
  278. int warMachinesGiven = 0;
  279. if(pom < 9)
  280. howManyStacks = 1;
  281. else if(pom < 79)
  282. howManyStacks = 2;
  283. else
  284. howManyStacks = 3;
  285. vstd::amin(howManyStacks, type->initialArmy.size());
  286. for(int stackNo=0; stackNo < howManyStacks; stackNo++)
  287. {
  288. auto & stack = type->initialArmy[stackNo];
  289. int count = cb->gameState()->getRandomGenerator().nextInt(stack.minAmount, stack.maxAmount);
  290. if(stack.creature >= CreatureID::CATAPULT &&
  291. stack.creature <= CreatureID::ARROW_TOWERS) //war machine
  292. {
  293. warMachinesGiven++;
  294. if(dst != this)
  295. continue;
  296. int slot = -1;
  297. ArtifactID aid = ArtifactID::NONE;
  298. switch (stack.creature)
  299. {
  300. case CreatureID::CATAPULT:
  301. slot = ArtifactPosition::MACH4;
  302. aid = ArtifactID::CATAPULT;
  303. break;
  304. default:
  305. aid = CArtHandler::creatureToMachineID(stack.creature);
  306. slot = 9 + aid;
  307. break;
  308. }
  309. auto convSlot = ArtifactPosition(slot);
  310. if(!getArt(convSlot))
  311. putArtifact(convSlot, CArtifactInstance::createNewArtifactInstance(aid));
  312. else
  313. logGlobal->warnStream() << "Hero " << name << " already has artifact at " << slot << ", omitting giving " << aid;
  314. }
  315. else
  316. dst->setCreature(SlotID(stackNo-warMachinesGiven), stack.creature, count);
  317. }
  318. }
  319. CGHeroInstance::~CGHeroInstance()
  320. {
  321. commander.dellNull();
  322. }
  323. bool CGHeroInstance::needsLastStack() const
  324. {
  325. return true;
  326. }
  327. void CGHeroInstance::onHeroVisit(const CGHeroInstance * h) const
  328. {
  329. if(h == this) return; //exclude potential self-visiting
  330. if (ID == Obj::HERO)
  331. {
  332. if( cb->gameState()->getPlayerRelations(tempOwner, h->tempOwner)) //our or ally hero
  333. {
  334. //exchange
  335. cb->heroExchange(h->id, id);
  336. }
  337. else //battle
  338. {
  339. if(visitedTown) //we're in town
  340. visitedTown->onHeroVisit(h); //town will handle attacking
  341. else
  342. cb->startBattleI(h, this);
  343. }
  344. }
  345. else if(ID == Obj::PRISON)
  346. {
  347. int txt_id;
  348. if (cb->getHeroCount(h->tempOwner, false) < VLC->modh->settings.MAX_HEROES_ON_MAP_PER_PLAYER)//GameConstants::MAX_HEROES_PER_PLAYER) //free hero slot
  349. {
  350. cb->changeObjPos(id,pos+int3(1,0,0),0);
  351. //update hero parameters
  352. SetMovePoints smp;
  353. smp.hid = id;
  354. smp.val = maxMovePoints (true); //TODO: hota prison on water?
  355. cb->setMovePoints (&smp);
  356. cb->setManaPoints (id, manaLimit());
  357. cb->setObjProperty(id, ObjProperty::ID, Obj::HERO); //set ID to 34
  358. cb->giveHero(id,h->tempOwner); //recreates def and adds hero to player
  359. txt_id = 102;
  360. }
  361. else //already 8 wandering heroes
  362. {
  363. txt_id = 103;
  364. }
  365. showInfoDialog(h,txt_id,soundBase::ROGUE);
  366. }
  367. }
  368. std::string CGHeroInstance::getObjectName() const
  369. {
  370. if(ID != Obj::PRISON)
  371. {
  372. std::string hoverName = VLC->generaltexth->allTexts[15];
  373. boost::algorithm::replace_first(hoverName,"%s",name);
  374. boost::algorithm::replace_first(hoverName,"%s", type->heroClass->name);
  375. return hoverName;
  376. }
  377. else
  378. return CGObjectInstance::getObjectName();
  379. }
  380. const std::string & CGHeroInstance::getBiography() const
  381. {
  382. if (biography.length())
  383. return biography;
  384. return type->biography;
  385. }
  386. ui8 CGHeroInstance::maxlevelsToMagicSchool() const
  387. {
  388. return type->heroClass->isMagicHero() ? 3 : 4;
  389. }
  390. ui8 CGHeroInstance::maxlevelsToWisdom() const
  391. {
  392. return type->heroClass->isMagicHero() ? 3 : 6;
  393. }
  394. void CGHeroInstance::SecondarySkillsInfo::resetMagicSchoolCounter()
  395. {
  396. magicSchoolCounter = 1;
  397. }
  398. void CGHeroInstance::SecondarySkillsInfo::resetWisdomCounter()
  399. {
  400. wisdomCounter = 1;
  401. }
  402. void CGHeroInstance::initObj()
  403. {
  404. blockVisit = true;
  405. auto hs = new HeroSpecial();
  406. hs->setNodeType(CBonusSystemNode::SPECIALTY);
  407. attachTo(hs); //do we ever need to detach it?
  408. if(!type)
  409. initHero(); //TODO: set up everything for prison before specialties are configured
  410. skillsInfo.rand.setSeed(cb->gameState()->getRandomGenerator().nextInt());
  411. skillsInfo.resetMagicSchoolCounter();
  412. skillsInfo.resetWisdomCounter();
  413. if (ID != Obj::PRISON)
  414. {
  415. auto customApp = VLC->objtypeh->getHandlerFor(ID, type->heroClass->id)->getOverride(cb->gameState()->getTile(visitablePos())->terType, this);
  416. if (customApp)
  417. appearance = customApp.get();
  418. }
  419. for(const auto &spec : type->spec) //TODO: unfity with bonus system
  420. {
  421. auto bonus = new Bonus();
  422. bonus->val = spec.val;
  423. bonus->sid = id.getNum(); //from the hero, specialty has no unique id
  424. bonus->duration = Bonus::PERMANENT;
  425. bonus->source = Bonus::HERO_SPECIAL;
  426. switch (spec.type)
  427. {
  428. case 1:// creature specialty
  429. {
  430. hs->growsWithLevel = true;
  431. const CCreature &specCreature = *VLC->creh->creatures[spec.additionalinfo]; //creature in which we have specialty
  432. //int creLevel = specCreature.level;
  433. //if(!creLevel)
  434. //{
  435. // if(spec.additionalinfo == 146)
  436. // creLevel = 5; //treat ballista as 5-level
  437. // else
  438. // {
  439. // logGlobal->warnStream() << "Warning: unknown level of " << specCreature.namePl;
  440. // continue;
  441. // }
  442. //}
  443. //bonus->additionalInfo = spec.additionalinfo; //creature id, should not be used again - this works only with limiter
  444. bonus->limiter.reset(new CCreatureTypeLimiter (specCreature, true)); //with upgrades
  445. bonus->type = Bonus::PRIMARY_SKILL;
  446. bonus->valType = Bonus::ADDITIVE_VALUE;
  447. bonus->subtype = PrimarySkill::ATTACK;
  448. hs->addNewBonus(bonus);
  449. bonus = new Bonus(*bonus);
  450. bonus->subtype = PrimarySkill::DEFENSE;
  451. hs->addNewBonus(bonus);
  452. //values will be calculated later
  453. bonus = new Bonus(*bonus);
  454. bonus->type = Bonus::STACKS_SPEED;
  455. bonus->val = 1; //+1 speed
  456. hs->addNewBonus(bonus);
  457. }
  458. break;
  459. case 2://secondary skill
  460. hs->growsWithLevel = true;
  461. bonus->type = Bonus::SPECIAL_SECONDARY_SKILL; //needs to be recalculated with level, based on this value
  462. bonus->valType = Bonus::BASE_NUMBER; // to receive nonzero value
  463. bonus->subtype = spec.subtype; //skill id
  464. bonus->val = spec.val; //value per level, in percent
  465. hs->addNewBonus(bonus);
  466. bonus = new Bonus(*bonus);
  467. switch (spec.additionalinfo)
  468. {
  469. case 0: //normal
  470. bonus->valType = Bonus::PERCENT_TO_BASE;
  471. break;
  472. case 1: //when it's navigation or there's no 'base' at all
  473. bonus->valType = Bonus::PERCENT_TO_ALL;
  474. break;
  475. }
  476. bonus->type = Bonus::SECONDARY_SKILL_PREMY; //value will be calculated later
  477. hs->addNewBonus(bonus);
  478. break;
  479. case 3://spell damage bonus, level dependent but calculated elsewhere
  480. bonus->type = Bonus::SPECIAL_SPELL_LEV;
  481. bonus->subtype = spec.subtype;
  482. hs->addNewBonus(bonus);
  483. break;
  484. case 4://creature stat boost
  485. switch (spec.subtype)
  486. {
  487. case 1://attack
  488. bonus->type = Bonus::PRIMARY_SKILL;
  489. bonus->subtype = PrimarySkill::ATTACK;
  490. break;
  491. case 2://defense
  492. bonus->type = Bonus::PRIMARY_SKILL;
  493. bonus->subtype = PrimarySkill::DEFENSE;
  494. break;
  495. case 3:
  496. bonus->type = Bonus::CREATURE_DAMAGE;
  497. bonus->subtype = 0; //both min and max
  498. break;
  499. case 4://hp
  500. bonus->type = Bonus::STACK_HEALTH;
  501. break;
  502. case 5:
  503. bonus->type = Bonus::STACKS_SPEED;
  504. break;
  505. default:
  506. continue;
  507. }
  508. bonus->additionalInfo = spec.additionalinfo; //creature id
  509. bonus->valType = Bonus::ADDITIVE_VALUE;
  510. bonus->limiter.reset(new CCreatureTypeLimiter (*VLC->creh->creatures[spec.additionalinfo], true));
  511. hs->addNewBonus(bonus);
  512. break;
  513. case 5://spell damage bonus in percent
  514. bonus->type = Bonus::SPECIFIC_SPELL_DAMAGE;
  515. bonus->valType = Bonus::BASE_NUMBER; // current spell system is screwed
  516. bonus->subtype = spec.subtype; //spell id
  517. hs->addNewBonus(bonus);
  518. break;
  519. case 6://damage bonus for bless (Adela)
  520. bonus->type = Bonus::SPECIAL_BLESS_DAMAGE;
  521. bonus->subtype = spec.subtype; //spell id if you ever wanted to use it otherwise
  522. bonus->additionalInfo = spec.additionalinfo; //damage factor
  523. hs->addNewBonus(bonus);
  524. break;
  525. case 7://maxed mastery for spell
  526. bonus->type = Bonus::MAXED_SPELL;
  527. bonus->subtype = spec.subtype; //spell i
  528. hs->addNewBonus(bonus);
  529. break;
  530. case 8://peculiar spells - enchantments
  531. bonus->type = Bonus::SPECIAL_PECULIAR_ENCHANT;
  532. bonus->subtype = spec.subtype; //spell id
  533. bonus->additionalInfo = spec.additionalinfo;//0, 1 for Coronius
  534. hs->addNewBonus(bonus);
  535. break;
  536. case 9://upgrade creatures
  537. {
  538. const auto &creatures = VLC->creh->creatures;
  539. bonus->type = Bonus::SPECIAL_UPGRADE;
  540. bonus->subtype = spec.subtype; //base id
  541. bonus->additionalInfo = spec.additionalinfo; //target id
  542. hs->addNewBonus(bonus);
  543. bonus = new Bonus(*bonus);
  544. for(auto cre_id : creatures[spec.subtype]->upgrades)
  545. {
  546. bonus->subtype = cre_id; //propagate for regular upgrades of base creature
  547. hs->addNewBonus(bonus);
  548. bonus = new Bonus(*bonus);
  549. }
  550. vstd::clear_pointer(bonus);
  551. break;
  552. }
  553. case 10://resource generation
  554. bonus->type = Bonus::GENERATE_RESOURCE;
  555. bonus->subtype = spec.subtype;
  556. hs->addNewBonus(bonus);
  557. break;
  558. case 11://starting skill with mastery (Adrienne)
  559. setSecSkillLevel(SecondarySkill(spec.val), spec.additionalinfo, true);
  560. break;
  561. case 12://army speed
  562. bonus->type = Bonus::STACKS_SPEED;
  563. hs->addNewBonus(bonus);
  564. break;
  565. case 13://Dragon bonuses (Mutare)
  566. bonus->type = Bonus::PRIMARY_SKILL;
  567. bonus->valType = Bonus::ADDITIVE_VALUE;
  568. switch (spec.subtype)
  569. {
  570. case 1:
  571. bonus->subtype = PrimarySkill::ATTACK;
  572. break;
  573. case 2:
  574. bonus->subtype = PrimarySkill::DEFENSE;
  575. break;
  576. }
  577. bonus->limiter.reset(new HasAnotherBonusLimiter(Bonus::DRAGON_NATURE));
  578. hs->addNewBonus(bonus);
  579. break;
  580. default:
  581. logGlobal->warnStream() << "Unexpected hero specialty " << type;
  582. }
  583. }
  584. specialty.push_back(hs); //will it work?
  585. for (auto hs2 : type->specialty) //copy active (probably growing) bonuses from hero prootype to hero object
  586. {
  587. auto hs = new HeroSpecial();
  588. attachTo(hs); //do we ever need to detach it?
  589. hs->setNodeType(CBonusSystemNode::SPECIALTY);
  590. for (auto bonus : hs2.bonuses)
  591. {
  592. hs->addNewBonus (bonus);
  593. }
  594. hs->growsWithLevel = hs2.growsWithLevel;
  595. specialty.push_back(hs); //will it work?
  596. }
  597. //initialize bonuses
  598. recreateSecondarySkillsBonuses();
  599. Updatespecialty();
  600. mana = manaLimit(); //after all bonuses are taken into account, make sure this line is the last one
  601. type->name = name;
  602. }
  603. void CGHeroInstance::Updatespecialty() //TODO: calculate special value of bonuses on-the-fly?
  604. {
  605. for (auto hs : specialty)
  606. {
  607. if (hs->growsWithLevel)
  608. {
  609. //const auto &creatures = VLC->creh->creatures;
  610. for(Bonus * b : hs->getBonusList())
  611. {
  612. switch (b->type)
  613. {
  614. case Bonus::SECONDARY_SKILL_PREMY:
  615. b->val = (hs->valOfBonuses(Bonus::SPECIAL_SECONDARY_SKILL, b->subtype) * level);
  616. break; //use only hero skills as bonuses to avoid feedback loop
  617. case Bonus::PRIMARY_SKILL: //for creatures, that is
  618. {
  619. const CCreature * cre = nullptr;
  620. int creLevel = 0;
  621. if (auto creatureLimiter = std::dynamic_pointer_cast<CCreatureTypeLimiter>(b->limiter)) //TODO: more general eveluation of bonuses?
  622. {
  623. cre = creatureLimiter->creature;
  624. creLevel = cre->level;
  625. if (!creLevel)
  626. {
  627. creLevel = 5; //treat ballista as tier 5
  628. }
  629. }
  630. else //no creature found, can't calculate value
  631. {
  632. logGlobal->warnStream() << "Primary skill specialty growth supported only with creature type limiters";
  633. break;
  634. }
  635. double primSkillModifier = (int)(level / creLevel) / 20.0;
  636. int param;
  637. switch (b->subtype)
  638. {
  639. case PrimarySkill::ATTACK:
  640. param = cre->Attack();
  641. break;
  642. case PrimarySkill::DEFENSE:
  643. param = cre->Defense();
  644. break;
  645. default:
  646. continue;
  647. }
  648. b->val = ceil(param * (1 + primSkillModifier)) - param; //yep, overcomplicated but matches original
  649. break;
  650. }
  651. }
  652. }
  653. }
  654. }
  655. }
  656. void CGHeroInstance::recreateSecondarySkillsBonuses()
  657. {
  658. auto secondarySkillsBonuses = getBonuses(Selector::sourceType(Bonus::SECONDARY_SKILL));
  659. for(auto bonus : *secondarySkillsBonuses)
  660. removeBonus(bonus);
  661. for(auto skill_info : secSkills)
  662. updateSkill(SecondarySkill(skill_info.first), skill_info.second);
  663. }
  664. void CGHeroInstance::updateSkill(SecondarySkill which, int val)
  665. {
  666. if(which == SecondarySkill::LEADERSHIP || which == SecondarySkill::LUCK)
  667. { //luck-> VLC->generaltexth->arraytxt[73+luckSkill]; VLC->generaltexth->arraytxt[104+moraleSkill]
  668. bool luck = which == SecondarySkill::LUCK;
  669. Bonus::BonusType type[] = {Bonus::MORALE, Bonus::LUCK};
  670. Bonus *b = getBonusLocalFirst(Selector::type(type[luck]).And(Selector::sourceType(Bonus::SECONDARY_SKILL)));
  671. if(!b)
  672. {
  673. b = new Bonus(Bonus::PERMANENT, type[luck], Bonus::SECONDARY_SKILL, +val, which, which, Bonus::BASE_NUMBER);
  674. addNewBonus(b);
  675. }
  676. else
  677. b->val = +val;
  678. }
  679. else if(which == SecondarySkill::DIPLOMACY) //surrender discount: 20% per level
  680. {
  681. if(Bonus *b = getBonusLocalFirst(Selector::type(Bonus::SURRENDER_DISCOUNT).And(Selector::sourceType(Bonus::SECONDARY_SKILL))))
  682. b->val = +val;
  683. else
  684. addNewBonus(new Bonus(Bonus::PERMANENT, Bonus::SURRENDER_DISCOUNT, Bonus::SECONDARY_SKILL, val * 20, which));
  685. }
  686. int skillVal = 0;
  687. switch (which)
  688. {
  689. case SecondarySkill::ARCHERY:
  690. switch (val)
  691. {
  692. case 1:
  693. skillVal = 10; break;
  694. case 2:
  695. skillVal = 25; break;
  696. case 3:
  697. skillVal = 50; break;
  698. }
  699. break;
  700. case SecondarySkill::LOGISTICS:
  701. skillVal = 10 * val; break;
  702. case SecondarySkill::NAVIGATION:
  703. skillVal = 50 * val; break;
  704. case SecondarySkill::MYSTICISM:
  705. skillVal = val; break;
  706. case SecondarySkill::EAGLE_EYE:
  707. skillVal = 30 + 10 * val; break;
  708. case SecondarySkill::NECROMANCY:
  709. skillVal = 10 * val; break;
  710. case SecondarySkill::LEARNING:
  711. skillVal = 5 * val; break;
  712. case SecondarySkill::OFFENCE:
  713. skillVal = 10 * val; break;
  714. case SecondarySkill::ARMORER:
  715. skillVal = 5 * val; break;
  716. case SecondarySkill::INTELLIGENCE:
  717. skillVal = 25 << (val-1); break;
  718. case SecondarySkill::SORCERY:
  719. skillVal = 5 * val; break;
  720. case SecondarySkill::RESISTANCE:
  721. skillVal = 5 << (val-1); break;
  722. case SecondarySkill::FIRST_AID:
  723. skillVal = 25 + 25*val; break;
  724. case SecondarySkill::ESTATES:
  725. skillVal = 125 << (val-1); break;
  726. }
  727. Bonus::ValueType skillValType = skillVal ? Bonus::BASE_NUMBER : Bonus::INDEPENDENT_MIN;
  728. if(Bonus * b = getBonusList().getFirst(Selector::typeSubtype(Bonus::SECONDARY_SKILL_PREMY, which)
  729. .And(Selector::sourceType(Bonus::SECONDARY_SKILL)))) //only local hero bonus
  730. {
  731. b->val = skillVal;
  732. b->valType = skillValType;
  733. }
  734. else
  735. {
  736. auto bonus = new Bonus(Bonus::PERMANENT, Bonus::SECONDARY_SKILL_PREMY, Bonus::SECONDARY_SKILL, skillVal, id.getNum(), which, skillValType);
  737. bonus->source = Bonus::SECONDARY_SKILL;
  738. addNewBonus(bonus);
  739. }
  740. }
  741. void CGHeroInstance::setPropertyDer( ui8 what, ui32 val )
  742. {
  743. if(what == ObjProperty::PRIMARY_STACK_COUNT)
  744. setStackCount(SlotID(0), val);
  745. }
  746. double CGHeroInstance::getFightingStrength() const
  747. {
  748. return sqrt((1.0 + 0.05*getPrimSkillLevel(PrimarySkill::ATTACK)) * (1.0 + 0.05*getPrimSkillLevel(PrimarySkill::DEFENSE)));
  749. }
  750. double CGHeroInstance::getMagicStrength() const
  751. {
  752. return sqrt((1.0 + 0.05*getPrimSkillLevel(PrimarySkill::KNOWLEDGE)) * (1.0 + 0.05*getPrimSkillLevel(PrimarySkill::SPELL_POWER)));
  753. }
  754. double CGHeroInstance::getHeroStrength() const
  755. {
  756. return sqrt(pow(getFightingStrength(), 2.0) * pow(getMagicStrength(), 2.0));
  757. }
  758. ui64 CGHeroInstance::getTotalStrength() const
  759. {
  760. double ret = getFightingStrength() * getArmyStrength();
  761. return (ui64) ret;
  762. }
  763. TExpType CGHeroInstance::calculateXp(TExpType exp) const
  764. {
  765. return exp * (100 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::LEARNING))/100.0;
  766. }
  767. ui8 CGHeroInstance::getSpellSchoolLevel(const CSpell * spell, int *outSelectedSchool) const
  768. {
  769. si16 skill = -1; //skill level
  770. #define TRY_SCHOOL(schoolName, schoolMechanicsId, schoolOutId) \
  771. if(spell-> schoolName) \
  772. { \
  773. int thisSchool = std::max<int>(getSecSkillLevel( \
  774. SecondarySkill(14 + (schoolMechanicsId))), \
  775. valOfBonuses(Bonus::MAGIC_SCHOOL_SKILL, 1 << (schoolMechanicsId))); \
  776. if(thisSchool > skill) \
  777. { \
  778. skill = thisSchool; \
  779. if(outSelectedSchool) \
  780. *outSelectedSchool = schoolOutId; \
  781. } \
  782. }
  783. TRY_SCHOOL(fire, 0, 1)
  784. TRY_SCHOOL(air, 1, 0)
  785. TRY_SCHOOL(water, 2, 2)
  786. TRY_SCHOOL(earth, 3, 3)
  787. #undef TRY_SCHOOL
  788. vstd::amax(skill, valOfBonuses(Bonus::MAGIC_SCHOOL_SKILL, 0)); //any school bonus
  789. vstd::amax(skill, valOfBonuses(Bonus::SPELL, spell->id.toEnum())); //given by artifact or other effect
  790. if (hasBonusOfType(Bonus::MAXED_SPELL, spell->id))//hero specialty (Daremyth, Melodia)
  791. skill = 3;
  792. assert(skill >= 0 && skill <= 3);
  793. return skill;
  794. }
  795. bool CGHeroInstance::canCastThisSpell(const CSpell * spell) const
  796. {
  797. if(!getArt(ArtifactPosition::SPELLBOOK)) //if hero has no spellbook
  798. return false;
  799. if (spell->isSpecialSpell())
  800. {
  801. if (vstd::contains(spells, spell->id))
  802. {//hero has this spell in spellbook
  803. logGlobal->errorStream() << "Special spell in spellbook "<<spell->name;
  804. }
  805. if (hasBonusOfType(Bonus::SPELL, spell->id))
  806. return true;
  807. return false;
  808. }
  809. else
  810. {
  811. if(vstd::contains(spells, spell->id) //hero has this spell in spellbook
  812. || (spell->air && hasBonusOfType(Bonus::AIR_SPELLS)) // this is air spell and hero can cast all air spells
  813. || (spell->fire && hasBonusOfType(Bonus::FIRE_SPELLS)) // this is fire spell and hero can cast all fire spells
  814. || (spell->water && hasBonusOfType(Bonus::WATER_SPELLS)) // this is water spell and hero can cast all water spells
  815. || (spell->earth && hasBonusOfType(Bonus::EARTH_SPELLS)) // this is earth spell and hero can cast all earth spells
  816. || hasBonusOfType(Bonus::SPELL, spell->id)
  817. || hasBonusOfType(Bonus::SPELLS_OF_LEVEL, spell->level)
  818. )
  819. return true;
  820. return false;
  821. }
  822. }
  823. /**
  824. * Calculates what creatures and how many to be raised from a battle.
  825. * @param battleResult The results of the battle.
  826. * @return Returns a pair with the first value indicating the ID of the creature
  827. * type and second value the amount. Both values are returned as -1 if necromancy
  828. * could not be applied.
  829. */
  830. CStackBasicDescriptor CGHeroInstance::calculateNecromancy (const BattleResult &battleResult) const
  831. {
  832. const ui8 necromancyLevel = getSecSkillLevel(SecondarySkill::NECROMANCY);
  833. // Hero knows necromancy or has Necromancer Cloak
  834. if (necromancyLevel > 0 || hasBonusOfType(Bonus::IMPROVED_NECROMANCY))
  835. {
  836. double necromancySkill = valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::NECROMANCY)/100.0;
  837. vstd::amin(necromancySkill, 1.0); //it's impossible to raise more creatures than all...
  838. const std::map<ui32,si32> &casualties = battleResult.casualties[!battleResult.winner];
  839. ui32 raisedUnits = 0;
  840. // Figure out what to raise and how many.
  841. const CreatureID creatureTypes[] = {CreatureID::SKELETON, CreatureID::WALKING_DEAD, CreatureID::WIGHTS, CreatureID::LICHES};
  842. const bool improvedNecromancy = hasBonusOfType(Bonus::IMPROVED_NECROMANCY);
  843. const CCreature *raisedUnitType = VLC->creh->creatures[creatureTypes[improvedNecromancy ? necromancyLevel : 0]];
  844. const ui32 raisedUnitHP = raisedUnitType->valOfBonuses(Bonus::STACK_HEALTH);
  845. //calculate creatures raised from each defeated stack
  846. for (auto & casualtie : casualties)
  847. {
  848. // Get lost enemy hit points convertible to units.
  849. CCreature * c = VLC->creh->creatures[casualtie.first];
  850. const ui32 raisedHP = c->valOfBonuses(Bonus::STACK_HEALTH) * casualtie.second * necromancySkill;
  851. raisedUnits += std::min<ui32>(raisedHP / raisedUnitHP, casualtie.second * necromancySkill); //limit to % of HP and % of original stack count
  852. }
  853. // Make room for new units.
  854. SlotID slot = getSlotFor(raisedUnitType->idNumber);
  855. if (slot == SlotID())
  856. {
  857. // If there's no room for unit, try it's upgraded version 2/3rds the size.
  858. raisedUnitType = VLC->creh->creatures[*raisedUnitType->upgrades.begin()];
  859. raisedUnits = (raisedUnits*2)/3;
  860. slot = getSlotFor(raisedUnitType->idNumber);
  861. }
  862. if (raisedUnits <= 0)
  863. raisedUnits = 1;
  864. return CStackBasicDescriptor(raisedUnitType->idNumber, raisedUnits);
  865. }
  866. return CStackBasicDescriptor();
  867. }
  868. /**
  869. * Show the necromancy dialog with information about units raised.
  870. * @param raisedStack Pair where the first element represents ID of the raised creature
  871. * and the second element the amount.
  872. */
  873. void CGHeroInstance::showNecromancyDialog(const CStackBasicDescriptor &raisedStack) const
  874. {
  875. InfoWindow iw;
  876. iw.soundID = soundBase::pickup01 + cb->gameState()->getRandomGenerator().nextInt(6);
  877. iw.player = tempOwner;
  878. iw.components.push_back(Component(raisedStack));
  879. if (raisedStack.count > 1) // Practicing the dark arts of necromancy, ... (plural)
  880. {
  881. iw.text.addTxt(MetaString::GENERAL_TXT, 145);
  882. iw.text.addReplacement(raisedStack.count);
  883. }
  884. else // Practicing the dark arts of necromancy, ... (singular)
  885. {
  886. iw.text.addTxt(MetaString::GENERAL_TXT, 146);
  887. }
  888. iw.text.addReplacement(raisedStack);
  889. cb->showInfoDialog(&iw);
  890. }
  891. /*
  892. int3 CGHeroInstance::getSightCenter() const
  893. {
  894. return getPosition(false);
  895. }*/
  896. int CGHeroInstance::getSightRadious() const
  897. {
  898. return 5 + getSecSkillLevel(SecondarySkill::SCOUTING) + valOfBonuses(Bonus::SIGHT_RADIOUS); //default + scouting
  899. }
  900. si32 CGHeroInstance::manaRegain() const
  901. {
  902. if (hasBonusOfType(Bonus::FULL_MANA_REGENERATION))
  903. return manaLimit();
  904. return 1 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, 8) + valOfBonuses(Bonus::MANA_REGENERATION); //1 + Mysticism level
  905. }
  906. // /**
  907. // * Places an artifact in hero's backpack. If it's a big artifact equips it
  908. // * or discards it if it cannot be equipped.
  909. // */
  910. // void CGHeroInstance::giveArtifact (ui32 aid) //use only for fixed artifacts
  911. // {
  912. // CArtifact * const artifact = VLC->arth->artifacts[aid]; //pointer to constant object
  913. // CArtifactInstance *ai = CArtifactInstance::createNewArtifactInstance(artifact);
  914. // ai->putAt(this, ai->firstAvailableSlot(this));
  915. // }
  916. int CGHeroInstance::getBoatType() const
  917. {
  918. switch(type->heroClass->getAlignment())
  919. {
  920. case EAlignment::GOOD:
  921. return 1;
  922. case EAlignment::EVIL:
  923. return 0;
  924. case EAlignment::NEUTRAL:
  925. return 2;
  926. default:
  927. throw std::runtime_error("Wrong alignment!");
  928. }
  929. }
  930. void CGHeroInstance::getOutOffsets(std::vector<int3> &offsets) const
  931. {
  932. offsets =
  933. {
  934. int3(0,1,0), int3(0,-1,0), int3(-1,0,0), int3(+1,0,0), int3(1,1,0), int3(-1,1,0), int3(1,-1,0), int3(-1,-1,0)
  935. };
  936. }
  937. int CGHeroInstance::getSpellCost(const CSpell *sp) const
  938. {
  939. return sp->getCost(getSpellSchoolLevel(sp));
  940. }
  941. void CGHeroInstance::pushPrimSkill( PrimarySkill::PrimarySkill which, int val )
  942. {
  943. assert(!hasBonus(Selector::typeSubtype(Bonus::PRIMARY_SKILL, which)
  944. .And(Selector::sourceType(Bonus::HERO_BASE_SKILL))));
  945. addNewBonus(new Bonus(Bonus::PERMANENT, Bonus::PRIMARY_SKILL, Bonus::HERO_BASE_SKILL, val, id.getNum(), which));
  946. }
  947. EAlignment::EAlignment CGHeroInstance::getAlignment() const
  948. {
  949. return type->heroClass->getAlignment();
  950. }
  951. void CGHeroInstance::initExp()
  952. {
  953. exp = cb->gameState()->getRandomGenerator().nextInt(40, 89);
  954. }
  955. std::string CGHeroInstance::nodeName() const
  956. {
  957. return "Hero " + name;
  958. }
  959. void CGHeroInstance::putArtifact(ArtifactPosition pos, CArtifactInstance *art)
  960. {
  961. assert(!getArt(pos));
  962. art->putAt(ArtifactLocation(this, pos));
  963. }
  964. void CGHeroInstance::putInBackpack(CArtifactInstance *art)
  965. {
  966. putArtifact(art->firstBackpackSlot(this), art);
  967. }
  968. bool CGHeroInstance::hasSpellbook() const
  969. {
  970. return getArt(ArtifactPosition::SPELLBOOK);
  971. }
  972. void CGHeroInstance::deserializationFix()
  973. {
  974. artDeserializationFix(this);
  975. for (auto hs : specialty)
  976. {
  977. attachTo (hs);
  978. }
  979. }
  980. CBonusSystemNode * CGHeroInstance::whereShouldBeAttached(CGameState *gs)
  981. {
  982. if(visitedTown)
  983. {
  984. if(inTownGarrison)
  985. return visitedTown;
  986. else
  987. return &visitedTown->townAndVis;
  988. }
  989. else
  990. return CArmedInstance::whereShouldBeAttached(gs);
  991. }
  992. int CGHeroInstance::movementPointsAfterEmbark(int MPsBefore, int basicCost, bool disembark /*= false*/) const
  993. {
  994. if(hasBonusOfType(Bonus::FREE_SHIP_BOARDING))
  995. return (MPsBefore - basicCost) * static_cast<double>(maxMovePoints(disembark)) / maxMovePoints(!disembark);
  996. return 0; //take all MPs otherwise
  997. }
  998. CGHeroInstance::ECanDig CGHeroInstance::diggingStatus() const
  999. {
  1000. if(movement < maxMovePoints(true))
  1001. return LACK_OF_MOVEMENT;
  1002. else if(cb->getTile(getPosition(false))->terType == ETerrainType::WATER)
  1003. return WRONG_TERRAIN;
  1004. else
  1005. {
  1006. const TerrainTile *t = cb->getTile(getPosition());
  1007. //TODO look for hole
  1008. //CGI->mh->getTerrainDescr(h->getPosition(false), hlp, false);
  1009. if(/*hlp.length() || */t->blockingObjects.size() > 1)
  1010. return TILE_OCCUPIED;
  1011. else
  1012. return CAN_DIG;
  1013. }
  1014. }
  1015. ArtBearer::ArtBearer CGHeroInstance::bearerType() const
  1016. {
  1017. return ArtBearer::HERO;
  1018. }
  1019. std::vector<SecondarySkill> CGHeroInstance::getLevelUpProposedSecondarySkills() const
  1020. {
  1021. std::vector<SecondarySkill> obligatorySkills; //hero is offered magic school or wisdom if possible
  1022. if (!skillsInfo.wisdomCounter)
  1023. {
  1024. if (cb->isAllowed(2, SecondarySkill::WISDOM) && !getSecSkillLevel(SecondarySkill::WISDOM))
  1025. obligatorySkills.push_back(SecondarySkill::WISDOM);
  1026. }
  1027. if (!skillsInfo.magicSchoolCounter)
  1028. {
  1029. std::vector<SecondarySkill> ss =
  1030. {
  1031. SecondarySkill::FIRE_MAGIC, SecondarySkill::AIR_MAGIC, SecondarySkill::WATER_MAGIC, SecondarySkill::EARTH_MAGIC
  1032. };
  1033. std::shuffle(ss.begin(), ss.end(), skillsInfo.rand.getStdGenerator());
  1034. for (auto skill : ss)
  1035. {
  1036. if (cb->isAllowed(2, skill) && !getSecSkillLevel(skill)) //only schools hero doesn't know yet
  1037. {
  1038. obligatorySkills.push_back(skill);
  1039. break; //only one
  1040. }
  1041. }
  1042. }
  1043. std::vector<SecondarySkill> skills;
  1044. //picking sec. skills for choice
  1045. std::set<SecondarySkill> basicAndAdv, expert, none;
  1046. for(int i=0;i<GameConstants::SKILL_QUANTITY;i++)
  1047. if (cb->isAllowed(2,i))
  1048. none.insert(SecondarySkill(i));
  1049. for(auto & elem : secSkills)
  1050. {
  1051. if(elem.second < SecSkillLevel::EXPERT)
  1052. basicAndAdv.insert(elem.first);
  1053. else
  1054. expert.insert(elem.first);
  1055. none.erase(elem.first);
  1056. }
  1057. for (auto s : obligatorySkills) //don't duplicate them
  1058. {
  1059. none.erase (s);
  1060. basicAndAdv.erase (s);
  1061. expert.erase (s);
  1062. }
  1063. //first offered skill:
  1064. // 1) give obligatory skill
  1065. // 2) give any other new skill
  1066. // 3) upgrade existing
  1067. if (canLearnSkill() && obligatorySkills.size() > 0)
  1068. {
  1069. skills.push_back (obligatorySkills[0]);
  1070. }
  1071. else if(none.size() && canLearnSkill()) //hero have free skill slot
  1072. {
  1073. skills.push_back(type->heroClass->chooseSecSkill(none, skillsInfo.rand)); //new skill
  1074. none.erase(skills.back());
  1075. }
  1076. else if(!basicAndAdv.empty())
  1077. {
  1078. skills.push_back(type->heroClass->chooseSecSkill(basicAndAdv, skillsInfo.rand)); //upgrade existing
  1079. basicAndAdv.erase(skills.back());
  1080. }
  1081. //second offered skill:
  1082. //1) upgrade existing
  1083. //2) give obligatory skill
  1084. //3) give any other new skill
  1085. if(!basicAndAdv.empty())
  1086. {
  1087. SecondarySkill s = type->heroClass->chooseSecSkill(basicAndAdv, skillsInfo.rand);//upgrade existing
  1088. skills.push_back(s);
  1089. basicAndAdv.erase(s);
  1090. }
  1091. else if (canLearnSkill() && obligatorySkills.size() > 1)
  1092. {
  1093. skills.push_back (obligatorySkills[1]);
  1094. }
  1095. else if(none.size() && canLearnSkill())
  1096. {
  1097. skills.push_back(type->heroClass->chooseSecSkill(none, skillsInfo.rand)); //give new skill
  1098. none.erase(skills.back());
  1099. }
  1100. if (skills.size() == 2) // Fix for #1868 to avoid changing logic (possibly causing bugs in process)
  1101. std::swap(skills[0], skills[1]);
  1102. return skills;
  1103. }
  1104. PrimarySkill::PrimarySkill CGHeroInstance::nextPrimarySkill() const
  1105. {
  1106. assert(gainsLevel());
  1107. int randomValue = cb->gameState()->getRandomGenerator().nextInt(99), pom = 0, primarySkill = 0;
  1108. const auto & skillChances = (level > 9) ? type->heroClass->primarySkillLowLevel : type->heroClass->primarySkillHighLevel;
  1109. for(; primarySkill < GameConstants::PRIMARY_SKILLS; ++primarySkill)
  1110. {
  1111. pom += skillChances[primarySkill];
  1112. if(randomValue < pom)
  1113. {
  1114. break;
  1115. }
  1116. }
  1117. logGlobal->traceStream() << "The hero gets the primary skill " << primarySkill << " with a probability of " << randomValue << "%.";
  1118. return static_cast<PrimarySkill::PrimarySkill>(primarySkill);
  1119. }
  1120. boost::optional<SecondarySkill> CGHeroInstance::nextSecondarySkill() const
  1121. {
  1122. assert(gainsLevel());
  1123. boost::optional<SecondarySkill> chosenSecondarySkill;
  1124. const auto proposedSecondarySkills = getLevelUpProposedSecondarySkills();
  1125. if(!proposedSecondarySkills.empty())
  1126. {
  1127. std::vector<SecondarySkill> learnedSecondarySkills;
  1128. for(auto secondarySkill : proposedSecondarySkills)
  1129. {
  1130. if(getSecSkillLevel(secondarySkill) > 0)
  1131. {
  1132. learnedSecondarySkills.push_back(secondarySkill);
  1133. }
  1134. }
  1135. auto & rand = cb->gameState()->getRandomGenerator();
  1136. if(learnedSecondarySkills.empty())
  1137. {
  1138. // there are only new skills to learn, so choose anyone of them
  1139. chosenSecondarySkill = *RandomGeneratorUtil::nextItem(proposedSecondarySkills, rand);
  1140. }
  1141. else
  1142. {
  1143. // preferably upgrade a already learned secondary skill
  1144. chosenSecondarySkill = *RandomGeneratorUtil::nextItem(learnedSecondarySkills, rand);
  1145. }
  1146. }
  1147. return chosenSecondarySkill;
  1148. }
  1149. void CGHeroInstance::setPrimarySkill(PrimarySkill::PrimarySkill primarySkill, si64 value, ui8 abs)
  1150. {
  1151. if(primarySkill < PrimarySkill::EXPERIENCE)
  1152. {
  1153. Bonus * skill = getBonusLocalFirst(Selector::type(Bonus::PRIMARY_SKILL)
  1154. .And(Selector::subtype(primarySkill))
  1155. .And(Selector::sourceType(Bonus::HERO_BASE_SKILL)));
  1156. assert(skill);
  1157. if(abs)
  1158. {
  1159. skill->val = value;
  1160. }
  1161. else
  1162. {
  1163. skill->val += value;
  1164. }
  1165. }
  1166. else if(primarySkill == PrimarySkill::EXPERIENCE)
  1167. {
  1168. if(abs)
  1169. {
  1170. exp = value;
  1171. }
  1172. else
  1173. {
  1174. exp += value;
  1175. }
  1176. }
  1177. }
  1178. bool CGHeroInstance::gainsLevel() const
  1179. {
  1180. return exp >= VLC->heroh->reqExp(level+1);
  1181. }
  1182. void CGHeroInstance::levelUp(std::vector<SecondarySkill> skills)
  1183. {
  1184. ++level;
  1185. //deterministic secondary skills
  1186. skillsInfo.magicSchoolCounter = (skillsInfo.magicSchoolCounter + 1) % maxlevelsToMagicSchool();
  1187. skillsInfo.wisdomCounter = (skillsInfo.wisdomCounter + 1) % maxlevelsToWisdom();
  1188. if(vstd::contains(skills, SecondarySkill::WISDOM))
  1189. {
  1190. skillsInfo.resetWisdomCounter();
  1191. }
  1192. SecondarySkill spellSchools[] = {
  1193. SecondarySkill::FIRE_MAGIC, SecondarySkill::AIR_MAGIC, SecondarySkill::WATER_MAGIC, SecondarySkill::EARTH_MAGIC};
  1194. for(auto skill : spellSchools)
  1195. {
  1196. if(vstd::contains(skills, skill))
  1197. {
  1198. skillsInfo.resetMagicSchoolCounter();
  1199. break;
  1200. }
  1201. }
  1202. //specialty
  1203. Updatespecialty();
  1204. }
  1205. void CGHeroInstance::levelUpAutomatically()
  1206. {
  1207. while(gainsLevel())
  1208. {
  1209. const auto primarySkill = nextPrimarySkill();
  1210. setPrimarySkill(primarySkill, 1, false);
  1211. auto proposedSecondarySkills = getLevelUpProposedSecondarySkills();
  1212. const auto secondarySkill = nextSecondarySkill();
  1213. if(secondarySkill)
  1214. {
  1215. setSecSkillLevel(*secondarySkill, 1, false);
  1216. }
  1217. //TODO why has the secondary skills to be passed to the method?
  1218. levelUp(proposedSecondarySkills);
  1219. }
  1220. }