CGHeroInstance.cpp 41 KB

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