CGHeroInstance.cpp 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662
  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 <vcmi/ServerCallback.h>
  13. #include <vcmi/spells/Spell.h>
  14. #include "../NetPacks.h"
  15. #include "../CGeneralTextHandler.h"
  16. #include "../CHeroHandler.h"
  17. #include "../TerrainHandler.h"
  18. #include "../RoadHandler.h"
  19. #include "../CModHandler.h"
  20. #include "../CSoundBase.h"
  21. #include "../spells/CSpellHandler.h"
  22. #include "../CSkillHandler.h"
  23. #include "CObjectClassesHandler.h"
  24. #include "../IGameCallback.h"
  25. #include "../CGameState.h"
  26. #include "../CCreatureHandler.h"
  27. #include "../CTownHandler.h"
  28. #include "../mapping/CMap.h"
  29. #include "CGTownInstance.h"
  30. #include "../serializer/JsonSerializeFormat.h"
  31. #include "../StringConstants.h"
  32. #include "../battle/Unit.h"
  33. VCMI_LIB_NAMESPACE_BEGIN
  34. ///helpers
  35. static void showInfoDialog(const PlayerColor playerID, const ui32 txtID, const ui16 soundID = 0)
  36. {
  37. InfoWindow iw;
  38. iw.soundID = soundID;
  39. iw.player = playerID;
  40. iw.text.addTxt(MetaString::ADVOB_TXT,txtID);
  41. IObjectInterface::cb->sendAndApply(&iw);
  42. }
  43. static void showInfoDialog(const CGHeroInstance* h, const ui32 txtID, const ui16 soundID = 0)
  44. {
  45. const PlayerColor playerID = h->getOwner();
  46. showInfoDialog(playerID,txtID,soundID);
  47. }
  48. static int lowestSpeed(const CGHeroInstance * chi)
  49. {
  50. static const CSelector selectorSTACKS_SPEED = Selector::type()(Bonus::STACKS_SPEED);
  51. static const std::string keySTACKS_SPEED = "type_" + std::to_string((si32)Bonus::STACKS_SPEED);
  52. if(!chi->stacksCount())
  53. {
  54. if(chi->commander && chi->commander->alive)
  55. {
  56. return chi->commander->valOfBonuses(selectorSTACKS_SPEED, keySTACKS_SPEED);
  57. }
  58. logGlobal->error("Hero %d (%s) has no army!", chi->id.getNum(), chi->getNameTranslated());
  59. return 20;
  60. }
  61. auto i = chi->Slots().begin();
  62. //TODO? should speed modifiers (eg from artifacts) affect hero movement?
  63. int ret = (i++)->second->valOfBonuses(selectorSTACKS_SPEED, keySTACKS_SPEED);
  64. for(; i != chi->Slots().end(); i++)
  65. ret = std::min(ret, i->second->valOfBonuses(selectorSTACKS_SPEED, keySTACKS_SPEED));
  66. return ret;
  67. }
  68. ui32 CGHeroInstance::getTileCost(const TerrainTile & dest, const TerrainTile & from, const TurnInfo * ti) const
  69. {
  70. int64_t ret = GameConstants::BASE_MOVEMENT_COST;
  71. //if there is road both on dest and src tiles - use road movement cost
  72. if(dest.roadType->getId() != Road::NO_ROAD && from.roadType->getId() != Road::NO_ROAD)
  73. {
  74. ret = std::max(dest.roadType->movementCost, from.roadType->movementCost);
  75. }
  76. else if(ti->nativeTerrain != from.terType->getId() &&//the terrain is not native
  77. ti->nativeTerrain != ETerrainId::ANY_TERRAIN && //no special creature bonus
  78. !ti->hasBonusOfType(Bonus::NO_TERRAIN_PENALTY, from.terType->getIndex())) //no special movement bonus
  79. {
  80. ret = VLC->heroh->terrCosts[from.terType->getId()];
  81. ret -= ti->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::PATHFINDING);
  82. if(ret < GameConstants::BASE_MOVEMENT_COST)
  83. ret = GameConstants::BASE_MOVEMENT_COST;
  84. }
  85. return (ui32)ret;
  86. }
  87. TerrainId CGHeroInstance::getNativeTerrain() const
  88. {
  89. // NOTE: in H3 neutral stacks will ignore terrain penalty only if placed as topmost stack(s) in hero army.
  90. // This is clearly bug in H3 however intended behaviour is not clear.
  91. // Current VCMI behaviour will ignore neutrals in calculations so army in VCMI
  92. // will always have best penalty without any influence from player-defined stacks order
  93. // and army that consist solely from neutral will always be considered to be on native terrain
  94. TerrainId nativeTerrain = ETerrainId::ANY_TERRAIN;
  95. for(auto stack : stacks)
  96. {
  97. TerrainId stackNativeTerrain = stack.second->type->getNativeTerrain(); //consider terrain bonuses e.g. Lodestar.
  98. if(stackNativeTerrain == ETerrainId::NONE)
  99. continue;
  100. if(nativeTerrain == ETerrainId::ANY_TERRAIN)
  101. nativeTerrain = stackNativeTerrain;
  102. else if(nativeTerrain != stackNativeTerrain)
  103. return ETerrainId::NONE;
  104. }
  105. return nativeTerrain;
  106. }
  107. BattleField CGHeroInstance::getBattlefield() const
  108. {
  109. return BattleField::NONE;
  110. }
  111. ui8 CGHeroInstance::getSecSkillLevel(SecondarySkill skill) const
  112. {
  113. for(auto & elem : secSkills)
  114. if(elem.first == skill)
  115. return elem.second;
  116. return 0;
  117. }
  118. void CGHeroInstance::setSecSkillLevel(SecondarySkill which, int val, bool abs)
  119. {
  120. if(getSecSkillLevel(which) == 0)
  121. {
  122. secSkills.push_back(std::pair<SecondarySkill,ui8>(which, val));
  123. updateSkillBonus(which, val);
  124. }
  125. else
  126. {
  127. for (auto & elem : secSkills)
  128. {
  129. if(elem.first == which)
  130. {
  131. if(abs)
  132. elem.second = val;
  133. else
  134. elem.second += val;
  135. if(elem.second > 3) //workaround to avoid crashes when same sec skill is given more than once
  136. {
  137. logGlobal->warn("Skill %d increased over limit! Decreasing to Expert.", static_cast<int>(which.toEnum()));
  138. elem.second = 3;
  139. }
  140. updateSkillBonus(which, elem.second); //when we know final value
  141. }
  142. }
  143. }
  144. }
  145. int3 CGHeroInstance::convertToVisitablePos(const int3 & position) const
  146. {
  147. return position - getVisitableOffset();
  148. }
  149. int3 CGHeroInstance::convertFromVisitablePos(const int3 & position) const
  150. {
  151. return position + getVisitableOffset();
  152. }
  153. bool CGHeroInstance::canLearnSkill() const
  154. {
  155. return secSkills.size() < GameConstants::SKILL_PER_HERO;
  156. }
  157. bool CGHeroInstance::canLearnSkill(SecondarySkill which) const
  158. {
  159. if ( !canLearnSkill())
  160. return false;
  161. if (!cb->isAllowed(2, which))
  162. return false;
  163. if (getSecSkillLevel(which) > 0)
  164. return false;
  165. if (type->heroClass->secSkillProbability[which] == 0)
  166. return false;
  167. return true;
  168. }
  169. int CGHeroInstance::maxMovePoints(bool onLand) const
  170. {
  171. TurnInfo ti(this);
  172. return maxMovePointsCached(onLand, &ti);
  173. }
  174. int CGHeroInstance::maxMovePointsCached(bool onLand, const TurnInfo * ti) const
  175. {
  176. int base;
  177. if(onLand)
  178. {
  179. // used function is f(x) = 66.6x + 1300, rounded to second digit, where x is lowest speed in army
  180. static const int baseSpeed = 1300; // base speed from creature with 0 speed
  181. int armySpeed = lowestSpeed(this) * 20 / 3;
  182. base = armySpeed * 10 + baseSpeed; // separate *10 is intentional to receive same rounding as in h3
  183. vstd::abetween(base, 1500, 2000); // base speed is limited by these values
  184. }
  185. else
  186. {
  187. base = 1500; //on water base movement is always 1500 (speed of army doesn't matter)
  188. }
  189. const Bonus::BonusType bt = onLand ? Bonus::LAND_MOVEMENT : Bonus::SEA_MOVEMENT;
  190. const int bonus = ti->valOfBonuses(Bonus::MOVEMENT) + ti->valOfBonuses(bt);
  191. const int subtype = onLand ? SecondarySkill::LOGISTICS : SecondarySkill::NAVIGATION;
  192. const double modifier = ti->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, subtype) / 100.0;
  193. return int(base * (1 + modifier)) + bonus;
  194. }
  195. CGHeroInstance::CGHeroInstance()
  196. : IBoatGenerator(this)
  197. {
  198. setNodeType(HERO);
  199. ID = Obj::HERO;
  200. tacticFormationEnabled = inTownGarrison = false;
  201. mana = UNINITIALIZED_MANA;
  202. movement = UNINITIALIZED_MOVEMENT;
  203. portrait = UNINITIALIZED_PORTRAIT;
  204. isStanding = true;
  205. moveDir = 4;
  206. level = 1;
  207. exp = 0xffffffff;
  208. visitedTown = nullptr;
  209. type = nullptr;
  210. boat = nullptr;
  211. commander = nullptr;
  212. sex = 0xff;
  213. secSkills.push_back(std::make_pair(SecondarySkill::DEFAULT, -1));
  214. }
  215. PlayerColor CGHeroInstance::getOwner() const
  216. {
  217. return tempOwner;
  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->objects[subID];
  228. portrait = type->imageIndex;
  229. CGObjectInstance::setType(ID, type->heroClass->getIndex()); // 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->objects[subID];
  238. if (ID == Obj::HERO)
  239. appearance = VLC->objtypeh->getHandlerFor(Obj::HERO, type->heroClass->getIndex())->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 (sex == 0xFF)//sex is default
  263. sex = type->sex;
  264. setFormation(false);
  265. if (!stacksCount()) //standard army//initial army
  266. {
  267. initArmy(rand);
  268. }
  269. assert(validTypes());
  270. if (patrol.patrolling)
  271. patrol.initialPos = visitablePos();
  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", getNameTranslated(), 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", getNameTranslated(), slot.toEnum(), aid.toEnum());
  328. }
  329. else
  330. {
  331. logGlobal->error("Hero %s has invalid war machine in initial army", getNameTranslated());
  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)//free hero slot
  370. {
  371. //update hero parameters
  372. SetMovePoints smp;
  373. smp.hid = id;
  374. smp.val = maxMovePoints (true); //TODO: hota prison on water?
  375. cb->setMovePoints (&smp);
  376. cb->setManaPoints (id, manaLimit());
  377. cb->setObjProperty(id, ObjProperty::ID, Obj::HERO); //set ID to 34
  378. cb->giveHero(id,h->tempOwner); //recreates def and adds hero to player
  379. txt_id = 102;
  380. }
  381. else //already 8 wandering heroes
  382. {
  383. txt_id = 103;
  384. }
  385. showInfoDialog(h,txt_id);
  386. }
  387. }
  388. std::string CGHeroInstance::getObjectName() const
  389. {
  390. if(ID != Obj::PRISON)
  391. {
  392. std::string hoverName = VLC->generaltexth->allTexts[15];
  393. boost::algorithm::replace_first(hoverName,"%s",getNameTranslated());
  394. boost::algorithm::replace_first(hoverName,"%s", type->heroClass->getNameTranslated());
  395. return hoverName;
  396. }
  397. else
  398. return VLC->objtypeh->getObjectName(ID, 0);
  399. }
  400. ui8 CGHeroInstance::maxlevelsToMagicSchool() const
  401. {
  402. return type->heroClass->isMagicHero() ? 3 : 4;
  403. }
  404. ui8 CGHeroInstance::maxlevelsToWisdom() const
  405. {
  406. return type->heroClass->isMagicHero() ? 3 : 6;
  407. }
  408. CGHeroInstance::SecondarySkillsInfo::SecondarySkillsInfo()
  409. {
  410. rand.setSeed(0);
  411. magicSchoolCounter = 1;
  412. wisdomCounter = 1;
  413. }
  414. void CGHeroInstance::SecondarySkillsInfo::resetMagicSchoolCounter()
  415. {
  416. magicSchoolCounter = 1;
  417. }
  418. void CGHeroInstance::SecondarySkillsInfo::resetWisdomCounter()
  419. {
  420. wisdomCounter = 1;
  421. }
  422. void CGHeroInstance::initObj(CRandomGenerator & rand)
  423. {
  424. blockVisit = true;
  425. if(!type)
  426. initHero(rand); //TODO: set up everything for prison before specialties are configured
  427. skillsInfo.rand.setSeed(rand.nextInt());
  428. skillsInfo.resetMagicSchoolCounter();
  429. skillsInfo.resetWisdomCounter();
  430. if (ID != Obj::PRISON)
  431. {
  432. auto terrain = cb->gameState()->getTile(visitablePos())->terType->getId();
  433. auto customApp = VLC->objtypeh->getHandlerFor(ID, type->heroClass->getIndex())->getOverride(terrain, this);
  434. if (customApp)
  435. appearance = customApp;
  436. }
  437. //copy active (probably growing) bonuses from hero prototype to hero object
  438. for(std::shared_ptr<Bonus> b : type->specialty)
  439. addNewBonus(b);
  440. //dito for old-style bonuses -> compatibility for old savegames
  441. for(SSpecialtyBonus & sb : type->specialtyDeprecated)
  442. for(std::shared_ptr<Bonus> b : sb.bonuses)
  443. addNewBonus(b);
  444. for(SSpecialtyInfo & spec : type->specDeprecated)
  445. for(std::shared_ptr<Bonus> b : SpecialtyInfoToBonuses(spec, type->getIndex()))
  446. addNewBonus(b);
  447. //initialize bonuses
  448. recreateSecondarySkillsBonuses();
  449. mana = manaLimit(); //after all bonuses are taken into account, make sure this line is the last one
  450. }
  451. void CGHeroInstance::recreateSecondarySkillsBonuses()
  452. {
  453. auto secondarySkillsBonuses = getBonuses(Selector::sourceType()(Bonus::SECONDARY_SKILL));
  454. for(auto bonus : *secondarySkillsBonuses)
  455. removeBonus(bonus);
  456. for(auto skill_info : secSkills)
  457. if(skill_info.second > 0)
  458. updateSkillBonus(SecondarySkill(skill_info.first), skill_info.second);
  459. }
  460. void CGHeroInstance::updateSkillBonus(SecondarySkill which, int val)
  461. {
  462. removeBonuses(Selector::source(Bonus::SECONDARY_SKILL, which));
  463. auto skillBonus = (*VLC->skillh)[which]->at(val).effects;
  464. for (auto b : skillBonus)
  465. addNewBonus(std::make_shared<Bonus>(*b));
  466. }
  467. void CGHeroInstance::setPropertyDer( ui8 what, ui32 val )
  468. {
  469. if(what == ObjProperty::PRIMARY_STACK_COUNT)
  470. setStackCount(SlotID(0), val);
  471. }
  472. double CGHeroInstance::getFightingStrength() const
  473. {
  474. return sqrt((1.0 + 0.05*getPrimSkillLevel(PrimarySkill::ATTACK)) * (1.0 + 0.05*getPrimSkillLevel(PrimarySkill::DEFENSE)));
  475. }
  476. double CGHeroInstance::getMagicStrength() const
  477. {
  478. return sqrt((1.0 + 0.05*getPrimSkillLevel(PrimarySkill::KNOWLEDGE)) * (1.0 + 0.05*getPrimSkillLevel(PrimarySkill::SPELL_POWER)));
  479. }
  480. double CGHeroInstance::getHeroStrength() const
  481. {
  482. return sqrt(pow(getFightingStrength(), 2.0) * pow(getMagicStrength(), 2.0));
  483. }
  484. ui64 CGHeroInstance::getTotalStrength() const
  485. {
  486. double ret = getFightingStrength() * getArmyStrength();
  487. return (ui64) ret;
  488. }
  489. TExpType CGHeroInstance::calculateXp(TExpType exp) const
  490. {
  491. return (TExpType)(exp * (100 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::LEARNING))/100.0);
  492. }
  493. int32_t CGHeroInstance::getCasterUnitId() const
  494. {
  495. return -1; //TODO: special value for attacker/defender hero
  496. }
  497. int32_t CGHeroInstance::getSpellSchoolLevel(const spells::Spell * spell, int32_t * outSelectedSchool) const
  498. {
  499. int32_t skill = -1; //skill level
  500. spell->forEachSchool([&, this](const spells::SchoolInfo & cnf, bool & stop)
  501. {
  502. int32_t thisSchool = std::max<int32_t>(
  503. valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, cnf.skill),
  504. valOfBonuses(Bonus::MAGIC_SCHOOL_SKILL, 1 << ((ui8)cnf.id))); //FIXME: Bonus shouldn't be additive (Witchking Artifacts : Crown of Skies)
  505. if(thisSchool > skill)
  506. {
  507. skill = thisSchool;
  508. if(outSelectedSchool)
  509. *outSelectedSchool = (ui8)cnf.id;
  510. }
  511. });
  512. vstd::amax(skill, valOfBonuses(Bonus::MAGIC_SCHOOL_SKILL, 0)); //any school bonus
  513. vstd::amax(skill, valOfBonuses(Bonus::SPELL, spell->getIndex())); //given by artifact or other effect
  514. vstd::amax(skill, 0); //in case we don't know any school
  515. vstd::amin(skill, 3);
  516. return skill;
  517. }
  518. int64_t CGHeroInstance::getSpellBonus(const spells::Spell * spell, int64_t base, const battle::Unit * affectedStack) const
  519. {
  520. //applying sorcery secondary skill
  521. base = (int64_t)(base * (100 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::SORCERY)) / 100.0);
  522. base = (int64_t)(base * (100 + valOfBonuses(Bonus::SPELL_DAMAGE) + valOfBonuses(Bonus::SPECIFIC_SPELL_DAMAGE, spell->getIndex())) / 100.0);
  523. int maxSchoolBonus = 0;
  524. spell->forEachSchool([&maxSchoolBonus, this](const spells::SchoolInfo & cnf, bool & stop)
  525. {
  526. vstd::amax(maxSchoolBonus, valOfBonuses(cnf.damagePremyBonus));
  527. });
  528. base = (int64_t)(base * (100 + maxSchoolBonus) / 100.0);
  529. if(affectedStack && affectedStack->creatureLevel() > 0) //Hero specials like Solmyr, Deemer
  530. base = (int64_t)(base * double(100 + valOfBonuses(Bonus::SPECIAL_SPELL_LEV, spell->getIndex()) / affectedStack->creatureLevel()) / 100.0);
  531. return base;
  532. }
  533. int64_t CGHeroInstance::getSpecificSpellBonus(const spells::Spell * spell, int64_t base) const
  534. {
  535. base = (int64_t)(base * (100 + valOfBonuses(Bonus::SPECIFIC_SPELL_DAMAGE, spell->getIndex())) / 100.0);
  536. return base;
  537. }
  538. int32_t CGHeroInstance::getEffectLevel(const spells::Spell * spell) const
  539. {
  540. if(hasBonusOfType(Bonus::MAXED_SPELL, spell->getIndex()))
  541. return 3;//todo: recheck specialty from where this bonus is. possible bug
  542. else
  543. return getSpellSchoolLevel(spell);
  544. }
  545. int32_t CGHeroInstance::getEffectPower(const spells::Spell * spell) const
  546. {
  547. return getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  548. }
  549. int32_t CGHeroInstance::getEnchantPower(const spells::Spell * spell) const
  550. {
  551. return getPrimSkillLevel(PrimarySkill::SPELL_POWER) + valOfBonuses(Bonus::SPELL_DURATION);
  552. }
  553. int64_t CGHeroInstance::getEffectValue(const spells::Spell * spell) const
  554. {
  555. return 0;
  556. }
  557. PlayerColor CGHeroInstance::getCasterOwner() const
  558. {
  559. return tempOwner;
  560. }
  561. void CGHeroInstance::getCasterName(MetaString & text) const
  562. {
  563. //FIXME: use local name, MetaString need access to gamestate as hero name is part of map object
  564. text.addReplacement(getNameTranslated());
  565. }
  566. void CGHeroInstance::getCastDescription(const spells::Spell * spell, const std::vector<const battle::Unit *> & attacked, MetaString & text) const
  567. {
  568. const bool singleTarget = attacked.size() == 1;
  569. const int textIndex = singleTarget ? 195 : 196;
  570. text.addTxt(MetaString::GENERAL_TXT, textIndex);
  571. getCasterName(text);
  572. text.addReplacement(MetaString::SPELL_NAME, spell->getIndex());
  573. if(singleTarget)
  574. attacked.at(0)->addNameReplacement(text, true);
  575. }
  576. void CGHeroInstance::spendMana(ServerCallback * server, const int spellCost) const
  577. {
  578. if(spellCost != 0)
  579. {
  580. SetMana sm;
  581. sm.absolute = false;
  582. sm.hid = id;
  583. sm.val = -spellCost;
  584. server->apply(&sm);
  585. }
  586. }
  587. bool CGHeroInstance::canCastThisSpell(const spells::Spell * spell) const
  588. {
  589. const bool isAllowed = IObjectInterface::cb->isAllowed(0, spell->getIndex());
  590. const bool inSpellBook = vstd::contains(spells, spell->getId()) && hasSpellbook();
  591. const bool specificBonus = hasBonusOfType(Bonus::SPELL, spell->getIndex());
  592. bool schoolBonus = false;
  593. spell->forEachSchool([this, &schoolBonus](const spells::SchoolInfo & cnf, bool & stop)
  594. {
  595. if(hasBonusOfType(cnf.knoledgeBonus))
  596. {
  597. schoolBonus = stop = true;
  598. }
  599. });
  600. const bool levelBonus = hasBonusOfType(Bonus::SPELLS_OF_LEVEL, spell->getLevel());
  601. if(spell->isSpecial())
  602. {
  603. if(inSpellBook)
  604. {//hero has this spell in spellbook
  605. logGlobal->error("Special spell %s in spellbook.", spell->getNameTranslated());
  606. }
  607. return specificBonus;
  608. }
  609. else if(!isAllowed)
  610. {
  611. if(inSpellBook)
  612. {
  613. //hero has this spell in spellbook
  614. //it is normal if set in map editor, but trace it to possible debug of magic guild
  615. logGlobal->trace("Banned spell %s in spellbook.", spell->getNameTranslated());
  616. }
  617. return inSpellBook || specificBonus || schoolBonus || levelBonus;
  618. }
  619. else
  620. {
  621. return inSpellBook || schoolBonus || specificBonus || levelBonus;
  622. }
  623. }
  624. bool CGHeroInstance::canLearnSpell(const spells::Spell * spell) const
  625. {
  626. if(!hasSpellbook())
  627. return false;
  628. if(spell->getLevel() > maxSpellLevel()) //not enough wisdom
  629. return false;
  630. if(vstd::contains(spells, spell->getId()))//already known
  631. return false;
  632. if(spell->isSpecial())
  633. {
  634. logGlobal->warn("Hero %s try to learn special spell %s", nodeName(), spell->getNameTranslated());
  635. return false;//special spells can not be learned
  636. }
  637. if(spell->isCreatureAbility())
  638. {
  639. logGlobal->warn("Hero %s try to learn creature spell %s", nodeName(), spell->getNameTranslated());
  640. return false;//creature abilities can not be learned
  641. }
  642. if(!IObjectInterface::cb->isAllowed(0, spell->getIndex()))
  643. {
  644. logGlobal->warn("Hero %s try to learn banned spell %s", nodeName(), spell->getNameTranslated());
  645. return false;//banned spells should not be learned
  646. }
  647. return true;
  648. }
  649. /**
  650. * Calculates what creatures and how many to be raised from a battle.
  651. * @param battleResult The results of the battle.
  652. * @return Returns a pair with the first value indicating the ID of the creature
  653. * type and second value the amount. Both values are returned as -1 if necromancy
  654. * could not be applied.
  655. */
  656. CStackBasicDescriptor CGHeroInstance::calculateNecromancy (const BattleResult &battleResult) const
  657. {
  658. const ui8 necromancyLevel = getSecSkillLevel(SecondarySkill::NECROMANCY);
  659. // need skill or cloak of undead king - lesser artifacts don't work without skill
  660. if (necromancyLevel > 0 || hasBonusOfType(Bonus::IMPROVED_NECROMANCY))
  661. {
  662. double necromancySkill = valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::NECROMANCY) / 100.0;
  663. vstd::amin(necromancySkill, 1.0); //it's impossible to raise more creatures than all...
  664. const std::map<ui32,si32> &casualties = battleResult.casualties[!battleResult.winner];
  665. // figure out what to raise - pick strongest creature meeting requirements
  666. CreatureID creatureTypeRaised = CreatureID::SKELETON;
  667. int requiredCasualtyLevel = 1;
  668. TConstBonusListPtr improvedNecromancy = getBonuses(Selector::type()(Bonus::IMPROVED_NECROMANCY));
  669. if(!improvedNecromancy->empty())
  670. {
  671. auto getCreatureID = [necromancyLevel](std::shared_ptr<Bonus> bonus) -> CreatureID
  672. {
  673. const CreatureID legacyTypes[] = {CreatureID::SKELETON, CreatureID::WALKING_DEAD, CreatureID::WIGHTS, CreatureID::LICHES};
  674. return CreatureID(bonus->subtype >= 0 ? bonus->subtype : legacyTypes[necromancyLevel]);
  675. };
  676. int maxCasualtyLevel = 1;
  677. for(auto & casualty : casualties)
  678. vstd::amax(maxCasualtyLevel, VLC->creh->objects[casualty.first]->level);
  679. // pick best bonus available
  680. std::shared_ptr<Bonus> topPick;
  681. for(std::shared_ptr<Bonus> newPick : *improvedNecromancy)
  682. {
  683. // addInfo[0] = required necromancy skill, addInfo[1] = required casualty level
  684. if(newPick->additionalInfo[0] > necromancyLevel || newPick->additionalInfo[1] > maxCasualtyLevel)
  685. continue;
  686. if(!topPick)
  687. {
  688. topPick = newPick;
  689. }
  690. else
  691. {
  692. auto quality = [getCreatureID](std::shared_ptr<Bonus> pick) -> std::tuple<int, int, int>
  693. {
  694. const CCreature * c = VLC->creh->objects[getCreatureID(pick)];
  695. return std::tuple<int, int, int> {c->level, static_cast<int>(c->cost.marketValue()), -pick->additionalInfo[1]};
  696. };
  697. if(quality(topPick) < quality(newPick))
  698. topPick = newPick;
  699. }
  700. }
  701. if(topPick)
  702. {
  703. creatureTypeRaised = getCreatureID(topPick);
  704. requiredCasualtyLevel = std::max(topPick->additionalInfo[1], 1);
  705. }
  706. }
  707. // raise upgraded creature (at 2/3 rate) if no space available otherwise
  708. if(getSlotFor(creatureTypeRaised) == SlotID())
  709. {
  710. for(CreatureID upgraded : VLC->creh->objects[creatureTypeRaised]->upgrades)
  711. {
  712. if(getSlotFor(upgraded) != SlotID())
  713. {
  714. creatureTypeRaised = upgraded;
  715. necromancySkill *= 2/3.0;
  716. break;
  717. }
  718. }
  719. }
  720. // calculate number of creatures raised - low level units contribute at 50% rate
  721. const double raisedUnitHealth = VLC->creh->objects[creatureTypeRaised]->MaxHealth();
  722. double raisedUnits = 0;
  723. for(auto & casualty : casualties)
  724. {
  725. const CCreature * c = VLC->creh->objects[casualty.first];
  726. double raisedFromCasualty = std::min(c->MaxHealth() / raisedUnitHealth, 1.0) * casualty.second * necromancySkill;
  727. if(c->level < requiredCasualtyLevel)
  728. raisedFromCasualty *= 0.5;
  729. raisedUnits += raisedFromCasualty;
  730. }
  731. return CStackBasicDescriptor(creatureTypeRaised, std::max(static_cast<int>(raisedUnits), 1));
  732. }
  733. return CStackBasicDescriptor();
  734. }
  735. /**
  736. * Show the necromancy dialog with information about units raised.
  737. * @param raisedStack Pair where the first element represents ID of the raised creature
  738. * and the second element the amount.
  739. */
  740. void CGHeroInstance::showNecromancyDialog(const CStackBasicDescriptor &raisedStack, CRandomGenerator & rand) const
  741. {
  742. InfoWindow iw;
  743. iw.soundID = soundBase::pickup01 + rand.nextInt(6);
  744. iw.player = tempOwner;
  745. iw.components.push_back(Component(raisedStack));
  746. if (raisedStack.count > 1) // Practicing the dark arts of necromancy, ... (plural)
  747. {
  748. iw.text.addTxt(MetaString::GENERAL_TXT, 145);
  749. iw.text.addReplacement(raisedStack.count);
  750. }
  751. else // Practicing the dark arts of necromancy, ... (singular)
  752. {
  753. iw.text.addTxt(MetaString::GENERAL_TXT, 146);
  754. }
  755. iw.text.addReplacement(raisedStack);
  756. cb->showInfoDialog(&iw);
  757. }
  758. /*
  759. int3 CGHeroInstance::getSightCenter() const
  760. {
  761. return getPosition(false);
  762. }*/
  763. int CGHeroInstance::getSightRadius() const
  764. {
  765. return 5 + valOfBonuses(Bonus::SIGHT_RADIOUS); // scouting gives SIGHT_RADIUS bonus
  766. }
  767. si32 CGHeroInstance::manaRegain() const
  768. {
  769. if (hasBonusOfType(Bonus::FULL_MANA_REGENERATION))
  770. return manaLimit();
  771. return 1 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::MYSTICISM) + valOfBonuses(Bonus::MANA_REGENERATION); //1 + Mysticism level
  772. }
  773. si32 CGHeroInstance::getManaNewTurn() const
  774. {
  775. if(visitedTown && visitedTown->hasBuilt(BuildingID::MAGES_GUILD_1))
  776. {
  777. //if hero starts turn in town with mage guild - restore all mana
  778. return std::max(mana, manaLimit());
  779. }
  780. si32 res = mana + manaRegain();
  781. res = std::min(res, manaLimit());
  782. res = std::max(res, mana);
  783. res = std::max(res, 0);
  784. return res;
  785. }
  786. // /**
  787. // * Places an artifact in hero's backpack. If it's a big artifact equips it
  788. // * or discards it if it cannot be equipped.
  789. // */
  790. // void CGHeroInstance::giveArtifact (ui32 aid) //use only for fixed artifacts
  791. // {
  792. // CArtifact * const artifact = VLC->arth->objects[aid]; //pointer to constant object
  793. // CArtifactInstance *ai = CArtifactInstance::createNewArtifactInstance(artifact);
  794. // ai->putAt(this, ai->firstAvailableSlot(this));
  795. // }
  796. int CGHeroInstance::getBoatType() const
  797. {
  798. switch(type->heroClass->getAlignment())
  799. {
  800. case EAlignment::GOOD:
  801. return 1;
  802. case EAlignment::EVIL:
  803. return 0;
  804. case EAlignment::NEUTRAL:
  805. return 2;
  806. default:
  807. throw std::runtime_error("Wrong alignment!");
  808. }
  809. }
  810. void CGHeroInstance::getOutOffsets(std::vector<int3> &offsets) const
  811. {
  812. // FIXME: Offsets need to be fixed once we get rid of convertPosition
  813. // Check issue 515 for details
  814. offsets =
  815. {
  816. 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)
  817. };
  818. }
  819. int32_t CGHeroInstance::getSpellCost(const spells::Spell * sp) const
  820. {
  821. return sp->getCost(getSpellSchoolLevel(sp));
  822. }
  823. void CGHeroInstance::pushPrimSkill( PrimarySkill::PrimarySkill which, int val )
  824. {
  825. assert(!hasBonus(Selector::typeSubtype(Bonus::PRIMARY_SKILL, which)
  826. .And(Selector::sourceType()(Bonus::HERO_BASE_SKILL))));
  827. addNewBonus(std::make_shared<Bonus>(Bonus::PERMANENT, Bonus::PRIMARY_SKILL, Bonus::HERO_BASE_SKILL, val, id.getNum(), which));
  828. }
  829. EAlignment::EAlignment CGHeroInstance::getAlignment() const
  830. {
  831. return type->heroClass->getAlignment();
  832. }
  833. void CGHeroInstance::initExp(CRandomGenerator & rand)
  834. {
  835. exp = rand.nextInt(40, 89);
  836. }
  837. std::string CGHeroInstance::nodeName() const
  838. {
  839. return "Hero " + getNameTextID();
  840. }
  841. std::string CGHeroInstance::getNameTranslated() const
  842. {
  843. return VLC->generaltexth->translate(getNameTextID());
  844. }
  845. std::string CGHeroInstance::getNameTextID() const
  846. {
  847. if (!nameCustom.empty())
  848. return nameCustom;
  849. if (type)
  850. return type->getNameTextID();
  851. // FIXME: called by logging from some specialties (mods?) before type is set on deserialization
  852. // assert(0);
  853. return "";
  854. }
  855. std::string CGHeroInstance::getBiographyTranslated() const
  856. {
  857. return VLC->generaltexth->translate(getBiographyTextID());
  858. }
  859. std::string CGHeroInstance::getBiographyTextID() const
  860. {
  861. if (!biographyCustom.empty())
  862. return biographyCustom;
  863. if (type)
  864. return type->getBiographyTextID();
  865. assert(0);
  866. return "";
  867. }
  868. void CGHeroInstance::putArtifact(ArtifactPosition pos, CArtifactInstance *art)
  869. {
  870. assert(!getArt(pos));
  871. art->putAt(ArtifactLocation(this, pos));
  872. }
  873. void CGHeroInstance::putInBackpack(CArtifactInstance *art)
  874. {
  875. putArtifact(art->firstBackpackSlot(this), art);
  876. }
  877. bool CGHeroInstance::hasSpellbook() const
  878. {
  879. return getArt(ArtifactPosition::SPELLBOOK);
  880. }
  881. void CGHeroInstance::addSpellToSpellbook(SpellID spell)
  882. {
  883. spells.insert(spell);
  884. }
  885. void CGHeroInstance::removeSpellFromSpellbook(SpellID spell)
  886. {
  887. spells.erase(spell);
  888. }
  889. bool CGHeroInstance::spellbookContainsSpell(SpellID spell) const
  890. {
  891. return vstd::contains(spells, spell);
  892. }
  893. void CGHeroInstance::removeSpellbook()
  894. {
  895. spells.clear();
  896. if(hasSpellbook())
  897. {
  898. ArtifactLocation(this, ArtifactPosition(ArtifactPosition::SPELLBOOK)).removeArtifact();
  899. }
  900. }
  901. const std::set<SpellID> & CGHeroInstance::getSpellsInSpellbook() const
  902. {
  903. return spells;
  904. }
  905. int CGHeroInstance::maxSpellLevel() const
  906. {
  907. return std::min(GameConstants::SPELL_LEVELS, 2 + valOfBonuses(Selector::typeSubtype(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::WISDOM)));
  908. }
  909. void CGHeroInstance::deserializationFix()
  910. {
  911. artDeserializationFix(this);
  912. }
  913. CBonusSystemNode * CGHeroInstance::whereShouldBeAttachedOnSiege(const bool isBattleOutsideTown) const
  914. {
  915. if(!visitedTown)
  916. return nullptr;
  917. return isBattleOutsideTown ? (CBonusSystemNode *)(& visitedTown->townAndVis)
  918. : (CBonusSystemNode *)(visitedTown.get());
  919. }
  920. CBonusSystemNode * CGHeroInstance::whereShouldBeAttachedOnSiege(CGameState * gs)
  921. {
  922. if(visitedTown)
  923. return whereShouldBeAttachedOnSiege(visitedTown->isBattleOutsideTown(this));
  924. return &CArmedInstance::whereShouldBeAttached(gs);
  925. }
  926. CBonusSystemNode & CGHeroInstance::whereShouldBeAttached(CGameState * gs)
  927. {
  928. if(visitedTown)
  929. {
  930. if(inTownGarrison)
  931. return *visitedTown;
  932. else
  933. return visitedTown->townAndVis;
  934. }
  935. else
  936. return CArmedInstance::whereShouldBeAttached(gs);
  937. }
  938. int CGHeroInstance::movementPointsAfterEmbark(int MPsBefore, int basicCost, bool disembark, const TurnInfo * ti) const
  939. {
  940. int ret = 0; //take all MPs by default
  941. bool localTi = false;
  942. if(!ti)
  943. {
  944. localTi = true;
  945. ti = new TurnInfo(this);
  946. }
  947. int mp1 = ti->getMaxMovePoints(disembark ? EPathfindingLayer::LAND : EPathfindingLayer::SAIL);
  948. int mp2 = ti->getMaxMovePoints(disembark ? EPathfindingLayer::SAIL : EPathfindingLayer::LAND);
  949. if(ti->hasBonusOfType(Bonus::FREE_SHIP_BOARDING))
  950. ret = static_cast<int>((MPsBefore - basicCost) * static_cast<double>(mp1) / mp2);
  951. if(localTi)
  952. delete ti;
  953. return ret;
  954. }
  955. EDiggingStatus CGHeroInstance::diggingStatus() const
  956. {
  957. if((int)movement < maxMovePoints(true))
  958. return EDiggingStatus::LACK_OF_MOVEMENT;
  959. return cb->getTile(visitablePos())->getDiggingStatus();
  960. }
  961. ArtBearer::ArtBearer CGHeroInstance::bearerType() const
  962. {
  963. return ArtBearer::HERO;
  964. }
  965. std::vector<SecondarySkill> CGHeroInstance::getLevelUpProposedSecondarySkills() const
  966. {
  967. std::vector<SecondarySkill> obligatorySkills; //hero is offered magic school or wisdom if possible
  968. if (!skillsInfo.wisdomCounter)
  969. {
  970. if (canLearnSkill(SecondarySkill::WISDOM))
  971. obligatorySkills.push_back(SecondarySkill::WISDOM);
  972. }
  973. if (!skillsInfo.magicSchoolCounter)
  974. {
  975. std::vector<SecondarySkill> ss =
  976. {
  977. SecondarySkill::FIRE_MAGIC, SecondarySkill::AIR_MAGIC, SecondarySkill::WATER_MAGIC, SecondarySkill::EARTH_MAGIC
  978. };
  979. std::shuffle(ss.begin(), ss.end(), skillsInfo.rand.getStdGenerator());
  980. for (auto skill : ss)
  981. {
  982. if (canLearnSkill(skill)) //only schools hero doesn't know yet
  983. {
  984. obligatorySkills.push_back(skill);
  985. break; //only one
  986. }
  987. }
  988. }
  989. std::vector<SecondarySkill> skills;
  990. //picking sec. skills for choice
  991. std::set<SecondarySkill> basicAndAdv, expert, none;
  992. for(int i = 0; i < VLC->skillh->size(); i++)
  993. if (canLearnSkill(SecondarySkill(i)))
  994. none.insert(SecondarySkill(i));
  995. for(auto & elem : secSkills)
  996. {
  997. if(elem.second < SecSkillLevel::EXPERT)
  998. basicAndAdv.insert(elem.first);
  999. else
  1000. expert.insert(elem.first);
  1001. none.erase(elem.first);
  1002. }
  1003. for (auto s : obligatorySkills) //don't duplicate them
  1004. {
  1005. none.erase (s);
  1006. basicAndAdv.erase (s);
  1007. expert.erase (s);
  1008. }
  1009. //first offered skill:
  1010. // 1) give obligatory skill
  1011. // 2) give any other new skill
  1012. // 3) upgrade existing
  1013. if (canLearnSkill() && obligatorySkills.size() > 0)
  1014. {
  1015. skills.push_back (obligatorySkills[0]);
  1016. }
  1017. else if(none.size() && canLearnSkill()) //hero have free skill slot
  1018. {
  1019. skills.push_back(type->heroClass->chooseSecSkill(none, skillsInfo.rand)); //new skill
  1020. none.erase(skills.back());
  1021. }
  1022. else if(!basicAndAdv.empty())
  1023. {
  1024. skills.push_back(type->heroClass->chooseSecSkill(basicAndAdv, skillsInfo.rand)); //upgrade existing
  1025. basicAndAdv.erase(skills.back());
  1026. }
  1027. //second offered skill:
  1028. //1) upgrade existing
  1029. //2) give obligatory skill
  1030. //3) give any other new skill
  1031. if(!basicAndAdv.empty())
  1032. {
  1033. SecondarySkill s = type->heroClass->chooseSecSkill(basicAndAdv, skillsInfo.rand);//upgrade existing
  1034. skills.push_back(s);
  1035. basicAndAdv.erase(s);
  1036. }
  1037. else if (canLearnSkill() && obligatorySkills.size() > 1)
  1038. {
  1039. skills.push_back (obligatorySkills[1]);
  1040. }
  1041. else if(none.size() && canLearnSkill())
  1042. {
  1043. skills.push_back(type->heroClass->chooseSecSkill(none, skillsInfo.rand)); //give new skill
  1044. none.erase(skills.back());
  1045. }
  1046. if (skills.size() == 2) // Fix for #1868 to avoid changing logic (possibly causing bugs in process)
  1047. std::swap(skills[0], skills[1]);
  1048. return skills;
  1049. }
  1050. PrimarySkill::PrimarySkill CGHeroInstance::nextPrimarySkill(CRandomGenerator & rand) const
  1051. {
  1052. assert(gainsLevel());
  1053. int randomValue = rand.nextInt(99), pom = 0, primarySkill = 0;
  1054. const auto isLowLevelHero = level < GameConstants::HERO_HIGH_LEVEL;
  1055. const auto & skillChances = isLowLevelHero ? type->heroClass->primarySkillLowLevel : type->heroClass->primarySkillHighLevel;
  1056. for(; primarySkill < GameConstants::PRIMARY_SKILLS; ++primarySkill)
  1057. {
  1058. pom += skillChances[primarySkill];
  1059. if(randomValue < pom)
  1060. {
  1061. break;
  1062. }
  1063. }
  1064. if(primarySkill >= GameConstants::PRIMARY_SKILLS)
  1065. {
  1066. primarySkill = rand.nextInt(GameConstants::PRIMARY_SKILLS - 1);
  1067. logGlobal->error("Wrong values in primarySkill%sLevel for hero class %s", isLowLevelHero ? "Low" : "High", type->heroClass->getNameTranslated());
  1068. randomValue = 100 / GameConstants::PRIMARY_SKILLS;
  1069. }
  1070. logGlobal->trace("The hero gets the primary skill %d with a probability of %d %%.", primarySkill, randomValue);
  1071. return static_cast<PrimarySkill::PrimarySkill>(primarySkill);
  1072. }
  1073. boost::optional<SecondarySkill> CGHeroInstance::nextSecondarySkill(CRandomGenerator & rand) const
  1074. {
  1075. assert(gainsLevel());
  1076. boost::optional<SecondarySkill> chosenSecondarySkill;
  1077. const auto proposedSecondarySkills = getLevelUpProposedSecondarySkills();
  1078. if(!proposedSecondarySkills.empty())
  1079. {
  1080. std::vector<SecondarySkill> learnedSecondarySkills;
  1081. for(auto secondarySkill : proposedSecondarySkills)
  1082. {
  1083. if(getSecSkillLevel(secondarySkill) > 0)
  1084. {
  1085. learnedSecondarySkills.push_back(secondarySkill);
  1086. }
  1087. }
  1088. if(learnedSecondarySkills.empty())
  1089. {
  1090. // there are only new skills to learn, so choose anyone of them
  1091. chosenSecondarySkill = boost::make_optional(*RandomGeneratorUtil::nextItem(proposedSecondarySkills, rand));
  1092. }
  1093. else
  1094. {
  1095. // preferably upgrade a already learned secondary skill
  1096. chosenSecondarySkill = boost::make_optional(*RandomGeneratorUtil::nextItem(learnedSecondarySkills, rand));
  1097. }
  1098. }
  1099. return chosenSecondarySkill;
  1100. }
  1101. void CGHeroInstance::setPrimarySkill(PrimarySkill::PrimarySkill primarySkill, si64 value, ui8 abs)
  1102. {
  1103. if(primarySkill < PrimarySkill::EXPERIENCE)
  1104. {
  1105. auto skill = getBonusLocalFirst(Selector::type()(Bonus::PRIMARY_SKILL)
  1106. .And(Selector::subtype()(primarySkill))
  1107. .And(Selector::sourceType()(Bonus::HERO_BASE_SKILL)));
  1108. assert(skill);
  1109. if(abs)
  1110. {
  1111. skill->val = static_cast<si32>(value);
  1112. }
  1113. else
  1114. {
  1115. skill->val += static_cast<si32>(value);
  1116. }
  1117. CBonusSystemNode::treeHasChanged();
  1118. }
  1119. else if(primarySkill == PrimarySkill::EXPERIENCE)
  1120. {
  1121. if(abs)
  1122. {
  1123. exp = value;
  1124. }
  1125. else
  1126. {
  1127. exp += value;
  1128. }
  1129. }
  1130. }
  1131. bool CGHeroInstance::gainsLevel() const
  1132. {
  1133. return exp >= static_cast<TExpType>(VLC->heroh->reqExp(level+1));
  1134. }
  1135. void CGHeroInstance::levelUp(std::vector<SecondarySkill> skills)
  1136. {
  1137. ++level;
  1138. //deterministic secondary skills
  1139. skillsInfo.magicSchoolCounter = (skillsInfo.magicSchoolCounter + 1) % maxlevelsToMagicSchool();
  1140. skillsInfo.wisdomCounter = (skillsInfo.wisdomCounter + 1) % maxlevelsToWisdom();
  1141. if(vstd::contains(skills, SecondarySkill::WISDOM))
  1142. {
  1143. skillsInfo.resetWisdomCounter();
  1144. }
  1145. SecondarySkill spellSchools[] = {
  1146. SecondarySkill::FIRE_MAGIC, SecondarySkill::AIR_MAGIC, SecondarySkill::WATER_MAGIC, SecondarySkill::EARTH_MAGIC};
  1147. for(auto skill : spellSchools)
  1148. {
  1149. if(vstd::contains(skills, skill))
  1150. {
  1151. skillsInfo.resetMagicSchoolCounter();
  1152. break;
  1153. }
  1154. }
  1155. //update specialty and other bonuses that scale with level
  1156. treeHasChanged();
  1157. }
  1158. void CGHeroInstance::levelUpAutomatically(CRandomGenerator & rand)
  1159. {
  1160. while(gainsLevel())
  1161. {
  1162. const auto primarySkill = nextPrimarySkill(rand);
  1163. setPrimarySkill(primarySkill, 1, false);
  1164. auto proposedSecondarySkills = getLevelUpProposedSecondarySkills();
  1165. const auto secondarySkill = nextSecondarySkill(rand);
  1166. if(secondarySkill)
  1167. {
  1168. setSecSkillLevel(*secondarySkill, 1, false);
  1169. }
  1170. //TODO why has the secondary skills to be passed to the method?
  1171. levelUp(proposedSecondarySkills);
  1172. }
  1173. }
  1174. bool CGHeroInstance::hasVisions(const CGObjectInstance * target, const int subtype) const
  1175. {
  1176. //VISIONS spell support
  1177. const std::string cached = boost::to_string((boost::format("type_%d__subtype_%d") % Bonus::VISIONS % subtype));
  1178. const int visionsMultiplier = valOfBonuses(Selector::typeSubtype(Bonus::VISIONS,subtype), cached);
  1179. int visionsRange = visionsMultiplier * getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  1180. if (visionsMultiplier > 0)
  1181. vstd::amax(visionsRange, 3); //minimum range is 3 tiles, but only if VISIONS bonus present
  1182. const int distance = static_cast<int>(target->pos.dist2d(visitablePos()));
  1183. //logGlobal->debug(boost::to_string(boost::format("Visions: dist %d, mult %d, range %d") % distance % visionsMultiplier % visionsRange));
  1184. return (distance < visionsRange) && (target->pos.z == pos.z);
  1185. }
  1186. std::string CGHeroInstance::getHeroTypeName() const
  1187. {
  1188. if(ID == Obj::HERO || ID == Obj::PRISON)
  1189. {
  1190. if(type)
  1191. {
  1192. return type->getJsonKey();
  1193. }
  1194. else
  1195. {
  1196. return VLC->heroh->objects[subID]->getJsonKey();
  1197. }
  1198. }
  1199. return "";
  1200. }
  1201. void CGHeroInstance::afterAddToMap(CMap * map)
  1202. {
  1203. if(ID == Obj::HERO)
  1204. map->heroesOnMap.push_back(this);
  1205. }
  1206. void CGHeroInstance::afterRemoveFromMap(CMap* map)
  1207. {
  1208. if (ID == Obj::HERO)
  1209. vstd::erase_if_present(map->heroesOnMap, this);
  1210. }
  1211. void CGHeroInstance::setHeroTypeName(const std::string & identifier)
  1212. {
  1213. if(ID == Obj::HERO || ID == Obj::PRISON)
  1214. {
  1215. auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeMap(), "hero", identifier);
  1216. if(rawId)
  1217. subID = rawId.get();
  1218. else
  1219. {
  1220. throw std::runtime_error("Couldn't resolve hero identifier " + identifier);
  1221. }
  1222. }
  1223. }
  1224. void CGHeroInstance::updateFrom(const JsonNode & data)
  1225. {
  1226. CGObjectInstance::updateFrom(data);
  1227. }
  1228. void CGHeroInstance::serializeCommonOptions(JsonSerializeFormat & handler)
  1229. {
  1230. handler.serializeString("biography", biographyCustom);
  1231. handler.serializeInt("experience", exp, 0);
  1232. if(!handler.saving && exp != 0xffffffff) //do not gain levels if experience is not initialized
  1233. {
  1234. while (gainsLevel())
  1235. {
  1236. ++level;
  1237. }
  1238. }
  1239. handler.serializeString("name", nameCustom);
  1240. handler.serializeBool<ui8>("female", sex, 1, 0, 0xFF);
  1241. {
  1242. const int legacyHeroes = static_cast<int>(VLC->modh->settings.data["textData"]["hero"].Integer());
  1243. const int moddedStart = legacyHeroes + GameConstants::HERO_PORTRAIT_SHIFT;
  1244. if(handler.saving)
  1245. {
  1246. if(portrait >= 0)
  1247. {
  1248. if(portrait < legacyHeroes || portrait >= moddedStart)
  1249. handler.serializeId<si32, si32, HeroTypeID>("portrait", portrait, -1);
  1250. else
  1251. handler.serializeInt("portrait", portrait, -1);
  1252. }
  1253. }
  1254. else
  1255. {
  1256. const JsonNode & portraitNode = handler.getCurrent()["portrait"];
  1257. if(portraitNode.getType() == JsonNode::JsonType::DATA_STRING)
  1258. handler.serializeId<si32, si32, HeroTypeID>("portrait", portrait, -1);
  1259. else
  1260. handler.serializeInt("portrait", portrait, -1);
  1261. }
  1262. }
  1263. //primary skills
  1264. if(handler.saving)
  1265. {
  1266. const bool haveSkills = hasBonus(Selector::type()(Bonus::PRIMARY_SKILL).And(Selector::sourceType()(Bonus::HERO_BASE_SKILL)));
  1267. if(haveSkills)
  1268. {
  1269. auto primarySkills = handler.enterStruct("primarySkills");
  1270. for(int i = 0; i < GameConstants::PRIMARY_SKILLS; ++i)
  1271. {
  1272. int value = valOfBonuses(Selector::typeSubtype(Bonus::PRIMARY_SKILL, i).And(Selector::sourceType()(Bonus::HERO_BASE_SKILL)));
  1273. handler.serializeInt(PrimarySkill::names[i], value, 0);
  1274. }
  1275. }
  1276. }
  1277. else
  1278. {
  1279. auto primarySkills = handler.enterStruct("primarySkills");
  1280. if(handler.getCurrent().getType() == JsonNode::JsonType::DATA_STRUCT)
  1281. {
  1282. for(int i = 0; i < GameConstants::PRIMARY_SKILLS; ++i)
  1283. {
  1284. int value = 0;
  1285. handler.serializeInt(PrimarySkill::names[i], value, 0);
  1286. pushPrimSkill(static_cast<PrimarySkill::PrimarySkill>(i), value);
  1287. }
  1288. }
  1289. }
  1290. //secondary skills
  1291. if(handler.saving)
  1292. {
  1293. //does hero have default skills?
  1294. bool defaultSkills = false;
  1295. bool normalSkills = false;
  1296. for(const auto & p : secSkills)
  1297. {
  1298. if(p.first == SecondarySkill(SecondarySkill::DEFAULT))
  1299. defaultSkills = true;
  1300. else
  1301. normalSkills = true;
  1302. }
  1303. if(defaultSkills && normalSkills)
  1304. logGlobal->error("Mixed default and normal secondary skills");
  1305. //in json default skills means no field/null
  1306. if(!defaultSkills)
  1307. {
  1308. //enter structure here as handler initialize it
  1309. auto secondarySkills = handler.enterStruct("secondarySkills");
  1310. for(auto & p : secSkills)
  1311. {
  1312. const si32 rawId = p.first.num;
  1313. if(rawId < 0 || rawId >= VLC->skillh->size())
  1314. logGlobal->error("Invalid secondary skill %d", rawId);
  1315. handler.serializeEnum((*VLC->skillh)[SecondarySkill(rawId)]->getJsonKey(), p.second, 0, NSecondarySkill::levels);
  1316. }
  1317. }
  1318. }
  1319. else
  1320. {
  1321. auto secondarySkills = handler.enterStruct("secondarySkills");
  1322. const JsonNode & skillMap = handler.getCurrent();
  1323. secSkills.clear();
  1324. if(skillMap.getType() == JsonNode::JsonType::DATA_NULL)
  1325. {
  1326. secSkills.push_back(std::pair<SecondarySkill,ui8>(SecondarySkill::DEFAULT, -1));
  1327. }
  1328. else
  1329. {
  1330. for(const auto & p : skillMap.Struct())
  1331. {
  1332. const std::string skillId = p.first;
  1333. const std::string levelId = p.second.String();
  1334. const int rawId = CSkillHandler::decodeSkill(skillId);
  1335. if(rawId < 0)
  1336. {
  1337. logGlobal->error("Invalid secondary skill %s", skillId);
  1338. continue;
  1339. }
  1340. const int level = vstd::find_pos(NSecondarySkill::levels, levelId);
  1341. if(level < 0)
  1342. {
  1343. logGlobal->error("Invalid secondary skill level%s", levelId);
  1344. continue;
  1345. }
  1346. secSkills.push_back(std::pair<SecondarySkill,ui8>(SecondarySkill(rawId), level));
  1347. }
  1348. }
  1349. }
  1350. handler.serializeIdArray("spellBook", spells);
  1351. if(handler.saving)
  1352. CArtifactSet::serializeJsonArtifacts(handler, "artifacts", nullptr);
  1353. }
  1354. void CGHeroInstance::serializeJsonOptions(JsonSerializeFormat & handler)
  1355. {
  1356. serializeCommonOptions(handler);
  1357. serializeJsonOwner(handler);
  1358. if(ID == Obj::HERO || ID == Obj::PRISON)
  1359. {
  1360. std::string typeName;
  1361. if(handler.saving)
  1362. typeName = getHeroTypeName();
  1363. handler.serializeString("type", typeName);
  1364. if(!handler.saving)
  1365. setHeroTypeName(typeName);
  1366. }
  1367. CCreatureSet::serializeJson(handler, "army", 7);
  1368. handler.serializeBool<ui8>("tightFormation", formation, 1, 0, 0);
  1369. {
  1370. static const int NO_PATROLING = -1;
  1371. int rawPatrolRadius = NO_PATROLING;
  1372. if(handler.saving)
  1373. {
  1374. rawPatrolRadius = patrol.patrolling ? patrol.patrolRadius : NO_PATROLING;
  1375. }
  1376. handler.serializeInt("patrolRadius", rawPatrolRadius, NO_PATROLING);
  1377. if(!handler.saving)
  1378. {
  1379. patrol.patrolling = (rawPatrolRadius > NO_PATROLING);
  1380. patrol.initialPos = visitablePos();
  1381. patrol.patrolRadius = (rawPatrolRadius > NO_PATROLING) ? rawPatrolRadius : 0;
  1382. }
  1383. }
  1384. }
  1385. void CGHeroInstance::serializeJsonDefinition(JsonSerializeFormat & handler)
  1386. {
  1387. serializeCommonOptions(handler);
  1388. }
  1389. bool CGHeroInstance::isMissionCritical() const
  1390. {
  1391. for(const TriggeredEvent & event : IObjectInterface::cb->getMapHeader()->triggeredEvents)
  1392. {
  1393. if(event.trigger.test([&](const EventCondition & condition)
  1394. {
  1395. if ((condition.condition == EventCondition::CONTROL || condition.condition == EventCondition::HAVE_0) && condition.object)
  1396. {
  1397. auto hero = dynamic_cast<const CGHeroInstance*>(condition.object);
  1398. return (hero != this);
  1399. }
  1400. else if(condition.condition == EventCondition::IS_HUMAN)
  1401. {
  1402. return true;
  1403. }
  1404. return false;
  1405. }))
  1406. {
  1407. return true;
  1408. }
  1409. }
  1410. return false;
  1411. }
  1412. VCMI_LIB_NAMESPACE_END