CCreatureWindow.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182
  1. /*
  2. * CCreatureWindow.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 "CCreatureWindow.h"
  12. #include <vcmi/spells/Spell.h>
  13. #include <vcmi/spells/Service.h>
  14. #include "../CPlayerInterface.h"
  15. #include "../render/Canvas.h"
  16. #include "../widgets/Buttons.h"
  17. #include "../widgets/CComponent.h"
  18. #include "../widgets/CComponentHolder.h"
  19. #include "../widgets/GraphicalPrimitiveCanvas.h"
  20. #include "../widgets/Images.h"
  21. #include "../widgets/TextControls.h"
  22. #include "../widgets/ObjectLists.h"
  23. #include "../widgets/GraphicalPrimitiveCanvas.h"
  24. #include "../windows/InfoWindows.h"
  25. #include "../GameEngine.h"
  26. #include "../GameInstance.h"
  27. #include "../gui/Shortcut.h"
  28. #include "../battle/BattleInterface.h"
  29. #include "../../lib/CBonusTypeHandler.h"
  30. #include "../../lib/CStack.h"
  31. #include "../../lib/GameLibrary.h"
  32. #include "../../lib/IGameSettings.h"
  33. #include "../../lib/bonuses/Propagators.h"
  34. #include "../../lib/callback/CCallback.h"
  35. #include "../../lib/entities/artifact/ArtifactUtils.h"
  36. #include "../../lib/entities/hero/CHeroHandler.h"
  37. #include "../../lib/gameState/CGameState.h"
  38. #include "../../lib/gameState/UpgradeInfo.h"
  39. #include "../../lib/networkPacks/ArtifactLocation.h"
  40. #include "../../lib/texts/CGeneralTextHandler.h"
  41. #include "../../lib/texts/TextOperations.h"
  42. #include "../../lib/texts/Languages.h"
  43. class CCreatureArtifactInstance;
  44. class CSelectableSkill;
  45. class UnitView
  46. {
  47. public:
  48. // helper structs
  49. struct CommanderLevelInfo
  50. {
  51. std::vector<ui32> skills;
  52. std::function<void(ui32)> callback;
  53. };
  54. struct StackDismissInfo
  55. {
  56. std::function<void()> callback;
  57. };
  58. struct StackUpgradeInfo
  59. {
  60. StackUpgradeInfo() = delete;
  61. StackUpgradeInfo(const UpgradeInfo & upgradeInfo)
  62. : info(upgradeInfo)
  63. { }
  64. UpgradeInfo info;
  65. std::function<void(CreatureID)> callback;
  66. };
  67. // pointers to permanent objects in game state
  68. const CCreature * creature;
  69. const CCommanderInstance * commander;
  70. const CStackInstance * stackNode;
  71. const CStack * stack;
  72. const CGHeroInstance * owner;
  73. // temporary objects which should be kept as copy if needed
  74. std::optional<CommanderLevelInfo> levelupInfo;
  75. std::optional<StackDismissInfo> dismissInfo;
  76. std::optional<StackUpgradeInfo> upgradeInfo;
  77. // misc fields
  78. unsigned int creatureCount;
  79. bool popupWindow;
  80. UnitView()
  81. : creature(nullptr),
  82. commander(nullptr),
  83. stackNode(nullptr),
  84. stack(nullptr),
  85. owner(nullptr),
  86. creatureCount(0),
  87. popupWindow(false)
  88. {
  89. }
  90. std::string getName() const
  91. {
  92. if(commander)
  93. return commander->getType()->getNameSingularTranslated();
  94. else
  95. return creature->getNamePluralTranslated();
  96. }
  97. private:
  98. };
  99. CCommanderSkillIcon::CCommanderSkillIcon(std::shared_ptr<CIntObject> object_, bool isMasterAbility_, std::function<void()> callback)
  100. : object(),
  101. isMasterAbility(isMasterAbility_),
  102. isSelected(false),
  103. callback(callback)
  104. {
  105. pos = object_->pos;
  106. this->isMasterAbility = isMasterAbility_;
  107. setObject(object_);
  108. }
  109. void CCommanderSkillIcon::setObject(std::shared_ptr<CIntObject> newObject)
  110. {
  111. if(object)
  112. removeChild(object.get());
  113. object = newObject;
  114. addChild(object.get());
  115. object->moveTo(pos.topLeft());
  116. redraw();
  117. }
  118. void CCommanderSkillIcon::clickPressed(const Point & cursorPosition)
  119. {
  120. callback();
  121. isSelected = true;
  122. redraw();
  123. }
  124. void CCommanderSkillIcon::deselect()
  125. {
  126. isSelected = false;
  127. redraw();
  128. }
  129. bool CCommanderSkillIcon::getIsMasterAbility()
  130. {
  131. return isMasterAbility;
  132. }
  133. void CCommanderSkillIcon::show(Canvas &to)
  134. {
  135. CIntObject::show(to);
  136. if(isMasterAbility && isSelected)
  137. to.drawBorder(pos, Colors::YELLOW, 2);
  138. }
  139. static ImagePath skillToFile(int skill, int level, bool selected)
  140. {
  141. // FIXME: is this a correct handling?
  142. // level 0 = skill not present, use image with "no" suffix
  143. // level 1-5 = skill available, mapped to images indexed as 0-4
  144. // selecting skill means that it will appear one level higher (as if already upgraded)
  145. std::string file = "zvs/Lib1.res/_";
  146. switch (skill)
  147. {
  148. case ECommander::ATTACK:
  149. file += "AT";
  150. break;
  151. case ECommander::DEFENSE:
  152. file += "DF";
  153. break;
  154. case ECommander::HEALTH:
  155. file += "HP";
  156. break;
  157. case ECommander::DAMAGE:
  158. file += "DM";
  159. break;
  160. case ECommander::SPEED:
  161. file += "SP";
  162. break;
  163. case ECommander::SPELL_POWER:
  164. file += "MP";
  165. break;
  166. }
  167. std::string suffix;
  168. if (selected)
  169. level++; // UI will display resulting level
  170. if (level == 0)
  171. suffix = "no"; //not available - no number
  172. else
  173. suffix = std::to_string(level-1);
  174. if (selected)
  175. suffix += "="; //level-up highlight
  176. return ImagePath::builtin(file + suffix + ".bmp");
  177. }
  178. CStackWindow::CWindowSection::CWindowSection(CStackWindow * parent, const ImagePath & backgroundPath, int yOffset)
  179. : parent(parent)
  180. {
  181. pos.y += yOffset;
  182. OBJECT_CONSTRUCTION;
  183. if(!backgroundPath.empty())
  184. {
  185. background = std::make_shared<CPicture>(backgroundPath);
  186. pos.w = background->pos.w;
  187. pos.h = background->pos.h;
  188. }
  189. }
  190. CStackWindow::ActiveSpellsSection::ActiveSpellsSection(CStackWindow * owner, int yOffset)
  191. : CWindowSection(owner, ImagePath::builtin("stackWindow/spell-effects"), yOffset)
  192. {
  193. static const Point firstPos(6, 2); // position of 1st spell box
  194. static const Point offset(54, 0); // offset of each spell box from previous
  195. OBJECT_CONSTRUCTION;
  196. const CStack * battleStack = parent->info->stack;
  197. assert(battleStack); // Section should be created only for battles
  198. //spell effects
  199. int printed=0; //how many effect pics have been printed
  200. std::vector<SpellID> spells = battleStack->activeSpells();
  201. for(SpellID effect : spells)
  202. {
  203. const spells::Spell * spell = LIBRARY->spells()->getById(effect);
  204. //not all effects have graphics (for eg. Acid Breath)
  205. //for modded spells iconEffect is added to SpellInt.def
  206. const bool hasGraphics = (effect < SpellID::THUNDERBOLT) || (effect >= SpellID::AFTER_LAST);
  207. if (hasGraphics)
  208. {
  209. auto spellBonuses = battleStack->getBonuses(Selector::source(BonusSource::SPELL_EFFECT, BonusSourceID(effect)));
  210. if (spellBonuses->empty())
  211. throw std::runtime_error("Failed to find effects for spell " + effect.toSpell()->getJsonKey());
  212. int duration = spellBonuses->front()->turnsRemain;
  213. std::string preferredLanguage = LIBRARY->generaltexth->getPreferredLanguage();
  214. MetaString spellText;
  215. spellText.appendTextID(spell->getDescriptionTextID(0)); // TODO: select correct mastery level?
  216. spellText.appendRawString("\n");
  217. spellText.appendTextID(Languages::getPluralFormTextID( preferredLanguage, duration, "vcmi.battleResultsWindow.spellDurationRemaining"));
  218. spellText.replaceNumber(duration);
  219. std::string spellDescription = spellText.toString();
  220. spellIcons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("SpellInt"), effect + 1, 0, firstPos.x + offset.x * printed, firstPos.y + offset.y * printed));
  221. labels.push_back(std::make_shared<CLabel>(firstPos.x + offset.x * printed + 46, firstPos.y + offset.y * printed + 36, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(duration)));
  222. clickableAreas.push_back(std::make_shared<LRClickableAreaWText>(Rect(firstPos + offset * printed, Point(50, 38)), spellDescription, spellDescription));
  223. if(++printed >= 8) // interface limit reached
  224. break;
  225. }
  226. }
  227. }
  228. CStackWindow::BonusLineSection::BonusLineSection(CStackWindow * owner, size_t lineIndex)
  229. : CWindowSection(owner, ImagePath::builtin("stackWindow/bonus-effects"), 0)
  230. {
  231. OBJECT_CONSTRUCTION;
  232. static const std::array<Point, 2> offset =
  233. {
  234. Point(6, 2),
  235. Point(214, 2)
  236. };
  237. auto drawBonusSource = [this](int leftRight, Point p, BonusInfo & bi)
  238. {
  239. std::map<BonusSource, ColorRGBA> bonusColors = {
  240. {BonusSource::ARTIFACT, Colors::GREEN},
  241. {BonusSource::ARTIFACT_INSTANCE, Colors::GREEN},
  242. {BonusSource::CREATURE_ABILITY, Colors::YELLOW},
  243. {BonusSource::SPELL_EFFECT, Colors::ORANGE},
  244. {BonusSource::SECONDARY_SKILL, Colors::PURPLE},
  245. {BonusSource::HERO_SPECIAL, Colors::PURPLE},
  246. {BonusSource::STACK_EXPERIENCE, Colors::CYAN},
  247. {BonusSource::COMMANDER, Colors::CYAN},
  248. };
  249. std::map<BonusSource, std::string> bonusNames = {
  250. {BonusSource::ARTIFACT, LIBRARY->generaltexth->translate("vcmi.bonusSource.artifact")},
  251. {BonusSource::ARTIFACT_INSTANCE, LIBRARY->generaltexth->translate("vcmi.bonusSource.artifact")},
  252. {BonusSource::CREATURE_ABILITY, LIBRARY->generaltexth->translate("vcmi.bonusSource.creature")},
  253. {BonusSource::SPELL_EFFECT, LIBRARY->generaltexth->translate("vcmi.bonusSource.spell")},
  254. {BonusSource::SECONDARY_SKILL, LIBRARY->generaltexth->translate("vcmi.bonusSource.hero")},
  255. {BonusSource::HERO_SPECIAL, LIBRARY->generaltexth->translate("vcmi.bonusSource.hero")},
  256. {BonusSource::STACK_EXPERIENCE, LIBRARY->generaltexth->translate("vcmi.bonusSource.commander")},
  257. {BonusSource::COMMANDER, LIBRARY->generaltexth->translate("vcmi.bonusSource.commander")},
  258. };
  259. auto c = bonusColors.count(bi.bonusSource) ? bonusColors[bi.bonusSource] : ColorRGBA(192, 192, 192);
  260. std::string t = bonusNames.count(bi.bonusSource) ? bonusNames[bi.bonusSource] : LIBRARY->generaltexth->translate("vcmi.bonusSource.other");
  261. int maxLen = 50;
  262. EFonts f = FONT_TINY;
  263. Point pText = p + Point(4, 38);
  264. // 1px Black border
  265. bonusSource[leftRight].push_back(std::make_shared<CLabel>(pText.x - 1, pText.y, f, ETextAlignment::TOPLEFT, Colors::BLACK, t, maxLen));
  266. bonusSource[leftRight].push_back(std::make_shared<CLabel>(pText.x + 1, pText.y, f, ETextAlignment::TOPLEFT, Colors::BLACK, t, maxLen));
  267. bonusSource[leftRight].push_back(std::make_shared<CLabel>(pText.x, pText.y - 1, f, ETextAlignment::TOPLEFT, Colors::BLACK, t, maxLen));
  268. bonusSource[leftRight].push_back(std::make_shared<CLabel>(pText.x, pText.y + 1, f, ETextAlignment::TOPLEFT, Colors::BLACK, t, maxLen));
  269. bonusSource[leftRight].push_back(std::make_shared<CLabel>(pText.x, pText.y, f, ETextAlignment::TOPLEFT, c, t, maxLen));
  270. frame[leftRight] = std::make_shared<GraphicalPrimitiveCanvas>(Rect(p.x, p.y, 52, 52));
  271. frame[leftRight]->addRectangle(Point(0, 0), Point(52, 52), c);
  272. };
  273. for(size_t leftRight : {0, 1})
  274. {
  275. auto position = offset[leftRight];
  276. size_t bonusIndex = lineIndex * 2 + leftRight;
  277. if(parent->activeBonuses.size() > bonusIndex)
  278. {
  279. BonusInfo & bi = parent->activeBonuses[bonusIndex];
  280. if (!bi.imagePath.empty())
  281. icon[leftRight] = std::make_shared<CPicture>(bi.imagePath, position.x, position.y);
  282. description[leftRight] = std::make_shared<CMultiLineLabel>(Rect(position.x + 60, position.y, 137, 50), FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, bi.description);
  283. drawBonusSource(leftRight, Point(position.x - 1, position.y - 1), bi);
  284. }
  285. }
  286. }
  287. CStackWindow::BonusesSection::BonusesSection(CStackWindow * owner, int yOffset, std::optional<size_t> preferredSize):
  288. CWindowSection(owner, {}, yOffset)
  289. {
  290. OBJECT_CONSTRUCTION;
  291. // size of single image for an item
  292. static const int itemHeight = 59;
  293. size_t totalSize = (owner->activeBonuses.size() + 1) / 2;
  294. size_t visibleSize = preferredSize.value_or(std::min<size_t>(3, totalSize));
  295. pos.w = owner->pos.w;
  296. pos.h = itemHeight * (int)visibleSize;
  297. auto onCreate = [=](size_t index) -> std::shared_ptr<CIntObject>
  298. {
  299. return std::make_shared<BonusLineSection>(owner, index);
  300. };
  301. lines = std::make_shared<CListBox>(onCreate, Point(0, 0), Point(0, itemHeight), visibleSize, totalSize, 0, totalSize > 3 ? 1 : 0, Rect(pos.w - 15, 0, pos.h, pos.h));
  302. lines->onScroll = [owner](){ owner->redraw(); };
  303. }
  304. CStackWindow::ButtonsSection::ButtonsSection(CStackWindow * owner, int yOffset)
  305. : CWindowSection(owner, ImagePath::builtin("stackWindow/button-panel"), yOffset)
  306. {
  307. OBJECT_CONSTRUCTION;
  308. if(parent->info->dismissInfo && parent->info->dismissInfo->callback)
  309. {
  310. auto onDismiss = [this]()
  311. {
  312. parent->info->dismissInfo->callback();
  313. parent->close();
  314. };
  315. auto onClick = [=] ()
  316. {
  317. GAME->interface()->showYesNoDialog(LIBRARY->generaltexth->allTexts[12], onDismiss, nullptr);
  318. };
  319. dismiss = std::make_shared<CButton>(Point(5, 5),AnimationPath::builtin("IVIEWCR2.DEF"), LIBRARY->generaltexth->zelp[445], onClick, EShortcut::HERO_DISMISS);
  320. }
  321. if(parent->info->upgradeInfo && !parent->info->commander)
  322. {
  323. // used space overlaps with commander switch button
  324. // besides - should commander really be upgradeable?
  325. auto & upgradeInfo = parent->info->upgradeInfo.value();
  326. const size_t buttonsToCreate = std::min<size_t>(upgradeInfo.info.size(), upgrade.size());
  327. for(size_t buttonIndex = 0; buttonIndex < buttonsToCreate; buttonIndex++)
  328. {
  329. TResources totalCost = upgradeInfo.info.getAvailableUpgradeCosts().at(buttonIndex) * parent->info->creatureCount;
  330. auto onUpgrade = [this, upgradeInfo, buttonIndex]()
  331. {
  332. upgradeInfo.callback(upgradeInfo.info.getAvailableUpgrades().at(buttonIndex));
  333. parent->close();
  334. };
  335. auto onClick = [totalCost, onUpgrade]()
  336. {
  337. std::vector<std::shared_ptr<CComponent>> resComps;
  338. for(TResources::nziterator i(totalCost); i.valid(); i++)
  339. {
  340. resComps.push_back(std::make_shared<CComponent>(ComponentType::RESOURCE, i->resType, i->resVal));
  341. }
  342. if(GAME->interface()->cb->getResourceAmount().canAfford(totalCost))
  343. {
  344. GAME->interface()->showYesNoDialog(LIBRARY->generaltexth->allTexts[207], onUpgrade, nullptr, resComps);
  345. }
  346. else
  347. {
  348. GAME->interface()->showInfoDialog(LIBRARY->generaltexth->allTexts[314], resComps);
  349. }
  350. };
  351. auto upgradeBtn = std::make_shared<CButton>(Point(221 + (int)buttonIndex * 40, 5), AnimationPath::builtin("stackWindow/upgradeButton"), LIBRARY->generaltexth->zelp[446], onClick);
  352. upgradeBtn->setOverlay(std::make_shared<CAnimImage>(AnimationPath::builtin("CPRSMALL"), LIBRARY->creh->objects[upgradeInfo.info.getAvailableUpgrades()[buttonIndex]]->getIconIndex()));
  353. if(buttonsToCreate == 1) // single upgrade available
  354. upgradeBtn->assignedKey = EShortcut::RECRUITMENT_UPGRADE;
  355. upgrade[buttonIndex] = upgradeBtn;
  356. }
  357. }
  358. if(parent->info->commander)
  359. {
  360. for(size_t buttonIndex = 0; buttonIndex < 2; buttonIndex++)
  361. {
  362. std::string btnIDs[2] = { "showSkills", "showBonuses" };
  363. auto onSwitch = [buttonIndex, this]()
  364. {
  365. logAnim->debug("Switch %d->%d", parent->activeTab, buttonIndex);
  366. parent->switchButtons[parent->activeTab]->enable();
  367. parent->commanderTab->setActive(buttonIndex);
  368. parent->switchButtons[buttonIndex]->disable();
  369. parent->redraw(); // FIXME: enable/disable don't redraw screen themselves
  370. };
  371. std::string tooltipText = "vcmi.creatureWindow." + btnIDs[buttonIndex];
  372. parent->switchButtons[buttonIndex] = std::make_shared<CButton>(Point(342, 5), AnimationPath::builtin("stackWindow/upgradeButton"), CButton::tooltipLocalized(tooltipText), onSwitch);
  373. parent->switchButtons[buttonIndex]->setOverlay(std::make_shared<CAnimImage>(AnimationPath::builtin("stackWindow/switchModeIcons"), buttonIndex));
  374. }
  375. parent->switchButtons[parent->activeTab]->disable();
  376. }
  377. exit = std::make_shared<CButton>(Point(382, 5), AnimationPath::builtin("hsbtns.def"), LIBRARY->generaltexth->zelp[447], [this](){ parent->close(); }, EShortcut::GLOBAL_RETURN);
  378. }
  379. CStackWindow::CommanderMainSection::CommanderMainSection(CStackWindow * owner, int yOffset)
  380. : CWindowSection(owner, ImagePath::builtin("stackWindow/commander-bg"), yOffset)
  381. {
  382. OBJECT_CONSTRUCTION;
  383. auto getSkillPos = [](int index)
  384. {
  385. return Point(10 + 80 * (index%3), 20 + 80 * (index/3));
  386. };
  387. auto getSkillImage = [this](int skillIndex)
  388. {
  389. bool selected = ((parent->selectedSkill == skillIndex) && parent->info->levelupInfo );
  390. return skillToFile(skillIndex, parent->info->commander->secondarySkills[skillIndex], selected);
  391. };
  392. auto getSkillDescription = [this](int skillIndex) -> std::string
  393. {
  394. return parent->getCommanderSkillDescription(skillIndex, parent->info->commander->secondarySkills[skillIndex]);
  395. };
  396. for(int index = ECommander::ATTACK; index <= ECommander::SPELL_POWER; ++index)
  397. {
  398. Point skillPos = getSkillPos(index);
  399. auto icon = std::make_shared<CCommanderSkillIcon>(std::make_shared<CPicture>(getSkillImage(index), skillPos.x, skillPos.y), false, [=]()
  400. {
  401. GAME->interface()->showInfoDialog(getSkillDescription(index));
  402. });
  403. icon->text = getSkillDescription(index); //used to handle right click description via LRClickableAreaWText::ClickRight()
  404. if(parent->selectedSkill == index)
  405. parent->selectedIcon = icon;
  406. if(parent->info->levelupInfo && vstd::contains(parent->info->levelupInfo->skills, index)) // can be upgraded - enable selection switch
  407. {
  408. if(parent->selectedSkill == index)
  409. parent->setSelection(index, icon);
  410. icon->callback = [this, index, icon]()
  411. {
  412. parent->setSelection(index, icon);
  413. };
  414. }
  415. skillIcons.push_back(icon);
  416. }
  417. auto getArtifactPos = [](int index)
  418. {
  419. return Point(269 + 52 * (index % 3), 22 + 52 * (index / 3));
  420. };
  421. for(auto equippedArtifact : parent->info->commander->artifactsWorn)
  422. {
  423. Point artPos = getArtifactPos(equippedArtifact.first);
  424. const auto commanderArt = equippedArtifact.second.getArt();
  425. assert(commanderArt);
  426. auto artPlace = std::make_shared<CCommanderArtPlace>(artPos, parent->info->owner, equippedArtifact.first, commanderArt->getTypeId());
  427. artifacts.push_back(artPlace);
  428. }
  429. if(parent->info->levelupInfo)
  430. {
  431. abilitiesBackground = std::make_shared<CPicture>(ImagePath::builtin("stackWindow/commander-abilities.png"));
  432. abilitiesBackground->moveBy(Point(0, pos.h));
  433. size_t abilitiesCount = boost::range::count_if(parent->info->levelupInfo->skills, [](ui32 skillID)
  434. {
  435. return skillID >= 100;
  436. });
  437. auto onCreate = [this](size_t index)->std::shared_ptr<CIntObject>
  438. {
  439. for(auto skillID : parent->info->levelupInfo->skills)
  440. {
  441. if(index == 0 && skillID >= 100)
  442. {
  443. const auto bonuses = LIBRARY->creh->skillRequirements[skillID-100].first;
  444. const CStackInstance * stack = parent->info->commander;
  445. auto icon = std::make_shared<CCommanderSkillIcon>(std::make_shared<CPicture>(stack->bonusToGraphics(bonuses[0])), true, [](){});
  446. icon->callback = [this, skillID, icon]()
  447. {
  448. parent->setSelection(skillID, icon);
  449. };
  450. std::string abilityDescription;
  451. for(size_t i = 0; i < bonuses.size(); i++)
  452. {
  453. if(!abilityDescription.empty())
  454. abilityDescription += "\n";
  455. abilityDescription += LIBRARY->bth->bonusToString(bonuses[i]);
  456. }
  457. icon->hoverText = abilityDescription;
  458. icon->text = abilityDescription;
  459. return icon;
  460. }
  461. }
  462. return nullptr;
  463. };
  464. abilities = std::make_shared<CListBox>(onCreate, Point(38, 3+pos.h), Point(63, 0), 6, abilitiesCount);
  465. abilities->onScroll = [owner](){ owner->redraw(); };
  466. leftBtn = std::make_shared<CButton>(Point(10, pos.h + 6), AnimationPath::builtin("hsbtns3.def"), CButton::tooltip(), [this](){ abilities->moveToPrev(); }, EShortcut::MOVE_LEFT);
  467. rightBtn = std::make_shared<CButton>(Point(411, pos.h + 6), AnimationPath::builtin("hsbtns5.def"), CButton::tooltip(), [this](){ abilities->moveToNext(); }, EShortcut::MOVE_RIGHT);
  468. if(abilitiesCount <= 6)
  469. {
  470. leftBtn->block(true);
  471. rightBtn->block(true);
  472. }
  473. pos.h += abilitiesBackground->pos.h;
  474. }
  475. }
  476. CStackWindow::MainSection::MainSection(CStackWindow * owner, int yOffset, bool showExp, bool showArt)
  477. : CWindowSection(owner, getBackgroundName(showExp, showArt), yOffset)
  478. {
  479. OBJECT_CONSTRUCTION;
  480. statNames =
  481. {
  482. LIBRARY->generaltexth->primarySkillNames[0], //ATTACK
  483. LIBRARY->generaltexth->primarySkillNames[1],//DEFENCE
  484. LIBRARY->generaltexth->allTexts[198],//SHOTS
  485. LIBRARY->generaltexth->allTexts[199],//DAMAGE
  486. LIBRARY->generaltexth->allTexts[388],//HEALTH
  487. LIBRARY->generaltexth->allTexts[200],//HEALTH_LEFT
  488. LIBRARY->generaltexth->zelp[441].first,//SPEED
  489. LIBRARY->generaltexth->allTexts[399]//MANA
  490. };
  491. statFormats =
  492. {
  493. "%d (%d)",
  494. "%d (%d)",
  495. "%d (%d)",
  496. "%d - %d",
  497. "%d (%d)",
  498. "%d (%d)",
  499. "%d (%d)",
  500. "%d (%d)"
  501. };
  502. animation = std::make_shared<CCreaturePic>(5, 41, parent->info->creature);
  503. animationArea = std::make_shared<LRClickableArea>(Rect(5, 41, 100, 130), nullptr, [&]{
  504. if(!parent->info->creature->getDescriptionTranslated().empty())
  505. CRClickPopup::createAndPush(parent->info->creature->getDescriptionTranslated());
  506. });
  507. if(parent->info->stackNode != nullptr && parent->info->commander == nullptr)
  508. {
  509. //normal stack, not a commander and not non-existing stack (e.g. recruitment dialog)
  510. animation->setAmount(parent->info->creatureCount);
  511. }
  512. name = std::make_shared<CLabel>(215, 13, FONT_SMALL, ETextAlignment::CENTER, Colors::YELLOW,
  513. parent->info->getName() + (parent->info->commander && !parent->info->commander->alive ? (" {red|(" + LIBRARY->generaltexth->translate("vcmi.battleWindow.killed") + ")}") : "")
  514. );
  515. const CStack* battleStack = parent->info->stack;
  516. int dmgMultiply = 1;
  517. if (battleStack != nullptr && battleStack->hasBonusOfType(BonusType::SIEGE_WEAPON))
  518. {
  519. static const auto bonusSelector =
  520. Selector::sourceTypeSel(BonusSource::ARTIFACT).Or(
  521. Selector::sourceTypeSel(BonusSource::HERO_BASE_SKILL)).And(
  522. Selector::typeSubtype(BonusType::PRIMARY_SKILL, BonusSubtypeID(PrimarySkill::ATTACK)));
  523. dmgMultiply += battleStack->valOfBonuses(bonusSelector);
  524. }
  525. icons = std::make_shared<CPicture>(ImagePath::builtin("stackWindow/icons"), 117, 32);
  526. morale = std::make_shared<MoraleLuckBox>(true, Rect(Point(321, 32), Point(42, 42) ));
  527. luck = std::make_shared<MoraleLuckBox>(false, Rect(Point(375, 32), Point(42, 42) ));
  528. if(battleStack != nullptr) // in battle
  529. {
  530. addStatLabel(EStat::ATTACK, parent->info->creature->getAttack(battleStack->isShooter()), battleStack->getAttack(battleStack->isShooter()));
  531. addStatLabel(EStat::DEFENCE, parent->info->creature->getDefense(battleStack->isShooter()), battleStack->getDefense(battleStack->isShooter()));
  532. addStatLabel(EStat::DAMAGE, parent->info->stackNode->getMinDamage(battleStack->isShooter()) * dmgMultiply, battleStack->getMaxDamage(battleStack->isShooter()) * dmgMultiply);
  533. addStatLabel(EStat::HEALTH, parent->info->creature->getMaxHealth(), battleStack->getMaxHealth());
  534. addStatLabel(EStat::SPEED, parent->info->creature->getMovementRange(), battleStack->getMovementRange());
  535. if(battleStack->isShooter())
  536. addStatLabel(EStat::SHOTS, battleStack->shots.total(), battleStack->shots.available());
  537. if(battleStack->isCaster())
  538. addStatLabel(EStat::MANA, battleStack->casts.total(), battleStack->casts.available());
  539. addStatLabel(EStat::HEALTH_LEFT, battleStack->getFirstHPleft());
  540. morale->set(battleStack);
  541. luck->set(battleStack);
  542. }
  543. else
  544. {
  545. const bool shooter = parent->info->stackNode->hasBonusOfType(BonusType::SHOOTER) && parent->info->stackNode->valOfBonuses(BonusType::SHOTS);
  546. const bool caster = parent->info->stackNode->valOfBonuses(BonusType::CASTS);
  547. addStatLabel(EStat::ATTACK, parent->info->creature->getAttack(shooter), parent->info->stackNode->getAttack(shooter));
  548. addStatLabel(EStat::DEFENCE, parent->info->creature->getDefense(shooter), parent->info->stackNode->getDefense(shooter));
  549. addStatLabel(EStat::DAMAGE, parent->info->stackNode->getMinDamage(shooter), parent->info->stackNode->getMaxDamage(shooter));
  550. addStatLabel(EStat::HEALTH, parent->info->creature->getMaxHealth(), parent->info->stackNode->getMaxHealth());
  551. addStatLabel(EStat::SPEED, parent->info->creature->getMovementRange(), parent->info->stackNode->getMovementRange());
  552. if(shooter)
  553. addStatLabel(EStat::SHOTS, parent->info->stackNode->valOfBonuses(BonusType::SHOTS));
  554. if(caster)
  555. addStatLabel(EStat::MANA, parent->info->stackNode->valOfBonuses(BonusType::CASTS));
  556. morale->set(parent->info->stackNode);
  557. luck->set(parent->info->stackNode);
  558. }
  559. if(showExp)
  560. {
  561. const CStackInstance * stack = parent->info->stackNode;
  562. Point pos = showArt ? Point(321, 111) : Point(349, 111);
  563. if(parent->info->commander)
  564. {
  565. const CCommanderInstance * commander = parent->info->commander;
  566. expRankIcon = std::make_shared<CAnimImage>(AnimationPath::builtin("PSKIL42"), 4, 0, pos.x, pos.y);
  567. auto area = std::make_shared<LRClickableAreaWTextComp>(Rect(pos.x, pos.y, 44, 44), ComponentType::EXPERIENCE);
  568. expArea = area;
  569. area->text = LIBRARY->generaltexth->allTexts[2];
  570. area->component.value = commander->getExpRank();
  571. boost::replace_first(area->text, "%d", std::to_string(commander->getExpRank()));
  572. boost::replace_first(area->text, "%d", std::to_string(LIBRARY->heroh->reqExp(commander->getExpRank() + 1)));
  573. boost::replace_first(area->text, "%d", std::to_string(commander->getAverageExperience()));
  574. }
  575. else
  576. {
  577. expRankIcon = std::make_shared<CAnimImage>(AnimationPath::builtin("stackWindow/levels"), stack->getExpRank(), 0, pos.x, pos.y - 2);
  578. expArea = std::make_shared<LRClickableAreaWText>(Rect(pos.x, pos.y, 44, 44));
  579. expArea->text = parent->generateStackExpDescription();
  580. }
  581. expLabel = std::make_shared<CLabel>(
  582. pos.x + 21, pos.y + 55, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE,
  583. TextOperations::formatMetric(stack->getAverageExperience(), 6));
  584. }
  585. if(showArt)
  586. {
  587. Point pos = showExp ? Point(373, 109) : Point(347, 109);
  588. // ALARMA: do not refactor this into a separate function
  589. // otherwise, artifact icon is drawn near the hero's portrait
  590. // this is really strange
  591. auto art = parent->info->stackNode->getArt(ArtifactPosition::CREATURE_SLOT);
  592. if(art)
  593. {
  594. parent->stackArtifact = std::make_shared<CArtPlace>(pos, art->getTypeId());
  595. parent->stackArtifact->setShowPopupCallback([](CComponentHolder & artPlace, const Point & cursorPosition)
  596. {
  597. artPlace.LRClickableAreaWTextComp::showPopupWindow(cursorPosition);
  598. });
  599. if(parent->info->owner)
  600. {
  601. parent->stackArtifactButton = std::make_shared<CButton>(
  602. Point(pos.x , pos.y + 47), AnimationPath::builtin("stackWindow/cancelButton"),
  603. CButton::tooltipLocalized("vcmi.creatureWindow.returnArtifact"), [this]()
  604. {
  605. parent->removeStackArtifact(ArtifactPosition::CREATURE_SLOT);
  606. });
  607. }
  608. }
  609. }
  610. }
  611. ImagePath CStackWindow::MainSection::getBackgroundName(bool showExp, bool showArt)
  612. {
  613. if(showExp && showArt)
  614. return ImagePath::builtin("stackWindow/info-panel-2");
  615. else if(showExp || showArt)
  616. return ImagePath::builtin("stackWindow/info-panel-1");
  617. else
  618. return ImagePath::builtin("stackWindow/info-panel-0");
  619. }
  620. void CStackWindow::MainSection::addStatLabel(EStat index, int64_t value1, int64_t value2)
  621. {
  622. const auto title = statNames.at(static_cast<size_t>(index));
  623. stats.push_back(std::make_shared<CLabel>(145, 32 + (int)index*19, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE, title));
  624. const bool useRange = value1 != value2;
  625. std::string formatStr = useRange ? statFormats.at(static_cast<size_t>(index)) : "%d";
  626. boost::format fmt(formatStr);
  627. fmt % value1;
  628. if(useRange)
  629. fmt % value2;
  630. stats.push_back(std::make_shared<CLabel>(307, 48 + (int)index*19, FONT_SMALL, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, fmt.str()));
  631. }
  632. void CStackWindow::MainSection::addStatLabel(EStat index, int64_t value)
  633. {
  634. addStatLabel(index, value, value);
  635. }
  636. CStackWindow::CStackWindow(const CStack * stack, bool popup)
  637. : CWindowObject(BORDERED | (popup ? RCLICK_POPUP : 0)),
  638. info(std::make_unique<UnitView>())
  639. {
  640. info->stack = stack;
  641. info->stackNode = stack->base;
  642. info->commander = dynamic_cast<const CCommanderInstance*>(stack->base);
  643. info->creature = stack->unitType();
  644. info->creatureCount = stack->getCount();
  645. info->popupWindow = popup;
  646. init();
  647. }
  648. CStackWindow::CStackWindow(const CCreature * creature, bool popup)
  649. : CWindowObject(BORDERED | (popup ? RCLICK_POPUP : 0)),
  650. info(std::make_unique<UnitView>())
  651. {
  652. info->creature = creature;
  653. info->popupWindow = popup;
  654. init();
  655. }
  656. CStackWindow::CStackWindow(const CStackInstance * stack, bool popup)
  657. : CWindowObject(BORDERED | (popup ? RCLICK_POPUP : 0)),
  658. info(std::make_unique<UnitView>())
  659. {
  660. info->stackNode = stack;
  661. info->creature = stack->getCreature();
  662. info->creatureCount = stack->getCount();
  663. info->popupWindow = popup;
  664. info->owner = dynamic_cast<const CGHeroInstance *> (stack->getArmy());
  665. init();
  666. }
  667. CStackWindow::CStackWindow(const CStackInstance * stack, std::function<void()> dismiss, const UpgradeInfo & upgradeInfo, std::function<void(CreatureID)> callback)
  668. : CWindowObject(BORDERED),
  669. info(std::make_unique<UnitView>())
  670. {
  671. info->stackNode = stack;
  672. info->creature = stack->getCreature();
  673. info->creatureCount = stack->getCount();
  674. if(upgradeInfo.canUpgrade())
  675. {
  676. info->upgradeInfo = std::make_optional(UnitView::StackUpgradeInfo(upgradeInfo));
  677. info->upgradeInfo->callback = callback;
  678. }
  679. info->dismissInfo = std::make_optional(UnitView::StackDismissInfo());
  680. info->dismissInfo->callback = dismiss;
  681. info->owner = dynamic_cast<const CGHeroInstance *> (stack->getArmy());
  682. init();
  683. }
  684. CStackWindow::CStackWindow(const CCommanderInstance * commander, bool popup)
  685. : CWindowObject(BORDERED | (popup ? RCLICK_POPUP : 0)),
  686. info(std::make_unique<UnitView>())
  687. {
  688. info->stackNode = commander;
  689. info->creature = commander->getCreature();
  690. info->commander = commander;
  691. info->creatureCount = 1;
  692. info->popupWindow = popup;
  693. info->owner = dynamic_cast<const CGHeroInstance *> (commander->getArmy());
  694. init();
  695. }
  696. CStackWindow::CStackWindow(const CCommanderInstance * commander, std::vector<ui32> &skills, std::function<void(ui32)> callback)
  697. : CWindowObject(BORDERED),
  698. info(std::make_unique<UnitView>())
  699. {
  700. info->stackNode = commander;
  701. info->creature = commander->getCreature();
  702. info->commander = commander;
  703. info->creatureCount = 1;
  704. info->levelupInfo = std::make_optional(UnitView::CommanderLevelInfo());
  705. info->levelupInfo->skills = skills;
  706. info->levelupInfo->callback = callback;
  707. info->owner = dynamic_cast<const CGHeroInstance *> (commander->getArmy());
  708. init();
  709. }
  710. CStackWindow::~CStackWindow() = default;
  711. void CStackWindow::close()
  712. {
  713. if(info->levelupInfo && !info->levelupInfo->skills.empty())
  714. info->levelupInfo->callback(vstd::find_pos(info->levelupInfo->skills, selectedSkill));
  715. CWindowObject::close();
  716. }
  717. void CStackWindow::init()
  718. {
  719. OBJECT_CONSTRUCTION;
  720. background = std::make_shared<CFilledTexture>(ImagePath::builtin("DIBOXBCK"), pos);
  721. if(!info->stackNode)
  722. {
  723. //does not contain any propagated bonuses
  724. fakeNode = std::make_unique<CStackInstance>(nullptr, info->creature->getId(), 1, true);
  725. info->stackNode = fakeNode.get();
  726. }
  727. selectedIcon = nullptr;
  728. selectedSkill = -1;
  729. if(info->levelupInfo && !info->levelupInfo->skills.empty())
  730. selectedSkill = info->levelupInfo->skills.front();
  731. activeTab = 0;
  732. initBonusesList();
  733. initSections();
  734. background->pos = pos;
  735. }
  736. void CStackWindow::initBonusesList()
  737. {
  738. const IBonusBearer * bonusSource = info->stack
  739. ? static_cast<const IBonusBearer*>(info->stack) // Use CStack in battle
  740. : static_cast<const IBonusBearer*>(info->stackNode); // Use CStackInstance outside of battle
  741. auto bonusToString = [bonusSource](const std::shared_ptr<Bonus> & bonus) -> std::string
  742. {
  743. if(!bonus->description.empty())
  744. return bonus->description.toString();
  745. else
  746. return LIBRARY->getBth()->bonusToString(bonus, bonusSource);
  747. };
  748. BonusList receivedBonuses = *bonusSource->getBonuses(Selector::all);
  749. BonusList abilities = info->creature->getExportedBonusList();
  750. // remove all bonuses that are not propagated away
  751. // such bonuses should be present in received bonuses, and if not - this means that they are behind inactive limiter, such as inactive stack experience bonuses
  752. abilities.remove_if([](const Bonus* b){ return b->propagator == nullptr;});
  753. const auto & bonusSortingPredicate = [bonusToString](const std::shared_ptr<Bonus> & v1, const std::shared_ptr<Bonus> & v2){
  754. if (v1->source != v2->source)
  755. {
  756. int priorityV1 = v1->source == BonusSource::CREATURE_ABILITY ? -1 : static_cast<int>(v1->source);
  757. int priorityV2 = v2->source == BonusSource::CREATURE_ABILITY ? -1 : static_cast<int>(v2->source);
  758. return priorityV1 < priorityV2;
  759. }
  760. else
  761. return bonusToString(v1) < bonusToString(v2);
  762. };
  763. receivedBonuses.remove_if([](const Bonus* b)
  764. {
  765. return !LIBRARY->bth->shouldPropagateDescription(b->type);
  766. });
  767. std::vector<BonusList> groupedBonuses;
  768. while (!receivedBonuses.empty())
  769. {
  770. auto currentBonus = receivedBonuses.front();
  771. const auto & sameBonusPredicate = [currentBonus](const std::shared_ptr<Bonus> & b)
  772. {
  773. return currentBonus->type == b->type && currentBonus->subtype == b->subtype;
  774. };
  775. groupedBonuses.emplace_back();
  776. std::copy_if(receivedBonuses.begin(), receivedBonuses.end(), std::back_inserter(groupedBonuses.back()), sameBonusPredicate);
  777. receivedBonuses.remove_if(Selector::typeSubtype(currentBonus->type, currentBonus->subtype));
  778. // FIXME: potential edge case: unit has ability that is propagated away (and needs to be displayed), but also receives same bonus from someplace else
  779. abilities.remove_if(Selector::typeSubtype(currentBonus->type, currentBonus->subtype));
  780. }
  781. // Add any remaining abilities of this unit that don't affect it at the moment, such as abilities that are propagated away, e.g. to other side in combat
  782. BonusList visibleBonuses = abilities;
  783. for (auto & group : groupedBonuses)
  784. {
  785. // Try to find the bonus in the group that represents the final effect in the best way.
  786. std::sort(group.begin(), group.end(), bonusSortingPredicate);
  787. BonusList groupIndepMin = group;
  788. BonusList groupIndepMax = group;
  789. BonusList groupNoMinMax = group;
  790. BonusList groupBaseOnly = group;
  791. groupIndepMin.remove_if([](const Bonus * b) { return b->valType != BonusValueType::INDEPENDENT_MIN; });
  792. groupIndepMax.remove_if([](const Bonus * b) { return b->valType != BonusValueType::INDEPENDENT_MAX; });
  793. groupNoMinMax.remove_if([](const Bonus * b) { return b->valType == BonusValueType::INDEPENDENT_MAX || b->valType == BonusValueType::INDEPENDENT_MIN; });
  794. groupBaseOnly.remove_if([](const Bonus * b) { return b->valType != BonusValueType::ADDITIVE_VALUE && b->valType != BonusValueType::BASE_NUMBER; });
  795. int valIndepMin = groupIndepMin.totalValue();
  796. int valIndepMax = groupIndepMax.totalValue();
  797. int valNoMinMax = groupNoMinMax.totalValue();
  798. BonusList usedGroup;
  799. if (!groupIndepMin.empty() && valNoMinMax != valIndepMin)
  800. usedGroup = groupIndepMin; // bonus value was limited due to INDEPENDENT_MIN bonus -> show this bonus
  801. else if (!groupIndepMax.empty() && valNoMinMax != valIndepMax)
  802. usedGroup = groupIndepMax; // bonus value was limited due to INDEPENDENT_MAX bonus -> show this bonus
  803. else if (!groupBaseOnly.empty())
  804. usedGroup = groupNoMinMax; // bonus value is not limited and has bonuses other than percent to base / percent to all - show first non-independent bonus
  805. // It is possible that empty group was selected. For example, there is only INDEPENDENT effect with value of 0, which does not actually has any effect on this unit
  806. // For example, orb of vulnerability on unit without any resistances
  807. if (!usedGroup.empty())
  808. visibleBonuses.push_back(usedGroup.front());
  809. }
  810. std::sort(visibleBonuses.begin(), visibleBonuses.end(), bonusSortingPredicate);
  811. BonusInfo bonusInfo;
  812. for(auto b : visibleBonuses)
  813. {
  814. bonusInfo.description = bonusToString(b);
  815. //FIXME: we possibly use fakeNode, which does not have the correct bonus value
  816. bonusInfo.imagePath = info->stackNode->bonusToGraphics(b);
  817. bonusInfo.bonusSource = b->source;
  818. //if it's possible to give any description or image for this kind of bonus
  819. if(!bonusInfo.description.empty() && !b->hidden)
  820. activeBonuses.push_back(bonusInfo);
  821. }
  822. }
  823. void CStackWindow::initSections()
  824. {
  825. OBJECT_CONSTRUCTION;
  826. bool showArt = GAME->interface() && GAME->interface()->cb->getSettings().getBoolean(EGameSettings::MODULE_STACK_ARTIFACT) && info->commander == nullptr && info->stackNode;
  827. bool showExp = ((GAME->interface() && GAME->interface()->cb->getSettings().getBoolean(EGameSettings::MODULE_STACK_EXPERIENCE)) || info->commander != nullptr) && info->stackNode;
  828. mainSection = std::make_shared<MainSection>(this, pos.h, showExp, showArt);
  829. pos.w = mainSection->pos.w;
  830. pos.h += mainSection->pos.h;
  831. if(info->stack) // in battle
  832. {
  833. activeSpellsSection = std::make_shared<ActiveSpellsSection>(this, pos.h);
  834. pos.h += activeSpellsSection->pos.h;
  835. }
  836. if(info->commander)
  837. {
  838. auto onCreate = [this](size_t index) -> std::shared_ptr<CIntObject>
  839. {
  840. auto obj = switchTab(index);
  841. if(obj)
  842. obj->enable();
  843. return obj;
  844. };
  845. auto deactivateObj = [=](std::shared_ptr<CIntObject> obj)
  846. {
  847. obj->disable();
  848. };
  849. commanderMainSection = std::make_shared<CommanderMainSection>(this, 0);
  850. auto size = std::make_optional<size_t>((info->levelupInfo) ? 4 : 3);
  851. commanderBonusesSection = std::make_shared<BonusesSection>(this, 0, size);
  852. deactivateObj(commanderBonusesSection);
  853. commanderTab = std::make_shared<CTabbedInt>(onCreate, Point(0, pos.h), 0);
  854. pos.h += commanderMainSection->pos.h;
  855. }
  856. if(!info->commander && !activeBonuses.empty())
  857. {
  858. bonusesSection = std::make_shared<BonusesSection>(this, pos.h);
  859. pos.h += bonusesSection->pos.h;
  860. }
  861. if(!info->popupWindow)
  862. {
  863. buttonsSection = std::make_shared<ButtonsSection>(this, pos.h);
  864. pos.h += buttonsSection->pos.h;
  865. //FIXME: add status bar to image?
  866. }
  867. updateShadow();
  868. pos = center(pos);
  869. }
  870. std::string CStackWindow::generateStackExpDescription()
  871. {
  872. const CStackInstance * stack = info->stackNode;
  873. const CCreature * creature = info->creature;
  874. int tier = stack->getType()->getLevel();
  875. int rank = stack->getExpRank();
  876. if (!vstd::iswithin(tier, 1, 7))
  877. tier = 0;
  878. int number;
  879. std::string expText = LIBRARY->generaltexth->translate("vcmi.stackExperience.description");
  880. boost::replace_first(expText, "%s", creature->getNamePluralTranslated());
  881. boost::replace_first(expText, "%s", LIBRARY->generaltexth->translate("vcmi.stackExperience.rank", rank));
  882. boost::replace_first(expText, "%i", std::to_string(rank));
  883. boost::replace_first(expText, "%i", std::to_string(stack->getAverageExperience()));
  884. number = static_cast<int>(LIBRARY->creh->expRanks[tier][rank] - stack->getAverageExperience());
  885. boost::replace_first(expText, "%i", std::to_string(number));
  886. number = LIBRARY->creh->maxExpPerBattle[tier]; //percent
  887. boost::replace_first(expText, "%i%", std::to_string(number));
  888. number *= LIBRARY->creh->expRanks[tier].back() / 100; //actual amount
  889. boost::replace_first(expText, "%i", std::to_string(number));
  890. boost::replace_first(expText, "%i", std::to_string(stack->getCount())); //Number of Creatures in stack
  891. int expmin = std::max(LIBRARY->creh->expRanks[tier][std::max(rank-1, 0)], (ui32)1);
  892. number = stack->getTotalExperience() / expmin - stack->getCount(); //Maximum New Recruits without losing current Rank
  893. boost::replace_first(expText, "%i", std::to_string(number)); //TODO
  894. boost::replace_first(expText, "%.2f", std::to_string(1)); //TODO Experience Multiplier
  895. number = LIBRARY->creh->expAfterUpgrade;
  896. boost::replace_first(expText, "%.2f", std::to_string(number) + "%"); //Upgrade Multiplier
  897. expmin = LIBRARY->creh->expRanks[tier][9];
  898. int expmax = LIBRARY->creh->expRanks[tier][10];
  899. number = expmax - expmin;
  900. boost::replace_first(expText, "%i", std::to_string(number)); //Experience after Rank 10
  901. number = (stack->getCount() * (expmax - expmin)) / expmin;
  902. boost::replace_first(expText, "%i", std::to_string(number)); //Maximum New Recruits to remain at Rank 10 if at Maximum Experience
  903. return expText;
  904. }
  905. std::string CStackWindow::getCommanderSkillDescription(int skillIndex, int skillLevel)
  906. {
  907. constexpr std::array skillNames = {
  908. "attack",
  909. "defence",
  910. "health",
  911. "damage",
  912. "speed",
  913. "magic"
  914. };
  915. std::string textID = TextIdentifier("vcmi", "commander", "skill", skillNames.at(skillIndex), skillLevel).get();
  916. return LIBRARY->generaltexth->translate(textID);
  917. }
  918. void CStackWindow::setSelection(si32 newSkill, std::shared_ptr<CCommanderSkillIcon> newIcon)
  919. {
  920. auto getSkillDescription = [this](int skillIndex, bool selected) -> std::string
  921. {
  922. if(selected)
  923. return getCommanderSkillDescription(skillIndex, info->commander->secondarySkills[skillIndex] + 1); //upgrade description
  924. else
  925. return getCommanderSkillDescription(skillIndex, info->commander->secondarySkills[skillIndex]);
  926. };
  927. auto getSkillImage = [this](int skillIndex)
  928. {
  929. bool selected = ((selectedSkill == skillIndex) && info->levelupInfo );
  930. return skillToFile(skillIndex, info->commander->secondarySkills[skillIndex], selected);
  931. };
  932. OBJECT_CONSTRUCTION;
  933. int oldSelection = selectedSkill; // update selection
  934. selectedSkill = newSkill;
  935. if(selectedIcon && oldSelection < 100) // recreate image on old selection, only for skills
  936. selectedIcon->setObject(std::make_shared<CPicture>(getSkillImage(oldSelection)));
  937. if(selectedIcon)
  938. {
  939. if(!selectedIcon->getIsMasterAbility()) //unlike WoG, in VCMI master skill descriptions are taken from bonus descriptions
  940. {
  941. selectedIcon->text = getSkillDescription(oldSelection, false); //update previously selected icon's message to existing skill level
  942. }
  943. selectedIcon->deselect();
  944. }
  945. selectedIcon = newIcon; // update new selection
  946. if(newSkill < 100)
  947. {
  948. newIcon->setObject(std::make_shared<CPicture>(getSkillImage(newSkill)));
  949. if(!newIcon->getIsMasterAbility())
  950. {
  951. newIcon->text = getSkillDescription(newSkill, true); //update currently selected icon's message to show upgrade description
  952. }
  953. }
  954. }
  955. std::shared_ptr<CIntObject> CStackWindow::switchTab(size_t index)
  956. {
  957. std::shared_ptr<CIntObject> ret;
  958. switch(index)
  959. {
  960. case 0:
  961. {
  962. activeTab = 0;
  963. ret = commanderMainSection;
  964. }
  965. break;
  966. case 1:
  967. {
  968. activeTab = 1;
  969. ret = commanderBonusesSection;
  970. }
  971. break;
  972. default:
  973. break;
  974. }
  975. return ret;
  976. }
  977. void CStackWindow::removeStackArtifact(ArtifactPosition pos)
  978. {
  979. auto art = info->stackNode->getArt(ArtifactPosition::CREATURE_SLOT);
  980. if(!art)
  981. {
  982. logGlobal->error("Attempt to remove missing artifact");
  983. return;
  984. }
  985. const auto slot = ArtifactUtils::getArtBackpackPosition(info->owner, art->getTypeId());
  986. if(slot != ArtifactPosition::PRE_FIRST)
  987. {
  988. auto artLoc = ArtifactLocation(info->owner->id, pos);
  989. artLoc.creature = info->stackNode->getArmy()->findStack(info->stackNode);
  990. GAME->interface()->cb->swapArtifacts(artLoc, ArtifactLocation(info->owner->id, slot));
  991. stackArtifactButton.reset();
  992. stackArtifact.reset();
  993. redraw();
  994. }
  995. }