CCreatureWindow.cpp 33 KB

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