CCreatureSet.cpp 24 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108
  1. /*
  2. * CCreatureSet.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 "CCreatureSet.h"
  12. #include "ArtifactUtils.h"
  13. #include "CConfigHandler.h"
  14. #include "CCreatureHandler.h"
  15. #include "VCMI_Lib.h"
  16. #include "IGameSettings.h"
  17. #include "entities/hero/CHeroHandler.h"
  18. #include "mapObjects/CGHeroInstance.h"
  19. #include "modding/ModScope.h"
  20. #include "IGameCallback.h"
  21. #include "texts/CGeneralTextHandler.h"
  22. #include "spells/CSpellHandler.h"
  23. #include "IBonusTypeHandler.h"
  24. #include "serializer/JsonSerializeFormat.h"
  25. #include <vcmi/FactionService.h>
  26. #include <vcmi/Faction.h>
  27. VCMI_LIB_NAMESPACE_BEGIN
  28. bool CreatureSlotComparer::operator()(const TPairCreatureSlot & lhs, const TPairCreatureSlot & rhs)
  29. {
  30. return lhs.first->getAIValue() < rhs.first->getAIValue(); // Descendant order sorting
  31. }
  32. const CStackInstance & CCreatureSet::operator[](const SlotID & slot) const
  33. {
  34. auto i = stacks.find(slot);
  35. if (i != stacks.end())
  36. return *i->second;
  37. else
  38. throw std::runtime_error("That slot is empty!");
  39. }
  40. const CCreature * CCreatureSet::getCreature(const SlotID & slot) const
  41. {
  42. auto i = stacks.find(slot);
  43. if (i != stacks.end())
  44. return i->second->getCreature();
  45. else
  46. return nullptr;
  47. }
  48. bool CCreatureSet::setCreature(SlotID slot, CreatureID type, TQuantity quantity) /*slots 0 to 6 */
  49. {
  50. if(!slot.validSlot())
  51. {
  52. logGlobal->error("Cannot set slot %d", slot.getNum());
  53. return false;
  54. }
  55. if(!quantity)
  56. {
  57. logGlobal->warn("Using set creature to delete stack?");
  58. eraseStack(slot);
  59. return true;
  60. }
  61. if(hasStackAtSlot(slot)) //remove old creature
  62. eraseStack(slot);
  63. auto * armyObj = castToArmyObj();
  64. bool isHypotheticArmy = armyObj ? armyObj->isHypothetic() : false;
  65. putStack(slot, new CStackInstance(type, quantity, isHypotheticArmy));
  66. return true;
  67. }
  68. SlotID CCreatureSet::getSlotFor(const CreatureID & creature, ui32 slotsAmount) const /*returns -1 if no slot available */
  69. {
  70. return getSlotFor(creature.toCreature(), slotsAmount);
  71. }
  72. SlotID CCreatureSet::getSlotFor(const CCreature *c, ui32 slotsAmount) const
  73. {
  74. assert(c);
  75. for(const auto & elem : stacks)
  76. {
  77. if(elem.second->getType() == c)
  78. {
  79. return elem.first; //if there is already such creature we return its slot id
  80. }
  81. }
  82. return getFreeSlot(slotsAmount);
  83. }
  84. bool CCreatureSet::hasCreatureSlots(const CCreature * c, const SlotID & exclude) const
  85. {
  86. assert(c);
  87. for(const auto & elem : stacks) // elem is const
  88. {
  89. if(elem.first == exclude) // Check slot
  90. continue;
  91. if(!elem.second || !elem.second->getType()) // Check creature
  92. continue;
  93. if(elem.second->getType() == c)
  94. return true;
  95. }
  96. return false;
  97. }
  98. std::vector<SlotID> CCreatureSet::getCreatureSlots(const CCreature * c, const SlotID & exclude, TQuantity ignoreAmount) const
  99. {
  100. assert(c);
  101. std::vector<SlotID> result;
  102. for(const auto & elem : stacks)
  103. {
  104. if(elem.first == exclude)
  105. continue;
  106. if(!elem.second || !elem.second->getType() || elem.second->getType() != c)
  107. continue;
  108. if(elem.second->count == ignoreAmount || elem.second->count < 1)
  109. continue;
  110. result.push_back(elem.first);
  111. }
  112. return result;
  113. }
  114. bool CCreatureSet::isCreatureBalanced(const CCreature * c, TQuantity ignoreAmount) const
  115. {
  116. assert(c);
  117. TQuantity max = 0;
  118. auto min = std::numeric_limits<TQuantity>::max();
  119. for(const auto & elem : stacks)
  120. {
  121. if(!elem.second || !elem.second->getType() || elem.second->getType() != c)
  122. continue;
  123. const auto count = elem.second->count;
  124. if(count == ignoreAmount || count < 1)
  125. continue;
  126. if(count > max)
  127. max = count;
  128. if(count < min)
  129. min = count;
  130. if(max - min > 1)
  131. return false;
  132. }
  133. return true;
  134. }
  135. SlotID CCreatureSet::getFreeSlot(ui32 slotsAmount) const
  136. {
  137. for(ui32 i=0; i<slotsAmount; i++)
  138. {
  139. if(!vstd::contains(stacks, SlotID(i)))
  140. {
  141. return SlotID(i); //return first free slot
  142. }
  143. }
  144. return SlotID(); //no slot available
  145. }
  146. std::vector<SlotID> CCreatureSet::getFreeSlots(ui32 slotsAmount) const
  147. {
  148. std::vector<SlotID> freeSlots;
  149. for(ui32 i = 0; i < slotsAmount; i++)
  150. {
  151. auto slot = SlotID(i);
  152. if(!vstd::contains(stacks, slot))
  153. freeSlots.push_back(slot);
  154. }
  155. return freeSlots;
  156. }
  157. std::queue<SlotID> CCreatureSet::getFreeSlotsQueue(ui32 slotsAmount) const
  158. {
  159. std::queue<SlotID> freeSlots;
  160. for (ui32 i = 0; i < slotsAmount; i++)
  161. {
  162. auto slot = SlotID(i);
  163. if(!vstd::contains(stacks, slot))
  164. freeSlots.push(slot);
  165. }
  166. return freeSlots;
  167. }
  168. TMapCreatureSlot CCreatureSet::getCreatureMap() const
  169. {
  170. TMapCreatureSlot creatureMap;
  171. TMapCreatureSlot::key_compare keyComp = creatureMap.key_comp();
  172. // https://stackoverflow.com/questions/97050/stdmap-insert-or-stdmap-find
  173. // https://www.cplusplus.com/reference/map/map/key_comp/
  174. for(const auto & pair : stacks)
  175. {
  176. const auto * creature = pair.second->getCreature();
  177. auto slot = pair.first;
  178. auto lb = creatureMap.lower_bound(creature);
  179. if(lb != creatureMap.end() && !(keyComp(creature, lb->first)))
  180. continue;
  181. creatureMap.insert(lb, TMapCreatureSlot::value_type(creature, slot));
  182. }
  183. return creatureMap;
  184. }
  185. TCreatureQueue CCreatureSet::getCreatureQueue(const SlotID & exclude) const
  186. {
  187. TCreatureQueue creatureQueue;
  188. for(const auto & pair : stacks)
  189. {
  190. if(pair.first == exclude)
  191. continue;
  192. creatureQueue.push(std::make_pair(pair.second->getCreature(), pair.first));
  193. }
  194. return creatureQueue;
  195. }
  196. TQuantity CCreatureSet::getStackCount(const SlotID & slot) const
  197. {
  198. auto i = stacks.find(slot);
  199. if (i != stacks.end())
  200. return i->second->count;
  201. else
  202. return 0; //TODO? consider issuing a warning
  203. }
  204. TExpType CCreatureSet::getStackExperience(const SlotID & slot) const
  205. {
  206. auto i = stacks.find(slot);
  207. if (i != stacks.end())
  208. return i->second->experience;
  209. else
  210. return 0; //TODO? consider issuing a warning
  211. }
  212. bool CCreatureSet::mergeableStacks(std::pair<SlotID, SlotID> & out, const SlotID & preferable) const /*looks for two same stacks, returns slot positions */
  213. {
  214. //try to match creature to our preferred stack
  215. if(preferable.validSlot() && vstd::contains(stacks, preferable))
  216. {
  217. const CCreature *cr = stacks.find(preferable)->second->getCreature();
  218. for(const auto & elem : stacks)
  219. {
  220. if(cr == elem.second->getType() && elem.first != preferable)
  221. {
  222. out.first = preferable;
  223. out.second = elem.first;
  224. return true;
  225. }
  226. }
  227. }
  228. for(const auto & stack : stacks)
  229. {
  230. for(const auto & elem : stacks)
  231. {
  232. if(stack.second->getType() == elem.second->getType() && stack.first != elem.first)
  233. {
  234. out.first = stack.first;
  235. out.second = elem.first;
  236. return true;
  237. }
  238. }
  239. }
  240. return false;
  241. }
  242. void CCreatureSet::sweep()
  243. {
  244. for(auto i=stacks.begin(); i!=stacks.end(); ++i)
  245. {
  246. if(!i->second->count)
  247. {
  248. stacks.erase(i);
  249. sweep();
  250. break;
  251. }
  252. }
  253. }
  254. void CCreatureSet::addToSlot(const SlotID & slot, const CreatureID & cre, TQuantity count, bool allowMerging)
  255. {
  256. const CCreature *c = cre.toCreature();
  257. if(!hasStackAtSlot(slot))
  258. {
  259. setCreature(slot, cre, count);
  260. }
  261. else if(getCreature(slot) == c && allowMerging) //that slot was empty or contained same type creature
  262. {
  263. setStackCount(slot, getStackCount(slot) + count);
  264. }
  265. else
  266. {
  267. logGlobal->error("Failed adding to slot!");
  268. }
  269. }
  270. void CCreatureSet::addToSlot(const SlotID & slot, CStackInstance * stack, bool allowMerging)
  271. {
  272. assert(stack->valid(true));
  273. if(!hasStackAtSlot(slot))
  274. {
  275. putStack(slot, stack);
  276. }
  277. else if(allowMerging && stack->getType() == getCreature(slot))
  278. {
  279. joinStack(slot, stack);
  280. }
  281. else
  282. {
  283. logGlobal->error("Cannot add to slot %d stack %s", slot.getNum(), stack->nodeName());
  284. }
  285. }
  286. bool CCreatureSet::validTypes(bool allowUnrandomized) const
  287. {
  288. for(const auto & elem : stacks)
  289. {
  290. if(!elem.second->valid(allowUnrandomized))
  291. return false;
  292. }
  293. return true;
  294. }
  295. bool CCreatureSet::slotEmpty(const SlotID & slot) const
  296. {
  297. return !hasStackAtSlot(slot);
  298. }
  299. bool CCreatureSet::needsLastStack() const
  300. {
  301. return false;
  302. }
  303. ui64 CCreatureSet::getArmyStrength() const
  304. {
  305. ui64 ret = 0;
  306. for(const auto & elem : stacks)
  307. ret += elem.second->getPower();
  308. return ret;
  309. }
  310. ui64 CCreatureSet::getArmyCost() const
  311. {
  312. ui64 ret = 0;
  313. for (const auto& elem : stacks)
  314. ret += elem.second->getMarketValue();
  315. return ret;
  316. }
  317. ui64 CCreatureSet::getPower(const SlotID & slot) const
  318. {
  319. return getStack(slot).getPower();
  320. }
  321. std::string CCreatureSet::getRoughAmount(const SlotID & slot, int mode) const
  322. {
  323. /// Mode represent return string format
  324. /// "Pack" - 0, "A pack of" - 1, "a pack of" - 2
  325. CCreature::CreatureQuantityId quantity = CCreature::getQuantityID(getStackCount(slot));
  326. if((int)quantity)
  327. {
  328. if(settings["gameTweaks"]["numericCreaturesQuantities"].Bool())
  329. return CCreature::getQuantityRangeStringForId(quantity);
  330. return VLC->generaltexth->arraytxt[(174 + mode) + 3*(int)quantity];
  331. }
  332. return "";
  333. }
  334. std::string CCreatureSet::getArmyDescription() const
  335. {
  336. std::string text;
  337. std::vector<std::string> guards;
  338. for(const auto & elem : stacks)
  339. {
  340. auto str = boost::str(boost::format("%s %s") % getRoughAmount(elem.first, 2) % getCreature(elem.first)->getNamePluralTranslated());
  341. guards.push_back(str);
  342. }
  343. if(!guards.empty())
  344. {
  345. for(int i = 0; i < guards.size(); i++)
  346. {
  347. text += guards[i];
  348. if(i + 2 < guards.size())
  349. text += ", ";
  350. else if(i + 2 == guards.size())
  351. text += VLC->generaltexth->allTexts[237];
  352. }
  353. }
  354. return text;
  355. }
  356. int CCreatureSet::stacksCount() const
  357. {
  358. return static_cast<int>(stacks.size());
  359. }
  360. void CCreatureSet::setFormation(EArmyFormation mode)
  361. {
  362. formation = mode;
  363. }
  364. void CCreatureSet::setStackCount(const SlotID & slot, TQuantity count)
  365. {
  366. assert(hasStackAtSlot(slot));
  367. assert(stacks[slot]->count + count > 0);
  368. if (count > stacks[slot]->count)
  369. stacks[slot]->experience = static_cast<TExpType>(stacks[slot]->experience * (count / static_cast<double>(stacks[slot]->count)));
  370. stacks[slot]->count = count;
  371. armyChanged();
  372. }
  373. void CCreatureSet::giveStackExp(TExpType exp)
  374. {
  375. for(TSlots::const_iterator i = stacks.begin(); i != stacks.end(); i++)
  376. i->second->giveStackExp(exp);
  377. }
  378. void CCreatureSet::setStackExp(const SlotID & slot, TExpType exp)
  379. {
  380. assert(hasStackAtSlot(slot));
  381. stacks[slot]->experience = exp;
  382. }
  383. void CCreatureSet::clearSlots()
  384. {
  385. while(!stacks.empty())
  386. {
  387. eraseStack(stacks.begin()->first);
  388. }
  389. }
  390. const CStackInstance & CCreatureSet::getStack(const SlotID & slot) const
  391. {
  392. assert(hasStackAtSlot(slot));
  393. return *getStackPtr(slot);
  394. }
  395. CStackInstance * CCreatureSet::getStackPtr(const SlotID & slot) const
  396. {
  397. if(hasStackAtSlot(slot))
  398. return stacks.find(slot)->second;
  399. else return nullptr;
  400. }
  401. void CCreatureSet::eraseStack(const SlotID & slot)
  402. {
  403. assert(hasStackAtSlot(slot));
  404. CStackInstance *toErase = detachStack(slot);
  405. vstd::clear_pointer(toErase);
  406. }
  407. bool CCreatureSet::contains(const CStackInstance *stack) const
  408. {
  409. if(!stack)
  410. return false;
  411. for(const auto & elem : stacks)
  412. if(elem.second == stack)
  413. return true;
  414. return false;
  415. }
  416. SlotID CCreatureSet::findStack(const CStackInstance *stack) const
  417. {
  418. const auto * h = dynamic_cast<const CGHeroInstance *>(this);
  419. if (h && h->commander == stack)
  420. return SlotID::COMMANDER_SLOT_PLACEHOLDER;
  421. if(!stack)
  422. return SlotID();
  423. for(const auto & elem : stacks)
  424. if(elem.second == stack)
  425. return elem.first;
  426. return SlotID();
  427. }
  428. CArmedInstance * CCreatureSet::castToArmyObj()
  429. {
  430. return dynamic_cast<CArmedInstance *>(this);
  431. }
  432. void CCreatureSet::putStack(const SlotID & slot, CStackInstance * stack)
  433. {
  434. assert(slot.getNum() < GameConstants::ARMY_SIZE);
  435. assert(!hasStackAtSlot(slot));
  436. stacks[slot] = stack;
  437. stack->setArmyObj(castToArmyObj());
  438. armyChanged();
  439. }
  440. void CCreatureSet::joinStack(const SlotID & slot, CStackInstance * stack)
  441. {
  442. [[maybe_unused]] const CCreature *c = getCreature(slot);
  443. assert(c == stack->getType());
  444. assert(c);
  445. //TODO move stuff
  446. changeStackCount(slot, stack->count);
  447. vstd::clear_pointer(stack);
  448. }
  449. void CCreatureSet::changeStackCount(const SlotID & slot, TQuantity toAdd)
  450. {
  451. setStackCount(slot, getStackCount(slot) + toAdd);
  452. }
  453. CCreatureSet::~CCreatureSet()
  454. {
  455. clearSlots();
  456. }
  457. void CCreatureSet::setToArmy(CSimpleArmy &src)
  458. {
  459. clearSlots();
  460. while(src)
  461. {
  462. auto i = src.army.begin();
  463. putStack(i->first, new CStackInstance(i->second.first, i->second.second));
  464. src.army.erase(i);
  465. }
  466. }
  467. CStackInstance * CCreatureSet::detachStack(const SlotID & slot)
  468. {
  469. assert(hasStackAtSlot(slot));
  470. CStackInstance *ret = stacks[slot];
  471. //if(CArmedInstance *armedObj = castToArmyObj())
  472. if(ret)
  473. {
  474. ret->setArmyObj(nullptr); //detaches from current armyobj
  475. assert(!ret->armyObj); //we failed detaching?
  476. }
  477. stacks.erase(slot);
  478. armyChanged();
  479. return ret;
  480. }
  481. void CCreatureSet::setStackType(const SlotID & slot, const CreatureID & type)
  482. {
  483. assert(hasStackAtSlot(slot));
  484. CStackInstance *s = stacks[slot];
  485. s->setType(type);
  486. armyChanged();
  487. }
  488. bool CCreatureSet::canBeMergedWith(const CCreatureSet &cs, bool allowMergingStacks) const
  489. {
  490. if(!allowMergingStacks)
  491. {
  492. int freeSlots = stacksCount() - GameConstants::ARMY_SIZE;
  493. std::set<const CCreature*> cresToAdd;
  494. for(const auto & elem : cs.stacks)
  495. {
  496. SlotID dest = getSlotFor(elem.second->getCreature());
  497. if(!dest.validSlot() || hasStackAtSlot(dest))
  498. cresToAdd.insert(elem.second->getCreature());
  499. }
  500. return cresToAdd.size() <= freeSlots;
  501. }
  502. else
  503. {
  504. CCreatureSet cres;
  505. SlotID j;
  506. //get types of creatures that need their own slot
  507. for(const auto & elem : cs.stacks)
  508. if ((j = cres.getSlotFor(elem.second->getCreature())).validSlot())
  509. cres.addToSlot(j, elem.second->getId(), 1, true); //merge if possible
  510. //cres.addToSlot(elem.first, elem.second->type->getId(), 1, true);
  511. for(const auto & elem : stacks)
  512. {
  513. if ((j = cres.getSlotFor(elem.second->getCreature())).validSlot())
  514. cres.addToSlot(j, elem.second->getId(), 1, true); //merge if possible
  515. else
  516. return false; //no place found
  517. }
  518. return true; //all stacks found their slots
  519. }
  520. }
  521. bool CCreatureSet::hasStackAtSlot(const SlotID & slot) const
  522. {
  523. return vstd::contains(stacks, slot);
  524. }
  525. CCreatureSet & CCreatureSet::operator=(const CCreatureSet&cs)
  526. {
  527. assert(0);
  528. return *this;
  529. }
  530. void CCreatureSet::armyChanged()
  531. {
  532. }
  533. void CCreatureSet::serializeJson(JsonSerializeFormat & handler, const std::string & armyFieldName, const std::optional<int> fixedSize)
  534. {
  535. if(handler.saving && stacks.empty())
  536. return;
  537. handler.serializeEnum("formation", formation, NArmyFormation::names);
  538. auto a = handler.enterArray(armyFieldName);
  539. if(handler.saving)
  540. {
  541. size_t sz = 0;
  542. for(const auto & p : stacks)
  543. vstd::amax(sz, p.first.getNum()+1);
  544. if(fixedSize)
  545. vstd::amax(sz, fixedSize.value());
  546. a.resize(sz, JsonNode::JsonType::DATA_STRUCT);
  547. for(const auto & p : stacks)
  548. {
  549. auto s = a.enterStruct(p.first.getNum());
  550. p.second->serializeJson(handler);
  551. }
  552. }
  553. else
  554. {
  555. for(size_t idx = 0; idx < a.size(); idx++)
  556. {
  557. auto s = a.enterStruct(idx);
  558. TQuantity amount = 0;
  559. handler.serializeInt("amount", amount);
  560. if(amount > 0)
  561. {
  562. auto * new_stack = new CStackInstance();
  563. new_stack->serializeJson(handler);
  564. putStack(SlotID(static_cast<si32>(idx)), new_stack);
  565. }
  566. }
  567. }
  568. }
  569. CStackInstance::CStackInstance(bool isHypothetic)
  570. : CBonusSystemNode(isHypothetic),
  571. armyObj(_armyObj),
  572. nativeTerrain(this, Selector::type()(BonusType::TERRAIN_NATIVE)),
  573. initiative(this, Selector::type()(BonusType::STACKS_SPEED))
  574. {
  575. init();
  576. }
  577. CStackInstance::CStackInstance(const CreatureID & id, TQuantity Count, bool isHypothetic)
  578. : CStackInstance(false)
  579. {
  580. init();
  581. setType(id);
  582. count = Count;
  583. }
  584. CStackInstance::CStackInstance(const CCreature *cre, TQuantity Count, bool isHypothetic)
  585. : CStackInstance(false)
  586. {
  587. init();
  588. setType(cre);
  589. count = Count;
  590. }
  591. void CStackInstance::init()
  592. {
  593. experience = 0;
  594. count = 0;
  595. setType(nullptr);
  596. _armyObj = nullptr;
  597. setNodeType(STACK_INSTANCE);
  598. }
  599. CCreature::CreatureQuantityId CStackInstance::getQuantityID() const
  600. {
  601. return CCreature::getQuantityID(count);
  602. }
  603. int CStackInstance::getExpRank() const
  604. {
  605. if (!VLC->engineSettings()->getBoolean(EGameSettings::MODULE_STACK_EXPERIENCE))
  606. return 0;
  607. int tier = getType()->getLevel();
  608. if (vstd::iswithin(tier, 1, 7))
  609. {
  610. for(int i = static_cast<int>(VLC->creh->expRanks[tier].size()) - 2; i > -1; --i) //sic!
  611. { //exp values vary from 1st level to max exp at 11th level
  612. if (experience >= VLC->creh->expRanks[tier][i])
  613. return ++i; //faster, but confusing - 0 index mean 1st level of experience
  614. }
  615. return 0;
  616. }
  617. else //higher tier
  618. {
  619. for(int i = static_cast<int>(VLC->creh->expRanks[0].size()) - 2; i > -1; --i)
  620. {
  621. if (experience >= VLC->creh->expRanks[0][i])
  622. return ++i;
  623. }
  624. return 0;
  625. }
  626. }
  627. int CStackInstance::getLevel() const
  628. {
  629. return std::max(1, getType()->getLevel());
  630. }
  631. void CStackInstance::giveStackExp(TExpType exp)
  632. {
  633. int level = getType()->getLevel();
  634. if (!vstd::iswithin(level, 1, 7))
  635. level = 0;
  636. ui32 maxExp = VLC->creh->expRanks[level].back();
  637. vstd::amin(exp, static_cast<TExpType>(maxExp)); //prevent exp overflow due to different types
  638. vstd::amin(exp, (maxExp * VLC->creh->maxExpPerBattle[level])/100);
  639. vstd::amin(experience += exp, maxExp); //can't get more exp than this limit
  640. }
  641. void CStackInstance::setType(const CreatureID & creID)
  642. {
  643. if (creID == CreatureID::NONE)
  644. setType(nullptr);//FIXME: unused branch?
  645. else
  646. setType(creID.toCreature());
  647. }
  648. void CStackInstance::setType(const CCreature *c)
  649. {
  650. if(getCreature())
  651. {
  652. detachFromSource(*getCreature());
  653. if (getCreature()->isMyUpgrade(c) && VLC->engineSettings()->getBoolean(EGameSettings::MODULE_STACK_EXPERIENCE))
  654. experience = static_cast<TExpType>(experience * VLC->creh->expAfterUpgrade / 100.0);
  655. }
  656. CStackBasicDescriptor::setType(c);
  657. if(getCreature())
  658. attachToSource(*getCreature());
  659. }
  660. std::string CStackInstance::bonusToString(const std::shared_ptr<Bonus>& bonus, bool description) const
  661. {
  662. return VLC->getBth()->bonusToString(bonus, this, description);
  663. }
  664. ImagePath CStackInstance::bonusToGraphics(const std::shared_ptr<Bonus> & bonus) const
  665. {
  666. return VLC->getBth()->bonusToGraphics(bonus);
  667. }
  668. void CStackInstance::setArmyObj(const CArmedInstance * ArmyObj)
  669. {
  670. if(_armyObj)
  671. detachFrom(const_cast<CArmedInstance&>(*_armyObj));
  672. _armyObj = ArmyObj;
  673. if(ArmyObj)
  674. attachTo(const_cast<CArmedInstance&>(*_armyObj));
  675. }
  676. std::string CStackInstance::getQuantityTXT(bool capitalized) const
  677. {
  678. CCreature::CreatureQuantityId quantity = getQuantityID();
  679. if ((int)quantity)
  680. {
  681. if(settings["gameTweaks"]["numericCreaturesQuantities"].Bool())
  682. return CCreature::getQuantityRangeStringForId(quantity);
  683. return VLC->generaltexth->arraytxt[174 + (int)quantity*3 - 1 - capitalized];
  684. }
  685. else
  686. return "";
  687. }
  688. bool CStackInstance::valid(bool allowUnrandomized) const
  689. {
  690. if(!randomStack)
  691. {
  692. return (getType() && getType() == getId().toEntity(VLC));
  693. }
  694. else
  695. return allowUnrandomized;
  696. }
  697. std::string CStackInstance::nodeName() const
  698. {
  699. std::ostringstream oss;
  700. oss << "Stack of " << count << " of ";
  701. if(getType())
  702. oss << getType()->getNamePluralTextID();
  703. else
  704. oss << "[UNDEFINED TYPE]";
  705. return oss.str();
  706. }
  707. PlayerColor CStackInstance::getOwner() const
  708. {
  709. return _armyObj ? _armyObj->getOwner() : PlayerColor::NEUTRAL;
  710. }
  711. int32_t CStackInstance::getInitiative(int turn) const
  712. {
  713. if (turn == 0)
  714. return initiative.getValue();
  715. return ACreature::getInitiative(turn);
  716. }
  717. TerrainId CStackInstance::getNativeTerrain() const
  718. {
  719. if (nativeTerrain.hasBonus())
  720. return TerrainId::ANY_TERRAIN;
  721. return getFactionID().toEntity(VLC)->getNativeTerrain();
  722. }
  723. void CStackInstance::deserializationFix()
  724. {
  725. const CArmedInstance *armyBackup = _armyObj;
  726. _armyObj = nullptr;
  727. setArmyObj(armyBackup);
  728. artDeserializationFix(this);
  729. }
  730. CreatureID CStackInstance::getCreatureID() const
  731. {
  732. if(getType())
  733. return getType()->getId();
  734. else
  735. return CreatureID::NONE;
  736. }
  737. std::string CStackInstance::getName() const
  738. {
  739. return (count > 1) ? getType()->getNamePluralTranslated() : getType()->getNameSingularTranslated();
  740. }
  741. ui64 CStackInstance::getPower() const
  742. {
  743. assert(getType());
  744. return static_cast<ui64>(getType()->getAIValue()) * count;
  745. }
  746. ui64 CStackInstance::getMarketValue() const
  747. {
  748. assert(getType());
  749. return getType()->getFullRecruitCost().marketValue() * count;
  750. }
  751. ArtBearer::ArtBearer CStackInstance::bearerType() const
  752. {
  753. return ArtBearer::CREATURE;
  754. }
  755. CStackInstance::ArtPlacementMap CStackInstance::putArtifact(const ArtifactPosition & pos, CArtifactInstance * art)
  756. {
  757. assert(!getArt(pos));
  758. assert(art->canBePutAt(this, pos));
  759. attachTo(*art);
  760. return CArtifactSet::putArtifact(pos, art);
  761. }
  762. void CStackInstance::removeArtifact(const ArtifactPosition & pos)
  763. {
  764. assert(getArt(pos));
  765. detachFrom(*getArt(pos));
  766. CArtifactSet::removeArtifact(pos);
  767. }
  768. void CStackInstance::serializeJson(JsonSerializeFormat & handler)
  769. {
  770. //todo: artifacts
  771. CStackBasicDescriptor::serializeJson(handler);//must be first
  772. if(handler.saving)
  773. {
  774. if(randomStack)
  775. {
  776. int level = randomStack->level;
  777. int upgrade = randomStack->upgrade;
  778. handler.serializeInt("level", level, 0);
  779. handler.serializeInt("upgraded", upgrade, 0);
  780. }
  781. }
  782. else
  783. {
  784. //type set by CStackBasicDescriptor::serializeJson
  785. if(getType() == nullptr)
  786. {
  787. uint8_t level = 0;
  788. uint8_t upgrade = 0;
  789. handler.serializeInt("level", level, 0);
  790. handler.serializeInt("upgrade", upgrade, 0);
  791. randomStack = RandomStackInfo{ level, upgrade };
  792. }
  793. }
  794. }
  795. FactionID CStackInstance::getFactionID() const
  796. {
  797. if(getType())
  798. return getType()->getFactionID();
  799. return FactionID::NEUTRAL;
  800. }
  801. const IBonusBearer* CStackInstance::getBonusBearer() const
  802. {
  803. return this;
  804. }
  805. CCommanderInstance::CCommanderInstance()
  806. {
  807. init();
  808. }
  809. CCommanderInstance::CCommanderInstance(const CreatureID & id): name("Commando")
  810. {
  811. init();
  812. setType(id);
  813. //TODO - parse them
  814. }
  815. void CCommanderInstance::init()
  816. {
  817. alive = true;
  818. experience = 0;
  819. level = 1;
  820. count = 1;
  821. setType(nullptr);
  822. _armyObj = nullptr;
  823. setNodeType (CBonusSystemNode::COMMANDER);
  824. secondarySkills.resize (ECommander::SPELL_POWER + 1);
  825. }
  826. void CCommanderInstance::setAlive (bool Alive)
  827. {
  828. //TODO: helm of immortality
  829. alive = Alive;
  830. if (!alive)
  831. {
  832. removeBonusesRecursive(Bonus::UntilCommanderKilled);
  833. }
  834. }
  835. void CCommanderInstance::giveStackExp (TExpType exp)
  836. {
  837. if (alive)
  838. experience += exp;
  839. }
  840. int CCommanderInstance::getExpRank() const
  841. {
  842. return VLC->heroh->level (experience);
  843. }
  844. int CCommanderInstance::getLevel() const
  845. {
  846. return std::max (1, getExpRank());
  847. }
  848. void CCommanderInstance::levelUp ()
  849. {
  850. level++;
  851. for(const auto & bonus : VLC->creh->commanderLevelPremy)
  852. { //grant all regular level-up bonuses
  853. accumulateBonus(bonus);
  854. }
  855. }
  856. ArtBearer::ArtBearer CCommanderInstance::bearerType() const
  857. {
  858. return ArtBearer::COMMANDER;
  859. }
  860. bool CCommanderInstance::gainsLevel() const
  861. {
  862. return experience >= VLC->heroh->reqExp(level + 1);
  863. }
  864. //This constructor should be placed here to avoid side effects
  865. CStackBasicDescriptor::CStackBasicDescriptor() = default;
  866. CStackBasicDescriptor::CStackBasicDescriptor(const CreatureID & id, TQuantity Count):
  867. typeID(id),
  868. count(Count)
  869. {
  870. }
  871. CStackBasicDescriptor::CStackBasicDescriptor(const CCreature *c, TQuantity Count)
  872. : typeID(c ? c->getId() : CreatureID()), count(Count)
  873. {
  874. }
  875. const CCreature * CStackBasicDescriptor::getCreature() const
  876. {
  877. return typeID.hasValue() ? typeID.toCreature() : nullptr;
  878. }
  879. const Creature * CStackBasicDescriptor::getType() const
  880. {
  881. return typeID.hasValue() ? typeID.toEntity(VLC) : nullptr;
  882. }
  883. CreatureID CStackBasicDescriptor::getId() const
  884. {
  885. return typeID;
  886. }
  887. TQuantity CStackBasicDescriptor::getCount() const
  888. {
  889. return count;
  890. }
  891. void CStackBasicDescriptor::setType(const CCreature * c)
  892. {
  893. typeID = c ? c->getId() : CreatureID();
  894. }
  895. bool operator== (const CStackBasicDescriptor & l, const CStackBasicDescriptor & r)
  896. {
  897. return l.typeID == r.typeID && l.count == r.count;
  898. }
  899. void CStackBasicDescriptor::serializeJson(JsonSerializeFormat & handler)
  900. {
  901. handler.serializeInt("amount", count);
  902. if(handler.saving)
  903. {
  904. if(typeID.hasValue())
  905. {
  906. std::string typeName = typeID.toEntity(VLC)->getJsonKey();
  907. handler.serializeString("type", typeName);
  908. }
  909. }
  910. else
  911. {
  912. std::string typeName;
  913. handler.serializeString("type", typeName);
  914. if(!typeName.empty())
  915. setType(CreatureID(CreatureID::decode(typeName)).toCreature());
  916. }
  917. }
  918. void CSimpleArmy::clearSlots()
  919. {
  920. army.clear();
  921. }
  922. CSimpleArmy::operator bool() const
  923. {
  924. return !army.empty();
  925. }
  926. bool CSimpleArmy::setCreature(SlotID slot, CreatureID cre, TQuantity count)
  927. {
  928. assert(!vstd::contains(army, slot));
  929. army[slot] = std::make_pair(cre, count);
  930. return true;
  931. }
  932. VCMI_LIB_NAMESPACE_END