CGHeroInstance.cpp 45 KB

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