CCreatureSet.cpp 23 KB

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