CGHeroInstance.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383
  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. #define TRY_SCHOOL(schoolName, schoolMechanicsId, schoolOutId) \
  775. if(spell-> schoolName) \
  776. { \
  777. int thisSchool = std::max<int>(getSecSkillLevel( \
  778. SecondarySkill(14 + (schoolMechanicsId))), \
  779. valOfBonuses(Bonus::MAGIC_SCHOOL_SKILL, 1 << (schoolMechanicsId))); \
  780. if(thisSchool > skill) \
  781. { \
  782. skill = thisSchool; \
  783. if(outSelectedSchool) \
  784. *outSelectedSchool = schoolOutId; \
  785. } \
  786. }
  787. TRY_SCHOOL(fire, 0, 1)
  788. TRY_SCHOOL(air, 1, 0)
  789. TRY_SCHOOL(water, 2, 2)
  790. TRY_SCHOOL(earth, 3, 3)
  791. #undef TRY_SCHOOL
  792. vstd::amax(skill, valOfBonuses(Bonus::MAGIC_SCHOOL_SKILL, 0)); //any school bonus
  793. vstd::amax(skill, valOfBonuses(Bonus::SPELL, spell->id.toEnum())); //given by artifact or other effect
  794. if (hasBonusOfType(Bonus::MAXED_SPELL, spell->id))//hero specialty (Daremyth, Melodia)
  795. skill = 3;
  796. assert(skill >= 0 && skill <= 3);
  797. return skill;
  798. }
  799. bool CGHeroInstance::canCastThisSpell(const CSpell * spell) const
  800. {
  801. if(!getArt(ArtifactPosition::SPELLBOOK)) //if hero has no spellbook
  802. return false;
  803. if (spell->isSpecialSpell())
  804. {
  805. if (vstd::contains(spells, spell->id))
  806. {//hero has this spell in spellbook
  807. logGlobal->errorStream() << "Special spell in spellbook "<<spell->name;
  808. }
  809. if (hasBonusOfType(Bonus::SPELL, spell->id))
  810. return true;
  811. return false;
  812. }
  813. else
  814. {
  815. if(vstd::contains(spells, spell->id) //hero has this spell in spellbook
  816. || (spell->air && hasBonusOfType(Bonus::AIR_SPELLS)) // this is air spell and hero can cast all air spells
  817. || (spell->fire && hasBonusOfType(Bonus::FIRE_SPELLS)) // this is fire spell and hero can cast all fire spells
  818. || (spell->water && hasBonusOfType(Bonus::WATER_SPELLS)) // this is water spell and hero can cast all water spells
  819. || (spell->earth && hasBonusOfType(Bonus::EARTH_SPELLS)) // this is earth spell and hero can cast all earth spells
  820. || hasBonusOfType(Bonus::SPELL, spell->id)
  821. || hasBonusOfType(Bonus::SPELLS_OF_LEVEL, spell->level)
  822. )
  823. return true;
  824. return false;
  825. }
  826. }
  827. /**
  828. * Calculates what creatures and how many to be raised from a battle.
  829. * @param battleResult The results of the battle.
  830. * @return Returns a pair with the first value indicating the ID of the creature
  831. * type and second value the amount. Both values are returned as -1 if necromancy
  832. * could not be applied.
  833. */
  834. CStackBasicDescriptor CGHeroInstance::calculateNecromancy (const BattleResult &battleResult) const
  835. {
  836. const ui8 necromancyLevel = getSecSkillLevel(SecondarySkill::NECROMANCY);
  837. // Hero knows necromancy or has Necromancer Cloak
  838. if (necromancyLevel > 0 || hasBonusOfType(Bonus::IMPROVED_NECROMANCY))
  839. {
  840. double necromancySkill = valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::NECROMANCY)/100.0;
  841. vstd::amin(necromancySkill, 1.0); //it's impossible to raise more creatures than all...
  842. const std::map<ui32,si32> &casualties = battleResult.casualties[!battleResult.winner];
  843. ui32 raisedUnits = 0;
  844. // Figure out what to raise and how many.
  845. const CreatureID creatureTypes[] = {CreatureID::SKELETON, CreatureID::WALKING_DEAD, CreatureID::WIGHTS, CreatureID::LICHES};
  846. const bool improvedNecromancy = hasBonusOfType(Bonus::IMPROVED_NECROMANCY);
  847. const CCreature *raisedUnitType = VLC->creh->creatures[creatureTypes[improvedNecromancy ? necromancyLevel : 0]];
  848. const ui32 raisedUnitHP = raisedUnitType->valOfBonuses(Bonus::STACK_HEALTH);
  849. //calculate creatures raised from each defeated stack
  850. for (auto & casualtie : casualties)
  851. {
  852. // Get lost enemy hit points convertible to units.
  853. CCreature * c = VLC->creh->creatures[casualtie.first];
  854. const ui32 raisedHP = c->valOfBonuses(Bonus::STACK_HEALTH) * casualtie.second * necromancySkill;
  855. raisedUnits += std::min<ui32>(raisedHP / raisedUnitHP, casualtie.second * necromancySkill); //limit to % of HP and % of original stack count
  856. }
  857. // Make room for new units.
  858. SlotID slot = getSlotFor(raisedUnitType->idNumber);
  859. if (slot == SlotID())
  860. {
  861. // If there's no room for unit, try it's upgraded version 2/3rds the size.
  862. raisedUnitType = VLC->creh->creatures[*raisedUnitType->upgrades.begin()];
  863. raisedUnits = (raisedUnits*2)/3;
  864. slot = getSlotFor(raisedUnitType->idNumber);
  865. }
  866. if (raisedUnits <= 0)
  867. raisedUnits = 1;
  868. return CStackBasicDescriptor(raisedUnitType->idNumber, raisedUnits);
  869. }
  870. return CStackBasicDescriptor();
  871. }
  872. /**
  873. * Show the necromancy dialog with information about units raised.
  874. * @param raisedStack Pair where the first element represents ID of the raised creature
  875. * and the second element the amount.
  876. */
  877. void CGHeroInstance::showNecromancyDialog(const CStackBasicDescriptor &raisedStack) const
  878. {
  879. InfoWindow iw;
  880. iw.soundID = soundBase::pickup01 + cb->gameState()->getRandomGenerator().nextInt(6);
  881. iw.player = tempOwner;
  882. iw.components.push_back(Component(raisedStack));
  883. if (raisedStack.count > 1) // Practicing the dark arts of necromancy, ... (plural)
  884. {
  885. iw.text.addTxt(MetaString::GENERAL_TXT, 145);
  886. iw.text.addReplacement(raisedStack.count);
  887. }
  888. else // Practicing the dark arts of necromancy, ... (singular)
  889. {
  890. iw.text.addTxt(MetaString::GENERAL_TXT, 146);
  891. }
  892. iw.text.addReplacement(raisedStack);
  893. cb->showInfoDialog(&iw);
  894. }
  895. /*
  896. int3 CGHeroInstance::getSightCenter() const
  897. {
  898. return getPosition(false);
  899. }*/
  900. int CGHeroInstance::getSightRadious() const
  901. {
  902. return 5 + getSecSkillLevel(SecondarySkill::SCOUTING) + valOfBonuses(Bonus::SIGHT_RADIOUS); //default + scouting
  903. }
  904. si32 CGHeroInstance::manaRegain() const
  905. {
  906. if (hasBonusOfType(Bonus::FULL_MANA_REGENERATION))
  907. return manaLimit();
  908. return 1 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, 8) + valOfBonuses(Bonus::MANA_REGENERATION); //1 + Mysticism level
  909. }
  910. // /**
  911. // * Places an artifact in hero's backpack. If it's a big artifact equips it
  912. // * or discards it if it cannot be equipped.
  913. // */
  914. // void CGHeroInstance::giveArtifact (ui32 aid) //use only for fixed artifacts
  915. // {
  916. // CArtifact * const artifact = VLC->arth->artifacts[aid]; //pointer to constant object
  917. // CArtifactInstance *ai = CArtifactInstance::createNewArtifactInstance(artifact);
  918. // ai->putAt(this, ai->firstAvailableSlot(this));
  919. // }
  920. int CGHeroInstance::getBoatType() const
  921. {
  922. switch(type->heroClass->getAlignment())
  923. {
  924. case EAlignment::GOOD:
  925. return 1;
  926. case EAlignment::EVIL:
  927. return 0;
  928. case EAlignment::NEUTRAL:
  929. return 2;
  930. default:
  931. throw std::runtime_error("Wrong alignment!");
  932. }
  933. }
  934. void CGHeroInstance::getOutOffsets(std::vector<int3> &offsets) const
  935. {
  936. offsets =
  937. {
  938. 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)
  939. };
  940. }
  941. int CGHeroInstance::getSpellCost(const CSpell *sp) const
  942. {
  943. return sp->getCost(getSpellSchoolLevel(sp));
  944. }
  945. void CGHeroInstance::pushPrimSkill( PrimarySkill::PrimarySkill which, int val )
  946. {
  947. assert(!hasBonus(Selector::typeSubtype(Bonus::PRIMARY_SKILL, which)
  948. .And(Selector::sourceType(Bonus::HERO_BASE_SKILL))));
  949. addNewBonus(new Bonus(Bonus::PERMANENT, Bonus::PRIMARY_SKILL, Bonus::HERO_BASE_SKILL, val, id.getNum(), which));
  950. }
  951. EAlignment::EAlignment CGHeroInstance::getAlignment() const
  952. {
  953. return type->heroClass->getAlignment();
  954. }
  955. void CGHeroInstance::initExp()
  956. {
  957. exp = cb->gameState()->getRandomGenerator().nextInt(40, 89);
  958. }
  959. std::string CGHeroInstance::nodeName() const
  960. {
  961. return "Hero " + name;
  962. }
  963. void CGHeroInstance::putArtifact(ArtifactPosition pos, CArtifactInstance *art)
  964. {
  965. assert(!getArt(pos));
  966. art->putAt(ArtifactLocation(this, pos));
  967. }
  968. void CGHeroInstance::putInBackpack(CArtifactInstance *art)
  969. {
  970. putArtifact(art->firstBackpackSlot(this), art);
  971. }
  972. bool CGHeroInstance::hasSpellbook() const
  973. {
  974. return getArt(ArtifactPosition::SPELLBOOK);
  975. }
  976. void CGHeroInstance::deserializationFix()
  977. {
  978. artDeserializationFix(this);
  979. for (auto hs : specialty)
  980. {
  981. attachTo (hs);
  982. }
  983. }
  984. CBonusSystemNode * CGHeroInstance::whereShouldBeAttached(CGameState *gs)
  985. {
  986. if(visitedTown)
  987. {
  988. if(inTownGarrison)
  989. return visitedTown;
  990. else
  991. return &visitedTown->townAndVis;
  992. }
  993. else
  994. return CArmedInstance::whereShouldBeAttached(gs);
  995. }
  996. int CGHeroInstance::movementPointsAfterEmbark(int MPsBefore, int basicCost, bool disembark /*= false*/) const
  997. {
  998. if(hasBonusOfType(Bonus::FREE_SHIP_BOARDING))
  999. return (MPsBefore - basicCost) * static_cast<double>(maxMovePoints(disembark)) / maxMovePoints(!disembark);
  1000. return 0; //take all MPs otherwise
  1001. }
  1002. CGHeroInstance::ECanDig CGHeroInstance::diggingStatus() const
  1003. {
  1004. if(movement < maxMovePoints(true))
  1005. return LACK_OF_MOVEMENT;
  1006. else if(cb->getTile(getPosition(false))->terType == ETerrainType::WATER)
  1007. return WRONG_TERRAIN;
  1008. else
  1009. {
  1010. const TerrainTile *t = cb->getTile(getPosition());
  1011. //TODO look for hole
  1012. //CGI->mh->getTerrainDescr(h->getPosition(false), hlp, false);
  1013. if(/*hlp.length() || */t->blockingObjects.size() > 1)
  1014. return TILE_OCCUPIED;
  1015. else
  1016. return CAN_DIG;
  1017. }
  1018. }
  1019. ArtBearer::ArtBearer CGHeroInstance::bearerType() const
  1020. {
  1021. return ArtBearer::HERO;
  1022. }
  1023. std::vector<SecondarySkill> CGHeroInstance::getLevelUpProposedSecondarySkills() const
  1024. {
  1025. std::vector<SecondarySkill> obligatorySkills; //hero is offered magic school or wisdom if possible
  1026. if (!skillsInfo.wisdomCounter)
  1027. {
  1028. if (cb->isAllowed(2, SecondarySkill::WISDOM) && !getSecSkillLevel(SecondarySkill::WISDOM))
  1029. obligatorySkills.push_back(SecondarySkill::WISDOM);
  1030. }
  1031. if (!skillsInfo.magicSchoolCounter)
  1032. {
  1033. std::vector<SecondarySkill> ss =
  1034. {
  1035. SecondarySkill::FIRE_MAGIC, SecondarySkill::AIR_MAGIC, SecondarySkill::WATER_MAGIC, SecondarySkill::EARTH_MAGIC
  1036. };
  1037. std::shuffle(ss.begin(), ss.end(), skillsInfo.rand.getStdGenerator());
  1038. for (auto skill : ss)
  1039. {
  1040. if (cb->isAllowed(2, skill) && !getSecSkillLevel(skill)) //only schools hero doesn't know yet
  1041. {
  1042. obligatorySkills.push_back(skill);
  1043. break; //only one
  1044. }
  1045. }
  1046. }
  1047. std::vector<SecondarySkill> skills;
  1048. //picking sec. skills for choice
  1049. std::set<SecondarySkill> basicAndAdv, expert, none;
  1050. for(int i=0;i<GameConstants::SKILL_QUANTITY;i++)
  1051. if (cb->isAllowed(2,i))
  1052. none.insert(SecondarySkill(i));
  1053. for(auto & elem : secSkills)
  1054. {
  1055. if(elem.second < SecSkillLevel::EXPERT)
  1056. basicAndAdv.insert(elem.first);
  1057. else
  1058. expert.insert(elem.first);
  1059. none.erase(elem.first);
  1060. }
  1061. for (auto s : obligatorySkills) //don't duplicate them
  1062. {
  1063. none.erase (s);
  1064. basicAndAdv.erase (s);
  1065. expert.erase (s);
  1066. }
  1067. //first offered skill:
  1068. // 1) give obligatory skill
  1069. // 2) give any other new skill
  1070. // 3) upgrade existing
  1071. if (canLearnSkill() && obligatorySkills.size() > 0)
  1072. {
  1073. skills.push_back (obligatorySkills[0]);
  1074. }
  1075. else if(none.size() && canLearnSkill()) //hero have free skill slot
  1076. {
  1077. skills.push_back(type->heroClass->chooseSecSkill(none, skillsInfo.rand)); //new skill
  1078. none.erase(skills.back());
  1079. }
  1080. else if(!basicAndAdv.empty())
  1081. {
  1082. skills.push_back(type->heroClass->chooseSecSkill(basicAndAdv, skillsInfo.rand)); //upgrade existing
  1083. basicAndAdv.erase(skills.back());
  1084. }
  1085. //second offered skill:
  1086. //1) upgrade existing
  1087. //2) give obligatory skill
  1088. //3) give any other new skill
  1089. if(!basicAndAdv.empty())
  1090. {
  1091. SecondarySkill s = type->heroClass->chooseSecSkill(basicAndAdv, skillsInfo.rand);//upgrade existing
  1092. skills.push_back(s);
  1093. basicAndAdv.erase(s);
  1094. }
  1095. else if (canLearnSkill() && obligatorySkills.size() > 1)
  1096. {
  1097. skills.push_back (obligatorySkills[1]);
  1098. }
  1099. else if(none.size() && canLearnSkill())
  1100. {
  1101. skills.push_back(type->heroClass->chooseSecSkill(none, skillsInfo.rand)); //give new skill
  1102. none.erase(skills.back());
  1103. }
  1104. if (skills.size() == 2) // Fix for #1868 to avoid changing logic (possibly causing bugs in process)
  1105. std::swap(skills[0], skills[1]);
  1106. return skills;
  1107. }
  1108. PrimarySkill::PrimarySkill CGHeroInstance::nextPrimarySkill() const
  1109. {
  1110. assert(gainsLevel());
  1111. int randomValue = cb->gameState()->getRandomGenerator().nextInt(99), pom = 0, primarySkill = 0;
  1112. const auto & skillChances = (level > 9) ? type->heroClass->primarySkillLowLevel : type->heroClass->primarySkillHighLevel;
  1113. for(; primarySkill < GameConstants::PRIMARY_SKILLS; ++primarySkill)
  1114. {
  1115. pom += skillChances[primarySkill];
  1116. if(randomValue < pom)
  1117. {
  1118. break;
  1119. }
  1120. }
  1121. logGlobal->traceStream() << "The hero gets the primary skill " << primarySkill << " with a probability of " << randomValue << "%.";
  1122. return static_cast<PrimarySkill::PrimarySkill>(primarySkill);
  1123. }
  1124. boost::optional<SecondarySkill> CGHeroInstance::nextSecondarySkill() const
  1125. {
  1126. assert(gainsLevel());
  1127. boost::optional<SecondarySkill> chosenSecondarySkill;
  1128. const auto proposedSecondarySkills = getLevelUpProposedSecondarySkills();
  1129. if(!proposedSecondarySkills.empty())
  1130. {
  1131. std::vector<SecondarySkill> learnedSecondarySkills;
  1132. for(auto secondarySkill : proposedSecondarySkills)
  1133. {
  1134. if(getSecSkillLevel(secondarySkill) > 0)
  1135. {
  1136. learnedSecondarySkills.push_back(secondarySkill);
  1137. }
  1138. }
  1139. auto & rand = cb->gameState()->getRandomGenerator();
  1140. if(learnedSecondarySkills.empty())
  1141. {
  1142. // there are only new skills to learn, so choose anyone of them
  1143. chosenSecondarySkill = *RandomGeneratorUtil::nextItem(proposedSecondarySkills, rand);
  1144. }
  1145. else
  1146. {
  1147. // preferably upgrade a already learned secondary skill
  1148. chosenSecondarySkill = *RandomGeneratorUtil::nextItem(learnedSecondarySkills, rand);
  1149. }
  1150. }
  1151. return chosenSecondarySkill;
  1152. }
  1153. void CGHeroInstance::setPrimarySkill(PrimarySkill::PrimarySkill primarySkill, si64 value, ui8 abs)
  1154. {
  1155. if(primarySkill < PrimarySkill::EXPERIENCE)
  1156. {
  1157. Bonus * skill = getBonusLocalFirst(Selector::type(Bonus::PRIMARY_SKILL)
  1158. .And(Selector::subtype(primarySkill))
  1159. .And(Selector::sourceType(Bonus::HERO_BASE_SKILL)));
  1160. assert(skill);
  1161. if(abs)
  1162. {
  1163. skill->val = value;
  1164. }
  1165. else
  1166. {
  1167. skill->val += value;
  1168. }
  1169. }
  1170. else if(primarySkill == PrimarySkill::EXPERIENCE)
  1171. {
  1172. if(abs)
  1173. {
  1174. exp = value;
  1175. }
  1176. else
  1177. {
  1178. exp += value;
  1179. }
  1180. }
  1181. }
  1182. bool CGHeroInstance::gainsLevel() const
  1183. {
  1184. return exp >= VLC->heroh->reqExp(level+1);
  1185. }
  1186. void CGHeroInstance::levelUp(std::vector<SecondarySkill> skills)
  1187. {
  1188. ++level;
  1189. //deterministic secondary skills
  1190. skillsInfo.magicSchoolCounter = (skillsInfo.magicSchoolCounter + 1) % maxlevelsToMagicSchool();
  1191. skillsInfo.wisdomCounter = (skillsInfo.wisdomCounter + 1) % maxlevelsToWisdom();
  1192. if(vstd::contains(skills, SecondarySkill::WISDOM))
  1193. {
  1194. skillsInfo.resetWisdomCounter();
  1195. }
  1196. SecondarySkill spellSchools[] = {
  1197. SecondarySkill::FIRE_MAGIC, SecondarySkill::AIR_MAGIC, SecondarySkill::WATER_MAGIC, SecondarySkill::EARTH_MAGIC};
  1198. for(auto skill : spellSchools)
  1199. {
  1200. if(vstd::contains(skills, skill))
  1201. {
  1202. skillsInfo.resetMagicSchoolCounter();
  1203. break;
  1204. }
  1205. }
  1206. //specialty
  1207. Updatespecialty();
  1208. }
  1209. void CGHeroInstance::levelUpAutomatically()
  1210. {
  1211. while(gainsLevel())
  1212. {
  1213. const auto primarySkill = nextPrimarySkill();
  1214. setPrimarySkill(primarySkill, 1, false);
  1215. auto proposedSecondarySkills = getLevelUpProposedSecondarySkills();
  1216. const auto secondarySkill = nextSecondarySkill();
  1217. if(secondarySkill)
  1218. {
  1219. setSecSkillLevel(*secondarySkill, 1, false);
  1220. }
  1221. //TODO why has the secondary skills to be passed to the method?
  1222. levelUp(proposedSecondarySkills);
  1223. }
  1224. }