CCreatureSet.cpp 23 KB

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