2
0

CGHeroInstance.cpp 50 KB

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