CCreatureWindow.cpp 33 KB

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