CGHeroInstance.cpp 43 KB

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