CCreatureSet.cpp 23 KB

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