CGHeroInstance.cpp 39 KB

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