CCreatureSet.cpp 24 KB

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