CCreatureWindow.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  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 "../CGameInfo.h"
  15. #include "../CPlayerInterface.h"
  16. #include "../render/Canvas.h"
  17. #include "../widgets/Buttons.h"
  18. #include "../widgets/CArtifactHolder.h"
  19. #include "../widgets/CComponent.h"
  20. #include "../widgets/Images.h"
  21. #include "../widgets/TextControls.h"
  22. #include "../widgets/ObjectLists.h"
  23. #include "../gui/CGuiHandler.h"
  24. #include "../gui/Shortcut.h"
  25. #include "../../CCallback.h"
  26. #include "../../lib/ArtifactUtils.h"
  27. #include "../../lib/CStack.h"
  28. #include "../../lib/CBonusTypeHandler.h"
  29. #include "../../lib/CGeneralTextHandler.h"
  30. #include "../../lib/GameSettings.h"
  31. #include "../../lib/CHeroHandler.h"
  32. #include "../../lib/gameState/CGameState.h"
  33. #include "../../lib/TextOperations.h"
  34. class CCreatureArtifactInstance;
  35. class CSelectableSkill;
  36. class UnitView
  37. {
  38. public:
  39. // helper structs
  40. struct CommanderLevelInfo
  41. {
  42. std::vector<ui32> skills;
  43. std::function<void(ui32)> callback;
  44. };
  45. struct StackDismissInfo
  46. {
  47. std::function<void()> callback;
  48. };
  49. struct StackUpgradeInfo
  50. {
  51. UpgradeInfo info;
  52. std::function<void(CreatureID)> callback;
  53. };
  54. // pointers to permament objects in game state
  55. const CCreature * creature;
  56. const CCommanderInstance * commander;
  57. const CStackInstance * stackNode;
  58. const CStack * stack;
  59. const CGHeroInstance * owner;
  60. // temporary objects which should be kept as copy if needed
  61. std::optional<CommanderLevelInfo> levelupInfo;
  62. std::optional<StackDismissInfo> dismissInfo;
  63. std::optional<StackUpgradeInfo> upgradeInfo;
  64. // misc fields
  65. unsigned int creatureCount;
  66. bool popupWindow;
  67. UnitView()
  68. : creature(nullptr),
  69. commander(nullptr),
  70. stackNode(nullptr),
  71. stack(nullptr),
  72. owner(nullptr),
  73. creatureCount(0),
  74. popupWindow(false)
  75. {
  76. }
  77. std::string getName() const
  78. {
  79. if(commander)
  80. return commander->type->getNameSingularTranslated();
  81. else
  82. return creature->getNamePluralTranslated();
  83. }
  84. private:
  85. };
  86. CCommanderSkillIcon::CCommanderSkillIcon(std::shared_ptr<CIntObject> object_, bool isMasterAbility_, std::function<void()> callback)
  87. : object(),
  88. isMasterAbility(isMasterAbility_),
  89. isSelected(false),
  90. callback(callback)
  91. {
  92. pos = object_->pos;
  93. this->isMasterAbility = isMasterAbility_;
  94. setObject(object_);
  95. }
  96. void CCommanderSkillIcon::setObject(std::shared_ptr<CIntObject> newObject)
  97. {
  98. if(object)
  99. removeChild(object.get());
  100. object = newObject;
  101. addChild(object.get());
  102. object->moveTo(pos.topLeft());
  103. redraw();
  104. }
  105. void CCommanderSkillIcon::clickPressed(const Point & cursorPosition)
  106. {
  107. callback();
  108. isSelected = true;
  109. }
  110. void CCommanderSkillIcon::deselect()
  111. {
  112. isSelected = false;
  113. }
  114. bool CCommanderSkillIcon::getIsMasterAbility()
  115. {
  116. return isMasterAbility;
  117. }
  118. void CCommanderSkillIcon::show(Canvas &to)
  119. {
  120. CIntObject::show(to);
  121. if(isMasterAbility && isSelected)
  122. to.drawBorder(pos, Colors::YELLOW, 2);
  123. }
  124. static ImagePath skillToFile(int skill, int level, bool selected)
  125. {
  126. // FIXME: is this a correct hadling?
  127. // level 0 = skill not present, use image with "no" suffix
  128. // level 1-5 = skill available, mapped to images indexed as 0-4
  129. // selecting skill means that it will appear one level higher (as if alredy upgraded)
  130. std::string file = "zvs/Lib1.res/_";
  131. switch (skill)
  132. {
  133. case ECommander::ATTACK:
  134. file += "AT";
  135. break;
  136. case ECommander::DEFENSE:
  137. file += "DF";
  138. break;
  139. case ECommander::HEALTH:
  140. file += "HP";
  141. break;
  142. case ECommander::DAMAGE:
  143. file += "DM";
  144. break;
  145. case ECommander::SPEED:
  146. file += "SP";
  147. break;
  148. case ECommander::SPELL_POWER:
  149. file += "MP";
  150. break;
  151. }
  152. std::string sufix;
  153. if (selected)
  154. level++; // UI will display resulting level
  155. if (level == 0)
  156. sufix = "no"; //not avaliable - no number
  157. else
  158. sufix = std::to_string(level-1);
  159. if (selected)
  160. sufix += "="; //level-up highlight
  161. return ImagePath::builtin(file + sufix + ".bmp");
  162. }
  163. CStackWindow::CWindowSection::CWindowSection(CStackWindow * parent, const ImagePath & backgroundPath, int yOffset)
  164. : parent(parent)
  165. {
  166. pos.y += yOffset;
  167. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  168. if(!backgroundPath.empty())
  169. {
  170. background = std::make_shared<CPicture>(backgroundPath);
  171. pos.w = background->pos.w;
  172. pos.h = background->pos.h;
  173. }
  174. }
  175. CStackWindow::ActiveSpellsSection::ActiveSpellsSection(CStackWindow * owner, int yOffset)
  176. : CWindowSection(owner, ImagePath::builtin("stackWindow/spell-effects"), yOffset)
  177. {
  178. static const Point firstPos(6, 2); // position of 1st spell box
  179. static const Point offset(54, 0); // offset of each spell box from previous
  180. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  181. const CStack * battleStack = parent->info->stack;
  182. assert(battleStack); // Section should be created only for battles
  183. //spell effects
  184. int printed=0; //how many effect pics have been printed
  185. std::vector<si32> spells = battleStack->activeSpells();
  186. for(si32 effect : spells)
  187. {
  188. const spells::Spell * spell = CGI->spells()->getByIndex(effect);
  189. std::string spellText;
  190. //not all effects have graphics (for eg. Acid Breath)
  191. //for modded spells iconEffect is added to SpellInt.def
  192. const bool hasGraphics = (effect < SpellID::THUNDERBOLT) || (effect >= SpellID::AFTER_LAST);
  193. if (hasGraphics)
  194. {
  195. spellText = CGI->generaltexth->allTexts[610]; //"%s, duration: %d rounds."
  196. boost::replace_first(spellText, "%s", spell->getNameTranslated());
  197. //FIXME: support permanent duration
  198. int duration = battleStack->getBonusLocalFirst(Selector::source(BonusSource::SPELL_EFFECT,effect))->turnsRemain;
  199. boost::replace_first(spellText, "%d", std::to_string(duration));
  200. spellIcons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("SpellInt"), effect + 1, 0, firstPos.x + offset.x * printed, firstPos.y + offset.y * printed));
  201. clickableAreas.push_back(std::make_shared<LRClickableAreaWText>(Rect(firstPos + offset * printed, Point(50, 38)), spellText, spellText));
  202. if(++printed >= 8) // interface limit reached
  203. break;
  204. }
  205. }
  206. }
  207. CStackWindow::BonusLineSection::BonusLineSection(CStackWindow * owner, size_t lineIndex)
  208. : CWindowSection(owner, ImagePath::builtin("stackWindow/bonus-effects"), 0)
  209. {
  210. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  211. static const std::array<Point, 2> offset =
  212. {
  213. Point(6, 4),
  214. Point(214, 4)
  215. };
  216. for(size_t leftRight : {0, 1})
  217. {
  218. auto position = offset[leftRight];
  219. size_t bonusIndex = lineIndex * 2 + leftRight;
  220. if(parent->activeBonuses.size() > bonusIndex)
  221. {
  222. BonusInfo & bi = parent->activeBonuses[bonusIndex];
  223. icon[leftRight] = std::make_shared<CPicture>(bi.imagePath, position.x, position.y);
  224. name[leftRight] = std::make_shared<CLabel>(position.x + 60, position.y + 2, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE, bi.name);
  225. description[leftRight] = std::make_shared<CMultiLineLabel>(Rect(position.x + 60, position.y + 17, 137, 30), FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE, bi.description);
  226. }
  227. }
  228. }
  229. CStackWindow::BonusesSection::BonusesSection(CStackWindow * owner, int yOffset, std::optional<size_t> preferredSize):
  230. CWindowSection(owner, {}, yOffset)
  231. {
  232. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  233. // size of single image for an item
  234. static const int itemHeight = 59;
  235. size_t totalSize = (owner->activeBonuses.size() + 1) / 2;
  236. size_t visibleSize = preferredSize.value_or(std::min<size_t>(3, totalSize));
  237. pos.w = owner->pos.w;
  238. pos.h = itemHeight * (int)visibleSize;
  239. auto onCreate = [=](size_t index) -> std::shared_ptr<CIntObject>
  240. {
  241. return std::make_shared<BonusLineSection>(owner, index);
  242. };
  243. lines = std::make_shared<CListBox>(onCreate, Point(0, 0), Point(0, itemHeight), visibleSize, totalSize, 0, 1, Rect(pos.w - 15, 0, pos.h, pos.h));
  244. }
  245. CStackWindow::ButtonsSection::ButtonsSection(CStackWindow * owner, int yOffset)
  246. : CWindowSection(owner, ImagePath::builtin("stackWindow/button-panel"), yOffset)
  247. {
  248. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  249. if(parent->info->dismissInfo && parent->info->dismissInfo->callback)
  250. {
  251. auto onDismiss = [=]()
  252. {
  253. parent->info->dismissInfo->callback();
  254. parent->close();
  255. };
  256. auto onClick = [=] ()
  257. {
  258. LOCPLINT->showYesNoDialog(CGI->generaltexth->allTexts[12], onDismiss, nullptr);
  259. };
  260. dismiss = std::make_shared<CButton>(Point(5, 5),AnimationPath::builtin("IVIEWCR2.DEF"), CGI->generaltexth->zelp[445], onClick, EShortcut::HERO_DISMISS);
  261. }
  262. if(parent->info->upgradeInfo && !parent->info->commander)
  263. {
  264. // used space overlaps with commander switch button
  265. // besides - should commander really be upgradeable?
  266. auto & upgradeInfo = parent->info->upgradeInfo.value();
  267. const size_t buttonsToCreate = std::min<size_t>(upgradeInfo.info.newID.size(), upgrade.size());
  268. for(size_t buttonIndex = 0; buttonIndex < buttonsToCreate; buttonIndex++)
  269. {
  270. TResources totalCost = upgradeInfo.info.cost[buttonIndex] * parent->info->creatureCount;
  271. auto onUpgrade = [=]()
  272. {
  273. upgradeInfo.callback(upgradeInfo.info.newID[buttonIndex]);
  274. parent->close();
  275. };
  276. auto onClick = [=]()
  277. {
  278. std::vector<std::shared_ptr<CComponent>> resComps;
  279. for(TResources::nziterator i(totalCost); i.valid(); i++)
  280. {
  281. resComps.push_back(std::make_shared<CComponent>(CComponent::resource, i->resType, (int)i->resVal));
  282. }
  283. if(LOCPLINT->cb->getResourceAmount().canAfford(totalCost))
  284. {
  285. LOCPLINT->showYesNoDialog(CGI->generaltexth->allTexts[207], onUpgrade, nullptr, resComps);
  286. }
  287. else
  288. {
  289. LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[314], resComps);
  290. }
  291. };
  292. auto upgradeBtn = std::make_shared<CButton>(Point(221 + (int)buttonIndex * 40, 5), AnimationPath::builtin("stackWindow/upgradeButton"), CGI->generaltexth->zelp[446], onClick);
  293. upgradeBtn->addOverlay(std::make_shared<CAnimImage>(AnimationPath::builtin("CPRSMALL"), VLC->creh->objects[upgradeInfo.info.newID[buttonIndex]]->getIconIndex()));
  294. if(buttonsToCreate == 1) // single upgrade avaialbe
  295. upgradeBtn->assignedKey = EShortcut::RECRUITMENT_UPGRADE;
  296. upgrade[buttonIndex] = upgradeBtn;
  297. }
  298. }
  299. if(parent->info->commander)
  300. {
  301. for(size_t buttonIndex = 0; buttonIndex < 2; buttonIndex++)
  302. {
  303. std::string btnIDs[2] = { "showSkills", "showBonuses" };
  304. auto onSwitch = [buttonIndex, this]()
  305. {
  306. logAnim->debug("Switch %d->%d", parent->activeTab, buttonIndex);
  307. parent->switchButtons[parent->activeTab]->enable();
  308. parent->commanderTab->setActive(buttonIndex);
  309. parent->switchButtons[buttonIndex]->disable();
  310. parent->redraw(); // FIXME: enable/disable don't redraw screen themselves
  311. };
  312. std::string tooltipText = "vcmi.creatureWindow." + btnIDs[buttonIndex];
  313. parent->switchButtons[buttonIndex] = std::make_shared<CButton>(Point(302 + (int)buttonIndex*40, 5), AnimationPath::builtin("stackWindow/upgradeButton"), CButton::tooltipLocalized(tooltipText), onSwitch);
  314. parent->switchButtons[buttonIndex]->addOverlay(std::make_shared<CAnimImage>(AnimationPath::builtin("stackWindow/switchModeIcons"), buttonIndex));
  315. }
  316. parent->switchButtons[parent->activeTab]->disable();
  317. }
  318. exit = std::make_shared<CButton>(Point(382, 5), AnimationPath::builtin("hsbtns.def"), CGI->generaltexth->zelp[447], [=](){ parent->close(); }, EShortcut::GLOBAL_RETURN);
  319. }
  320. CStackWindow::CommanderMainSection::CommanderMainSection(CStackWindow * owner, int yOffset)
  321. : CWindowSection(owner, ImagePath::builtin("stackWindow/commander-bg"), yOffset)
  322. {
  323. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  324. auto getSkillPos = [](int index)
  325. {
  326. return Point(10 + 80 * (index%3), 20 + 80 * (index/3));
  327. };
  328. auto getSkillImage = [this](int skillIndex)
  329. {
  330. bool selected = ((parent->selectedSkill == skillIndex) && parent->info->levelupInfo );
  331. return skillToFile(skillIndex, parent->info->commander->secondarySkills[skillIndex], selected);
  332. };
  333. auto getSkillDescription = [this](int skillIndex) -> std::string
  334. {
  335. return CGI->generaltexth->znpc00[152 + (12 * skillIndex) + (parent->info->commander->secondarySkills[skillIndex] * 2)];
  336. };
  337. for(int index = ECommander::ATTACK; index <= ECommander::SPELL_POWER; ++index)
  338. {
  339. Point skillPos = getSkillPos(index);
  340. auto icon = std::make_shared<CCommanderSkillIcon>(std::make_shared<CPicture>(getSkillImage(index), skillPos.x, skillPos.y), false, [=]()
  341. {
  342. LOCPLINT->showInfoDialog(getSkillDescription(index));
  343. });
  344. icon->text = getSkillDescription(index); //used to handle right click description via LRClickableAreaWText::ClickRight()
  345. if(parent->selectedSkill == index)
  346. parent->selectedIcon = icon;
  347. if(parent->info->levelupInfo && vstd::contains(parent->info->levelupInfo->skills, index)) // can be upgraded - enable selection switch
  348. {
  349. if(parent->selectedSkill == index)
  350. parent->setSelection(index, icon);
  351. icon->callback = [=]()
  352. {
  353. parent->setSelection(index, icon);
  354. };
  355. }
  356. skillIcons.push_back(icon);
  357. }
  358. auto getArtifactPos = [](int index)
  359. {
  360. return Point(269 + 47 * (index % 3), 22 + 47 * (index / 3));
  361. };
  362. for(auto equippedArtifact : parent->info->commander->artifactsWorn)
  363. {
  364. Point artPos = getArtifactPos(equippedArtifact.first);
  365. auto artPlace = std::make_shared<CCommanderArtPlace>(artPos, parent->info->owner, equippedArtifact.first, equippedArtifact.second.artifact);
  366. artifacts.push_back(artPlace);
  367. }
  368. if(parent->info->levelupInfo)
  369. {
  370. abilitiesBackground = std::make_shared<CPicture>(ImagePath::builtin("stackWindow/commander-abilities.png"));
  371. abilitiesBackground->moveBy(Point(0, pos.h));
  372. size_t abilitiesCount = boost::range::count_if(parent->info->levelupInfo->skills, [](ui32 skillID)
  373. {
  374. return skillID >= 100;
  375. });
  376. auto onCreate = [=](size_t index)->std::shared_ptr<CIntObject>
  377. {
  378. for(auto skillID : parent->info->levelupInfo->skills)
  379. {
  380. if(index == 0 && skillID >= 100)
  381. {
  382. const auto bonus = CGI->creh->skillRequirements[skillID-100].first;
  383. const CStackInstance * stack = parent->info->commander;
  384. auto icon = std::make_shared<CCommanderSkillIcon>(std::make_shared<CPicture>(stack->bonusToGraphics(bonus)), true, [](){});
  385. icon->callback = [=]()
  386. {
  387. parent->setSelection(skillID, icon);
  388. };
  389. icon->text = stack->bonusToString(bonus, true);
  390. icon->hoverText = stack->bonusToString(bonus, false);
  391. return icon;
  392. }
  393. if(skillID >= 100)
  394. index--;
  395. }
  396. return nullptr;
  397. };
  398. abilities = std::make_shared<CListBox>(onCreate, Point(38, 3+pos.h), Point(63, 0), 6, abilitiesCount);
  399. abilities->setRedrawParent(true);
  400. leftBtn = std::make_shared<CButton>(Point(10, pos.h + 6), AnimationPath::builtin("hsbtns3.def"), CButton::tooltip(), [=](){ abilities->moveToPrev(); }, EShortcut::MOVE_LEFT);
  401. rightBtn = std::make_shared<CButton>(Point(411, pos.h + 6), AnimationPath::builtin("hsbtns5.def"), CButton::tooltip(), [=](){ abilities->moveToNext(); }, EShortcut::MOVE_RIGHT);
  402. if(abilitiesCount <= 6)
  403. {
  404. leftBtn->block(true);
  405. rightBtn->block(true);
  406. }
  407. pos.h += abilitiesBackground->pos.h;
  408. }
  409. }
  410. CStackWindow::MainSection::MainSection(CStackWindow * owner, int yOffset, bool showExp, bool showArt)
  411. : CWindowSection(owner, getBackgroundName(showExp, showArt), yOffset)
  412. {
  413. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  414. statNames =
  415. {
  416. CGI->generaltexth->primarySkillNames[0], //ATTACK
  417. CGI->generaltexth->primarySkillNames[1],//DEFENCE
  418. CGI->generaltexth->allTexts[198],//SHOTS
  419. CGI->generaltexth->allTexts[199],//DAMAGE
  420. CGI->generaltexth->allTexts[388],//HEALTH
  421. CGI->generaltexth->allTexts[200],//HEALTH_LEFT
  422. CGI->generaltexth->zelp[441].first,//SPEED
  423. CGI->generaltexth->allTexts[399]//MANA
  424. };
  425. statFormats =
  426. {
  427. "%d (%d)",
  428. "%d (%d)",
  429. "%d (%d)",
  430. "%d - %d",
  431. "%d (%d)",
  432. "%d (%d)",
  433. "%d (%d)",
  434. "%d (%d)"
  435. };
  436. animation = std::make_shared<CCreaturePic>(5, 41, parent->info->creature);
  437. if(parent->info->stackNode != nullptr && parent->info->commander == nullptr)
  438. {
  439. //normal stack, not a commander and not non-existing stack (e.g. recruitment dialog)
  440. animation->setAmount(parent->info->creatureCount);
  441. }
  442. name = std::make_shared<CLabel>(215, 12, FONT_SMALL, ETextAlignment::CENTER, Colors::YELLOW, parent->info->getName());
  443. int dmgMultiply = 1;
  444. if(parent->info->owner && parent->info->stackNode->hasBonusOfType(BonusType::SIEGE_WEAPON))
  445. dmgMultiply += parent->info->owner->getPrimSkillLevel(PrimarySkill::ATTACK);
  446. icons = std::make_shared<CPicture>(ImagePath::builtin("stackWindow/icons"), 117, 32);
  447. const CStack * battleStack = parent->info->stack;
  448. morale = std::make_shared<MoraleLuckBox>(true, Rect(Point(321, 110), Point(42, 42) ));
  449. luck = std::make_shared<MoraleLuckBox>(false, Rect(Point(375, 110), Point(42, 42) ));
  450. if(battleStack != nullptr) // in battle
  451. {
  452. addStatLabel(EStat::ATTACK, parent->info->creature->getAttack(battleStack->isShooter()), battleStack->getAttack(battleStack->isShooter()));
  453. addStatLabel(EStat::DEFENCE, parent->info->creature->getDefense(battleStack->isShooter()), battleStack->getDefense(battleStack->isShooter()));
  454. addStatLabel(EStat::DAMAGE, parent->info->stackNode->getMinDamage(battleStack->isShooter()) * dmgMultiply, battleStack->getMaxDamage(battleStack->isShooter()) * dmgMultiply);
  455. addStatLabel(EStat::HEALTH, parent->info->creature->getMaxHealth(), battleStack->getMaxHealth());
  456. addStatLabel(EStat::SPEED, parent->info->creature->speed(), battleStack->speed());
  457. if(battleStack->isShooter())
  458. addStatLabel(EStat::SHOTS, battleStack->shots.total(), battleStack->shots.available());
  459. if(battleStack->isCaster())
  460. addStatLabel(EStat::MANA, battleStack->casts.total(), battleStack->casts.available());
  461. addStatLabel(EStat::HEALTH_LEFT, battleStack->getFirstHPleft());
  462. morale->set(battleStack);
  463. luck->set(battleStack);
  464. }
  465. else
  466. {
  467. const bool shooter = parent->info->stackNode->hasBonusOfType(BonusType::SHOOTER) && parent->info->stackNode->valOfBonuses(BonusType::SHOTS);
  468. const bool caster = parent->info->stackNode->valOfBonuses(BonusType::CASTS);
  469. addStatLabel(EStat::ATTACK, parent->info->creature->getAttack(shooter), parent->info->stackNode->getAttack(shooter));
  470. addStatLabel(EStat::DEFENCE, parent->info->creature->getDefense(shooter), parent->info->stackNode->getDefense(shooter));
  471. addStatLabel(EStat::DAMAGE, parent->info->stackNode->getMinDamage(shooter) * dmgMultiply, parent->info->stackNode->getMaxDamage(shooter) * dmgMultiply);
  472. addStatLabel(EStat::HEALTH, parent->info->creature->getMaxHealth(), parent->info->stackNode->getMaxHealth());
  473. addStatLabel(EStat::SPEED, parent->info->creature->speed(), parent->info->stackNode->speed());
  474. if(shooter)
  475. addStatLabel(EStat::SHOTS, parent->info->stackNode->valOfBonuses(BonusType::SHOTS));
  476. if(caster)
  477. addStatLabel(EStat::MANA, parent->info->stackNode->valOfBonuses(BonusType::CASTS));
  478. morale->set(parent->info->stackNode);
  479. luck->set(parent->info->stackNode);
  480. }
  481. if(showExp)
  482. {
  483. const CStackInstance * stack = parent->info->stackNode;
  484. Point pos = showArt ? Point(321, 32) : Point(347, 32);
  485. if(parent->info->commander)
  486. {
  487. const CCommanderInstance * commander = parent->info->commander;
  488. expRankIcon = std::make_shared<CAnimImage>(AnimationPath::builtin("PSKIL42"), 4, 0, pos.x, pos.y);
  489. auto area = std::make_shared<LRClickableAreaWTextComp>(Rect(pos.x, pos.y, 44, 44), CComponent::experience);
  490. expArea = area;
  491. area->text = CGI->generaltexth->allTexts[2];
  492. area->bonusValue = commander->getExpRank();
  493. boost::replace_first(area->text, "%d", std::to_string(commander->getExpRank()));
  494. boost::replace_first(area->text, "%d", std::to_string(CGI->heroh->reqExp(commander->getExpRank() + 1)));
  495. boost::replace_first(area->text, "%d", std::to_string(commander->experience));
  496. }
  497. else
  498. {
  499. expRankIcon = std::make_shared<CAnimImage>(AnimationPath::builtin("stackWindow/levels"), stack->getExpRank(), 0, pos.x, pos.y);
  500. expArea = std::make_shared<LRClickableAreaWText>(Rect(pos.x, pos.y, 44, 44));
  501. expArea->text = parent->generateStackExpDescription();
  502. }
  503. expLabel = std::make_shared<CLabel>(
  504. pos.x + 21, pos.y + 52, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE,
  505. TextOperations::formatMetric(stack->experience, 6));
  506. }
  507. if(showArt)
  508. {
  509. Point pos = showExp ? Point(375, 32) : Point(347, 32);
  510. // ALARMA: do not refactor this into a separate function
  511. // otherwise, artifact icon is drawn near the hero's portrait
  512. // this is really strange
  513. auto art = parent->info->stackNode->getArt(ArtifactPosition::CREATURE_SLOT);
  514. if(art)
  515. {
  516. parent->stackArtifactIcon = std::make_shared<CAnimImage>(AnimationPath::builtin("ARTIFACT"), art->artType->getIconIndex(), 0, pos.x, pos.y);
  517. parent->stackArtifactHelp = std::make_shared<LRClickableAreaWTextComp>(Rect(pos, Point(44, 44)), CComponent::artifact);
  518. parent->stackArtifactHelp->type = art->artType->getId();
  519. if(parent->info->owner)
  520. {
  521. parent->stackArtifactButton = std::make_shared<CButton>(
  522. Point(pos.x - 2 , pos.y + 46), AnimationPath::builtin("stackWindow/cancelButton"),
  523. CButton::tooltipLocalized("vcmi.creatureWindow.returnArtifact"), [=]()
  524. {
  525. parent->removeStackArtifact(ArtifactPosition::CREATURE_SLOT);
  526. });
  527. }
  528. }
  529. }
  530. }
  531. ImagePath CStackWindow::MainSection::getBackgroundName(bool showExp, bool showArt)
  532. {
  533. if(showExp && showArt)
  534. return ImagePath::builtin("stackWindow/info-panel-2");
  535. else if(showExp || showArt)
  536. return ImagePath::builtin("stackWindow/info-panel-1");
  537. else
  538. return ImagePath::builtin("stackWindow/info-panel-0");
  539. }
  540. void CStackWindow::MainSection::addStatLabel(EStat index, int64_t value1, int64_t value2)
  541. {
  542. const auto title = statNames.at(static_cast<size_t>(index));
  543. stats.push_back(std::make_shared<CLabel>(145, 32 + (int)index*19, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE, title));
  544. const bool useRange = value1 != value2;
  545. std::string formatStr = useRange ? statFormats.at(static_cast<size_t>(index)) : "%d";
  546. boost::format fmt(formatStr);
  547. fmt % value1;
  548. if(useRange)
  549. fmt % value2;
  550. stats.push_back(std::make_shared<CLabel>(307, 48 + (int)index*19, FONT_SMALL, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, fmt.str()));
  551. }
  552. void CStackWindow::MainSection::addStatLabel(EStat index, int64_t value)
  553. {
  554. addStatLabel(index, value, value);
  555. }
  556. CStackWindow::CStackWindow(const CStack * stack, bool popup)
  557. : CWindowObject(BORDERED | (popup ? RCLICK_POPUP : 0)),
  558. info(new UnitView())
  559. {
  560. info->stack = stack;
  561. info->stackNode = stack->base;
  562. info->creature = stack->unitType();
  563. info->creatureCount = stack->getCount();
  564. info->popupWindow = popup;
  565. init();
  566. }
  567. CStackWindow::CStackWindow(const CCreature * creature, bool popup)
  568. : CWindowObject(BORDERED | (popup ? RCLICK_POPUP : 0)),
  569. info(new UnitView())
  570. {
  571. info->creature = creature;
  572. info->popupWindow = popup;
  573. init();
  574. }
  575. CStackWindow::CStackWindow(const CStackInstance * stack, bool popup)
  576. : CWindowObject(BORDERED | (popup ? RCLICK_POPUP : 0)),
  577. info(new UnitView())
  578. {
  579. info->stackNode = stack;
  580. info->creature = stack->type;
  581. info->creatureCount = stack->count;
  582. info->popupWindow = popup;
  583. info->owner = dynamic_cast<const CGHeroInstance *> (stack->armyObj);
  584. init();
  585. }
  586. CStackWindow::CStackWindow(const CStackInstance * stack, std::function<void()> dismiss, const UpgradeInfo & upgradeInfo, std::function<void(CreatureID)> callback)
  587. : CWindowObject(BORDERED),
  588. info(new UnitView())
  589. {
  590. info->stackNode = stack;
  591. info->creature = stack->type;
  592. info->creatureCount = stack->count;
  593. info->upgradeInfo = std::make_optional(UnitView::StackUpgradeInfo());
  594. info->dismissInfo = std::make_optional(UnitView::StackDismissInfo());
  595. info->upgradeInfo->info = upgradeInfo;
  596. info->upgradeInfo->callback = callback;
  597. info->dismissInfo->callback = dismiss;
  598. info->owner = dynamic_cast<const CGHeroInstance *> (stack->armyObj);
  599. init();
  600. }
  601. CStackWindow::CStackWindow(const CCommanderInstance * commander, bool popup)
  602. : CWindowObject(BORDERED | (popup ? RCLICK_POPUP : 0)),
  603. info(new UnitView())
  604. {
  605. info->stackNode = commander;
  606. info->creature = commander->type;
  607. info->commander = commander;
  608. info->creatureCount = 1;
  609. info->popupWindow = popup;
  610. info->owner = dynamic_cast<const CGHeroInstance *> (commander->armyObj);
  611. init();
  612. }
  613. CStackWindow::CStackWindow(const CCommanderInstance * commander, std::vector<ui32> &skills, std::function<void(ui32)> callback)
  614. : CWindowObject(BORDERED),
  615. info(new UnitView())
  616. {
  617. info->stackNode = commander;
  618. info->creature = commander->type;
  619. info->commander = commander;
  620. info->creatureCount = 1;
  621. info->levelupInfo = std::make_optional(UnitView::CommanderLevelInfo());
  622. info->levelupInfo->skills = skills;
  623. info->levelupInfo->callback = callback;
  624. info->owner = dynamic_cast<const CGHeroInstance *> (commander->armyObj);
  625. init();
  626. }
  627. CStackWindow::~CStackWindow()
  628. {
  629. if(info->levelupInfo && !info->levelupInfo->skills.empty())
  630. info->levelupInfo->callback(vstd::find_pos(info->levelupInfo->skills, selectedSkill));
  631. }
  632. void CStackWindow::init()
  633. {
  634. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  635. if(!info->stackNode)
  636. info->stackNode = new CStackInstance(info->creature, 1, true);// FIXME: free data
  637. selectedIcon = nullptr;
  638. selectedSkill = -1;
  639. if(info->levelupInfo && !info->levelupInfo->skills.empty())
  640. selectedSkill = info->levelupInfo->skills.front();
  641. activeTab = 0;
  642. initBonusesList();
  643. initSections();
  644. }
  645. void CStackWindow::initBonusesList()
  646. {
  647. BonusList output, input;
  648. input = *(info->stackNode->getBonuses(CSelector(Bonus::Permanent), Selector::all));
  649. while(!input.empty())
  650. {
  651. auto b = input.front();
  652. output.push_back(std::make_shared<Bonus>(*b));
  653. output.back()->val = input.valOfBonuses(Selector::typeSubtype(b->type, b->subtype)); //merge multiple bonuses into one
  654. input.remove_if (Selector::typeSubtype(b->type, b->subtype)); //remove used bonuses
  655. }
  656. BonusInfo bonusInfo;
  657. for(auto b : output)
  658. {
  659. bonusInfo.name = info->stackNode->bonusToString(b, false);
  660. bonusInfo.description = info->stackNode->bonusToString(b, true);
  661. bonusInfo.imagePath = info->stackNode->bonusToGraphics(b);
  662. //if it's possible to give any description or image for this kind of bonus
  663. //TODO: figure out why half of bonuses don't have proper description
  664. if(!bonusInfo.name.empty() || !bonusInfo.imagePath.empty())
  665. activeBonuses.push_back(bonusInfo);
  666. }
  667. }
  668. void CStackWindow::initSections()
  669. {
  670. OBJECT_CONSTRUCTION_CUSTOM_CAPTURING(255-DISPOSE);
  671. bool showArt = CGI->settings()->getBoolean(EGameSettings::MODULE_STACK_ARTIFACT) && info->commander == nullptr && info->stackNode;
  672. bool showExp = (CGI->settings()->getBoolean(EGameSettings::MODULE_STACK_EXPERIENCE) || info->commander != nullptr) && info->stackNode;
  673. mainSection = std::make_shared<MainSection>(this, pos.h, showExp, showArt);
  674. pos.w = mainSection->pos.w;
  675. pos.h += mainSection->pos.h;
  676. if(info->stack) // in battle
  677. {
  678. activeSpellsSection = std::make_shared<ActiveSpellsSection>(this, pos.h);
  679. pos.h += activeSpellsSection->pos.h;
  680. }
  681. if(info->commander)
  682. {
  683. auto onCreate = [=](size_t index) -> std::shared_ptr<CIntObject>
  684. {
  685. auto obj = switchTab(index);
  686. if(obj)
  687. {
  688. obj->activate();
  689. obj->recActions |= (UPDATE | SHOWALL);
  690. }
  691. return obj;
  692. };
  693. auto deactivateObj = [=](std::shared_ptr<CIntObject> obj)
  694. {
  695. obj->deactivate();
  696. obj->recActions &= ~(UPDATE | SHOWALL);
  697. };
  698. commanderMainSection = std::make_shared<CommanderMainSection>(this, 0);
  699. auto size = std::make_optional<size_t>((info->levelupInfo) ? 4 : 3);
  700. commanderBonusesSection = std::make_shared<BonusesSection>(this, 0, size);
  701. deactivateObj(commanderBonusesSection);
  702. commanderTab = std::make_shared<CTabbedInt>(onCreate, Point(0, pos.h), 0);
  703. pos.h += commanderMainSection->pos.h;
  704. }
  705. if(!info->commander && !activeBonuses.empty())
  706. {
  707. bonusesSection = std::make_shared<BonusesSection>(this, pos.h);
  708. pos.h += bonusesSection->pos.h;
  709. }
  710. if(!info->popupWindow)
  711. {
  712. buttonsSection = std::make_shared<ButtonsSection>(this, pos.h);
  713. pos.h += buttonsSection->pos.h;
  714. //FIXME: add status bar to image?
  715. }
  716. updateShadow();
  717. pos = center(pos);
  718. }
  719. std::string CStackWindow::generateStackExpDescription()
  720. {
  721. const CStackInstance * stack = info->stackNode;
  722. const CCreature * creature = info->creature;
  723. int tier = stack->type->getLevel();
  724. int rank = stack->getExpRank();
  725. if (!vstd::iswithin(tier, 1, 7))
  726. tier = 0;
  727. int number;
  728. std::string expText = CGI->generaltexth->translate("vcmi.stackExperience.description");
  729. boost::replace_first(expText, "%s", creature->getNamePluralTranslated());
  730. boost::replace_first(expText, "%s", CGI->generaltexth->translate("vcmi.stackExperience.rank", rank));
  731. boost::replace_first(expText, "%i", std::to_string(rank));
  732. boost::replace_first(expText, "%i", std::to_string(stack->experience));
  733. number = static_cast<int>(CGI->creh->expRanks[tier][rank] - stack->experience);
  734. boost::replace_first(expText, "%i", std::to_string(number));
  735. number = CGI->creh->maxExpPerBattle[tier]; //percent
  736. boost::replace_first(expText, "%i%", std::to_string(number));
  737. number *= CGI->creh->expRanks[tier].back() / 100; //actual amount
  738. boost::replace_first(expText, "%i", std::to_string(number));
  739. boost::replace_first(expText, "%i", std::to_string(stack->count)); //Number of Creatures in stack
  740. int expmin = std::max(CGI->creh->expRanks[tier][std::max(rank-1, 0)], (ui32)1);
  741. number = static_cast<int>((stack->count * (stack->experience - expmin)) / expmin); //Maximum New Recruits without losing current Rank
  742. boost::replace_first(expText, "%i", std::to_string(number)); //TODO
  743. boost::replace_first(expText, "%.2f", std::to_string(1)); //TODO Experience Multiplier
  744. number = CGI->creh->expAfterUpgrade;
  745. boost::replace_first(expText, "%.2f", std::to_string(number) + "%"); //Upgrade Multiplier
  746. expmin = CGI->creh->expRanks[tier][9];
  747. int expmax = CGI->creh->expRanks[tier][10];
  748. number = expmax - expmin;
  749. boost::replace_first(expText, "%i", std::to_string(number)); //Experience after Rank 10
  750. number = (stack->count * (expmax - expmin)) / expmin;
  751. boost::replace_first(expText, "%i", std::to_string(number)); //Maximum New Recruits to remain at Rank 10 if at Maximum Experience
  752. return expText;
  753. }
  754. void CStackWindow::setSelection(si32 newSkill, std::shared_ptr<CCommanderSkillIcon> newIcon)
  755. {
  756. auto getSkillDescription = [this](int skillIndex, bool selected) -> std::string
  757. {
  758. if(selected)
  759. return CGI->generaltexth->znpc00[152 + (12 * skillIndex) + ((info->commander->secondarySkills[skillIndex] + 1) * 2)]; //upgrade description
  760. else
  761. return CGI->generaltexth->znpc00[152 + (12 * skillIndex) + (info->commander->secondarySkills[skillIndex] * 2)];
  762. };
  763. auto getSkillImage = [this](int skillIndex)
  764. {
  765. bool selected = ((selectedSkill == skillIndex) && info->levelupInfo );
  766. return skillToFile(skillIndex, info->commander->secondarySkills[skillIndex], selected);
  767. };
  768. OBJECT_CONSTRUCTION_CUSTOM_CAPTURING(255-DISPOSE);
  769. int oldSelection = selectedSkill; // update selection
  770. selectedSkill = newSkill;
  771. if(selectedIcon && oldSelection < 100) // recreate image on old selection, only for skills
  772. selectedIcon->setObject(std::make_shared<CPicture>(getSkillImage(oldSelection)));
  773. if(selectedIcon)
  774. {
  775. if(!selectedIcon->getIsMasterAbility()) //unlike WoG, in VCMI master skill descriptions are taken from bonus descriptions
  776. {
  777. selectedIcon->text = getSkillDescription(oldSelection, false); //update previously selected icon's message to existing skill level
  778. }
  779. selectedIcon->deselect();
  780. }
  781. selectedIcon = newIcon; // update new selection
  782. if(newSkill < 100)
  783. {
  784. newIcon->setObject(std::make_shared<CPicture>(getSkillImage(newSkill)));
  785. if(!newIcon->getIsMasterAbility())
  786. {
  787. newIcon->text = getSkillDescription(newSkill, true); //update currently selected icon's message to show upgrade description
  788. }
  789. }
  790. }
  791. std::shared_ptr<CIntObject> CStackWindow::switchTab(size_t index)
  792. {
  793. std::shared_ptr<CIntObject> ret;
  794. switch(index)
  795. {
  796. case 0:
  797. {
  798. activeTab = 0;
  799. ret = commanderMainSection;
  800. }
  801. break;
  802. case 1:
  803. {
  804. activeTab = 1;
  805. ret = commanderBonusesSection;
  806. }
  807. break;
  808. default:
  809. break;
  810. }
  811. return ret;
  812. }
  813. void CStackWindow::removeStackArtifact(ArtifactPosition pos)
  814. {
  815. auto art = info->stackNode->getArt(ArtifactPosition::CREATURE_SLOT);
  816. if(!art)
  817. {
  818. logGlobal->error("Attempt to remove missing artifact");
  819. return;
  820. }
  821. const auto slot = ArtifactUtils::getArtBackpackPosition(info->owner, art->getTypeId());
  822. if(slot != ArtifactPosition::PRE_FIRST)
  823. {
  824. LOCPLINT->cb->swapArtifacts(ArtifactLocation(info->stackNode, pos), ArtifactLocation(info->owner, slot));
  825. stackArtifactButton.reset();
  826. stackArtifactHelp.reset();
  827. stackArtifactIcon.reset();
  828. redraw();
  829. }
  830. }