CGHeroInstance.cpp 45 KB

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