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