CGHeroInstance.cpp 50 KB

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