CCreatureSet.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158
  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 "GameLibrary.h"
  15. #include "IGameSettings.h"
  16. #include "entities/hero/CHeroHandler.h"
  17. #include "mapObjects/CGHeroInstance.h"
  18. #include "modding/ModScope.h"
  19. #include "IGameCallback.h"
  20. #include "texts/CGeneralTextHandler.h"
  21. #include "spells/CSpellHandler.h"
  22. #include "IBonusTypeHandler.h"
  23. #include "serializer/JsonSerializeFormat.h"
  24. #include "gameState/CGameState.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 = getArmy();
  64. bool isHypotheticArmy = armyObj ? armyObj->isHypothetic() : false;
  65. putStack(slot, std::make_unique<CStackInstance>(armyObj ? armyObj->cb : nullptr, 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->getCount() == ignoreAmount || elem.second->getCount() < 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->getCount();
  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. if (!hasStackAtSlot(slot))
  199. return 0;
  200. return stacks.at(slot)->getCount();
  201. }
  202. TExpType CCreatureSet::getStackTotalExperience(const SlotID & slot) const
  203. {
  204. return stacks.at(slot)->getTotalExperience();
  205. }
  206. TExpType CCreatureSet::getStackAverageExperience(const SlotID & slot) const
  207. {
  208. return stacks.at(slot)->getAverageExperience();
  209. }
  210. bool CCreatureSet::mergeableStacks(std::pair<SlotID, SlotID> & out, const SlotID & preferable) const /*looks for two same stacks, returns slot positions */
  211. {
  212. //try to match creature to our preferred stack
  213. if(preferable.validSlot() && vstd::contains(stacks, preferable))
  214. {
  215. const CCreature *cr = stacks.find(preferable)->second->getCreature();
  216. for(const auto & elem : stacks)
  217. {
  218. if(cr == elem.second->getType() && elem.first != preferable)
  219. {
  220. out.first = preferable;
  221. out.second = elem.first;
  222. return true;
  223. }
  224. }
  225. }
  226. for(const auto & stack : stacks)
  227. {
  228. for(const auto & elem : stacks)
  229. {
  230. if(stack.second->getType() == elem.second->getType() && stack.first != elem.first)
  231. {
  232. out.first = stack.first;
  233. out.second = elem.first;
  234. return true;
  235. }
  236. }
  237. }
  238. return false;
  239. }
  240. void CCreatureSet::addToSlot(const SlotID & slot, const CreatureID & cre, TQuantity count, bool allowMerging)
  241. {
  242. const CCreature *c = cre.toCreature();
  243. if(!hasStackAtSlot(slot))
  244. {
  245. setCreature(slot, cre, count);
  246. }
  247. else if(getCreature(slot) == c && allowMerging) //that slot was empty or contained same type creature
  248. {
  249. setStackCount(slot, getStackCount(slot) + count);
  250. }
  251. else
  252. {
  253. logGlobal->error("Failed adding to slot!");
  254. }
  255. }
  256. void CCreatureSet::addToSlot(const SlotID & slot, std::unique_ptr<CStackInstance> stack, bool allowMerging)
  257. {
  258. assert(stack->valid(true));
  259. if(!hasStackAtSlot(slot))
  260. {
  261. putStack(slot, std::move(stack));
  262. }
  263. else if(allowMerging && stack->getType() == getCreature(slot))
  264. {
  265. joinStack(slot, std::move(stack));
  266. }
  267. else
  268. {
  269. logGlobal->error("Cannot add to slot %d stack %s", slot.getNum(), stack->nodeName());
  270. }
  271. }
  272. bool CCreatureSet::validTypes(bool allowUnrandomized) const
  273. {
  274. for(const auto & elem : stacks)
  275. {
  276. if(!elem.second->valid(allowUnrandomized))
  277. return false;
  278. }
  279. return true;
  280. }
  281. bool CCreatureSet::slotEmpty(const SlotID & slot) const
  282. {
  283. return !hasStackAtSlot(slot);
  284. }
  285. bool CCreatureSet::needsLastStack() const
  286. {
  287. return false;
  288. }
  289. ui64 CCreatureSet::getArmyStrength(int fortLevel) const
  290. {
  291. ui64 ret = 0;
  292. for (const auto& elem : stacks)
  293. {
  294. ui64 powerToAdd = elem.second->getPower();
  295. if (fortLevel > 0)
  296. {
  297. if (!elem.second->hasBonusOfType(BonusType::FLYING))
  298. {
  299. powerToAdd /= fortLevel;
  300. if (!elem.second->hasBonusOfType(BonusType::SHOOTER))
  301. powerToAdd /= fortLevel;
  302. }
  303. }
  304. ret += powerToAdd;
  305. }
  306. return ret;
  307. }
  308. ui64 CCreatureSet::getArmyCost() const
  309. {
  310. ui64 ret = 0;
  311. for (const auto& elem : stacks)
  312. ret += elem.second->getMarketValue();
  313. return ret;
  314. }
  315. ui64 CCreatureSet::getPower(const SlotID & slot) const
  316. {
  317. return getStack(slot).getPower();
  318. }
  319. std::string CCreatureSet::getRoughAmount(const SlotID & slot, int mode) const
  320. {
  321. /// Mode represent return string format
  322. /// "Pack" - 0, "A pack of" - 1, "a pack of" - 2
  323. CCreature::CreatureQuantityId quantity = CCreature::getQuantityID(getStackCount(slot));
  324. if((int)quantity)
  325. {
  326. if(settings["gameTweaks"]["numericCreaturesQuantities"].Bool())
  327. return CCreature::getQuantityRangeStringForId(quantity);
  328. return LIBRARY->generaltexth->arraytxt[(174 + mode) + 3*(int)quantity];
  329. }
  330. return "";
  331. }
  332. std::string CCreatureSet::getArmyDescription() const
  333. {
  334. std::string text;
  335. std::vector<std::string> guards;
  336. for(const auto & elem : stacks)
  337. {
  338. auto str = boost::str(boost::format("%s %s") % getRoughAmount(elem.first, 2) % getCreature(elem.first)->getNamePluralTranslated());
  339. guards.push_back(str);
  340. }
  341. if(!guards.empty())
  342. {
  343. for(int i = 0; i < guards.size(); i++)
  344. {
  345. text += guards[i];
  346. if(i + 2 < guards.size())
  347. text += ", ";
  348. else if(i + 2 == guards.size())
  349. text += LIBRARY->generaltexth->allTexts[237];
  350. }
  351. }
  352. return text;
  353. }
  354. int CCreatureSet::stacksCount() const
  355. {
  356. return static_cast<int>(stacks.size());
  357. }
  358. void CCreatureSet::setFormation(EArmyFormation mode)
  359. {
  360. formation = mode;
  361. }
  362. void CCreatureSet::setStackCount(const SlotID & slot, TQuantity count)
  363. {
  364. stacks.at(slot)->setCount(count);
  365. armyChanged();
  366. }
  367. void CCreatureSet::giveAverageStackExperience(TExpType exp)
  368. {
  369. for(const auto & stack : stacks)
  370. {
  371. stack.second->giveAverageStackExperience(exp);
  372. stack.second->nodeHasChanged();
  373. }
  374. }
  375. void CCreatureSet::giveTotalStackExperience(const SlotID & slot, TExpType exp)
  376. {
  377. assert(hasStackAtSlot(slot));
  378. stacks[slot]->giveTotalStackExperience(exp);
  379. stacks[slot]->nodeHasChanged();
  380. }
  381. void CCreatureSet::clearSlots()
  382. {
  383. while(!stacks.empty())
  384. {
  385. eraseStack(stacks.begin()->first);
  386. }
  387. }
  388. const CStackInstance & CCreatureSet::getStack(const SlotID & slot) const
  389. {
  390. assert(hasStackAtSlot(slot));
  391. return *getStackPtr(slot);
  392. }
  393. CStackInstance * CCreatureSet::getStackPtr(const SlotID & slot) const
  394. {
  395. if(hasStackAtSlot(slot))
  396. return stacks.find(slot)->second.get();
  397. else return nullptr;
  398. }
  399. void CCreatureSet::eraseStack(const SlotID & slot)
  400. {
  401. assert(hasStackAtSlot(slot));
  402. detachStack(slot);
  403. }
  404. bool CCreatureSet::contains(const CStackInstance *stack) const
  405. {
  406. if(!stack)
  407. return false;
  408. for(const auto & elem : stacks)
  409. if(elem.second.get() == stack)
  410. return true;
  411. return false;
  412. }
  413. SlotID CCreatureSet::findStack(const CStackInstance *stack) const
  414. {
  415. const auto * h = dynamic_cast<const CGHeroInstance *>(this);
  416. if (h && h->getCommander() == stack)
  417. return SlotID::COMMANDER_SLOT_PLACEHOLDER;
  418. if(!stack)
  419. return SlotID();
  420. for(const auto & elem : stacks)
  421. if(elem.second.get() == stack)
  422. return elem.first;
  423. return SlotID();
  424. }
  425. void CCreatureSet::putStack(const SlotID & slot, std::unique_ptr<CStackInstance> stack)
  426. {
  427. assert(slot.getNum() < GameConstants::ARMY_SIZE);
  428. assert(!hasStackAtSlot(slot));
  429. stacks[slot] = std::move(stack);
  430. stacks[slot]->setArmy(getArmy());
  431. armyChanged();
  432. }
  433. void CCreatureSet::joinStack(const SlotID & slot, std::unique_ptr<CStackInstance> stack)
  434. {
  435. [[maybe_unused]] const CCreature *c = getCreature(slot);
  436. assert(c == stack->getType());
  437. assert(c);
  438. //TODO move stuff
  439. changeStackCount(slot, stack->getCount());
  440. giveTotalStackExperience(slot, stack->getTotalExperience());
  441. }
  442. std::unique_ptr<CStackInstance> CCreatureSet::splitStack(const SlotID & slot, TQuantity toSplit)
  443. {
  444. auto & currentStack = stacks.at(slot);
  445. assert(currentStack->getCount() > toSplit);
  446. TExpType experienceBefore = currentStack->getTotalExperience();
  447. currentStack->setCount(currentStack->getCount() - toSplit);
  448. TExpType experienceAfter = currentStack->getTotalExperience();
  449. auto newStack = std::make_unique<CStackInstance>(currentStack->cb, currentStack->getCreatureID(), toSplit);
  450. newStack->giveTotalStackExperience(experienceBefore - experienceAfter);
  451. return newStack;
  452. }
  453. void CCreatureSet::changeStackCount(const SlotID & slot, TQuantity toAdd)
  454. {
  455. setStackCount(slot, getStackCount(slot) + toAdd);
  456. }
  457. CCreatureSet::~CCreatureSet() = default;
  458. void CCreatureSet::setToArmy(CSimpleArmy &src)
  459. {
  460. clearSlots();
  461. while(src)
  462. {
  463. auto i = src.army.begin();
  464. putStack(i->first, std::make_unique<CStackInstance>(getArmy()->cb, i->second.first, i->second.second));
  465. src.army.erase(i);
  466. }
  467. }
  468. std::unique_ptr<CStackInstance> CCreatureSet::detachStack(const SlotID & slot)
  469. {
  470. assert(hasStackAtSlot(slot));
  471. std::unique_ptr<CStackInstance> ret = std::move(stacks[slot]);
  472. //if(CArmedInstance *armedObj = castToArmyObj())
  473. if(ret)
  474. {
  475. ret->setArmy(nullptr); //detaches from current armyobj
  476. assert(!ret->getArmy()); //we failed detaching?
  477. }
  478. stacks.erase(slot);
  479. armyChanged();
  480. return ret;
  481. }
  482. void CCreatureSet::setStackType(const SlotID & slot, const CreatureID & type)
  483. {
  484. assert(hasStackAtSlot(slot));
  485. stacks[slot]->setType(type);
  486. armyChanged();
  487. }
  488. bool CCreatureSet::canBeMergedWith(const CCreatureSet &cs, bool allowMergingStacks) const
  489. {
  490. if(!allowMergingStacks)
  491. {
  492. int freeSlots = stacksCount() - GameConstants::ARMY_SIZE;
  493. std::set<const CCreature*> cresToAdd;
  494. for(const auto & elem : cs.stacks)
  495. {
  496. SlotID dest = getSlotFor(elem.second->getCreature());
  497. if(!dest.validSlot() || hasStackAtSlot(dest))
  498. cresToAdd.insert(elem.second->getCreature());
  499. }
  500. return cresToAdd.size() <= freeSlots;
  501. }
  502. else
  503. {
  504. CCreatureSet cres;
  505. SlotID j;
  506. //get types of creatures that need their own slot
  507. for(const auto & elem : cs.stacks)
  508. if ((j = cres.getSlotFor(elem.second->getCreature())).validSlot())
  509. cres.addToSlot(j, elem.second->getId(), 1, true); //merge if possible
  510. //cres.addToSlot(elem.first, elem.second->type->getId(), 1, true);
  511. for(const auto & elem : stacks)
  512. {
  513. if ((j = cres.getSlotFor(elem.second->getCreature())).validSlot())
  514. cres.addToSlot(j, elem.second->getId(), 1, true); //merge if possible
  515. else
  516. return false; //no place found
  517. }
  518. return true; //all stacks found their slots
  519. }
  520. }
  521. bool CCreatureSet::hasStackAtSlot(const SlotID & slot) const
  522. {
  523. return vstd::contains(stacks, slot);
  524. }
  525. CCreatureSet & CCreatureSet::operator=(const CCreatureSet&cs)
  526. {
  527. assert(0);
  528. return *this;
  529. }
  530. void CCreatureSet::armyChanged()
  531. {
  532. }
  533. void CCreatureSet::serializeJson(JsonSerializeFormat & handler, const std::string & armyFieldName, const std::optional<int> fixedSize)
  534. {
  535. if(handler.saving && stacks.empty())
  536. return;
  537. handler.serializeEnum("formation", formation, NArmyFormation::names);
  538. auto a = handler.enterArray(armyFieldName);
  539. if(handler.saving)
  540. {
  541. size_t sz = 0;
  542. for(const auto & p : stacks)
  543. vstd::amax(sz, p.first.getNum()+1);
  544. if(fixedSize)
  545. vstd::amax(sz, fixedSize.value());
  546. a.resize(sz, JsonNode::JsonType::DATA_STRUCT);
  547. for(const auto & p : stacks)
  548. {
  549. auto s = a.enterStruct(p.first.getNum());
  550. p.second->serializeJson(handler);
  551. }
  552. }
  553. else
  554. {
  555. for(size_t idx = 0; idx < a.size(); idx++)
  556. {
  557. auto s = a.enterStruct(idx);
  558. TQuantity amount = 0;
  559. handler.serializeInt("amount", amount);
  560. if(amount > 0)
  561. {
  562. auto newStack = std::make_unique<CStackInstance>(getArmy()->cb);
  563. newStack->serializeJson(handler);
  564. putStack(SlotID(static_cast<si32>(idx)), std::move(newStack));
  565. }
  566. }
  567. }
  568. }
  569. CStackInstance::CStackInstance(IGameCallback *cb, bool isHypothetic)
  570. : CBonusSystemNode(isHypothetic)
  571. , CStackBasicDescriptor(nullptr, 0)
  572. , CArtifactSet(cb)
  573. , GameCallbackHolder(cb)
  574. , nativeTerrain(this, Selector::type()(BonusType::TERRAIN_NATIVE))
  575. , initiative(this, Selector::type()(BonusType::STACKS_SPEED))
  576. , totalExperience(0)
  577. {
  578. setNodeType(STACK_INSTANCE);
  579. }
  580. CStackInstance::CStackInstance(IGameCallback *cb, const CreatureID & id, TQuantity Count, bool isHypothetic)
  581. : CStackInstance(cb, false)
  582. {
  583. setType(id);
  584. setCount(Count);
  585. }
  586. CCreature::CreatureQuantityId CStackInstance::getQuantityID() const
  587. {
  588. return CCreature::getQuantityID(getCount());
  589. }
  590. int CStackInstance::getExpRank() const
  591. {
  592. if (!LIBRARY->engineSettings()->getBoolean(EGameSettings::MODULE_STACK_EXPERIENCE))
  593. return 0;
  594. int tier = getType()->getLevel();
  595. if (vstd::iswithin(tier, 1, 7))
  596. {
  597. for(int i = static_cast<int>(LIBRARY->creh->expRanks[tier].size()) - 2; i > -1; --i) //sic!
  598. { //exp values vary from 1st level to max exp at 11th level
  599. if (getAverageExperience() >= LIBRARY->creh->expRanks[tier][i])
  600. return ++i; //faster, but confusing - 0 index mean 1st level of experience
  601. }
  602. return 0;
  603. }
  604. else //higher tier
  605. {
  606. for(int i = static_cast<int>(LIBRARY->creh->expRanks[0].size()) - 2; i > -1; --i)
  607. {
  608. if (getAverageExperience() >= LIBRARY->creh->expRanks[0][i])
  609. return ++i;
  610. }
  611. return 0;
  612. }
  613. }
  614. int CStackInstance::getLevel() const
  615. {
  616. return std::max(1, getType()->getLevel());
  617. }
  618. void CStackInstance::giveAverageStackExperience(TExpType desiredAmountPerUnit)
  619. {
  620. if (!canGainExperience())
  621. return;
  622. int level = std::clamp(getLevel(), 1, 7);
  623. TExpType maxAmountPerUnit = LIBRARY->creh->expRanks[level].back();
  624. TExpType actualAmountPerUnit = std::min(desiredAmountPerUnit, maxAmountPerUnit * LIBRARY->creh->maxExpPerBattle[level]/100);
  625. TExpType maxExperience = maxAmountPerUnit * getCount();
  626. TExpType maxExperienceToGain = maxExperience - totalExperience;
  627. TExpType actualGainedExperience = std::min(maxExperienceToGain, actualAmountPerUnit * getCount());
  628. totalExperience += actualGainedExperience;
  629. }
  630. void CStackInstance::giveTotalStackExperience(TExpType experienceToGive)
  631. {
  632. if (!canGainExperience())
  633. return;
  634. int level = std::clamp(getLevel(), 1, 7);
  635. TExpType maxAmountPerUnit = LIBRARY->creh->expRanks[level].back();
  636. TExpType maxExperience = maxAmountPerUnit * getCount();
  637. TExpType maxExperienceToGain = maxExperience - totalExperience;
  638. TExpType actualGainedExperience = std::min(maxExperienceToGain, experienceToGive);
  639. totalExperience += actualGainedExperience;
  640. }
  641. TExpType CStackInstance::getTotalExperience() const
  642. {
  643. return totalExperience;
  644. }
  645. TExpType CStackInstance::getAverageExperience() const
  646. {
  647. return totalExperience / getCount();
  648. }
  649. bool CStackInstance::canGainExperience() const
  650. {
  651. return cb->getSettings().getBoolean(EGameSettings::MODULE_STACK_EXPERIENCE);
  652. }
  653. void CStackInstance::setType(const CreatureID & creID)
  654. {
  655. if (creID == CreatureID::NONE)
  656. setType(nullptr);//FIXME: unused branch?
  657. else
  658. setType(creID.toCreature());
  659. }
  660. void CStackInstance::setType(const CCreature *c)
  661. {
  662. if(getCreature())
  663. {
  664. detachFromSource(*getCreature());
  665. if (LIBRARY->engineSettings()->getBoolean(EGameSettings::MODULE_STACK_EXPERIENCE))
  666. totalExperience = totalExperience * LIBRARY->creh->expAfterUpgrade / 100;
  667. }
  668. CStackBasicDescriptor::setType(c);
  669. if(getCreature())
  670. attachToSource(*getCreature());
  671. }
  672. void CStackInstance::setCount(TQuantity newCount)
  673. {
  674. assert(newCount >= 0);
  675. if (newCount < getCount())
  676. {
  677. TExpType averageExperience = totalExperience / getCount();
  678. totalExperience = averageExperience * newCount;
  679. }
  680. CStackBasicDescriptor::setCount(newCount);
  681. }
  682. std::string CStackInstance::bonusToString(const std::shared_ptr<Bonus>& bonus, bool description) const
  683. {
  684. return LIBRARY->getBth()->bonusToString(bonus, this, description);
  685. }
  686. ImagePath CStackInstance::bonusToGraphics(const std::shared_ptr<Bonus> & bonus) const
  687. {
  688. return LIBRARY->getBth()->bonusToGraphics(bonus);
  689. }
  690. CArmedInstance * CStackInstance::getArmy()
  691. {
  692. if (armyInstanceID.hasValue())
  693. return dynamic_cast<CArmedInstance*>(cb->gameState().getObjInstance(armyInstanceID));
  694. return nullptr;
  695. }
  696. const CArmedInstance * CStackInstance::getArmy() const
  697. {
  698. if (armyInstanceID.hasValue())
  699. return dynamic_cast<const CArmedInstance*>(cb->getObjInstance(armyInstanceID));
  700. return nullptr;
  701. }
  702. void CStackInstance::setArmy(const CArmedInstance * ArmyObj)
  703. {
  704. auto oldArmy = getArmy();
  705. if(oldArmy)
  706. {
  707. detachFrom(*oldArmy);
  708. armyInstanceID = {};
  709. }
  710. if(ArmyObj)
  711. {
  712. attachTo(const_cast<CArmedInstance&>(*ArmyObj));
  713. armyInstanceID = ArmyObj->id;
  714. }
  715. }
  716. std::string CStackInstance::getQuantityTXT(bool capitalized) const
  717. {
  718. CCreature::CreatureQuantityId quantity = getQuantityID();
  719. if ((int)quantity)
  720. {
  721. if(settings["gameTweaks"]["numericCreaturesQuantities"].Bool())
  722. return CCreature::getQuantityRangeStringForId(quantity);
  723. return LIBRARY->generaltexth->arraytxt[174 + (int)quantity*3 - 1 - capitalized];
  724. }
  725. else
  726. return "";
  727. }
  728. bool CStackInstance::valid(bool allowUnrandomized) const
  729. {
  730. if(!randomStack)
  731. {
  732. return (getType() && getType() == getId().toEntity(LIBRARY));
  733. }
  734. else
  735. return allowUnrandomized;
  736. }
  737. std::string CStackInstance::nodeName() const
  738. {
  739. std::ostringstream oss;
  740. oss << "Stack of " << getCount() << " of ";
  741. if(getType())
  742. oss << getType()->getNamePluralTextID();
  743. else
  744. oss << "[UNDEFINED TYPE]";
  745. return oss.str();
  746. }
  747. PlayerColor CStackInstance::getOwner() const
  748. {
  749. auto army = getArmy();
  750. return army ? army->getOwner() : PlayerColor::NEUTRAL;
  751. }
  752. int32_t CStackInstance::getInitiative(int turn) const
  753. {
  754. if (turn == 0)
  755. return initiative.getValue();
  756. return ACreature::getInitiative(turn);
  757. }
  758. TerrainId CStackInstance::getNativeTerrain() const
  759. {
  760. if (nativeTerrain.hasBonus())
  761. return TerrainId::ANY_TERRAIN;
  762. return getFactionID().toEntity(LIBRARY)->getNativeTerrain();
  763. }
  764. TerrainId CStackInstance::getCurrentTerrain() const
  765. {
  766. return getArmy()->getCurrentTerrain();
  767. }
  768. CreatureID CStackInstance::getCreatureID() const
  769. {
  770. if(getType())
  771. return getType()->getId();
  772. else
  773. return CreatureID::NONE;
  774. }
  775. std::string CStackInstance::getName() const
  776. {
  777. return (getCount() > 1) ? getType()->getNamePluralTranslated() : getType()->getNameSingularTranslated();
  778. }
  779. ui64 CStackInstance::getPower() const
  780. {
  781. assert(getType());
  782. return static_cast<ui64>(getType()->getAIValue()) * getCount();
  783. }
  784. ui64 CStackInstance::getMarketValue() const
  785. {
  786. assert(getType());
  787. return getType()->getFullRecruitCost().marketValue() * getCount();
  788. }
  789. ArtBearer::ArtBearer CStackInstance::bearerType() const
  790. {
  791. return ArtBearer::CREATURE;
  792. }
  793. CStackInstance::ArtPlacementMap CStackInstance::putArtifact(const ArtifactPosition & pos, const CArtifactInstance * art)
  794. {
  795. assert(!getArt(pos));
  796. assert(art->canBePutAt(this, pos));
  797. attachToSource(*art);
  798. return CArtifactSet::putArtifact(pos, art);
  799. }
  800. void CStackInstance::removeArtifact(const ArtifactPosition & pos)
  801. {
  802. assert(getArt(pos));
  803. detachFromSource(*getArt(pos));
  804. CArtifactSet::removeArtifact(pos);
  805. }
  806. void CStackInstance::serializeJson(JsonSerializeFormat & handler)
  807. {
  808. //todo: artifacts
  809. CStackBasicDescriptor::serializeJson(handler);//must be first
  810. if(handler.saving)
  811. {
  812. if(randomStack)
  813. {
  814. int level = randomStack->level;
  815. int upgrade = randomStack->upgrade;
  816. handler.serializeInt("level", level, 0);
  817. handler.serializeInt("upgraded", upgrade, 0);
  818. }
  819. }
  820. else
  821. {
  822. //type set by CStackBasicDescriptor::serializeJson
  823. if(getType() == nullptr)
  824. {
  825. uint8_t level = 0;
  826. uint8_t upgrade = 0;
  827. handler.serializeInt("level", level, 0);
  828. handler.serializeInt("upgrade", upgrade, 0);
  829. randomStack = RandomStackInfo{ level, upgrade };
  830. }
  831. }
  832. }
  833. FactionID CStackInstance::getFactionID() const
  834. {
  835. if(getType())
  836. return getType()->getFactionID();
  837. return FactionID::NEUTRAL;
  838. }
  839. const IBonusBearer* CStackInstance::getBonusBearer() const
  840. {
  841. return this;
  842. }
  843. CCommanderInstance::CCommanderInstance(IGameCallback *cb)
  844. :CStackInstance(cb)
  845. {}
  846. CCommanderInstance::CCommanderInstance(IGameCallback *cb, const CreatureID & id)
  847. : CStackInstance(cb)
  848. , name("Commando")
  849. {
  850. alive = true;
  851. level = 1;
  852. setCount(1);
  853. setType(nullptr);
  854. setNodeType (CBonusSystemNode::COMMANDER);
  855. secondarySkills.resize (ECommander::SPELL_POWER + 1);
  856. setType(id);
  857. //TODO - parse them
  858. }
  859. void CCommanderInstance::setAlive (bool Alive)
  860. {
  861. //TODO: helm of immortality
  862. alive = Alive;
  863. if (!alive)
  864. {
  865. removeBonusesRecursive(Bonus::UntilCommanderKilled);
  866. }
  867. }
  868. bool CCommanderInstance::canGainExperience() const
  869. {
  870. return alive && CStackInstance::canGainExperience();
  871. }
  872. int CCommanderInstance::getExpRank() const
  873. {
  874. return LIBRARY->heroh->level (getTotalExperience());
  875. }
  876. int CCommanderInstance::getLevel() const
  877. {
  878. return std::max (1, getExpRank());
  879. }
  880. void CCommanderInstance::levelUp ()
  881. {
  882. level++;
  883. for(const auto & bonus : LIBRARY->creh->commanderLevelPremy)
  884. { //grant all regular level-up bonuses
  885. accumulateBonus(bonus);
  886. }
  887. }
  888. ArtBearer::ArtBearer CCommanderInstance::bearerType() const
  889. {
  890. return ArtBearer::COMMANDER;
  891. }
  892. bool CCommanderInstance::gainsLevel() const
  893. {
  894. return getTotalExperience() >= LIBRARY->heroh->reqExp(level + 1);
  895. }
  896. //This constructor should be placed here to avoid side effects
  897. CStackBasicDescriptor::CStackBasicDescriptor() = default;
  898. CStackBasicDescriptor::CStackBasicDescriptor(const CreatureID & id, TQuantity Count):
  899. typeID(id),
  900. count(Count)
  901. {
  902. }
  903. CStackBasicDescriptor::CStackBasicDescriptor(const CCreature *c, TQuantity Count)
  904. : typeID(c ? c->getId() : CreatureID()), count(Count)
  905. {
  906. }
  907. const CCreature * CStackBasicDescriptor::getCreature() const
  908. {
  909. return typeID.hasValue() ? typeID.toCreature() : nullptr;
  910. }
  911. const Creature * CStackBasicDescriptor::getType() const
  912. {
  913. return typeID.hasValue() ? typeID.toEntity(LIBRARY) : nullptr;
  914. }
  915. CreatureID CStackBasicDescriptor::getId() const
  916. {
  917. return typeID;
  918. }
  919. TQuantity CStackBasicDescriptor::getCount() const
  920. {
  921. return count;
  922. }
  923. void CStackBasicDescriptor::setType(const CCreature * c)
  924. {
  925. typeID = c ? c->getId() : CreatureID();
  926. }
  927. void CStackBasicDescriptor::setCount(TQuantity newCount)
  928. {
  929. assert(newCount >= 0);
  930. count = newCount;
  931. }
  932. bool operator== (const CStackBasicDescriptor & l, const CStackBasicDescriptor & r)
  933. {
  934. return l.typeID == r.typeID && l.count == r.count;
  935. }
  936. void CStackBasicDescriptor::serializeJson(JsonSerializeFormat & handler)
  937. {
  938. handler.serializeInt("amount", count);
  939. if(handler.saving)
  940. {
  941. if(typeID.hasValue())
  942. {
  943. std::string typeName = typeID.toEntity(LIBRARY)->getJsonKey();
  944. handler.serializeString("type", typeName);
  945. }
  946. }
  947. else
  948. {
  949. std::string typeName;
  950. handler.serializeString("type", typeName);
  951. if(!typeName.empty())
  952. setType(CreatureID(CreatureID::decode(typeName)).toCreature());
  953. }
  954. }
  955. void CSimpleArmy::clearSlots()
  956. {
  957. army.clear();
  958. }
  959. CSimpleArmy::operator bool() const
  960. {
  961. return !army.empty();
  962. }
  963. bool CSimpleArmy::setCreature(SlotID slot, CreatureID cre, TQuantity count)
  964. {
  965. assert(!vstd::contains(army, slot));
  966. army[slot] = std::make_pair(cre, count);
  967. return true;
  968. }
  969. VCMI_LIB_NAMESPACE_END