CGHeroInstance.cpp 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559
  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(CRandomGenerator & rand, HeroTypeID SUBID)
  221. {
  222. subID = SUBID.getNum();
  223. initHero(rand);
  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(CRandomGenerator & rand)
  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(rand);
  270. }
  271. assert(validTypes());
  272. if(exp == 0xffffffff)
  273. {
  274. initExp(rand);
  275. }
  276. else
  277. {
  278. levelUpAutomatically(rand);
  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(CRandomGenerator & rand, 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 = rand.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 = rand.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. CGHeroInstance::SecondarySkillsInfo::SecondarySkillsInfo()
  412. {
  413. rand.setSeed(0);
  414. magicSchoolCounter = 1;
  415. wisdomCounter = 1;
  416. }
  417. void CGHeroInstance::SecondarySkillsInfo::resetMagicSchoolCounter()
  418. {
  419. magicSchoolCounter = 1;
  420. }
  421. void CGHeroInstance::SecondarySkillsInfo::resetWisdomCounter()
  422. {
  423. wisdomCounter = 1;
  424. }
  425. void CGHeroInstance::initObj(CRandomGenerator & rand)
  426. {
  427. blockVisit = true;
  428. auto hs = new HeroSpecial();
  429. hs->setNodeType(CBonusSystemNode::SPECIALTY);
  430. attachTo(hs); //do we ever need to detach it?
  431. if(!type)
  432. initHero(rand); //TODO: set up everything for prison before specialties are configured
  433. skillsInfo.rand.setSeed(rand.nextInt());
  434. skillsInfo.resetMagicSchoolCounter();
  435. skillsInfo.resetWisdomCounter();
  436. if (ID != Obj::PRISON)
  437. {
  438. auto customApp = VLC->objtypeh->getHandlerFor(ID, type->heroClass->id)->getOverride(cb->gameState()->getTile(visitablePos())->terType, this);
  439. if (customApp)
  440. appearance = customApp.get();
  441. }
  442. for(const auto &spec : type->spec) //TODO: unfity with bonus system
  443. {
  444. auto bonus = new Bonus();
  445. bonus->val = spec.val;
  446. bonus->sid = id.getNum(); //from the hero, specialty has no unique id
  447. bonus->duration = Bonus::PERMANENT;
  448. bonus->source = Bonus::HERO_SPECIAL;
  449. switch (spec.type)
  450. {
  451. case 1:// creature specialty
  452. {
  453. hs->growsWithLevel = true;
  454. const CCreature &specCreature = *VLC->creh->creatures[spec.additionalinfo]; //creature in which we have specialty
  455. //int creLevel = specCreature.level;
  456. //if(!creLevel)
  457. //{
  458. // if(spec.additionalinfo == 146)
  459. // creLevel = 5; //treat ballista as 5-level
  460. // else
  461. // {
  462. // logGlobal->warnStream() << "Warning: unknown level of " << specCreature.namePl;
  463. // continue;
  464. // }
  465. //}
  466. //bonus->additionalInfo = spec.additionalinfo; //creature id, should not be used again - this works only with limiter
  467. bonus->limiter.reset(new CCreatureTypeLimiter (specCreature, true)); //with upgrades
  468. bonus->type = Bonus::PRIMARY_SKILL;
  469. bonus->valType = Bonus::ADDITIVE_VALUE;
  470. bonus->subtype = PrimarySkill::ATTACK;
  471. hs->addNewBonus(bonus);
  472. bonus = new Bonus(*bonus);
  473. bonus->subtype = PrimarySkill::DEFENSE;
  474. hs->addNewBonus(bonus);
  475. //values will be calculated later
  476. bonus = new Bonus(*bonus);
  477. bonus->type = Bonus::STACKS_SPEED;
  478. bonus->val = 1; //+1 speed
  479. hs->addNewBonus(bonus);
  480. }
  481. break;
  482. case 2://secondary skill
  483. hs->growsWithLevel = true;
  484. bonus->type = Bonus::SPECIAL_SECONDARY_SKILL; //needs to be recalculated with level, based on this value
  485. bonus->valType = Bonus::BASE_NUMBER; // to receive nonzero value
  486. bonus->subtype = spec.subtype; //skill id
  487. bonus->val = spec.val; //value per level, in percent
  488. hs->addNewBonus(bonus);
  489. bonus = new Bonus(*bonus);
  490. switch (spec.additionalinfo)
  491. {
  492. case 0: //normal
  493. bonus->valType = Bonus::PERCENT_TO_BASE;
  494. break;
  495. case 1: //when it's navigation or there's no 'base' at all
  496. bonus->valType = Bonus::PERCENT_TO_ALL;
  497. break;
  498. }
  499. bonus->type = Bonus::SECONDARY_SKILL_PREMY; //value will be calculated later
  500. hs->addNewBonus(bonus);
  501. break;
  502. case 3://spell damage bonus, level dependent but calculated elsewhere
  503. bonus->type = Bonus::SPECIAL_SPELL_LEV;
  504. bonus->subtype = spec.subtype;
  505. hs->addNewBonus(bonus);
  506. break;
  507. case 4://creature stat boost
  508. switch (spec.subtype)
  509. {
  510. case 1://attack
  511. bonus->type = Bonus::PRIMARY_SKILL;
  512. bonus->subtype = PrimarySkill::ATTACK;
  513. break;
  514. case 2://defense
  515. bonus->type = Bonus::PRIMARY_SKILL;
  516. bonus->subtype = PrimarySkill::DEFENSE;
  517. break;
  518. case 3:
  519. bonus->type = Bonus::CREATURE_DAMAGE;
  520. bonus->subtype = 0; //both min and max
  521. break;
  522. case 4://hp
  523. bonus->type = Bonus::STACK_HEALTH;
  524. break;
  525. case 5:
  526. bonus->type = Bonus::STACKS_SPEED;
  527. break;
  528. default:
  529. continue;
  530. }
  531. bonus->additionalInfo = spec.additionalinfo; //creature id
  532. bonus->valType = Bonus::ADDITIVE_VALUE;
  533. bonus->limiter.reset(new CCreatureTypeLimiter (*VLC->creh->creatures[spec.additionalinfo], true));
  534. hs->addNewBonus(bonus);
  535. break;
  536. case 5://spell damage bonus in percent
  537. bonus->type = Bonus::SPECIFIC_SPELL_DAMAGE;
  538. bonus->valType = Bonus::BASE_NUMBER; // current spell system is screwed
  539. bonus->subtype = spec.subtype; //spell id
  540. hs->addNewBonus(bonus);
  541. break;
  542. case 6://damage bonus for bless (Adela)
  543. bonus->type = Bonus::SPECIAL_BLESS_DAMAGE;
  544. bonus->subtype = spec.subtype; //spell id if you ever wanted to use it otherwise
  545. bonus->additionalInfo = spec.additionalinfo; //damage factor
  546. hs->addNewBonus(bonus);
  547. break;
  548. case 7://maxed mastery for spell
  549. bonus->type = Bonus::MAXED_SPELL;
  550. bonus->subtype = spec.subtype; //spell i
  551. hs->addNewBonus(bonus);
  552. break;
  553. case 8://peculiar spells - enchantments
  554. bonus->type = Bonus::SPECIAL_PECULIAR_ENCHANT;
  555. bonus->subtype = spec.subtype; //spell id
  556. bonus->additionalInfo = spec.additionalinfo;//0, 1 for Coronius
  557. hs->addNewBonus(bonus);
  558. break;
  559. case 9://upgrade creatures
  560. {
  561. const auto &creatures = VLC->creh->creatures;
  562. bonus->type = Bonus::SPECIAL_UPGRADE;
  563. bonus->subtype = spec.subtype; //base id
  564. bonus->additionalInfo = spec.additionalinfo; //target id
  565. hs->addNewBonus(bonus);
  566. bonus = new Bonus(*bonus);
  567. for(auto cre_id : creatures[spec.subtype]->upgrades)
  568. {
  569. bonus->subtype = cre_id; //propagate for regular upgrades of base creature
  570. hs->addNewBonus(bonus);
  571. bonus = new Bonus(*bonus);
  572. }
  573. vstd::clear_pointer(bonus);
  574. break;
  575. }
  576. case 10://resource generation
  577. bonus->type = Bonus::GENERATE_RESOURCE;
  578. bonus->subtype = spec.subtype;
  579. hs->addNewBonus(bonus);
  580. break;
  581. case 11://starting skill with mastery (Adrienne)
  582. setSecSkillLevel(SecondarySkill(spec.val), spec.additionalinfo, true);
  583. break;
  584. case 12://army speed
  585. bonus->type = Bonus::STACKS_SPEED;
  586. hs->addNewBonus(bonus);
  587. break;
  588. case 13://Dragon bonuses (Mutare)
  589. bonus->type = Bonus::PRIMARY_SKILL;
  590. bonus->valType = Bonus::ADDITIVE_VALUE;
  591. switch (spec.subtype)
  592. {
  593. case 1:
  594. bonus->subtype = PrimarySkill::ATTACK;
  595. break;
  596. case 2:
  597. bonus->subtype = PrimarySkill::DEFENSE;
  598. break;
  599. }
  600. bonus->limiter.reset(new HasAnotherBonusLimiter(Bonus::DRAGON_NATURE));
  601. hs->addNewBonus(bonus);
  602. break;
  603. default:
  604. logGlobal->warnStream() << "Unexpected hero specialty " << type;
  605. }
  606. }
  607. specialty.push_back(hs); //will it work?
  608. for (auto hs2 : type->specialty) //copy active (probably growing) bonuses from hero prootype to hero object
  609. {
  610. auto hs = new HeroSpecial();
  611. attachTo(hs); //do we ever need to detach it?
  612. hs->setNodeType(CBonusSystemNode::SPECIALTY);
  613. for (auto bonus : hs2.bonuses)
  614. {
  615. hs->addNewBonus (bonus);
  616. }
  617. hs->growsWithLevel = hs2.growsWithLevel;
  618. specialty.push_back(hs); //will it work?
  619. }
  620. //initialize bonuses
  621. recreateSecondarySkillsBonuses();
  622. Updatespecialty();
  623. mana = manaLimit(); //after all bonuses are taken into account, make sure this line is the last one
  624. type->name = name;
  625. }
  626. void CGHeroInstance::Updatespecialty() //TODO: calculate special value of bonuses on-the-fly?
  627. {
  628. for (auto hs : specialty)
  629. {
  630. if (hs->growsWithLevel)
  631. {
  632. //const auto &creatures = VLC->creh->creatures;
  633. for(Bonus * b : hs->getBonusList())
  634. {
  635. switch (b->type)
  636. {
  637. case Bonus::SECONDARY_SKILL_PREMY:
  638. b->val = (hs->valOfBonuses(Bonus::SPECIAL_SECONDARY_SKILL, b->subtype) * level);
  639. break; //use only hero skills as bonuses to avoid feedback loop
  640. case Bonus::PRIMARY_SKILL: //for creatures, that is
  641. {
  642. const CCreature * cre = nullptr;
  643. int creLevel = 0;
  644. if (auto creatureLimiter = std::dynamic_pointer_cast<CCreatureTypeLimiter>(b->limiter)) //TODO: more general eveluation of bonuses?
  645. {
  646. cre = creatureLimiter->creature;
  647. creLevel = cre->level;
  648. if (!creLevel)
  649. {
  650. creLevel = 5; //treat ballista as tier 5
  651. }
  652. }
  653. else //no creature found, can't calculate value
  654. {
  655. logGlobal->warnStream() << "Primary skill specialty growth supported only with creature type limiters";
  656. break;
  657. }
  658. double primSkillModifier = (int)(level / creLevel) / 20.0;
  659. int param;
  660. switch (b->subtype)
  661. {
  662. case PrimarySkill::ATTACK:
  663. param = cre->Attack();
  664. break;
  665. case PrimarySkill::DEFENSE:
  666. param = cre->Defense();
  667. break;
  668. default:
  669. continue;
  670. }
  671. b->val = ceil(param * (1 + primSkillModifier)) - param; //yep, overcomplicated but matches original
  672. break;
  673. }
  674. }
  675. }
  676. }
  677. }
  678. }
  679. void CGHeroInstance::recreateSecondarySkillsBonuses()
  680. {
  681. auto secondarySkillsBonuses = getBonuses(Selector::sourceType(Bonus::SECONDARY_SKILL));
  682. for(auto bonus : *secondarySkillsBonuses)
  683. removeBonus(bonus);
  684. for(auto skill_info : secSkills)
  685. updateSkill(SecondarySkill(skill_info.first), skill_info.second);
  686. }
  687. void CGHeroInstance::updateSkill(SecondarySkill which, int val)
  688. {
  689. if(which == SecondarySkill::LEADERSHIP || which == SecondarySkill::LUCK)
  690. { //luck-> VLC->generaltexth->arraytxt[73+luckSkill]; VLC->generaltexth->arraytxt[104+moraleSkill]
  691. bool luck = which == SecondarySkill::LUCK;
  692. Bonus::BonusType type[] = {Bonus::MORALE, Bonus::LUCK};
  693. Bonus *b = getBonusLocalFirst(Selector::type(type[luck]).And(Selector::sourceType(Bonus::SECONDARY_SKILL)));
  694. if(!b)
  695. {
  696. b = new Bonus(Bonus::PERMANENT, type[luck], Bonus::SECONDARY_SKILL, +val, which, which, Bonus::BASE_NUMBER);
  697. addNewBonus(b);
  698. }
  699. else
  700. b->val = +val;
  701. }
  702. else if(which == SecondarySkill::DIPLOMACY) //surrender discount: 20% per level
  703. {
  704. if(Bonus *b = getBonusLocalFirst(Selector::type(Bonus::SURRENDER_DISCOUNT).And(Selector::sourceType(Bonus::SECONDARY_SKILL))))
  705. b->val = +val;
  706. else
  707. addNewBonus(new Bonus(Bonus::PERMANENT, Bonus::SURRENDER_DISCOUNT, Bonus::SECONDARY_SKILL, val * 20, which));
  708. }
  709. int skillVal = 0;
  710. switch (which)
  711. {
  712. case SecondarySkill::ARCHERY:
  713. switch (val)
  714. {
  715. case 1:
  716. skillVal = 10; break;
  717. case 2:
  718. skillVal = 25; break;
  719. case 3:
  720. skillVal = 50; break;
  721. }
  722. break;
  723. case SecondarySkill::LOGISTICS:
  724. skillVal = 10 * val; break;
  725. case SecondarySkill::NAVIGATION:
  726. skillVal = 50 * val; break;
  727. case SecondarySkill::MYSTICISM:
  728. skillVal = val; break;
  729. case SecondarySkill::EAGLE_EYE:
  730. skillVal = 30 + 10 * val; break;
  731. case SecondarySkill::NECROMANCY:
  732. skillVal = 10 * val; break;
  733. case SecondarySkill::LEARNING:
  734. skillVal = 5 * val; break;
  735. case SecondarySkill::OFFENCE:
  736. skillVal = 10 * val; break;
  737. case SecondarySkill::ARMORER:
  738. skillVal = 5 * val; break;
  739. case SecondarySkill::INTELLIGENCE:
  740. skillVal = 25 << (val-1); break;
  741. case SecondarySkill::SORCERY:
  742. skillVal = 5 * val; break;
  743. case SecondarySkill::RESISTANCE:
  744. skillVal = 5 << (val-1); break;
  745. case SecondarySkill::FIRST_AID:
  746. skillVal = 25 + 25*val; break;
  747. case SecondarySkill::ESTATES:
  748. skillVal = 125 << (val-1); break;
  749. }
  750. Bonus::ValueType skillValType = skillVal ? Bonus::BASE_NUMBER : Bonus::INDEPENDENT_MIN;
  751. if(Bonus * b = getExportedBonusList().getFirst(Selector::typeSubtype(Bonus::SECONDARY_SKILL_PREMY, which)
  752. .And(Selector::sourceType(Bonus::SECONDARY_SKILL)))) //only local hero bonus
  753. {
  754. b->val = skillVal;
  755. b->valType = skillValType;
  756. }
  757. else
  758. {
  759. auto bonus = new Bonus(Bonus::PERMANENT, Bonus::SECONDARY_SKILL_PREMY, Bonus::SECONDARY_SKILL, skillVal, id.getNum(), which, skillValType);
  760. bonus->source = Bonus::SECONDARY_SKILL;
  761. addNewBonus(bonus);
  762. }
  763. CBonusSystemNode::treeHasChanged();
  764. }
  765. void CGHeroInstance::setPropertyDer( ui8 what, ui32 val )
  766. {
  767. if(what == ObjProperty::PRIMARY_STACK_COUNT)
  768. setStackCount(SlotID(0), val);
  769. }
  770. double CGHeroInstance::getFightingStrength() const
  771. {
  772. return sqrt((1.0 + 0.05*getPrimSkillLevel(PrimarySkill::ATTACK)) * (1.0 + 0.05*getPrimSkillLevel(PrimarySkill::DEFENSE)));
  773. }
  774. double CGHeroInstance::getMagicStrength() const
  775. {
  776. return sqrt((1.0 + 0.05*getPrimSkillLevel(PrimarySkill::KNOWLEDGE)) * (1.0 + 0.05*getPrimSkillLevel(PrimarySkill::SPELL_POWER)));
  777. }
  778. double CGHeroInstance::getHeroStrength() const
  779. {
  780. return sqrt(pow(getFightingStrength(), 2.0) * pow(getMagicStrength(), 2.0));
  781. }
  782. ui64 CGHeroInstance::getTotalStrength() const
  783. {
  784. double ret = getFightingStrength() * getArmyStrength();
  785. return (ui64) ret;
  786. }
  787. TExpType CGHeroInstance::calculateXp(TExpType exp) const
  788. {
  789. return exp * (100 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::LEARNING))/100.0;
  790. }
  791. ui8 CGHeroInstance::getSpellSchoolLevel(const CSpell * spell, int *outSelectedSchool) const
  792. {
  793. si16 skill = -1; //skill level
  794. spell->forEachSchool([&, this](const SpellSchoolInfo & cnf, bool & stop)
  795. {
  796. 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)
  797. if(thisSchool > skill)
  798. {
  799. skill = thisSchool;
  800. if(outSelectedSchool)
  801. *outSelectedSchool = (ui8)cnf.id;
  802. }
  803. });
  804. vstd::amax(skill, valOfBonuses(Bonus::MAGIC_SCHOOL_SKILL, 0)); //any school bonus
  805. vstd::amax(skill, valOfBonuses(Bonus::SPELL, spell->id.toEnum())); //given by artifact or other effect
  806. vstd::amax(skill, 0); //in case we don't know any school
  807. vstd::amin(skill, 3);
  808. return skill;
  809. }
  810. ui32 CGHeroInstance::getSpellBonus(const CSpell * spell, ui32 base, const CStack * affectedStack) const
  811. {
  812. //applying sorcery secondary skill
  813. base *= (100.0 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::SORCERY)) / 100.0;
  814. base *= (100.0 + valOfBonuses(Bonus::SPELL_DAMAGE) + valOfBonuses(Bonus::SPECIFIC_SPELL_DAMAGE, spell->id.toEnum())) / 100.0;
  815. spell->forEachSchool([&base, this](const SpellSchoolInfo & cnf, bool & stop)
  816. {
  817. base *= (100.0 + valOfBonuses(cnf.damagePremyBonus)) / 100.0;
  818. stop = true; //only bonus from one school is used
  819. });
  820. if (affectedStack && affectedStack->getCreature()->level) //Hero specials like Solmyr, Deemer
  821. base *= (100. + ((valOfBonuses(Bonus::SPECIAL_SPELL_LEV, spell->id.toEnum()) * level) / affectedStack->getCreature()->level)) / 100.0;
  822. return base;
  823. }
  824. int CGHeroInstance::getEffectLevel(const CSpell * spell) const
  825. {
  826. if(hasBonusOfType(Bonus::MAXED_SPELL, spell->id))
  827. return 3;//todo: recheck specialty from where this bonus is. possible bug
  828. else
  829. return getSpellSchoolLevel(spell);
  830. }
  831. int CGHeroInstance::getEffectPower(const CSpell * spell) const
  832. {
  833. return getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  834. }
  835. int CGHeroInstance::getEnchantPower(const CSpell * spell) const
  836. {
  837. return getPrimSkillLevel(PrimarySkill::SPELL_POWER) + valOfBonuses(Bonus::SPELL_DURATION);
  838. }
  839. int CGHeroInstance::getEffectValue(const CSpell * spell) const
  840. {
  841. return 0;
  842. }
  843. const PlayerColor CGHeroInstance::getOwner() const
  844. {
  845. return tempOwner;
  846. }
  847. bool CGHeroInstance::canCastThisSpell(const CSpell * spell) const
  848. {
  849. if(nullptr == getArt(ArtifactPosition::SPELLBOOK))
  850. return false;
  851. const bool isAllowed = IObjectInterface::cb->isAllowed(0, spell->id);
  852. const bool inSpellBook = vstd::contains(spells, spell->id);
  853. const bool specificBonus = hasBonusOfType(Bonus::SPELL, spell->id);
  854. bool schoolBonus = false;
  855. spell->forEachSchool([this, &schoolBonus](const SpellSchoolInfo & cnf, bool & stop)
  856. {
  857. if(hasBonusOfType(cnf.knoledgeBonus))
  858. {
  859. schoolBonus = stop = true;
  860. }
  861. });
  862. const bool levelBonus = hasBonusOfType(Bonus::SPELLS_OF_LEVEL, spell->level);
  863. if(spell->isSpecialSpell())
  864. {
  865. if(inSpellBook)
  866. {//hero has this spell in spellbook
  867. logGlobal->errorStream() << "Special spell " << spell->name << "in spellbook.";
  868. }
  869. return specificBonus;
  870. }
  871. else if(!isAllowed)
  872. {
  873. if(inSpellBook)
  874. {//hero has this spell in spellbook
  875. logGlobal->errorStream() << "Banned spell " << spell->name << " in spellbook.";
  876. }
  877. return specificBonus || schoolBonus || levelBonus;
  878. }
  879. else
  880. {
  881. return inSpellBook || schoolBonus || specificBonus || levelBonus;
  882. }
  883. }
  884. /**
  885. * Calculates what creatures and how many to be raised from a battle.
  886. * @param battleResult The results of the battle.
  887. * @return Returns a pair with the first value indicating the ID of the creature
  888. * type and second value the amount. Both values are returned as -1 if necromancy
  889. * could not be applied.
  890. */
  891. CStackBasicDescriptor CGHeroInstance::calculateNecromancy (const BattleResult &battleResult) const
  892. {
  893. const ui8 necromancyLevel = getSecSkillLevel(SecondarySkill::NECROMANCY);
  894. // Hero knows necromancy or has Necromancer Cloak
  895. if (necromancyLevel > 0 || hasBonusOfType(Bonus::IMPROVED_NECROMANCY))
  896. {
  897. double necromancySkill = valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::NECROMANCY)/100.0;
  898. vstd::amin(necromancySkill, 1.0); //it's impossible to raise more creatures than all...
  899. const std::map<ui32,si32> &casualties = battleResult.casualties[!battleResult.winner];
  900. ui32 raisedUnits = 0;
  901. // Figure out what to raise and how many.
  902. const CreatureID creatureTypes[] = {CreatureID::SKELETON, CreatureID::WALKING_DEAD, CreatureID::WIGHTS, CreatureID::LICHES};
  903. const bool improvedNecromancy = hasBonusOfType(Bonus::IMPROVED_NECROMANCY);
  904. const CCreature *raisedUnitType = VLC->creh->creatures[creatureTypes[improvedNecromancy ? necromancyLevel : 0]];
  905. const ui32 raisedUnitHP = raisedUnitType->valOfBonuses(Bonus::STACK_HEALTH);
  906. //calculate creatures raised from each defeated stack
  907. for (auto & casualtie : casualties)
  908. {
  909. // Get lost enemy hit points convertible to units.
  910. CCreature * c = VLC->creh->creatures[casualtie.first];
  911. const ui32 raisedHP = c->valOfBonuses(Bonus::STACK_HEALTH) * casualtie.second * necromancySkill;
  912. raisedUnits += std::min<ui32>(raisedHP / raisedUnitHP, casualtie.second * necromancySkill); //limit to % of HP and % of original stack count
  913. }
  914. // Make room for new units.
  915. SlotID slot = getSlotFor(raisedUnitType->idNumber);
  916. if (slot == SlotID())
  917. {
  918. // If there's no room for unit, try it's upgraded version 2/3rds the size.
  919. raisedUnitType = VLC->creh->creatures[*raisedUnitType->upgrades.begin()];
  920. raisedUnits = (raisedUnits*2)/3;
  921. slot = getSlotFor(raisedUnitType->idNumber);
  922. }
  923. if (raisedUnits <= 0)
  924. raisedUnits = 1;
  925. return CStackBasicDescriptor(raisedUnitType->idNumber, raisedUnits);
  926. }
  927. return CStackBasicDescriptor();
  928. }
  929. /**
  930. * Show the necromancy dialog with information about units raised.
  931. * @param raisedStack Pair where the first element represents ID of the raised creature
  932. * and the second element the amount.
  933. */
  934. void CGHeroInstance::showNecromancyDialog(const CStackBasicDescriptor &raisedStack, CRandomGenerator & rand) const
  935. {
  936. InfoWindow iw;
  937. iw.soundID = soundBase::pickup01 + rand.nextInt(6);
  938. iw.player = tempOwner;
  939. iw.components.push_back(Component(raisedStack));
  940. if (raisedStack.count > 1) // Practicing the dark arts of necromancy, ... (plural)
  941. {
  942. iw.text.addTxt(MetaString::GENERAL_TXT, 145);
  943. iw.text.addReplacement(raisedStack.count);
  944. }
  945. else // Practicing the dark arts of necromancy, ... (singular)
  946. {
  947. iw.text.addTxt(MetaString::GENERAL_TXT, 146);
  948. }
  949. iw.text.addReplacement(raisedStack);
  950. cb->showInfoDialog(&iw);
  951. }
  952. /*
  953. int3 CGHeroInstance::getSightCenter() const
  954. {
  955. return getPosition(false);
  956. }*/
  957. int CGHeroInstance::getSightRadius() const
  958. {
  959. return 5 + getSecSkillLevel(SecondarySkill::SCOUTING) + valOfBonuses(Bonus::SIGHT_RADIOUS); //default + scouting
  960. }
  961. si32 CGHeroInstance::manaRegain() const
  962. {
  963. if (hasBonusOfType(Bonus::FULL_MANA_REGENERATION))
  964. return manaLimit();
  965. return 1 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, 8) + valOfBonuses(Bonus::MANA_REGENERATION); //1 + Mysticism level
  966. }
  967. si32 CGHeroInstance::getManaNewTurn() const
  968. {
  969. if(visitedTown && visitedTown->hasBuilt(BuildingID::MAGES_GUILD_1))
  970. {
  971. //if hero starts turn in town with mage guild - restore all mana
  972. return std::max(mana, manaLimit());
  973. }
  974. si32 res = mana + manaRegain();
  975. res = std::min(res, manaLimit());
  976. res = std::max(res, mana);
  977. res = std::max(res, 0);
  978. return res;
  979. }
  980. // /**
  981. // * Places an artifact in hero's backpack. If it's a big artifact equips it
  982. // * or discards it if it cannot be equipped.
  983. // */
  984. // void CGHeroInstance::giveArtifact (ui32 aid) //use only for fixed artifacts
  985. // {
  986. // CArtifact * const artifact = VLC->arth->artifacts[aid]; //pointer to constant object
  987. // CArtifactInstance *ai = CArtifactInstance::createNewArtifactInstance(artifact);
  988. // ai->putAt(this, ai->firstAvailableSlot(this));
  989. // }
  990. int CGHeroInstance::getBoatType() const
  991. {
  992. switch(type->heroClass->getAlignment())
  993. {
  994. case EAlignment::GOOD:
  995. return 1;
  996. case EAlignment::EVIL:
  997. return 0;
  998. case EAlignment::NEUTRAL:
  999. return 2;
  1000. default:
  1001. throw std::runtime_error("Wrong alignment!");
  1002. }
  1003. }
  1004. void CGHeroInstance::getOutOffsets(std::vector<int3> &offsets) const
  1005. {
  1006. // FIXME: Offsets need to be fixed once we get rid of convertPosition
  1007. // Check issue 515 for details
  1008. offsets =
  1009. {
  1010. 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)
  1011. };
  1012. }
  1013. int CGHeroInstance::getSpellCost(const CSpell *sp) const
  1014. {
  1015. return sp->getCost(getSpellSchoolLevel(sp));
  1016. }
  1017. void CGHeroInstance::pushPrimSkill( PrimarySkill::PrimarySkill which, int val )
  1018. {
  1019. assert(!hasBonus(Selector::typeSubtype(Bonus::PRIMARY_SKILL, which)
  1020. .And(Selector::sourceType(Bonus::HERO_BASE_SKILL))));
  1021. addNewBonus(new Bonus(Bonus::PERMANENT, Bonus::PRIMARY_SKILL, Bonus::HERO_BASE_SKILL, val, id.getNum(), which));
  1022. }
  1023. EAlignment::EAlignment CGHeroInstance::getAlignment() const
  1024. {
  1025. return type->heroClass->getAlignment();
  1026. }
  1027. void CGHeroInstance::initExp(CRandomGenerator & rand)
  1028. {
  1029. exp = rand.nextInt(40, 89);
  1030. }
  1031. std::string CGHeroInstance::nodeName() const
  1032. {
  1033. return "Hero " + name;
  1034. }
  1035. void CGHeroInstance::putArtifact(ArtifactPosition pos, CArtifactInstance *art)
  1036. {
  1037. assert(!getArt(pos));
  1038. art->putAt(ArtifactLocation(this, pos));
  1039. }
  1040. void CGHeroInstance::putInBackpack(CArtifactInstance *art)
  1041. {
  1042. putArtifact(art->firstBackpackSlot(this), art);
  1043. }
  1044. bool CGHeroInstance::hasSpellbook() const
  1045. {
  1046. return getArt(ArtifactPosition::SPELLBOOK);
  1047. }
  1048. void CGHeroInstance::deserializationFix()
  1049. {
  1050. artDeserializationFix(this);
  1051. for (auto hs : specialty)
  1052. {
  1053. attachTo (hs);
  1054. }
  1055. }
  1056. CBonusSystemNode * CGHeroInstance::whereShouldBeAttached(CGameState *gs)
  1057. {
  1058. if(visitedTown)
  1059. {
  1060. if(inTownGarrison)
  1061. return visitedTown;
  1062. else
  1063. return &visitedTown->townAndVis;
  1064. }
  1065. else
  1066. return CArmedInstance::whereShouldBeAttached(gs);
  1067. }
  1068. int CGHeroInstance::movementPointsAfterEmbark(int MPsBefore, int basicCost, bool disembark /*= false*/, const TurnInfo * ti) const
  1069. {
  1070. bool localTi = false;
  1071. if(!ti)
  1072. {
  1073. localTi = true;
  1074. ti = new TurnInfo(this);
  1075. }
  1076. int mp1 = ti->getMaxMovePoints(disembark ? EPathfindingLayer::LAND : EPathfindingLayer::SAIL);
  1077. int mp2 = ti->getMaxMovePoints(disembark ? EPathfindingLayer::SAIL : EPathfindingLayer::LAND);
  1078. if(ti->hasBonusOfType(Bonus::FREE_SHIP_BOARDING))
  1079. return (MPsBefore - basicCost) * static_cast<double>(mp1) / mp2;
  1080. if(localTi)
  1081. delete ti;
  1082. return 0; //take all MPs otherwise
  1083. }
  1084. EDiggingStatus CGHeroInstance::diggingStatus() const
  1085. {
  1086. if(movement < maxMovePoints(true))
  1087. return EDiggingStatus::LACK_OF_MOVEMENT;
  1088. return cb->getTile(getPosition(false))->getDiggingStatus();
  1089. }
  1090. ArtBearer::ArtBearer CGHeroInstance::bearerType() const
  1091. {
  1092. return ArtBearer::HERO;
  1093. }
  1094. std::vector<SecondarySkill> CGHeroInstance::getLevelUpProposedSecondarySkills() const
  1095. {
  1096. std::vector<SecondarySkill> obligatorySkills; //hero is offered magic school or wisdom if possible
  1097. if (!skillsInfo.wisdomCounter)
  1098. {
  1099. if (cb->isAllowed(2, SecondarySkill::WISDOM) && !getSecSkillLevel(SecondarySkill::WISDOM))
  1100. obligatorySkills.push_back(SecondarySkill::WISDOM);
  1101. }
  1102. if (!skillsInfo.magicSchoolCounter)
  1103. {
  1104. std::vector<SecondarySkill> ss =
  1105. {
  1106. SecondarySkill::FIRE_MAGIC, SecondarySkill::AIR_MAGIC, SecondarySkill::WATER_MAGIC, SecondarySkill::EARTH_MAGIC
  1107. };
  1108. std::shuffle(ss.begin(), ss.end(), skillsInfo.rand.getStdGenerator());
  1109. for (auto skill : ss)
  1110. {
  1111. if (cb->isAllowed(2, skill) && !getSecSkillLevel(skill)) //only schools hero doesn't know yet
  1112. {
  1113. obligatorySkills.push_back(skill);
  1114. break; //only one
  1115. }
  1116. }
  1117. }
  1118. std::vector<SecondarySkill> skills;
  1119. //picking sec. skills for choice
  1120. std::set<SecondarySkill> basicAndAdv, expert, none;
  1121. for(int i=0;i<GameConstants::SKILL_QUANTITY;i++)
  1122. if (cb->isAllowed(2,i))
  1123. none.insert(SecondarySkill(i));
  1124. for(auto & elem : secSkills)
  1125. {
  1126. if(elem.second < SecSkillLevel::EXPERT)
  1127. basicAndAdv.insert(elem.first);
  1128. else
  1129. expert.insert(elem.first);
  1130. none.erase(elem.first);
  1131. }
  1132. for (auto s : obligatorySkills) //don't duplicate them
  1133. {
  1134. none.erase (s);
  1135. basicAndAdv.erase (s);
  1136. expert.erase (s);
  1137. }
  1138. //first offered skill:
  1139. // 1) give obligatory skill
  1140. // 2) give any other new skill
  1141. // 3) upgrade existing
  1142. if (canLearnSkill() && obligatorySkills.size() > 0)
  1143. {
  1144. skills.push_back (obligatorySkills[0]);
  1145. }
  1146. else if(none.size() && canLearnSkill()) //hero have free skill slot
  1147. {
  1148. skills.push_back(type->heroClass->chooseSecSkill(none, skillsInfo.rand)); //new skill
  1149. none.erase(skills.back());
  1150. }
  1151. else if(!basicAndAdv.empty())
  1152. {
  1153. skills.push_back(type->heroClass->chooseSecSkill(basicAndAdv, skillsInfo.rand)); //upgrade existing
  1154. basicAndAdv.erase(skills.back());
  1155. }
  1156. //second offered skill:
  1157. //1) upgrade existing
  1158. //2) give obligatory skill
  1159. //3) give any other new skill
  1160. if(!basicAndAdv.empty())
  1161. {
  1162. SecondarySkill s = type->heroClass->chooseSecSkill(basicAndAdv, skillsInfo.rand);//upgrade existing
  1163. skills.push_back(s);
  1164. basicAndAdv.erase(s);
  1165. }
  1166. else if (canLearnSkill() && obligatorySkills.size() > 1)
  1167. {
  1168. skills.push_back (obligatorySkills[1]);
  1169. }
  1170. else if(none.size() && canLearnSkill())
  1171. {
  1172. skills.push_back(type->heroClass->chooseSecSkill(none, skillsInfo.rand)); //give new skill
  1173. none.erase(skills.back());
  1174. }
  1175. if (skills.size() == 2) // Fix for #1868 to avoid changing logic (possibly causing bugs in process)
  1176. std::swap(skills[0], skills[1]);
  1177. return skills;
  1178. }
  1179. PrimarySkill::PrimarySkill CGHeroInstance::nextPrimarySkill(CRandomGenerator & rand) const
  1180. {
  1181. assert(gainsLevel());
  1182. int randomValue = rand.nextInt(99), pom = 0, primarySkill = 0;
  1183. const auto & skillChances = (level > 9) ? type->heroClass->primarySkillLowLevel : type->heroClass->primarySkillHighLevel;
  1184. for(; primarySkill < GameConstants::PRIMARY_SKILLS; ++primarySkill)
  1185. {
  1186. pom += skillChances[primarySkill];
  1187. if(randomValue < pom)
  1188. {
  1189. break;
  1190. }
  1191. }
  1192. logGlobal->traceStream() << "The hero gets the primary skill " << primarySkill << " with a probability of " << randomValue << "%.";
  1193. return static_cast<PrimarySkill::PrimarySkill>(primarySkill);
  1194. }
  1195. boost::optional<SecondarySkill> CGHeroInstance::nextSecondarySkill(CRandomGenerator & rand) const
  1196. {
  1197. assert(gainsLevel());
  1198. boost::optional<SecondarySkill> chosenSecondarySkill;
  1199. const auto proposedSecondarySkills = getLevelUpProposedSecondarySkills();
  1200. if(!proposedSecondarySkills.empty())
  1201. {
  1202. std::vector<SecondarySkill> learnedSecondarySkills;
  1203. for(auto secondarySkill : proposedSecondarySkills)
  1204. {
  1205. if(getSecSkillLevel(secondarySkill) > 0)
  1206. {
  1207. learnedSecondarySkills.push_back(secondarySkill);
  1208. }
  1209. }
  1210. if(learnedSecondarySkills.empty())
  1211. {
  1212. // there are only new skills to learn, so choose anyone of them
  1213. chosenSecondarySkill = *RandomGeneratorUtil::nextItem(proposedSecondarySkills, rand);
  1214. }
  1215. else
  1216. {
  1217. // preferably upgrade a already learned secondary skill
  1218. chosenSecondarySkill = *RandomGeneratorUtil::nextItem(learnedSecondarySkills, rand);
  1219. }
  1220. }
  1221. return chosenSecondarySkill;
  1222. }
  1223. void CGHeroInstance::setPrimarySkill(PrimarySkill::PrimarySkill primarySkill, si64 value, ui8 abs)
  1224. {
  1225. if(primarySkill < PrimarySkill::EXPERIENCE)
  1226. {
  1227. Bonus * skill = getBonusLocalFirst(Selector::type(Bonus::PRIMARY_SKILL)
  1228. .And(Selector::subtype(primarySkill))
  1229. .And(Selector::sourceType(Bonus::HERO_BASE_SKILL)));
  1230. assert(skill);
  1231. if(abs)
  1232. {
  1233. skill->val = value;
  1234. }
  1235. else
  1236. {
  1237. skill->val += value;
  1238. }
  1239. CBonusSystemNode::treeHasChanged();
  1240. }
  1241. else if(primarySkill == PrimarySkill::EXPERIENCE)
  1242. {
  1243. if(abs)
  1244. {
  1245. exp = value;
  1246. }
  1247. else
  1248. {
  1249. exp += value;
  1250. }
  1251. }
  1252. }
  1253. bool CGHeroInstance::gainsLevel() const
  1254. {
  1255. return exp >= VLC->heroh->reqExp(level+1);
  1256. }
  1257. void CGHeroInstance::levelUp(std::vector<SecondarySkill> skills)
  1258. {
  1259. ++level;
  1260. //deterministic secondary skills
  1261. skillsInfo.magicSchoolCounter = (skillsInfo.magicSchoolCounter + 1) % maxlevelsToMagicSchool();
  1262. skillsInfo.wisdomCounter = (skillsInfo.wisdomCounter + 1) % maxlevelsToWisdom();
  1263. if(vstd::contains(skills, SecondarySkill::WISDOM))
  1264. {
  1265. skillsInfo.resetWisdomCounter();
  1266. }
  1267. SecondarySkill spellSchools[] = {
  1268. SecondarySkill::FIRE_MAGIC, SecondarySkill::AIR_MAGIC, SecondarySkill::WATER_MAGIC, SecondarySkill::EARTH_MAGIC};
  1269. for(auto skill : spellSchools)
  1270. {
  1271. if(vstd::contains(skills, skill))
  1272. {
  1273. skillsInfo.resetMagicSchoolCounter();
  1274. break;
  1275. }
  1276. }
  1277. //specialty
  1278. Updatespecialty();
  1279. }
  1280. void CGHeroInstance::levelUpAutomatically(CRandomGenerator & rand)
  1281. {
  1282. while(gainsLevel())
  1283. {
  1284. const auto primarySkill = nextPrimarySkill(rand);
  1285. setPrimarySkill(primarySkill, 1, false);
  1286. auto proposedSecondarySkills = getLevelUpProposedSecondarySkills();
  1287. const auto secondarySkill = nextSecondarySkill(rand);
  1288. if(secondarySkill)
  1289. {
  1290. setSecSkillLevel(*secondarySkill, 1, false);
  1291. }
  1292. //TODO why has the secondary skills to be passed to the method?
  1293. levelUp(proposedSecondarySkills);
  1294. }
  1295. }
  1296. bool CGHeroInstance::hasVisions(const CGObjectInstance * target, const int subtype) const
  1297. {
  1298. //VISIONS spell support
  1299. const std::string cached = boost::to_string((boost::format("type_%d__subtype_%d") % Bonus::VISIONS % subtype));
  1300. const int visionsMultiplier = valOfBonuses(Selector::typeSubtype(Bonus::VISIONS,subtype), cached);
  1301. int visionsRange = visionsMultiplier * getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  1302. if (visionsMultiplier > 0)
  1303. vstd::amax(visionsRange, 3); //minimum range is 3 tiles, but only if VISIONS bonus present
  1304. const int distance = target->pos.dist2d(getPosition(false));
  1305. //logGlobal->debug(boost::to_string(boost::format("Visions: dist %d, mult %d, range %d") % distance % visionsMultiplier % visionsRange));
  1306. return (distance < visionsRange) && (target->pos.z == pos.z);
  1307. }
  1308. void CGHeroInstance::serializeJsonOptions(JsonSerializeFormat& handler)
  1309. {
  1310. serializeJsonOwner(handler);
  1311. if(handler.saving)
  1312. {
  1313. if(type)
  1314. {
  1315. handler.serializeString("type", type->identifier);
  1316. }
  1317. else
  1318. {
  1319. auto temp = VLC->heroh->heroes[subID]->identifier;
  1320. handler.serializeString("type", temp);
  1321. }
  1322. }
  1323. else
  1324. {
  1325. if(ID == Obj::HERO || ID == Obj::PRISON)
  1326. {
  1327. std::string typeName;
  1328. handler.serializeString("type", typeName);
  1329. auto rawId = VLC->modh->identifiers.getIdentifier("core", "hero", typeName);
  1330. if(rawId)
  1331. subID = rawId.get();
  1332. else
  1333. subID = 0; //fallback to Orrin, throw error instead?
  1334. }
  1335. }
  1336. CCreatureSet::serializeJson(handler, "army");
  1337. {
  1338. auto artifacts = handler.enterStruct("artifacts");
  1339. if(handler.saving)
  1340. CArtifactSet::writeJson(handler.getCurrent());
  1341. else
  1342. CArtifactSet::readJson(handler.getCurrent());
  1343. }
  1344. }
  1345. bool CGHeroInstance::isMissionCritical() const
  1346. {
  1347. for(const TriggeredEvent & event : IObjectInterface::cb->getMapHeader()->triggeredEvents)
  1348. {
  1349. if(event.trigger.test([&](const EventCondition & condition)
  1350. {
  1351. if (condition.condition == EventCondition::CONTROL && condition.object)
  1352. {
  1353. auto hero = dynamic_cast<const CGHeroInstance*>(condition.object);
  1354. return (hero != this);
  1355. }
  1356. else if(condition.condition == EventCondition::IS_HUMAN)
  1357. {
  1358. return true;
  1359. }
  1360. return false;
  1361. }))
  1362. {
  1363. return true;
  1364. }
  1365. }
  1366. return false;
  1367. }