CCreatureSet.cpp 24 KB

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