CCreatureSet.cpp 24 KB

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