CCreatureSet.cpp 25 KB

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