2
0

CCreatureSet.cpp 25 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 "CConfigHandler.h"
  13. #include "CCreatureHandler.h"
  14. #include "GameLibrary.h"
  15. #include "IGameSettings.h"
  16. #include "entities/hero/CHeroHandler.h"
  17. #include "mapObjects/CGHeroInstance.h"
  18. #include "modding/ModScope.h"
  19. #include "IGameCallback.h"
  20. #include "texts/CGeneralTextHandler.h"
  21. #include "spells/CSpellHandler.h"
  22. #include "IBonusTypeHandler.h"
  23. #include "serializer/JsonSerializeFormat.h"
  24. #include "gameState/CGameState.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 = getArmy();
  64. bool isHypotheticArmy = armyObj ? armyObj->isHypothetic() : false;
  65. putStack(slot, std::make_unique<CStackInstance>(armyObj ? armyObj->cb : nullptr, 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, std::unique_ptr<CStackInstance> stack, bool allowMerging)
  271. {
  272. assert(stack->valid(true));
  273. if(!hasStackAtSlot(slot))
  274. {
  275. putStack(slot, std::move(stack));
  276. }
  277. else if(allowMerging && stack->getType() == getCreature(slot))
  278. {
  279. joinStack(slot, std::move(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(int fortLevel) const
  304. {
  305. ui64 ret = 0;
  306. for (const auto& elem : stacks)
  307. {
  308. ui64 powerToAdd = elem.second->getPower();
  309. if (fortLevel > 0)
  310. {
  311. if (!elem.second->hasBonusOfType(BonusType::FLYING))
  312. {
  313. powerToAdd /= fortLevel;
  314. if (!elem.second->hasBonusOfType(BonusType::SHOOTER))
  315. powerToAdd /= fortLevel;
  316. }
  317. }
  318. ret += powerToAdd;
  319. }
  320. return ret;
  321. }
  322. ui64 CCreatureSet::getArmyCost() const
  323. {
  324. ui64 ret = 0;
  325. for (const auto& elem : stacks)
  326. ret += elem.second->getMarketValue();
  327. return ret;
  328. }
  329. ui64 CCreatureSet::getPower(const SlotID & slot) const
  330. {
  331. return getStack(slot).getPower();
  332. }
  333. std::string CCreatureSet::getRoughAmount(const SlotID & slot, int mode) const
  334. {
  335. /// Mode represent return string format
  336. /// "Pack" - 0, "A pack of" - 1, "a pack of" - 2
  337. CCreature::CreatureQuantityId quantity = CCreature::getQuantityID(getStackCount(slot));
  338. if((int)quantity)
  339. {
  340. if(settings["gameTweaks"]["numericCreaturesQuantities"].Bool())
  341. return CCreature::getQuantityRangeStringForId(quantity);
  342. return LIBRARY->generaltexth->arraytxt[(174 + mode) + 3*(int)quantity];
  343. }
  344. return "";
  345. }
  346. std::string CCreatureSet::getArmyDescription() const
  347. {
  348. std::string text;
  349. std::vector<std::string> guards;
  350. for(const auto & elem : stacks)
  351. {
  352. auto str = boost::str(boost::format("%s %s") % getRoughAmount(elem.first, 2) % getCreature(elem.first)->getNamePluralTranslated());
  353. guards.push_back(str);
  354. }
  355. if(!guards.empty())
  356. {
  357. for(int i = 0; i < guards.size(); i++)
  358. {
  359. text += guards[i];
  360. if(i + 2 < guards.size())
  361. text += ", ";
  362. else if(i + 2 == guards.size())
  363. text += LIBRARY->generaltexth->allTexts[237];
  364. }
  365. }
  366. return text;
  367. }
  368. int CCreatureSet::stacksCount() const
  369. {
  370. return static_cast<int>(stacks.size());
  371. }
  372. void CCreatureSet::setFormation(EArmyFormation mode)
  373. {
  374. formation = mode;
  375. }
  376. void CCreatureSet::setStackCount(const SlotID & slot, TQuantity count)
  377. {
  378. assert(hasStackAtSlot(slot));
  379. assert(stacks[slot]->count + count > 0);
  380. if (count > stacks[slot]->count)
  381. stacks[slot]->experience = static_cast<TExpType>(stacks[slot]->experience * (count / static_cast<double>(stacks[slot]->count)));
  382. stacks[slot]->count = count;
  383. armyChanged();
  384. }
  385. void CCreatureSet::giveStackExp(TExpType exp)
  386. {
  387. for(TSlots::const_iterator i = stacks.begin(); i != stacks.end(); i++)
  388. i->second->giveStackExp(exp);
  389. }
  390. void CCreatureSet::setStackExp(const SlotID & slot, TExpType exp)
  391. {
  392. assert(hasStackAtSlot(slot));
  393. stacks[slot]->experience = exp;
  394. }
  395. void CCreatureSet::clearSlots()
  396. {
  397. while(!stacks.empty())
  398. {
  399. eraseStack(stacks.begin()->first);
  400. }
  401. }
  402. const CStackInstance & CCreatureSet::getStack(const SlotID & slot) const
  403. {
  404. assert(hasStackAtSlot(slot));
  405. return *getStackPtr(slot);
  406. }
  407. CStackInstance * CCreatureSet::getStackPtr(const SlotID & slot) const
  408. {
  409. if(hasStackAtSlot(slot))
  410. return stacks.find(slot)->second.get();
  411. else return nullptr;
  412. }
  413. void CCreatureSet::eraseStack(const SlotID & slot)
  414. {
  415. assert(hasStackAtSlot(slot));
  416. detachStack(slot);
  417. }
  418. bool CCreatureSet::contains(const CStackInstance *stack) const
  419. {
  420. if(!stack)
  421. return false;
  422. for(const auto & elem : stacks)
  423. if(elem.second.get() == stack)
  424. return true;
  425. return false;
  426. }
  427. SlotID CCreatureSet::findStack(const CStackInstance *stack) const
  428. {
  429. const auto * h = dynamic_cast<const CGHeroInstance *>(this);
  430. if (h && h->getCommander() == stack)
  431. return SlotID::COMMANDER_SLOT_PLACEHOLDER;
  432. if(!stack)
  433. return SlotID();
  434. for(const auto & elem : stacks)
  435. if(elem.second.get() == stack)
  436. return elem.first;
  437. return SlotID();
  438. }
  439. void CCreatureSet::putStack(const SlotID & slot, std::unique_ptr<CStackInstance> stack)
  440. {
  441. assert(slot.getNum() < GameConstants::ARMY_SIZE);
  442. assert(!hasStackAtSlot(slot));
  443. stacks[slot] = std::move(stack);
  444. stacks[slot]->setArmy(getArmy());
  445. armyChanged();
  446. }
  447. void CCreatureSet::joinStack(const SlotID & slot, std::unique_ptr<CStackInstance> stack)
  448. {
  449. [[maybe_unused]] const CCreature *c = getCreature(slot);
  450. assert(c == stack->getType());
  451. assert(c);
  452. //TODO move stuff
  453. changeStackCount(slot, stack->count);
  454. }
  455. void CCreatureSet::changeStackCount(const SlotID & slot, TQuantity toAdd)
  456. {
  457. setStackCount(slot, getStackCount(slot) + toAdd);
  458. }
  459. CCreatureSet::~CCreatureSet() = default;
  460. void CCreatureSet::setToArmy(CSimpleArmy &src)
  461. {
  462. clearSlots();
  463. while(src)
  464. {
  465. auto i = src.army.begin();
  466. putStack(i->first, std::make_unique<CStackInstance>(getArmy()->cb, i->second.first, i->second.second));
  467. src.army.erase(i);
  468. }
  469. }
  470. std::unique_ptr<CStackInstance> CCreatureSet::detachStack(const SlotID & slot)
  471. {
  472. assert(hasStackAtSlot(slot));
  473. std::unique_ptr<CStackInstance> ret = std::move(stacks[slot]);
  474. //if(CArmedInstance *armedObj = castToArmyObj())
  475. if(ret)
  476. {
  477. ret->setArmy(nullptr); //detaches from current armyobj
  478. assert(!ret->getArmy()); //we failed detaching?
  479. }
  480. stacks.erase(slot);
  481. armyChanged();
  482. return ret;
  483. }
  484. void CCreatureSet::setStackType(const SlotID & slot, const CreatureID & type)
  485. {
  486. assert(hasStackAtSlot(slot));
  487. stacks[slot]->setType(type);
  488. armyChanged();
  489. }
  490. bool CCreatureSet::canBeMergedWith(const CCreatureSet &cs, bool allowMergingStacks) const
  491. {
  492. if(!allowMergingStacks)
  493. {
  494. int freeSlots = stacksCount() - GameConstants::ARMY_SIZE;
  495. std::set<const CCreature*> cresToAdd;
  496. for(const auto & elem : cs.stacks)
  497. {
  498. SlotID dest = getSlotFor(elem.second->getCreature());
  499. if(!dest.validSlot() || hasStackAtSlot(dest))
  500. cresToAdd.insert(elem.second->getCreature());
  501. }
  502. return cresToAdd.size() <= freeSlots;
  503. }
  504. else
  505. {
  506. CCreatureSet cres;
  507. SlotID j;
  508. //get types of creatures that need their own slot
  509. for(const auto & elem : cs.stacks)
  510. if ((j = cres.getSlotFor(elem.second->getCreature())).validSlot())
  511. cres.addToSlot(j, elem.second->getId(), 1, true); //merge if possible
  512. //cres.addToSlot(elem.first, elem.second->type->getId(), 1, true);
  513. for(const auto & elem : stacks)
  514. {
  515. if ((j = cres.getSlotFor(elem.second->getCreature())).validSlot())
  516. cres.addToSlot(j, elem.second->getId(), 1, true); //merge if possible
  517. else
  518. return false; //no place found
  519. }
  520. return true; //all stacks found their slots
  521. }
  522. }
  523. bool CCreatureSet::hasStackAtSlot(const SlotID & slot) const
  524. {
  525. return vstd::contains(stacks, slot);
  526. }
  527. CCreatureSet & CCreatureSet::operator=(const CCreatureSet&cs)
  528. {
  529. assert(0);
  530. return *this;
  531. }
  532. void CCreatureSet::armyChanged()
  533. {
  534. }
  535. void CCreatureSet::serializeJson(JsonSerializeFormat & handler, const std::string & armyFieldName, const std::optional<int> fixedSize)
  536. {
  537. if(handler.saving && stacks.empty())
  538. return;
  539. handler.serializeEnum("formation", formation, NArmyFormation::names);
  540. auto a = handler.enterArray(armyFieldName);
  541. if(handler.saving)
  542. {
  543. size_t sz = 0;
  544. for(const auto & p : stacks)
  545. vstd::amax(sz, p.first.getNum()+1);
  546. if(fixedSize)
  547. vstd::amax(sz, fixedSize.value());
  548. a.resize(sz, JsonNode::JsonType::DATA_STRUCT);
  549. for(const auto & p : stacks)
  550. {
  551. auto s = a.enterStruct(p.first.getNum());
  552. p.second->serializeJson(handler);
  553. }
  554. }
  555. else
  556. {
  557. for(size_t idx = 0; idx < a.size(); idx++)
  558. {
  559. auto s = a.enterStruct(idx);
  560. TQuantity amount = 0;
  561. handler.serializeInt("amount", amount);
  562. if(amount > 0)
  563. {
  564. auto newStack = std::make_unique<CStackInstance>(getArmy()->cb);
  565. newStack->serializeJson(handler);
  566. putStack(SlotID(static_cast<si32>(idx)), std::move(newStack));
  567. }
  568. }
  569. }
  570. }
  571. CStackInstance::CStackInstance(IGameCallback *cb, bool isHypothetic)
  572. : CBonusSystemNode(isHypothetic)
  573. , CArtifactSet(cb)
  574. , GameCallbackHolder(cb)
  575. , nativeTerrain(this, Selector::type()(BonusType::TERRAIN_NATIVE))
  576. , initiative(this, Selector::type()(BonusType::STACKS_SPEED))
  577. {
  578. experience = 0;
  579. count = 0;
  580. setType(nullptr);
  581. setNodeType(STACK_INSTANCE);
  582. }
  583. CStackInstance::CStackInstance(IGameCallback *cb, const CreatureID & id, TQuantity Count, bool isHypothetic)
  584. : CStackInstance(cb, false)
  585. {
  586. setType(id);
  587. count = Count;
  588. }
  589. CCreature::CreatureQuantityId CStackInstance::getQuantityID() const
  590. {
  591. return CCreature::getQuantityID(count);
  592. }
  593. int CStackInstance::getExpRank() const
  594. {
  595. if (!LIBRARY->engineSettings()->getBoolean(EGameSettings::MODULE_STACK_EXPERIENCE))
  596. return 0;
  597. int tier = getType()->getLevel();
  598. if (vstd::iswithin(tier, 1, 7))
  599. {
  600. for(int i = static_cast<int>(LIBRARY->creh->expRanks[tier].size()) - 2; i > -1; --i) //sic!
  601. { //exp values vary from 1st level to max exp at 11th level
  602. if (experience >= LIBRARY->creh->expRanks[tier][i])
  603. return ++i; //faster, but confusing - 0 index mean 1st level of experience
  604. }
  605. return 0;
  606. }
  607. else //higher tier
  608. {
  609. for(int i = static_cast<int>(LIBRARY->creh->expRanks[0].size()) - 2; i > -1; --i)
  610. {
  611. if (experience >= LIBRARY->creh->expRanks[0][i])
  612. return ++i;
  613. }
  614. return 0;
  615. }
  616. }
  617. int CStackInstance::getLevel() const
  618. {
  619. return std::max(1, getType()->getLevel());
  620. }
  621. void CStackInstance::giveStackExp(TExpType exp)
  622. {
  623. int level = getType()->getLevel();
  624. if (!vstd::iswithin(level, 1, 7))
  625. level = 0;
  626. ui32 maxExp = LIBRARY->creh->expRanks[level].back();
  627. vstd::amin(exp, static_cast<TExpType>(maxExp)); //prevent exp overflow due to different types
  628. vstd::amin(exp, (maxExp * LIBRARY->creh->maxExpPerBattle[level])/100);
  629. vstd::amin(experience += exp, maxExp); //can't get more exp than this limit
  630. }
  631. void CStackInstance::setType(const CreatureID & creID)
  632. {
  633. if (creID == CreatureID::NONE)
  634. setType(nullptr);//FIXME: unused branch?
  635. else
  636. setType(creID.toCreature());
  637. }
  638. void CStackInstance::setType(const CCreature *c)
  639. {
  640. if(getCreature())
  641. {
  642. detachFromSource(*getCreature());
  643. if (getCreature()->isMyUpgrade(c) && LIBRARY->engineSettings()->getBoolean(EGameSettings::MODULE_STACK_EXPERIENCE))
  644. experience = static_cast<TExpType>(experience * LIBRARY->creh->expAfterUpgrade / 100.0);
  645. }
  646. CStackBasicDescriptor::setType(c);
  647. if(getCreature())
  648. attachToSource(*getCreature());
  649. }
  650. std::string CStackInstance::bonusToString(const std::shared_ptr<Bonus>& bonus, bool description) const
  651. {
  652. return LIBRARY->getBth()->bonusToString(bonus, this, description);
  653. }
  654. ImagePath CStackInstance::bonusToGraphics(const std::shared_ptr<Bonus> & bonus) const
  655. {
  656. return LIBRARY->getBth()->bonusToGraphics(bonus);
  657. }
  658. CArmedInstance * CStackInstance::getArmy()
  659. {
  660. if (armyInstanceID.hasValue())
  661. return dynamic_cast<CArmedInstance*>(cb->gameState().getObjInstance(armyInstanceID));
  662. return nullptr;
  663. }
  664. const CArmedInstance * CStackInstance::getArmy() const
  665. {
  666. if (armyInstanceID.hasValue())
  667. return dynamic_cast<const CArmedInstance*>(cb->getObjInstance(armyInstanceID));
  668. return nullptr;
  669. }
  670. void CStackInstance::setArmy(const CArmedInstance * ArmyObj)
  671. {
  672. auto oldArmy = getArmy();
  673. if(oldArmy)
  674. {
  675. detachFrom(*oldArmy);
  676. armyInstanceID = {};
  677. }
  678. if(ArmyObj)
  679. {
  680. attachTo(const_cast<CArmedInstance&>(*ArmyObj));
  681. armyInstanceID = ArmyObj->id;
  682. }
  683. }
  684. std::string CStackInstance::getQuantityTXT(bool capitalized) const
  685. {
  686. CCreature::CreatureQuantityId quantity = getQuantityID();
  687. if ((int)quantity)
  688. {
  689. if(settings["gameTweaks"]["numericCreaturesQuantities"].Bool())
  690. return CCreature::getQuantityRangeStringForId(quantity);
  691. return LIBRARY->generaltexth->arraytxt[174 + (int)quantity*3 - 1 - capitalized];
  692. }
  693. else
  694. return "";
  695. }
  696. bool CStackInstance::valid(bool allowUnrandomized) const
  697. {
  698. if(!randomStack)
  699. {
  700. return (getType() && getType() == getId().toEntity(LIBRARY));
  701. }
  702. else
  703. return allowUnrandomized;
  704. }
  705. std::string CStackInstance::nodeName() const
  706. {
  707. std::ostringstream oss;
  708. oss << "Stack of " << count << " of ";
  709. if(getType())
  710. oss << getType()->getNamePluralTextID();
  711. else
  712. oss << "[UNDEFINED TYPE]";
  713. return oss.str();
  714. }
  715. PlayerColor CStackInstance::getOwner() const
  716. {
  717. auto army = getArmy();
  718. return army ? army->getOwner() : PlayerColor::NEUTRAL;
  719. }
  720. int32_t CStackInstance::getInitiative(int turn) const
  721. {
  722. if (turn == 0)
  723. return initiative.getValue();
  724. return ACreature::getInitiative(turn);
  725. }
  726. TerrainId CStackInstance::getNativeTerrain() const
  727. {
  728. if (nativeTerrain.hasBonus())
  729. return TerrainId::ANY_TERRAIN;
  730. return getFactionID().toEntity(LIBRARY)->getNativeTerrain();
  731. }
  732. TerrainId CStackInstance::getCurrentTerrain() const
  733. {
  734. return getArmy()->getCurrentTerrain();
  735. }
  736. CreatureID CStackInstance::getCreatureID() const
  737. {
  738. if(getType())
  739. return getType()->getId();
  740. else
  741. return CreatureID::NONE;
  742. }
  743. std::string CStackInstance::getName() const
  744. {
  745. return (count > 1) ? getType()->getNamePluralTranslated() : getType()->getNameSingularTranslated();
  746. }
  747. ui64 CStackInstance::getPower() const
  748. {
  749. assert(getType());
  750. return static_cast<ui64>(getType()->getAIValue()) * count;
  751. }
  752. ui64 CStackInstance::getMarketValue() const
  753. {
  754. assert(getType());
  755. return getType()->getFullRecruitCost().marketValue() * count;
  756. }
  757. ArtBearer::ArtBearer CStackInstance::bearerType() const
  758. {
  759. return ArtBearer::CREATURE;
  760. }
  761. CStackInstance::ArtPlacementMap CStackInstance::putArtifact(const ArtifactPosition & pos, const CArtifactInstance * art)
  762. {
  763. assert(!getArt(pos));
  764. assert(art->canBePutAt(this, pos));
  765. attachToSource(*art);
  766. return CArtifactSet::putArtifact(pos, art);
  767. }
  768. void CStackInstance::removeArtifact(const ArtifactPosition & pos)
  769. {
  770. assert(getArt(pos));
  771. detachFromSource(*getArt(pos));
  772. CArtifactSet::removeArtifact(pos);
  773. }
  774. void CStackInstance::serializeJson(JsonSerializeFormat & handler)
  775. {
  776. //todo: artifacts
  777. CStackBasicDescriptor::serializeJson(handler);//must be first
  778. if(handler.saving)
  779. {
  780. if(randomStack)
  781. {
  782. int level = randomStack->level;
  783. int upgrade = randomStack->upgrade;
  784. handler.serializeInt("level", level, 0);
  785. handler.serializeInt("upgraded", upgrade, 0);
  786. }
  787. }
  788. else
  789. {
  790. //type set by CStackBasicDescriptor::serializeJson
  791. if(getType() == nullptr)
  792. {
  793. uint8_t level = 0;
  794. uint8_t upgrade = 0;
  795. handler.serializeInt("level", level, 0);
  796. handler.serializeInt("upgrade", upgrade, 0);
  797. randomStack = RandomStackInfo{ level, upgrade };
  798. }
  799. }
  800. }
  801. FactionID CStackInstance::getFactionID() const
  802. {
  803. if(getType())
  804. return getType()->getFactionID();
  805. return FactionID::NEUTRAL;
  806. }
  807. const IBonusBearer* CStackInstance::getBonusBearer() const
  808. {
  809. return this;
  810. }
  811. CCommanderInstance::CCommanderInstance(IGameCallback *cb)
  812. :CStackInstance(cb)
  813. {}
  814. CCommanderInstance::CCommanderInstance(IGameCallback *cb, const CreatureID & id)
  815. : CStackInstance(cb)
  816. , name("Commando")
  817. {
  818. alive = true;
  819. experience = 0;
  820. level = 1;
  821. count = 1;
  822. setType(nullptr);
  823. setNodeType (CBonusSystemNode::COMMANDER);
  824. secondarySkills.resize (ECommander::SPELL_POWER + 1);
  825. setType(id);
  826. //TODO - parse them
  827. }
  828. void CCommanderInstance::setAlive (bool Alive)
  829. {
  830. //TODO: helm of immortality
  831. alive = Alive;
  832. if (!alive)
  833. {
  834. removeBonusesRecursive(Bonus::UntilCommanderKilled);
  835. }
  836. }
  837. void CCommanderInstance::giveStackExp (TExpType exp)
  838. {
  839. if (alive)
  840. experience += exp;
  841. }
  842. int CCommanderInstance::getExpRank() const
  843. {
  844. return LIBRARY->heroh->level (experience);
  845. }
  846. int CCommanderInstance::getLevel() const
  847. {
  848. return std::max (1, getExpRank());
  849. }
  850. void CCommanderInstance::levelUp ()
  851. {
  852. level++;
  853. for(const auto & bonus : LIBRARY->creh->commanderLevelPremy)
  854. { //grant all regular level-up bonuses
  855. accumulateBonus(bonus);
  856. }
  857. }
  858. ArtBearer::ArtBearer CCommanderInstance::bearerType() const
  859. {
  860. return ArtBearer::COMMANDER;
  861. }
  862. bool CCommanderInstance::gainsLevel() const
  863. {
  864. return experience >= LIBRARY->heroh->reqExp(level + 1);
  865. }
  866. //This constructor should be placed here to avoid side effects
  867. CStackBasicDescriptor::CStackBasicDescriptor() = default;
  868. CStackBasicDescriptor::CStackBasicDescriptor(const CreatureID & id, TQuantity Count):
  869. typeID(id),
  870. count(Count)
  871. {
  872. }
  873. CStackBasicDescriptor::CStackBasicDescriptor(const CCreature *c, TQuantity Count)
  874. : typeID(c ? c->getId() : CreatureID()), count(Count)
  875. {
  876. }
  877. const CCreature * CStackBasicDescriptor::getCreature() const
  878. {
  879. return typeID.hasValue() ? typeID.toCreature() : nullptr;
  880. }
  881. const Creature * CStackBasicDescriptor::getType() const
  882. {
  883. return typeID.hasValue() ? typeID.toEntity(LIBRARY) : nullptr;
  884. }
  885. CreatureID CStackBasicDescriptor::getId() const
  886. {
  887. return typeID;
  888. }
  889. TQuantity CStackBasicDescriptor::getCount() const
  890. {
  891. return count;
  892. }
  893. void CStackBasicDescriptor::setType(const CCreature * c)
  894. {
  895. typeID = c ? c->getId() : CreatureID();
  896. }
  897. bool operator== (const CStackBasicDescriptor & l, const CStackBasicDescriptor & r)
  898. {
  899. return l.typeID == r.typeID && l.count == r.count;
  900. }
  901. void CStackBasicDescriptor::serializeJson(JsonSerializeFormat & handler)
  902. {
  903. handler.serializeInt("amount", count);
  904. if(handler.saving)
  905. {
  906. if(typeID.hasValue())
  907. {
  908. std::string typeName = typeID.toEntity(LIBRARY)->getJsonKey();
  909. handler.serializeString("type", typeName);
  910. }
  911. }
  912. else
  913. {
  914. std::string typeName;
  915. handler.serializeString("type", typeName);
  916. if(!typeName.empty())
  917. setType(CreatureID(CreatureID::decode(typeName)).toCreature());
  918. }
  919. }
  920. void CSimpleArmy::clearSlots()
  921. {
  922. army.clear();
  923. }
  924. CSimpleArmy::operator bool() const
  925. {
  926. return !army.empty();
  927. }
  928. bool CSimpleArmy::setCreature(SlotID slot, CreatureID cre, TQuantity count)
  929. {
  930. assert(!vstd::contains(army, slot));
  931. army[slot] = std::make_pair(cre, count);
  932. return true;
  933. }
  934. VCMI_LIB_NAMESPACE_END