CCreatureSet.cpp 25 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106
  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 <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->getCreature();
  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, std::make_unique<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);
  75. for(const auto & elem : stacks)
  76. {
  77. if(elem.second->getType() == c)
  78. {
  79. return elem.first; //if there is already such creature we return its slot id
  80. }
  81. }
  82. return getFreeSlot(slotsAmount);
  83. }
  84. bool CCreatureSet::hasCreatureSlots(const CCreature * c, const SlotID & exclude) const
  85. {
  86. assert(c);
  87. for(const auto & elem : stacks) // elem is const
  88. {
  89. if(elem.first == exclude) // Check slot
  90. continue;
  91. if(!elem.second || !elem.second->getType()) // Check creature
  92. continue;
  93. if(elem.second->getType() == c)
  94. return true;
  95. }
  96. return false;
  97. }
  98. std::vector<SlotID> CCreatureSet::getCreatureSlots(const CCreature * c, const SlotID & exclude, TQuantity ignoreAmount) const
  99. {
  100. assert(c);
  101. std::vector<SlotID> result;
  102. for(const auto & elem : stacks)
  103. {
  104. if(elem.first == exclude)
  105. continue;
  106. if(!elem.second || !elem.second->getType() || elem.second->getType() != c)
  107. continue;
  108. if(elem.second->count == ignoreAmount || elem.second->count < 1)
  109. continue;
  110. result.push_back(elem.first);
  111. }
  112. return result;
  113. }
  114. bool CCreatureSet::isCreatureBalanced(const CCreature * c, TQuantity ignoreAmount) const
  115. {
  116. assert(c);
  117. TQuantity max = 0;
  118. auto min = std::numeric_limits<TQuantity>::max();
  119. for(const auto & elem : stacks)
  120. {
  121. if(!elem.second || !elem.second->getType() || elem.second->getType() != c)
  122. continue;
  123. const auto count = elem.second->count;
  124. if(count == ignoreAmount || count < 1)
  125. continue;
  126. if(count > max)
  127. max = count;
  128. if(count < min)
  129. min = count;
  130. if(max - min > 1)
  131. return false;
  132. }
  133. return true;
  134. }
  135. SlotID CCreatureSet::getFreeSlot(ui32 slotsAmount) const
  136. {
  137. for(ui32 i=0; i<slotsAmount; i++)
  138. {
  139. if(!vstd::contains(stacks, SlotID(i)))
  140. {
  141. return SlotID(i); //return first free slot
  142. }
  143. }
  144. return SlotID(); //no slot available
  145. }
  146. std::vector<SlotID> CCreatureSet::getFreeSlots(ui32 slotsAmount) const
  147. {
  148. std::vector<SlotID> freeSlots;
  149. for(ui32 i = 0; i < slotsAmount; i++)
  150. {
  151. auto slot = SlotID(i);
  152. if(!vstd::contains(stacks, slot))
  153. freeSlots.push_back(slot);
  154. }
  155. return freeSlots;
  156. }
  157. std::queue<SlotID> CCreatureSet::getFreeSlotsQueue(ui32 slotsAmount) const
  158. {
  159. std::queue<SlotID> freeSlots;
  160. for (ui32 i = 0; i < slotsAmount; i++)
  161. {
  162. auto slot = SlotID(i);
  163. if(!vstd::contains(stacks, slot))
  164. freeSlots.push(slot);
  165. }
  166. return freeSlots;
  167. }
  168. TMapCreatureSlot CCreatureSet::getCreatureMap() const
  169. {
  170. TMapCreatureSlot creatureMap;
  171. TMapCreatureSlot::key_compare keyComp = creatureMap.key_comp();
  172. // https://stackoverflow.com/questions/97050/stdmap-insert-or-stdmap-find
  173. // https://www.cplusplus.com/reference/map/map/key_comp/
  174. for(const auto & pair : stacks)
  175. {
  176. const auto * creature = pair.second->getCreature();
  177. auto slot = pair.first;
  178. auto lb = creatureMap.lower_bound(creature);
  179. if(lb != creatureMap.end() && !(keyComp(creature, lb->first)))
  180. continue;
  181. creatureMap.insert(lb, TMapCreatureSlot::value_type(creature, slot));
  182. }
  183. return creatureMap;
  184. }
  185. TCreatureQueue CCreatureSet::getCreatureQueue(const SlotID & exclude) const
  186. {
  187. TCreatureQueue creatureQueue;
  188. for(const auto & pair : stacks)
  189. {
  190. if(pair.first == exclude)
  191. continue;
  192. creatureQueue.push(std::make_pair(pair.second->getCreature(), pair.first));
  193. }
  194. return creatureQueue;
  195. }
  196. TQuantity CCreatureSet::getStackCount(const SlotID & slot) const
  197. {
  198. auto i = stacks.find(slot);
  199. if (i != stacks.end())
  200. return i->second->count;
  201. else
  202. return 0; //TODO? consider issuing a warning
  203. }
  204. TExpType CCreatureSet::getStackExperience(const SlotID & slot) const
  205. {
  206. auto i = stacks.find(slot);
  207. if (i != stacks.end())
  208. return i->second->experience;
  209. else
  210. return 0; //TODO? consider issuing a warning
  211. }
  212. bool CCreatureSet::mergeableStacks(std::pair<SlotID, SlotID> & out, const SlotID & preferable) const /*looks for two same stacks, returns slot positions */
  213. {
  214. //try to match creature to our preferred stack
  215. if(preferable.validSlot() && vstd::contains(stacks, preferable))
  216. {
  217. const CCreature *cr = stacks.find(preferable)->second->getCreature();
  218. for(const auto & elem : stacks)
  219. {
  220. if(cr == elem.second->getType() && elem.first != preferable)
  221. {
  222. out.first = preferable;
  223. out.second = elem.first;
  224. return true;
  225. }
  226. }
  227. }
  228. for(const auto & stack : stacks)
  229. {
  230. for(const auto & elem : stacks)
  231. {
  232. if(stack.second->getType() == elem.second->getType() && stack.first != elem.first)
  233. {
  234. out.first = stack.first;
  235. out.second = elem.first;
  236. return true;
  237. }
  238. }
  239. }
  240. return false;
  241. }
  242. void CCreatureSet::sweep()
  243. {
  244. for(auto i=stacks.begin(); i!=stacks.end(); ++i)
  245. {
  246. if(!i->second->count)
  247. {
  248. stacks.erase(i);
  249. sweep();
  250. break;
  251. }
  252. }
  253. }
  254. void CCreatureSet::addToSlot(const SlotID & slot, const CreatureID & cre, TQuantity count, bool allowMerging)
  255. {
  256. const CCreature *c = cre.toCreature();
  257. if(!hasStackAtSlot(slot))
  258. {
  259. setCreature(slot, cre, count);
  260. }
  261. else if(getCreature(slot) == c && allowMerging) //that slot was empty or contained same type creature
  262. {
  263. setStackCount(slot, getStackCount(slot) + count);
  264. }
  265. else
  266. {
  267. logGlobal->error("Failed adding to slot!");
  268. }
  269. }
  270. void CCreatureSet::addToSlot(const SlotID & slot, std::unique_ptr<CStackInstance> stack, bool allowMerging)
  271. {
  272. assert(stack->valid(true));
  273. if(!hasStackAtSlot(slot))
  274. {
  275. putStack(slot, std::move(stack));
  276. }
  277. else if(allowMerging && stack->getType() == getCreature(slot))
  278. {
  279. joinStack(slot, std::move(stack));
  280. }
  281. else
  282. {
  283. logGlobal->error("Cannot add to slot %d stack %s", slot.getNum(), stack->nodeName());
  284. }
  285. }
  286. bool CCreatureSet::validTypes(bool allowUnrandomized) const
  287. {
  288. for(const auto & elem : stacks)
  289. {
  290. if(!elem.second->valid(allowUnrandomized))
  291. return false;
  292. }
  293. return true;
  294. }
  295. bool CCreatureSet::slotEmpty(const SlotID & slot) const
  296. {
  297. return !hasStackAtSlot(slot);
  298. }
  299. bool CCreatureSet::needsLastStack() const
  300. {
  301. return false;
  302. }
  303. ui64 CCreatureSet::getArmyStrength(int fortLevel) const
  304. {
  305. ui64 ret = 0;
  306. for (const auto& elem : stacks)
  307. {
  308. ui64 powerToAdd = elem.second->getPower();
  309. if (fortLevel > 0)
  310. {
  311. if (!elem.second->hasBonusOfType(BonusType::FLYING))
  312. {
  313. powerToAdd /= fortLevel;
  314. if (!elem.second->hasBonusOfType(BonusType::SHOOTER))
  315. powerToAdd /= fortLevel;
  316. }
  317. }
  318. ret += powerToAdd;
  319. }
  320. return ret;
  321. }
  322. ui64 CCreatureSet::getArmyCost() const
  323. {
  324. ui64 ret = 0;
  325. for (const auto& elem : stacks)
  326. ret += elem.second->getMarketValue();
  327. return ret;
  328. }
  329. ui64 CCreatureSet::getPower(const SlotID & slot) const
  330. {
  331. return getStack(slot).getPower();
  332. }
  333. std::string CCreatureSet::getRoughAmount(const SlotID & slot, int mode) const
  334. {
  335. /// Mode represent return string format
  336. /// "Pack" - 0, "A pack of" - 1, "a pack of" - 2
  337. CCreature::CreatureQuantityId quantity = CCreature::getQuantityID(getStackCount(slot));
  338. if((int)quantity)
  339. {
  340. if(settings["gameTweaks"]["numericCreaturesQuantities"].Bool())
  341. return CCreature::getQuantityRangeStringForId(quantity);
  342. return LIBRARY->generaltexth->arraytxt[(174 + mode) + 3*(int)quantity];
  343. }
  344. return "";
  345. }
  346. std::string CCreatureSet::getArmyDescription() const
  347. {
  348. std::string text;
  349. std::vector<std::string> guards;
  350. for(const auto & elem : stacks)
  351. {
  352. auto str = boost::str(boost::format("%s %s") % getRoughAmount(elem.first, 2) % getCreature(elem.first)->getNamePluralTranslated());
  353. guards.push_back(str);
  354. }
  355. if(!guards.empty())
  356. {
  357. for(int i = 0; i < guards.size(); i++)
  358. {
  359. text += guards[i];
  360. if(i + 2 < guards.size())
  361. text += ", ";
  362. else if(i + 2 == guards.size())
  363. text += LIBRARY->generaltexth->allTexts[237];
  364. }
  365. }
  366. return text;
  367. }
  368. int CCreatureSet::stacksCount() const
  369. {
  370. return static_cast<int>(stacks.size());
  371. }
  372. void CCreatureSet::setFormation(EArmyFormation mode)
  373. {
  374. formation = mode;
  375. }
  376. void CCreatureSet::setStackCount(const SlotID & slot, TQuantity count)
  377. {
  378. assert(hasStackAtSlot(slot));
  379. assert(stacks[slot]->count + count > 0);
  380. if (count > stacks[slot]->count)
  381. stacks[slot]->experience = static_cast<TExpType>(stacks[slot]->experience * (count / static_cast<double>(stacks[slot]->count)));
  382. stacks[slot]->count = count;
  383. armyChanged();
  384. }
  385. void CCreatureSet::giveStackExp(TExpType exp)
  386. {
  387. for(TSlots::const_iterator i = stacks.begin(); i != stacks.end(); i++)
  388. i->second->giveStackExp(exp);
  389. }
  390. void CCreatureSet::setStackExp(const SlotID & slot, TExpType exp)
  391. {
  392. assert(hasStackAtSlot(slot));
  393. stacks[slot]->experience = exp;
  394. }
  395. void CCreatureSet::clearSlots()
  396. {
  397. while(!stacks.empty())
  398. {
  399. eraseStack(stacks.begin()->first);
  400. }
  401. }
  402. const CStackInstance & CCreatureSet::getStack(const SlotID & slot) const
  403. {
  404. assert(hasStackAtSlot(slot));
  405. return *getStackPtr(slot);
  406. }
  407. CStackInstance * CCreatureSet::getStackPtr(const SlotID & slot) const
  408. {
  409. if(hasStackAtSlot(slot))
  410. return stacks.find(slot)->second.get();
  411. else return nullptr;
  412. }
  413. void CCreatureSet::eraseStack(const SlotID & slot)
  414. {
  415. assert(hasStackAtSlot(slot));
  416. detachStack(slot);
  417. }
  418. bool CCreatureSet::contains(const CStackInstance *stack) const
  419. {
  420. if(!stack)
  421. return false;
  422. for(const auto & elem : stacks)
  423. if(elem.second.get() == stack)
  424. return true;
  425. return false;
  426. }
  427. SlotID CCreatureSet::findStack(const CStackInstance *stack) const
  428. {
  429. const auto * h = dynamic_cast<const CGHeroInstance *>(this);
  430. if (h && h->getCommander() == stack)
  431. return SlotID::COMMANDER_SLOT_PLACEHOLDER;
  432. if(!stack)
  433. return SlotID();
  434. for(const auto & elem : stacks)
  435. if(elem.second.get() == stack)
  436. return elem.first;
  437. return SlotID();
  438. }
  439. CArmedInstance * CCreatureSet::castToArmyObj()
  440. {
  441. return dynamic_cast<CArmedInstance *>(this);
  442. }
  443. void CCreatureSet::putStack(const SlotID & slot, std::unique_ptr<CStackInstance> stack)
  444. {
  445. assert(slot.getNum() < GameConstants::ARMY_SIZE);
  446. assert(!hasStackAtSlot(slot));
  447. stacks[slot] = std::move(stack);
  448. stack->setArmyObj(castToArmyObj());
  449. armyChanged();
  450. }
  451. void CCreatureSet::joinStack(const SlotID & slot, std::unique_ptr<CStackInstance> stack)
  452. {
  453. [[maybe_unused]] const CCreature *c = getCreature(slot);
  454. assert(c == stack->getType());
  455. assert(c);
  456. //TODO move stuff
  457. changeStackCount(slot, stack->count);
  458. }
  459. void CCreatureSet::changeStackCount(const SlotID & slot, TQuantity toAdd)
  460. {
  461. setStackCount(slot, getStackCount(slot) + toAdd);
  462. }
  463. CCreatureSet::~CCreatureSet()
  464. {
  465. clearSlots();
  466. }
  467. void CCreatureSet::setToArmy(CSimpleArmy &src)
  468. {
  469. clearSlots();
  470. while(src)
  471. {
  472. auto i = src.army.begin();
  473. putStack(i->first, std::make_unique<CStackInstance>(i->second.first, i->second.second));
  474. src.army.erase(i);
  475. }
  476. }
  477. std::unique_ptr<CStackInstance> CCreatureSet::detachStack(const SlotID & slot)
  478. {
  479. assert(hasStackAtSlot(slot));
  480. std::unique_ptr<CStackInstance> ret = std::move(stacks[slot]);
  481. //if(CArmedInstance *armedObj = castToArmyObj())
  482. if(ret)
  483. {
  484. ret->setArmyObj(nullptr); //detaches from current armyobj
  485. assert(!ret->armyObj); //we failed detaching?
  486. }
  487. stacks.erase(slot);
  488. armyChanged();
  489. return ret;
  490. }
  491. void CCreatureSet::setStackType(const SlotID & slot, const CreatureID & type)
  492. {
  493. assert(hasStackAtSlot(slot));
  494. stacks[slot]->setType(type);
  495. armyChanged();
  496. }
  497. bool CCreatureSet::canBeMergedWith(const CCreatureSet &cs, bool allowMergingStacks) const
  498. {
  499. if(!allowMergingStacks)
  500. {
  501. int freeSlots = stacksCount() - GameConstants::ARMY_SIZE;
  502. std::set<const CCreature*> cresToAdd;
  503. for(const auto & elem : cs.stacks)
  504. {
  505. SlotID dest = getSlotFor(elem.second->getCreature());
  506. if(!dest.validSlot() || hasStackAtSlot(dest))
  507. cresToAdd.insert(elem.second->getCreature());
  508. }
  509. return cresToAdd.size() <= freeSlots;
  510. }
  511. else
  512. {
  513. CCreatureSet cres;
  514. SlotID j;
  515. //get types of creatures that need their own slot
  516. for(const auto & elem : cs.stacks)
  517. if ((j = cres.getSlotFor(elem.second->getCreature())).validSlot())
  518. cres.addToSlot(j, elem.second->getId(), 1, true); //merge if possible
  519. //cres.addToSlot(elem.first, elem.second->type->getId(), 1, true);
  520. for(const auto & elem : stacks)
  521. {
  522. if ((j = cres.getSlotFor(elem.second->getCreature())).validSlot())
  523. cres.addToSlot(j, elem.second->getId(), 1, true); //merge if possible
  524. else
  525. return false; //no place found
  526. }
  527. return true; //all stacks found their slots
  528. }
  529. }
  530. bool CCreatureSet::hasStackAtSlot(const SlotID & slot) const
  531. {
  532. return vstd::contains(stacks, slot);
  533. }
  534. CCreatureSet & CCreatureSet::operator=(const CCreatureSet&cs)
  535. {
  536. assert(0);
  537. return *this;
  538. }
  539. void CCreatureSet::armyChanged()
  540. {
  541. }
  542. void CCreatureSet::serializeJson(JsonSerializeFormat & handler, const std::string & armyFieldName, const std::optional<int> fixedSize)
  543. {
  544. if(handler.saving && stacks.empty())
  545. return;
  546. handler.serializeEnum("formation", formation, NArmyFormation::names);
  547. auto a = handler.enterArray(armyFieldName);
  548. if(handler.saving)
  549. {
  550. size_t sz = 0;
  551. for(const auto & p : stacks)
  552. vstd::amax(sz, p.first.getNum()+1);
  553. if(fixedSize)
  554. vstd::amax(sz, fixedSize.value());
  555. a.resize(sz, JsonNode::JsonType::DATA_STRUCT);
  556. for(const auto & p : stacks)
  557. {
  558. auto s = a.enterStruct(p.first.getNum());
  559. p.second->serializeJson(handler);
  560. }
  561. }
  562. else
  563. {
  564. for(size_t idx = 0; idx < a.size(); idx++)
  565. {
  566. auto s = a.enterStruct(idx);
  567. TQuantity amount = 0;
  568. handler.serializeInt("amount", amount);
  569. if(amount > 0)
  570. {
  571. auto new_stack = std::make_unique<CStackInstance>();
  572. new_stack->serializeJson(handler);
  573. putStack(SlotID(static_cast<si32>(idx)), std::move(new_stack));
  574. }
  575. }
  576. }
  577. }
  578. CStackInstance::CStackInstance(bool isHypothetic)
  579. : CBonusSystemNode(isHypothetic)
  580. , nativeTerrain(this, Selector::type()(BonusType::TERRAIN_NATIVE))
  581. , initiative(this, Selector::type()(BonusType::STACKS_SPEED))
  582. , armyObj(_armyObj)
  583. {
  584. experience = 0;
  585. count = 0;
  586. setType(nullptr);
  587. _armyObj = nullptr;
  588. setNodeType(STACK_INSTANCE);
  589. }
  590. CStackInstance::CStackInstance(const CreatureID & id, TQuantity Count, bool isHypothetic)
  591. : CStackInstance(false)
  592. {
  593. setType(id);
  594. count = Count;
  595. }
  596. CStackInstance::CStackInstance(const CCreature *cre, TQuantity Count, bool isHypothetic)
  597. : CStackInstance(false)
  598. {
  599. setType(cre);
  600. count = Count;
  601. }
  602. CCreature::CreatureQuantityId CStackInstance::getQuantityID() const
  603. {
  604. return CCreature::getQuantityID(count);
  605. }
  606. int CStackInstance::getExpRank() const
  607. {
  608. if (!LIBRARY->engineSettings()->getBoolean(EGameSettings::MODULE_STACK_EXPERIENCE))
  609. return 0;
  610. int tier = getType()->getLevel();
  611. if (vstd::iswithin(tier, 1, 7))
  612. {
  613. for(int i = static_cast<int>(LIBRARY->creh->expRanks[tier].size()) - 2; i > -1; --i) //sic!
  614. { //exp values vary from 1st level to max exp at 11th level
  615. if (experience >= LIBRARY->creh->expRanks[tier][i])
  616. return ++i; //faster, but confusing - 0 index mean 1st level of experience
  617. }
  618. return 0;
  619. }
  620. else //higher tier
  621. {
  622. for(int i = static_cast<int>(LIBRARY->creh->expRanks[0].size()) - 2; i > -1; --i)
  623. {
  624. if (experience >= LIBRARY->creh->expRanks[0][i])
  625. return ++i;
  626. }
  627. return 0;
  628. }
  629. }
  630. int CStackInstance::getLevel() const
  631. {
  632. return std::max(1, getType()->getLevel());
  633. }
  634. void CStackInstance::giveStackExp(TExpType exp)
  635. {
  636. int level = getType()->getLevel();
  637. if (!vstd::iswithin(level, 1, 7))
  638. level = 0;
  639. ui32 maxExp = LIBRARY->creh->expRanks[level].back();
  640. vstd::amin(exp, static_cast<TExpType>(maxExp)); //prevent exp overflow due to different types
  641. vstd::amin(exp, (maxExp * LIBRARY->creh->maxExpPerBattle[level])/100);
  642. vstd::amin(experience += exp, maxExp); //can't get more exp than this limit
  643. }
  644. void CStackInstance::setType(const CreatureID & creID)
  645. {
  646. if (creID == CreatureID::NONE)
  647. setType(nullptr);//FIXME: unused branch?
  648. else
  649. setType(creID.toCreature());
  650. }
  651. void CStackInstance::setType(const CCreature *c)
  652. {
  653. if(getCreature())
  654. {
  655. detachFromSource(*getCreature());
  656. if (getCreature()->isMyUpgrade(c) && LIBRARY->engineSettings()->getBoolean(EGameSettings::MODULE_STACK_EXPERIENCE))
  657. experience = static_cast<TExpType>(experience * LIBRARY->creh->expAfterUpgrade / 100.0);
  658. }
  659. CStackBasicDescriptor::setType(c);
  660. if(getCreature())
  661. attachToSource(*getCreature());
  662. }
  663. std::string CStackInstance::bonusToString(const std::shared_ptr<Bonus>& bonus, bool description) const
  664. {
  665. return LIBRARY->getBth()->bonusToString(bonus, this, description);
  666. }
  667. ImagePath CStackInstance::bonusToGraphics(const std::shared_ptr<Bonus> & bonus) const
  668. {
  669. return LIBRARY->getBth()->bonusToGraphics(bonus);
  670. }
  671. void CStackInstance::setArmyObj(const CArmedInstance * ArmyObj)
  672. {
  673. if(_armyObj)
  674. detachFrom(const_cast<CArmedInstance&>(*_armyObj));
  675. _armyObj = ArmyObj;
  676. if(ArmyObj)
  677. attachTo(const_cast<CArmedInstance&>(*_armyObj));
  678. }
  679. std::string CStackInstance::getQuantityTXT(bool capitalized) const
  680. {
  681. CCreature::CreatureQuantityId quantity = getQuantityID();
  682. if ((int)quantity)
  683. {
  684. if(settings["gameTweaks"]["numericCreaturesQuantities"].Bool())
  685. return CCreature::getQuantityRangeStringForId(quantity);
  686. return LIBRARY->generaltexth->arraytxt[174 + (int)quantity*3 - 1 - capitalized];
  687. }
  688. else
  689. return "";
  690. }
  691. bool CStackInstance::valid(bool allowUnrandomized) const
  692. {
  693. if(!randomStack)
  694. {
  695. return (getType() && getType() == getId().toEntity(LIBRARY));
  696. }
  697. else
  698. return allowUnrandomized;
  699. }
  700. std::string CStackInstance::nodeName() const
  701. {
  702. std::ostringstream oss;
  703. oss << "Stack of " << count << " of ";
  704. if(getType())
  705. oss << getType()->getNamePluralTextID();
  706. else
  707. oss << "[UNDEFINED TYPE]";
  708. return oss.str();
  709. }
  710. PlayerColor CStackInstance::getOwner() const
  711. {
  712. return _armyObj ? _armyObj->getOwner() : PlayerColor::NEUTRAL;
  713. }
  714. int32_t CStackInstance::getInitiative(int turn) const
  715. {
  716. if (turn == 0)
  717. return initiative.getValue();
  718. return ACreature::getInitiative(turn);
  719. }
  720. TerrainId CStackInstance::getNativeTerrain() const
  721. {
  722. if (nativeTerrain.hasBonus())
  723. return TerrainId::ANY_TERRAIN;
  724. return getFactionID().toEntity(LIBRARY)->getNativeTerrain();
  725. }
  726. TerrainId CStackInstance::getCurrentTerrain() const
  727. {
  728. return armyObj->getCurrentTerrain();
  729. }
  730. void CStackInstance::deserializationFix()
  731. {
  732. const CArmedInstance *armyBackup = _armyObj;
  733. _armyObj = nullptr;
  734. setArmyObj(armyBackup);
  735. artDeserializationFix(this);
  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() = default;
  813. CCommanderInstance::CCommanderInstance(const CreatureID & id): name("Commando")
  814. {
  815. alive = true;
  816. experience = 0;
  817. level = 1;
  818. count = 1;
  819. setType(nullptr);
  820. _armyObj = nullptr;
  821. setNodeType (CBonusSystemNode::COMMANDER);
  822. secondarySkills.resize (ECommander::SPELL_POWER + 1);
  823. setType(id);
  824. //TODO - parse them
  825. }
  826. void CCommanderInstance::setAlive (bool Alive)
  827. {
  828. //TODO: helm of immortality
  829. alive = Alive;
  830. if (!alive)
  831. {
  832. removeBonusesRecursive(Bonus::UntilCommanderKilled);
  833. }
  834. }
  835. void CCommanderInstance::giveStackExp (TExpType exp)
  836. {
  837. if (alive)
  838. experience += exp;
  839. }
  840. int CCommanderInstance::getExpRank() const
  841. {
  842. return LIBRARY->heroh->level (experience);
  843. }
  844. int CCommanderInstance::getLevel() const
  845. {
  846. return std::max (1, getExpRank());
  847. }
  848. void CCommanderInstance::levelUp ()
  849. {
  850. level++;
  851. for(const auto & bonus : LIBRARY->creh->commanderLevelPremy)
  852. { //grant all regular level-up bonuses
  853. accumulateBonus(bonus);
  854. }
  855. }
  856. ArtBearer::ArtBearer CCommanderInstance::bearerType() const
  857. {
  858. return ArtBearer::COMMANDER;
  859. }
  860. bool CCommanderInstance::gainsLevel() const
  861. {
  862. return experience >= LIBRARY->heroh->reqExp(level + 1);
  863. }
  864. //This constructor should be placed here to avoid side effects
  865. CStackBasicDescriptor::CStackBasicDescriptor() = default;
  866. CStackBasicDescriptor::CStackBasicDescriptor(const CreatureID & id, TQuantity Count):
  867. typeID(id),
  868. count(Count)
  869. {
  870. }
  871. CStackBasicDescriptor::CStackBasicDescriptor(const CCreature *c, TQuantity Count)
  872. : typeID(c ? c->getId() : CreatureID()), count(Count)
  873. {
  874. }
  875. const CCreature * CStackBasicDescriptor::getCreature() const
  876. {
  877. return typeID.hasValue() ? typeID.toCreature() : nullptr;
  878. }
  879. const Creature * CStackBasicDescriptor::getType() const
  880. {
  881. return typeID.hasValue() ? typeID.toEntity(LIBRARY) : nullptr;
  882. }
  883. CreatureID CStackBasicDescriptor::getId() const
  884. {
  885. return typeID;
  886. }
  887. TQuantity CStackBasicDescriptor::getCount() const
  888. {
  889. return count;
  890. }
  891. void CStackBasicDescriptor::setType(const CCreature * c)
  892. {
  893. typeID = c ? c->getId() : CreatureID();
  894. }
  895. bool operator== (const CStackBasicDescriptor & l, const CStackBasicDescriptor & r)
  896. {
  897. return l.typeID == r.typeID && l.count == r.count;
  898. }
  899. void CStackBasicDescriptor::serializeJson(JsonSerializeFormat & handler)
  900. {
  901. handler.serializeInt("amount", count);
  902. if(handler.saving)
  903. {
  904. if(typeID.hasValue())
  905. {
  906. std::string typeName = typeID.toEntity(LIBRARY)->getJsonKey();
  907. handler.serializeString("type", typeName);
  908. }
  909. }
  910. else
  911. {
  912. std::string typeName;
  913. handler.serializeString("type", typeName);
  914. if(!typeName.empty())
  915. setType(CreatureID(CreatureID::decode(typeName)).toCreature());
  916. }
  917. }
  918. void CSimpleArmy::clearSlots()
  919. {
  920. army.clear();
  921. }
  922. CSimpleArmy::operator bool() const
  923. {
  924. return !army.empty();
  925. }
  926. bool CSimpleArmy::setCreature(SlotID slot, CreatureID cre, TQuantity count)
  927. {
  928. assert(!vstd::contains(army, slot));
  929. army[slot] = std::make_pair(cre, count);
  930. return true;
  931. }
  932. VCMI_LIB_NAMESPACE_END