CCreatureWindow.cpp 34 KB

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