CGHeroInstance.cpp 50 KB

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