CCreatureSet.cpp 23 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079
  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 "GameSettings.h"
  17. #include "mapObjects/CGHeroInstance.h"
  18. #include "modding/ModScope.h"
  19. #include "IGameCallback.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 <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->type;
  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 && c->valid());
  75. for(const auto & elem : stacks)
  76. {
  77. assert(elem.second->type->valid());
  78. if(elem.second->type == c)
  79. {
  80. return elem.first; //if there is already such creature we return its slot id
  81. }
  82. }
  83. return getFreeSlot(slotsAmount);
  84. }
  85. bool CCreatureSet::hasCreatureSlots(const CCreature * c, const SlotID & exclude) const
  86. {
  87. assert(c && c->valid());
  88. for(const auto & elem : stacks) // elem is const
  89. {
  90. if(elem.first == exclude) // Check slot
  91. continue;
  92. if(!elem.second || !elem.second->type) // Check creature
  93. continue;
  94. assert(elem.second->type->valid());
  95. if(elem.second->type == c)
  96. return true;
  97. }
  98. return false;
  99. }
  100. std::vector<SlotID> CCreatureSet::getCreatureSlots(const CCreature * c, const SlotID & exclude, TQuantity ignoreAmount) const
  101. {
  102. assert(c && c->valid());
  103. std::vector<SlotID> result;
  104. for(const auto & elem : stacks)
  105. {
  106. if(elem.first == exclude)
  107. continue;
  108. if(!elem.second || !elem.second->type || elem.second->type != c)
  109. continue;
  110. if(elem.second->count == ignoreAmount || elem.second->count < 1)
  111. continue;
  112. assert(elem.second->type->valid());
  113. result.push_back(elem.first);
  114. }
  115. return result;
  116. }
  117. bool CCreatureSet::isCreatureBalanced(const CCreature * c, TQuantity ignoreAmount) const
  118. {
  119. assert(c && c->valid());
  120. TQuantity max = 0;
  121. auto min = std::numeric_limits<TQuantity>::max();
  122. for(const auto & elem : stacks)
  123. {
  124. if(!elem.second || !elem.second->type || elem.second->type != c)
  125. continue;
  126. const auto count = elem.second->count;
  127. if(count == ignoreAmount || count < 1)
  128. continue;
  129. assert(elem.second->type->valid());
  130. if(count > max)
  131. max = count;
  132. if(count < min)
  133. min = count;
  134. if(max - min > 1)
  135. return false;
  136. }
  137. return true;
  138. }
  139. SlotID CCreatureSet::getFreeSlot(ui32 slotsAmount) const
  140. {
  141. for(ui32 i=0; i<slotsAmount; i++)
  142. {
  143. if(!vstd::contains(stacks, SlotID(i)))
  144. {
  145. return SlotID(i); //return first free slot
  146. }
  147. }
  148. return SlotID(); //no slot available
  149. }
  150. std::vector<SlotID> CCreatureSet::getFreeSlots(ui32 slotsAmount) const
  151. {
  152. std::vector<SlotID> freeSlots;
  153. for(ui32 i = 0; i < slotsAmount; i++)
  154. {
  155. auto slot = SlotID(i);
  156. if(!vstd::contains(stacks, slot))
  157. freeSlots.push_back(slot);
  158. }
  159. return freeSlots;
  160. }
  161. std::queue<SlotID> CCreatureSet::getFreeSlotsQueue(ui32 slotsAmount) const
  162. {
  163. std::queue<SlotID> freeSlots;
  164. for (ui32 i = 0; i < slotsAmount; i++)
  165. {
  166. auto slot = SlotID(i);
  167. if(!vstd::contains(stacks, slot))
  168. freeSlots.push(slot);
  169. }
  170. return freeSlots;
  171. }
  172. TMapCreatureSlot CCreatureSet::getCreatureMap() const
  173. {
  174. TMapCreatureSlot creatureMap;
  175. TMapCreatureSlot::key_compare keyComp = creatureMap.key_comp();
  176. // https://stackoverflow.com/questions/97050/stdmap-insert-or-stdmap-find
  177. // https://www.cplusplus.com/reference/map/map/key_comp/
  178. for(const auto & pair : stacks)
  179. {
  180. const auto * creature = pair.second->type;
  181. auto slot = pair.first;
  182. auto lb = creatureMap.lower_bound(creature);
  183. if(lb != creatureMap.end() && !(keyComp(creature, lb->first)))
  184. continue;
  185. creatureMap.insert(lb, TMapCreatureSlot::value_type(creature, slot));
  186. }
  187. return creatureMap;
  188. }
  189. TCreatureQueue CCreatureSet::getCreatureQueue(const SlotID & exclude) const
  190. {
  191. TCreatureQueue creatureQueue;
  192. for(const auto & pair : stacks)
  193. {
  194. if(pair.first == exclude)
  195. continue;
  196. creatureQueue.push(std::make_pair(pair.second->type, pair.first));
  197. }
  198. return creatureQueue;
  199. }
  200. TQuantity CCreatureSet::getStackCount(const SlotID & slot) const
  201. {
  202. auto i = stacks.find(slot);
  203. if (i != stacks.end())
  204. return i->second->count;
  205. else
  206. return 0; //TODO? consider issuing a warning
  207. }
  208. TExpType CCreatureSet::getStackExperience(const SlotID & slot) const
  209. {
  210. auto i = stacks.find(slot);
  211. if (i != stacks.end())
  212. return i->second->experience;
  213. else
  214. return 0; //TODO? consider issuing a warning
  215. }
  216. bool CCreatureSet::mergableStacks(std::pair<SlotID, SlotID> & out, const SlotID & preferable) const /*looks for two same stacks, returns slot positions */
  217. {
  218. //try to match creature to our preferred stack
  219. if(preferable.validSlot() && vstd::contains(stacks, preferable))
  220. {
  221. const CCreature *cr = stacks.find(preferable)->second->type;
  222. for(const auto & elem : stacks)
  223. {
  224. if(cr == elem.second->type && elem.first != preferable)
  225. {
  226. out.first = preferable;
  227. out.second = elem.first;
  228. return true;
  229. }
  230. }
  231. }
  232. for(const auto & stack : stacks)
  233. {
  234. for(const auto & elem : stacks)
  235. {
  236. if(stack.second->type == elem.second->type && stack.first != elem.first)
  237. {
  238. out.first = stack.first;
  239. out.second = elem.first;
  240. return true;
  241. }
  242. }
  243. }
  244. return false;
  245. }
  246. void CCreatureSet::sweep()
  247. {
  248. for(auto i=stacks.begin(); i!=stacks.end(); ++i)
  249. {
  250. if(!i->second->count)
  251. {
  252. stacks.erase(i);
  253. sweep();
  254. break;
  255. }
  256. }
  257. }
  258. void CCreatureSet::addToSlot(const SlotID & slot, const CreatureID & cre, TQuantity count, bool allowMerging)
  259. {
  260. const CCreature *c = cre.toCreature();
  261. if(!hasStackAtSlot(slot))
  262. {
  263. setCreature(slot, cre, count);
  264. }
  265. else if(getCreature(slot) == c && allowMerging) //that slot was empty or contained same type creature
  266. {
  267. setStackCount(slot, getStackCount(slot) + count);
  268. }
  269. else
  270. {
  271. logGlobal->error("Failed adding to slot!");
  272. }
  273. }
  274. void CCreatureSet::addToSlot(const SlotID & slot, CStackInstance * stack, bool allowMerging)
  275. {
  276. assert(stack->valid(true));
  277. if(!hasStackAtSlot(slot))
  278. {
  279. putStack(slot, stack);
  280. }
  281. else if(allowMerging && stack->type == getCreature(slot))
  282. {
  283. joinStack(slot, stack);
  284. }
  285. else
  286. {
  287. logGlobal->error("Cannot add to slot %d stack %s", slot.getNum(), stack->nodeName());
  288. }
  289. }
  290. bool CCreatureSet::validTypes(bool allowUnrandomized) const
  291. {
  292. for(const auto & elem : stacks)
  293. {
  294. if(!elem.second->valid(allowUnrandomized))
  295. return false;
  296. }
  297. return true;
  298. }
  299. bool CCreatureSet::slotEmpty(const SlotID & slot) const
  300. {
  301. return !hasStackAtSlot(slot);
  302. }
  303. bool CCreatureSet::needsLastStack() const
  304. {
  305. return false;
  306. }
  307. ui64 CCreatureSet::getArmyStrength() const
  308. {
  309. ui64 ret = 0;
  310. for(const auto & elem : stacks)
  311. ret += elem.second->getPower();
  312. return ret;
  313. }
  314. ui64 CCreatureSet::getPower(const SlotID & slot) const
  315. {
  316. return getStack(slot).getPower();
  317. }
  318. std::string CCreatureSet::getRoughAmount(const SlotID & slot, int mode) const
  319. {
  320. /// Mode represent return string format
  321. /// "Pack" - 0, "A pack of" - 1, "a pack of" - 2
  322. CCreature::CreatureQuantityId quantity = CCreature::getQuantityID(getStackCount(slot));
  323. if((int)quantity)
  324. {
  325. if(settings["gameTweaks"]["numericCreaturesQuantities"].Bool())
  326. return CCreature::getQuantityRangeStringForId(quantity);
  327. return VLC->generaltexth->arraytxt[(174 + mode) + 3*(int)quantity];
  328. }
  329. return "";
  330. }
  331. std::string CCreatureSet::getArmyDescription() const
  332. {
  333. std::string text;
  334. std::vector<std::string> guards;
  335. for(const auto & elem : stacks)
  336. {
  337. auto str = boost::str(boost::format("%s %s") % getRoughAmount(elem.first, 2) % getCreature(elem.first)->getNamePluralTranslated());
  338. guards.push_back(str);
  339. }
  340. if(!guards.empty())
  341. {
  342. for(int i = 0; i < guards.size(); i++)
  343. {
  344. text += guards[i];
  345. if(i + 2 < guards.size())
  346. text += ", ";
  347. else if(i + 2 == guards.size())
  348. text += VLC->generaltexth->allTexts[237];
  349. }
  350. }
  351. return text;
  352. }
  353. int CCreatureSet::stacksCount() const
  354. {
  355. return static_cast<int>(stacks.size());
  356. }
  357. void CCreatureSet::setFormation(EArmyFormation mode)
  358. {
  359. formation = mode;
  360. }
  361. void CCreatureSet::setStackCount(const SlotID & slot, TQuantity count)
  362. {
  363. assert(hasStackAtSlot(slot));
  364. assert(stacks[slot]->count + count > 0);
  365. if (VLC->settings()->getBoolean(EGameSettings::MODULE_STACK_EXPERIENCE) && count > stacks[slot]->count)
  366. stacks[slot]->experience = static_cast<TExpType>(stacks[slot]->experience * (count / static_cast<double>(stacks[slot]->count)));
  367. stacks[slot]->count = count;
  368. armyChanged();
  369. }
  370. void CCreatureSet::giveStackExp(TExpType exp)
  371. {
  372. for(TSlots::const_iterator i = stacks.begin(); i != stacks.end(); i++)
  373. i->second->giveStackExp(exp);
  374. }
  375. void CCreatureSet::setStackExp(const SlotID & slot, TExpType exp)
  376. {
  377. assert(hasStackAtSlot(slot));
  378. stacks[slot]->experience = exp;
  379. }
  380. void CCreatureSet::clearSlots()
  381. {
  382. while(!stacks.empty())
  383. {
  384. eraseStack(stacks.begin()->first);
  385. }
  386. }
  387. const CStackInstance & CCreatureSet::getStack(const SlotID & slot) const
  388. {
  389. assert(hasStackAtSlot(slot));
  390. return *getStackPtr(slot);
  391. }
  392. CStackInstance * CCreatureSet::getStackPtr(const SlotID & slot) const
  393. {
  394. if(hasStackAtSlot(slot))
  395. return stacks.find(slot)->second;
  396. else return nullptr;
  397. }
  398. void CCreatureSet::eraseStack(const SlotID & slot)
  399. {
  400. assert(hasStackAtSlot(slot));
  401. CStackInstance *toErase = detachStack(slot);
  402. vstd::clear_pointer(toErase);
  403. }
  404. bool CCreatureSet::contains(const CStackInstance *stack) const
  405. {
  406. if(!stack)
  407. return false;
  408. for(const auto & elem : stacks)
  409. if(elem.second == stack)
  410. return true;
  411. return false;
  412. }
  413. SlotID CCreatureSet::findStack(const CStackInstance *stack) const
  414. {
  415. const auto * h = dynamic_cast<const CGHeroInstance *>(this);
  416. if (h && h->commander == stack)
  417. return SlotID::COMMANDER_SLOT_PLACEHOLDER;
  418. if(!stack)
  419. return SlotID();
  420. for(const auto & elem : stacks)
  421. if(elem.second == stack)
  422. return elem.first;
  423. return SlotID();
  424. }
  425. CArmedInstance * CCreatureSet::castToArmyObj()
  426. {
  427. return dynamic_cast<CArmedInstance *>(this);
  428. }
  429. void CCreatureSet::putStack(const SlotID & slot, CStackInstance * stack)
  430. {
  431. assert(slot.getNum() < GameConstants::ARMY_SIZE);
  432. assert(!hasStackAtSlot(slot));
  433. stacks[slot] = stack;
  434. stack->setArmyObj(castToArmyObj());
  435. armyChanged();
  436. }
  437. void CCreatureSet::joinStack(const SlotID & slot, CStackInstance * stack)
  438. {
  439. [[maybe_unused]] const CCreature *c = getCreature(slot);
  440. assert(c == stack->type);
  441. assert(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. clearSlots();
  453. }
  454. void CCreatureSet::setToArmy(CSimpleArmy &src)
  455. {
  456. clearSlots();
  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 & armyFieldName, const std::optional<int> fixedSize)
  531. {
  532. if(handler.saving && stacks.empty())
  533. return;
  534. handler.serializeEnum("formation", formation, NArmyFormation::names);
  535. auto a = handler.enterArray(armyFieldName);
  536. if(handler.saving)
  537. {
  538. size_t sz = 0;
  539. for(const auto & p : stacks)
  540. vstd::amax(sz, p.first.getNum()+1);
  541. if(fixedSize)
  542. vstd::amax(sz, fixedSize.value());
  543. a.resize(sz, JsonNode::JsonType::DATA_STRUCT);
  544. for(const auto & p : stacks)
  545. {
  546. auto s = a.enterStruct(p.first.getNum());
  547. p.second->serializeJson(handler);
  548. }
  549. }
  550. else
  551. {
  552. for(size_t idx = 0; idx < a.size(); idx++)
  553. {
  554. auto s = a.enterStruct(idx);
  555. TQuantity amount = 0;
  556. handler.serializeInt("amount", amount);
  557. if(amount > 0)
  558. {
  559. auto * new_stack = new CStackInstance();
  560. new_stack->serializeJson(handler);
  561. putStack(SlotID(static_cast<si32>(idx)), new_stack);
  562. }
  563. }
  564. }
  565. }
  566. CStackInstance::CStackInstance()
  567. : armyObj(_armyObj)
  568. {
  569. init();
  570. }
  571. CStackInstance::CStackInstance(const CreatureID & id, TQuantity Count, bool isHypothetic):
  572. CBonusSystemNode(isHypothetic), armyObj(_armyObj)
  573. {
  574. init();
  575. setType(id);
  576. count = Count;
  577. }
  578. CStackInstance::CStackInstance(const CCreature *cre, TQuantity Count, bool isHypothetic)
  579. : CBonusSystemNode(isHypothetic), armyObj(_armyObj)
  580. {
  581. init();
  582. setType(cre);
  583. count = Count;
  584. }
  585. void CStackInstance::init()
  586. {
  587. experience = 0;
  588. count = 0;
  589. type = nullptr;
  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. void CStackInstance::giveStackExp(TExpType exp)
  626. {
  627. int level = type->getLevel();
  628. if (!vstd::iswithin(level, 1, 7))
  629. level = 0;
  630. CCreatureHandler * creh = VLC->creh;
  631. ui32 maxExp = creh->expRanks[level].back();
  632. vstd::amin(exp, static_cast<TExpType>(maxExp)); //prevent exp overflow due to different types
  633. vstd::amin(exp, (maxExp * creh->maxExpPerBattle[level])/100);
  634. vstd::amin(experience += exp, maxExp); //can't get more exp than this limit
  635. }
  636. void CStackInstance::setType(const CreatureID & creID)
  637. {
  638. if (creID == CreatureID::NONE)
  639. setType(nullptr);//FIXME: unused branch?
  640. else
  641. setType(creID.toCreature());
  642. }
  643. void CStackInstance::setType(const CCreature *c)
  644. {
  645. if(type)
  646. {
  647. detachFrom(const_cast<CCreature&>(*type));
  648. if (type->isMyUpgrade(c) && VLC->settings()->getBoolean(EGameSettings::MODULE_STACK_EXPERIENCE))
  649. experience = static_cast<TExpType>(experience * VLC->creh->expAfterUpgrade / 100.0);
  650. }
  651. CStackBasicDescriptor::setType(c);
  652. if(type)
  653. attachTo(const_cast<CCreature&>(*type));
  654. }
  655. std::string CStackInstance::bonusToString(const std::shared_ptr<Bonus>& bonus, bool description) const
  656. {
  657. return VLC->getBth()->bonusToString(bonus, this, description);
  658. }
  659. ImagePath CStackInstance::bonusToGraphics(const std::shared_ptr<Bonus> & bonus) const
  660. {
  661. return VLC->getBth()->bonusToGraphics(bonus);
  662. }
  663. void CStackInstance::setArmyObj(const CArmedInstance * ArmyObj)
  664. {
  665. if(_armyObj)
  666. detachFrom(const_cast<CArmedInstance&>(*_armyObj));
  667. _armyObj = ArmyObj;
  668. if(ArmyObj)
  669. attachTo(const_cast<CArmedInstance&>(*_armyObj));
  670. }
  671. std::string CStackInstance::getQuantityTXT(bool capitalized) const
  672. {
  673. CCreature::CreatureQuantityId quantity = getQuantityID();
  674. if ((int)quantity)
  675. {
  676. if(settings["gameTweaks"]["numericCreaturesQuantities"].Bool())
  677. return CCreature::getQuantityRangeStringForId(quantity);
  678. return VLC->generaltexth->arraytxt[174 + (int)quantity*3 - 1 - capitalized];
  679. }
  680. else
  681. return "";
  682. }
  683. bool CStackInstance::valid(bool allowUnrandomized) const
  684. {
  685. if(!randomStack)
  686. {
  687. return (type && type == type->getId().toEntity(VLC));
  688. }
  689. else
  690. return allowUnrandomized;
  691. }
  692. std::string CStackInstance::nodeName() const
  693. {
  694. std::ostringstream oss;
  695. oss << "Stack of " << count << " of ";
  696. if(type)
  697. oss << type->getNamePluralTextID();
  698. else
  699. oss << "[UNDEFINED TYPE]";
  700. return oss.str();
  701. }
  702. PlayerColor CStackInstance::getOwner() const
  703. {
  704. return _armyObj ? _armyObj->getOwner() : PlayerColor::NEUTRAL;
  705. }
  706. void CStackInstance::deserializationFix()
  707. {
  708. const CArmedInstance *armyBackup = _armyObj;
  709. _armyObj = nullptr;
  710. setArmyObj(armyBackup);
  711. artDeserializationFix(this);
  712. }
  713. CreatureID CStackInstance::getCreatureID() const
  714. {
  715. if(type)
  716. return type->getId();
  717. else
  718. return CreatureID::NONE;
  719. }
  720. std::string CStackInstance::getName() const
  721. {
  722. return (count > 1) ? type->getNamePluralTranslated() : type->getNameSingularTranslated();
  723. }
  724. ui64 CStackInstance::getPower() const
  725. {
  726. assert(type);
  727. return type->getAIValue() * count;
  728. }
  729. ArtBearer::ArtBearer CStackInstance::bearerType() const
  730. {
  731. return ArtBearer::CREATURE;
  732. }
  733. CStackInstance::ArtPlacementMap CStackInstance::putArtifact(ArtifactPosition pos, CArtifactInstance * art)
  734. {
  735. assert(!getArt(pos));
  736. assert(art->canBePutAt(this, pos));
  737. attachTo(*art);
  738. return CArtifactSet::putArtifact(pos, art);
  739. }
  740. void CStackInstance::removeArtifact(ArtifactPosition pos)
  741. {
  742. assert(getArt(pos));
  743. detachFrom(*getArt(pos));
  744. CArtifactSet::removeArtifact(pos);
  745. }
  746. void CStackInstance::serializeJson(JsonSerializeFormat & handler)
  747. {
  748. //todo: artifacts
  749. CStackBasicDescriptor::serializeJson(handler);//must be first
  750. if(handler.saving)
  751. {
  752. if(randomStack)
  753. {
  754. int level = randomStack->level;
  755. int upgrade = randomStack->upgrade;
  756. handler.serializeInt("level", level, 0);
  757. handler.serializeInt("upgraded", upgrade, 0);
  758. }
  759. }
  760. else
  761. {
  762. //type set by CStackBasicDescriptor::serializeJson
  763. if(type == nullptr)
  764. {
  765. uint8_t level = 0;
  766. uint8_t upgrade = 0;
  767. handler.serializeInt("level", level, 0);
  768. handler.serializeInt("upgrade", upgrade, 0);
  769. randomStack = RandomStackInfo{ level, upgrade };
  770. }
  771. }
  772. }
  773. FactionID CStackInstance::getFaction() const
  774. {
  775. if(type)
  776. return type->getFaction();
  777. return FactionID::NEUTRAL;
  778. }
  779. const IBonusBearer* CStackInstance::getBonusBearer() const
  780. {
  781. return this;
  782. }
  783. CCommanderInstance::CCommanderInstance()
  784. {
  785. init();
  786. }
  787. CCommanderInstance::CCommanderInstance(const CreatureID & id): name("Commando")
  788. {
  789. init();
  790. setType(id);
  791. //TODO - parse them
  792. }
  793. void CCommanderInstance::init()
  794. {
  795. alive = true;
  796. experience = 0;
  797. level = 1;
  798. count = 1;
  799. type = nullptr;
  800. _armyObj = nullptr;
  801. setNodeType (CBonusSystemNode::COMMANDER);
  802. secondarySkills.resize (ECommander::SPELL_POWER + 1);
  803. }
  804. void CCommanderInstance::setAlive (bool Alive)
  805. {
  806. //TODO: helm of immortality
  807. alive = Alive;
  808. if (!alive)
  809. {
  810. removeBonusesRecursive(Bonus::UntilCommanderKilled);
  811. }
  812. }
  813. void CCommanderInstance::giveStackExp (TExpType exp)
  814. {
  815. if (alive)
  816. experience += exp;
  817. }
  818. int CCommanderInstance::getExpRank() const
  819. {
  820. return VLC->heroh->level (experience);
  821. }
  822. int CCommanderInstance::getLevel() const
  823. {
  824. return std::max (1, getExpRank());
  825. }
  826. void CCommanderInstance::levelUp ()
  827. {
  828. level++;
  829. for(const auto & bonus : VLC->creh->commanderLevelPremy)
  830. { //grant all regular level-up bonuses
  831. accumulateBonus(bonus);
  832. }
  833. }
  834. ArtBearer::ArtBearer CCommanderInstance::bearerType() const
  835. {
  836. return ArtBearer::COMMANDER;
  837. }
  838. bool CCommanderInstance::gainsLevel() const
  839. {
  840. return experience >= VLC->heroh->reqExp(level + 1);
  841. }
  842. //This constructor should be placed here to avoid side effects
  843. CStackBasicDescriptor::CStackBasicDescriptor() = default;
  844. CStackBasicDescriptor::CStackBasicDescriptor(const CreatureID & id, TQuantity Count):
  845. type(id.toCreature()),
  846. count(Count)
  847. {
  848. }
  849. CStackBasicDescriptor::CStackBasicDescriptor(const CCreature *c, TQuantity Count)
  850. : type(c), count(Count)
  851. {
  852. }
  853. const Creature * CStackBasicDescriptor::getType() const
  854. {
  855. return type;
  856. }
  857. CreatureID CStackBasicDescriptor::getId() const
  858. {
  859. return type->getId();
  860. }
  861. TQuantity CStackBasicDescriptor::getCount() const
  862. {
  863. return count;
  864. }
  865. void CStackBasicDescriptor::setType(const CCreature * c)
  866. {
  867. type = c;
  868. }
  869. bool operator== (const CStackBasicDescriptor & l, const CStackBasicDescriptor & r)
  870. {
  871. return (!l.type && !r.type)
  872. || (l.type && r.type
  873. && l.type->getId() == r.type->getId()
  874. && l.count == r.count);
  875. }
  876. void CStackBasicDescriptor::serializeJson(JsonSerializeFormat & handler)
  877. {
  878. handler.serializeInt("amount", count);
  879. if(handler.saving)
  880. {
  881. if(type)
  882. {
  883. std::string typeName = type->getJsonKey();
  884. handler.serializeString("type", typeName);
  885. }
  886. }
  887. else
  888. {
  889. std::string typeName;
  890. handler.serializeString("type", typeName);
  891. if(!typeName.empty())
  892. setType(VLC->creh->getCreature(ModScope::scopeMap(), typeName));
  893. }
  894. }
  895. void CSimpleArmy::clearSlots()
  896. {
  897. army.clear();
  898. }
  899. CSimpleArmy::operator bool() const
  900. {
  901. return !army.empty();
  902. }
  903. bool CSimpleArmy::setCreature(SlotID slot, CreatureID cre, TQuantity count)
  904. {
  905. assert(!vstd::contains(army, slot));
  906. army[slot] = std::make_pair(cre, count);
  907. return true;
  908. }
  909. VCMI_LIB_NAMESPACE_END