GUIClasses.cpp 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798
  1. /*
  2. * GUIClasses.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 "GUIClasses.h"
  12. #include "CCastleInterface.h"
  13. #include "CCreatureWindow.h"
  14. #include "CHeroWindow.h"
  15. #include "InfoWindows.h"
  16. #include "../CServerHandler.h"
  17. #include "../Client.h"
  18. #include "../CPlayerInterface.h"
  19. #include "../GameEngine.h"
  20. #include "../GameInstance.h"
  21. #include "../gui/CursorHandler.h"
  22. #include "../gui/Shortcut.h"
  23. #include "../gui/WindowHandler.h"
  24. #include "../widgets/CComponent.h"
  25. #include "../widgets/CGarrisonInt.h"
  26. #include "../widgets/CreatureCostBox.h"
  27. #include "../widgets/CTextInput.h"
  28. #include "../widgets/Buttons.h"
  29. #include "../widgets/Slider.h"
  30. #include "../widgets/TextControls.h"
  31. #include "../widgets/ObjectLists.h"
  32. #include "../widgets/VideoWidget.h"
  33. #include "../widgets/GraphicalPrimitiveCanvas.h"
  34. #include "../render/Canvas.h"
  35. #include "../render/IRenderHandler.h"
  36. #include "../render/IImage.h"
  37. #include "../render/IFont.h"
  38. #include "../../CCallback.h"
  39. #include "../lib/entities/building/CBuilding.h"
  40. #include "../lib/entities/faction/CTownHandler.h"
  41. #include "../lib/entities/hero/CHeroHandler.h"
  42. #include "../lib/mapObjectConstructors/CObjectClassesHandler.h"
  43. #include "../lib/mapObjectConstructors/CommonConstructors.h"
  44. #include "../lib/mapObjects/CGHeroInstance.h"
  45. #include "../lib/mapObjects/CGMarket.h"
  46. #include "../lib/mapObjects/CGTownInstance.h"
  47. #include "../lib/gameState/CGameState.h"
  48. #include "../lib/gameState/SThievesGuildInfo.h"
  49. #include "../lib/gameState/TavernHeroesPool.h"
  50. #include "../lib/gameState/UpgradeInfo.h"
  51. #include "../lib/texts/CGeneralTextHandler.h"
  52. #include "../lib/texts/TextOperations.h"
  53. #include "../lib/IGameSettings.h"
  54. #include "../lib/ConditionalWait.h"
  55. #include "../lib/CConfigHandler.h"
  56. #include "../lib/CRandomGenerator.h"
  57. #include "../lib/CSkillHandler.h"
  58. #include "../lib/CSoundBase.h"
  59. #include <boost/lexical_cast.hpp>
  60. CRecruitmentWindow::CCreatureCard::CCreatureCard(CRecruitmentWindow * window, const CCreature * crea, int totalAmount)
  61. : CIntObject(LCLICK | SHOW_POPUP),
  62. parent(window),
  63. selected(false),
  64. creature(crea),
  65. amount(totalAmount)
  66. {
  67. OBJECT_CONSTRUCTION;
  68. animation = std::make_shared<CCreaturePic>(1, 1, creature, true, true);
  69. // 1 + 1 px for borders
  70. pos.w = animation->pos.w + 2;
  71. pos.h = animation->pos.h + 2;
  72. }
  73. void CRecruitmentWindow::CCreatureCard::select(bool on)
  74. {
  75. selected = on;
  76. redraw();
  77. }
  78. void CRecruitmentWindow::CCreatureCard::clickPressed(const Point & cursorPosition)
  79. {
  80. parent->select(this->shared_from_this());
  81. }
  82. void CRecruitmentWindow::CCreatureCard::showPopupWindow(const Point & cursorPosition)
  83. {
  84. ENGINE->windows().createAndPushWindow<CStackWindow>(creature, true);
  85. }
  86. void CRecruitmentWindow::CCreatureCard::showAll(Canvas & to)
  87. {
  88. CIntObject::showAll(to);
  89. if(selected)
  90. to.drawBorder(pos, Colors::RED);
  91. else
  92. to.drawBorder(pos, Colors::YELLOW);
  93. }
  94. void CRecruitmentWindow::select(std::shared_ptr<CCreatureCard> card)
  95. {
  96. if(card == selected)
  97. return;
  98. if(selected)
  99. selected->select(false);
  100. selected = card;
  101. if(selected)
  102. selected->select(true);
  103. if(card)
  104. {
  105. si32 maxAmount = card->creature->maxAmount(GAME->interface()->cb->getResourceAmount());
  106. vstd::amin(maxAmount, card->amount);
  107. slider->setAmount(maxAmount);
  108. if(slider->getValue() != maxAmount)
  109. slider->scrollTo(maxAmount);
  110. else // if slider already at 0 - emulate call to sliderMoved()
  111. sliderMoved(maxAmount);
  112. costPerTroopValue->createItems(card->creature->getFullRecruitCost());
  113. totalCostValue->createItems(card->creature->getFullRecruitCost());
  114. costPerTroopValue->set(card->creature->getFullRecruitCost());
  115. totalCostValue->set(card->creature->getFullRecruitCost() * maxAmount);
  116. //Recruit %s
  117. title->setText(boost::str(boost::format(LIBRARY->generaltexth->tcommands[21]) % card->creature->getNamePluralTranslated()));
  118. maxButton->block(maxAmount == 0);
  119. slider->block(maxAmount == 0);
  120. }
  121. }
  122. void CRecruitmentWindow::close()
  123. {
  124. if (onClose)
  125. onClose();
  126. CStatusbarWindow::close();
  127. }
  128. void CRecruitmentWindow::buy()
  129. {
  130. CreatureID crid = selected->creature->getId();
  131. SlotID dstslot = dst->getSlotFor(crid);
  132. if(!dstslot.validSlot() && (selected->creature->warMachine == ArtifactID::NONE)) //no available slot
  133. {
  134. std::pair<SlotID, SlotID> toMerge;
  135. bool allowMerge = GAME->interface()->cb->getSettings().getBoolean(EGameSettings::DWELLINGS_ACCUMULATE_WHEN_OWNED);
  136. if (allowMerge && dst->mergeableStacks(toMerge))
  137. {
  138. GAME->interface()->cb->mergeStacks( dst, dst, toMerge.first, toMerge.second);
  139. }
  140. else
  141. {
  142. std::string txt;
  143. if(dwelling->ID != Obj::TOWN)
  144. {
  145. txt = LIBRARY->generaltexth->allTexts[425]; //The %s would join your hero, but there aren't enough provisions to support them.
  146. boost::algorithm::replace_first(txt, "%s", slider->getValue() > 1 ? LIBRARY->creh->objects[crid]->getNamePluralTranslated() : LIBRARY->creh->objects[crid]->getNameSingularTranslated());
  147. }
  148. else
  149. {
  150. txt = LIBRARY->generaltexth->allTexts[17]; //There is no room in the garrison for this army.
  151. }
  152. GAME->interface()->showInfoDialog(txt);
  153. return;
  154. }
  155. }
  156. onRecruit(crid, slider->getValue());
  157. if(level >= 0)
  158. close();
  159. }
  160. void CRecruitmentWindow::showAll(Canvas & to)
  161. {
  162. CWindowObject::showAll(to);
  163. Rect(172, 222, 67, 42) + pos.topLeft();
  164. // recruit\total values
  165. to.drawBorder(Rect(172, 222, 67, 42) + pos.topLeft(), Colors::YELLOW);
  166. to.drawBorder(Rect(246, 222, 67, 42) + pos.topLeft(), Colors::YELLOW);
  167. //cost boxes
  168. to.drawBorder(Rect( 64, 222, 99, 76) + pos.topLeft(), Colors::YELLOW);
  169. to.drawBorder(Rect(322, 222, 99, 76) + pos.topLeft(), Colors::YELLOW);
  170. //buttons borders
  171. to.drawBorder(Rect(133, 312, 66, 34) + pos.topLeft(), Colors::METALLIC_GOLD);
  172. to.drawBorder(Rect(211, 312, 66, 34) + pos.topLeft(), Colors::METALLIC_GOLD);
  173. to.drawBorder(Rect(289, 312, 66, 34) + pos.topLeft(), Colors::METALLIC_GOLD);
  174. }
  175. CRecruitmentWindow::CRecruitmentWindow(const CGDwelling * Dwelling, int Level, const CArmedInstance * Dst, const std::function<void(CreatureID,int)> & Recruit, const std::function<void()> & onClose, int y_offset):
  176. CWindowObject(PLAYER_COLORED, ImagePath::builtin("TPRCRT")),
  177. onRecruit(Recruit),
  178. onClose(onClose),
  179. level(Level),
  180. dst(Dst),
  181. selected(nullptr),
  182. dwelling(Dwelling)
  183. {
  184. moveBy(Point(0, y_offset));
  185. OBJECT_CONSTRUCTION;
  186. statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
  187. slider = std::make_shared<CSlider>(Point(176, 279), 135, std::bind(&CRecruitmentWindow::sliderMoved, this, _1), 0, 0, 0, Orientation::HORIZONTAL);
  188. maxButton = std::make_shared<CButton>(Point(134, 313), AnimationPath::builtin("IRCBTNS.DEF"), LIBRARY->generaltexth->zelp[553], std::bind(&CSlider::scrollToMax, slider), EShortcut::RECRUITMENT_MAX);
  189. buyButton = std::make_shared<CButton>(Point(212, 313), AnimationPath::builtin("IBY6432.DEF"), LIBRARY->generaltexth->zelp[554], std::bind(&CRecruitmentWindow::buy, this), EShortcut::GLOBAL_ACCEPT);
  190. cancelButton = std::make_shared<CButton>(Point(290, 313), AnimationPath::builtin("ICN6432.DEF"), LIBRARY->generaltexth->zelp[555], std::bind(&CRecruitmentWindow::close, this), EShortcut::GLOBAL_CANCEL);
  191. title = std::make_shared<CLabel>(243, 32, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW);
  192. availableValue = std::make_shared<CLabel>(205, 253, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  193. toRecruitValue = std::make_shared<CLabel>(279, 253, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  194. costPerTroopValue = std::make_shared<CreatureCostBox>(Rect(65, 222, 97, 74), LIBRARY->generaltexth->allTexts[346]);
  195. totalCostValue = std::make_shared<CreatureCostBox>(Rect(323, 222, 97, 74), LIBRARY->generaltexth->allTexts[466]);
  196. availableTitle = std::make_shared<CLabel>(205, 233, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, LIBRARY->generaltexth->allTexts[465]);
  197. toRecruitTitle = std::make_shared<CLabel>(279, 233, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, LIBRARY->generaltexth->allTexts[16]);
  198. availableCreaturesChanged();
  199. }
  200. void CRecruitmentWindow::availableCreaturesChanged()
  201. {
  202. OBJECT_CONSTRUCTION;
  203. size_t selectedIndex = 0;
  204. if(!cards.empty() && selected) // find position of selected item
  205. selectedIndex = std::find(cards.begin(), cards.end(), selected) - cards.begin();
  206. select(nullptr);
  207. cards.clear();
  208. for(int i=0; i<dwelling->creatures.size(); i++)
  209. {
  210. //find appropriate level
  211. if(level >= 0 && i != level)
  212. continue;
  213. int amount = dwelling->creatures[i].first;
  214. //create new cards
  215. for(auto & creature : boost::adaptors::reverse(dwelling->creatures[i].second))
  216. cards.push_back(std::make_shared<CCreatureCard>(this, creature.toCreature(), amount));
  217. }
  218. const int creatureWidth = 102;
  219. //normal distance between cards - 18px
  220. int requiredSpace = 18;
  221. //maximum distance we can use without reaching window borders
  222. int availableSpace = pos.w - 50 - creatureWidth * (int)cards.size();
  223. if (cards.size() > 1) // avoid division by zero
  224. availableSpace /= (int)cards.size() - 1;
  225. else
  226. availableSpace = 0;
  227. assert(availableSpace >= 0);
  228. const int spaceBetween = std::min(requiredSpace, availableSpace);
  229. const int totalCreatureWidth = spaceBetween + creatureWidth;
  230. //now we know total amount of cards and can move them to correct position
  231. int curx = pos.w / 2 - (creatureWidth*(int)cards.size()/2) - (spaceBetween*((int)cards.size()-1)/2);
  232. for(auto & card : cards)
  233. {
  234. card->moveBy(Point(curx, 64));
  235. curx += totalCreatureWidth;
  236. }
  237. //restore selection
  238. select(cards[selectedIndex]);
  239. if(slider->getValue() == slider->getAmount())
  240. slider->scrollToMax();
  241. else // if slider already at 0 - emulate call to sliderMoved()
  242. sliderMoved(slider->getAmount());
  243. }
  244. void CRecruitmentWindow::sliderMoved(int to)
  245. {
  246. if(!selected)
  247. return;
  248. buyButton->block(!to || !GAME->interface()->makingTurn);
  249. availableValue->setText(std::to_string(selected->amount - to));
  250. toRecruitValue->setText(std::to_string(to));
  251. totalCostValue->set(selected->creature->getFullRecruitCost() * to);
  252. }
  253. CSplitWindow::CSplitWindow(const CCreature * creature, std::function<void(int, int)> callback_, int leftMin_, int rightMin_, int leftAmount_, int rightAmount_)
  254. : CWindowObject(PLAYER_COLORED, ImagePath::builtin("GPUCRDIV")),
  255. callback(callback_),
  256. leftAmount(leftAmount_),
  257. rightAmount(rightAmount_),
  258. leftMin(leftMin_),
  259. rightMin(rightMin_)
  260. {
  261. OBJECT_CONSTRUCTION;
  262. int total = leftAmount + rightAmount;
  263. int leftMax = total - rightMin;
  264. int rightMax = total - leftMin;
  265. ok = std::make_shared<CButton>(Point(20, 263), AnimationPath::builtin("IOK6432"), CButton::tooltip(), std::bind(&CSplitWindow::apply, this), EShortcut::GLOBAL_ACCEPT);
  266. cancel = std::make_shared<CButton>(Point(214, 263), AnimationPath::builtin("ICN6432"), CButton::tooltip(), std::bind(&CSplitWindow::close, this), EShortcut::GLOBAL_CANCEL);
  267. int sliderPosition = total - leftMin - rightMin;
  268. leftInput = std::make_shared<CTextInput>(Rect(20, 218, 100, 36), FONT_BIG, ETextAlignment::CENTER, true);
  269. rightInput = std::make_shared<CTextInput>(Rect(176, 218, 100, 36), FONT_BIG, ETextAlignment::CENTER, true);
  270. leftInput->setCallback(std::bind(&CSplitWindow::setAmountText, this, _1, true));
  271. rightInput->setCallback(std::bind(&CSplitWindow::setAmountText, this, _1, false));
  272. //add filters to allow only number input
  273. leftInput->setFilterNumber(leftMin, leftMax);
  274. rightInput->setFilterNumber(rightMin, rightMax);
  275. leftInput->setText(std::to_string(leftAmount));
  276. rightInput->setText(std::to_string(rightAmount));
  277. animLeft = std::make_shared<CCreaturePic>(20, 54, creature, true, false);
  278. animRight = std::make_shared<CCreaturePic>(177, 54,creature, true, false);
  279. slider = std::make_shared<CSlider>(Point(21, 194), 257, std::bind(&CSplitWindow::sliderMoved, this, _1), 0, sliderPosition, rightAmount - rightMin, Orientation::HORIZONTAL);
  280. std::string titleStr = LIBRARY->generaltexth->allTexts[256];
  281. boost::algorithm::replace_first(titleStr,"%s", creature->getNamePluralTranslated());
  282. title = std::make_shared<CLabel>(150, 34, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, titleStr);
  283. }
  284. void CSplitWindow::setAmountText(std::string text, bool left)
  285. {
  286. int amount = 0;
  287. if(text.length())
  288. {
  289. try
  290. {
  291. amount = boost::lexical_cast<int>(text);
  292. }
  293. catch(boost::bad_lexical_cast &)
  294. {
  295. amount = left ? leftAmount : rightAmount;
  296. }
  297. int total = leftAmount + rightAmount;
  298. if(amount > total)
  299. amount = total;
  300. }
  301. setAmount(amount, left);
  302. slider->scrollTo(rightAmount - rightMin);
  303. }
  304. void CSplitWindow::setAmount(int value, bool left)
  305. {
  306. int total = leftAmount + rightAmount;
  307. leftAmount = left ? value : total - value;
  308. rightAmount = left ? total - value : value;
  309. leftInput->setText(std::to_string(leftAmount));
  310. rightInput->setText(std::to_string(rightAmount));
  311. }
  312. void CSplitWindow::apply()
  313. {
  314. callback(leftAmount, rightAmount);
  315. close();
  316. }
  317. void CSplitWindow::sliderMoved(int to)
  318. {
  319. setAmount(rightMin + to, false);
  320. }
  321. CLevelWindow::CLevelWindow(const CGHeroInstance * hero, PrimarySkill pskill, std::vector<SecondarySkill> & skills, std::function<void(ui32)> callback)
  322. : CWindowObject(PLAYER_COLORED, ImagePath::builtin("LVLUPBKG")),
  323. cb(callback)
  324. {
  325. OBJECT_CONSTRUCTION;
  326. GAME->interface()->showingDialog->setBusy();
  327. if(!skills.empty())
  328. {
  329. std::vector<std::shared_ptr<CSelectableComponent>> comps;
  330. for(auto & skill : skills)
  331. {
  332. auto comp = std::make_shared<CSelectableComponent>(ComponentType::SEC_SKILL, skill, hero->getSecSkillLevel(SecondarySkill(skill))+1, CComponent::medium);
  333. comp->onChoose = std::bind(&CLevelWindow::close, this);
  334. comps.push_back(comp);
  335. }
  336. box = std::make_shared<CComponentBox>(comps, Rect(75, 300, pos.w - 150, 100));
  337. }
  338. portrait = std::make_shared<CHeroArea>(170, 66, hero);
  339. portrait->addClickCallback(nullptr);
  340. portrait->addRClickCallback([hero](){ ENGINE->windows().createAndPushWindow<CRClickPopupInt>(std::make_shared<CHeroWindow>(hero)); });
  341. ok = std::make_shared<CButton>(Point(297, 413), AnimationPath::builtin("IOKAY"), CButton::tooltip(), std::bind(&CLevelWindow::close, this), EShortcut::GLOBAL_ACCEPT);
  342. //%s has gained a level.
  343. mainTitle = std::make_shared<CLabel>(192, 33, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, boost::str(boost::format(LIBRARY->generaltexth->allTexts[444]) % hero->getNameTranslated()));
  344. //%s is now a level %d %s.
  345. std::string levelTitleText = LIBRARY->generaltexth->translate("core.genrltxt.445");
  346. boost::replace_first(levelTitleText, "%s", hero->getNameTranslated());
  347. boost::replace_first(levelTitleText, "%d", std::to_string(hero->level));
  348. boost::replace_first(levelTitleText, "%s", hero->getClassNameTranslated());
  349. levelTitle = std::make_shared<CLabel>(192, 162, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, levelTitleText);
  350. skillIcon = std::make_shared<CAnimImage>(AnimationPath::builtin("PSKIL42"), static_cast<int>(pskill), 0, 174, 190);
  351. skillValue = std::make_shared<CLabel>(192, 253, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, LIBRARY->generaltexth->primarySkillNames[static_cast<int>(pskill)] + " +1");
  352. }
  353. void CLevelWindow::close()
  354. {
  355. //FIXME: call callback if there was nothing to select?
  356. if (box && box->selectedIndex() != -1)
  357. cb(box->selectedIndex());
  358. GAME->interface()->showingDialog->setFree();
  359. CWindowObject::close();
  360. }
  361. CTavernWindow::CTavernWindow(const CGObjectInstance * TavernObj, const std::function<void()> & onWindowClosed)
  362. : CWindowObject(PLAYER_COLORED, ImagePath::builtin("TPTAVERN")),
  363. onWindowClosed(onWindowClosed),
  364. tavernObj(TavernObj),
  365. heroToInvite(nullptr)
  366. {
  367. OBJECT_CONSTRUCTION;
  368. std::vector<const CGHeroInstance*> h = GAME->interface()->cb->getAvailableHeroes(TavernObj);
  369. if(h.size() < 2)
  370. h.resize(2, nullptr);
  371. selected = 0;
  372. if(!h[0])
  373. selected = 1;
  374. if(!h[0] && !h[1])
  375. selected = -1;
  376. oldSelected = -1;
  377. h1 = std::make_shared<HeroPortrait>(selected, 0, 72, 299, h[0], [this]() { if(!recruit->isBlocked()) recruitb(); });
  378. h2 = std::make_shared<HeroPortrait>(selected, 1, 162, 299, h[1], [this]() { if(!recruit->isBlocked()) recruitb(); });
  379. title = std::make_shared<CLabel>(197, 32, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, LIBRARY->generaltexth->jktexts[37]);
  380. cost = std::make_shared<CLabel>(320, 328, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, std::to_string(GameConstants::HERO_GOLD_COST));
  381. heroDescription = std::make_shared<CTextBox>("", Rect(30, 373, 233, 35), 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  382. heroesForHire = std::make_shared<CLabel>(145, 283, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, LIBRARY->generaltexth->jktexts[38]);
  383. rumor = std::make_shared<CTextBox>(GAME->interface()->cb->getTavernRumor(tavernObj), Rect(32, 188, 330, 66), 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  384. statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
  385. cancel = std::make_shared<CButton>(Point(310, 428), AnimationPath::builtin("ICANCEL.DEF"), CButton::tooltip(LIBRARY->generaltexth->tavernInfo[7]), std::bind(&CTavernWindow::close, this), EShortcut::GLOBAL_CANCEL);
  386. recruit = std::make_shared<CButton>(Point(272, 355), AnimationPath::builtin("TPTAV01.DEF"), CButton::tooltip(), std::bind(&CTavernWindow::recruitb, this), EShortcut::GLOBAL_ACCEPT);
  387. thiefGuild = std::make_shared<CButton>(Point(22, 428), AnimationPath::builtin("TPTAV02.DEF"), CButton::tooltip(LIBRARY->generaltexth->tavernInfo[5]), std::bind(&CTavernWindow::thievesguildb, this), EShortcut::ADVENTURE_THIEVES_GUILD);
  388. if(!GAME->interface()->makingTurn)
  389. {
  390. recruit->block(true);
  391. }
  392. else if(GAME->interface()->cb->getResourceAmount(EGameResID::GOLD) < GameConstants::HERO_GOLD_COST) //not enough gold
  393. {
  394. recruit->addHoverText(EButtonState::NORMAL, LIBRARY->generaltexth->tavernInfo[0]); //Cannot afford a Hero
  395. recruit->block(true);
  396. }
  397. else if(GAME->interface()->cb->howManyHeroes(true) >= GAME->interface()->cb->getSettings().getInteger(EGameSettings::HEROES_PER_PLAYER_TOTAL_CAP))
  398. {
  399. MetaString message;
  400. message.appendTextID("core.tvrninfo.1");
  401. message.replaceNumber(GAME->interface()->cb->howManyHeroes(true));
  402. //Cannot recruit. You already have %d Heroes.
  403. recruit->addHoverText(EButtonState::NORMAL, message.toString());
  404. recruit->block(true);
  405. }
  406. else if(GAME->interface()->cb->howManyHeroes(false) >= GAME->interface()->cb->getSettings().getInteger(EGameSettings::HEROES_PER_PLAYER_ON_MAP_CAP))
  407. {
  408. MetaString message;
  409. message.appendTextID("core.tvrninfo.1");
  410. message.replaceNumber(GAME->interface()->cb->howManyHeroes(false));
  411. recruit->addHoverText(EButtonState::NORMAL, message.toString());
  412. recruit->block(true);
  413. }
  414. else if(dynamic_cast<const CGTownInstance *>(TavernObj) && dynamic_cast<const CGTownInstance *>(TavernObj)->getVisitingHero())
  415. {
  416. recruit->addHoverText(EButtonState::NORMAL, LIBRARY->generaltexth->tavernInfo[2]); //Cannot recruit. You already have a Hero in this town.
  417. recruit->block(true);
  418. }
  419. else
  420. {
  421. if(selected == -1)
  422. recruit->block(true);
  423. }
  424. if(GAME->interface()->castleInt)
  425. videoPlayer = std::make_shared<VideoWidget>(Point(70, 56), GAME->interface()->castleInt->town->getTown()->clientInfo.tavernVideo, false);
  426. else if(const auto * townObj = dynamic_cast<const CGTownInstance *>(TavernObj))
  427. videoPlayer = std::make_shared<VideoWidget>(Point(70, 56), townObj->getTown()->clientInfo.tavernVideo, false);
  428. else
  429. videoPlayer = std::make_shared<VideoWidget>(Point(70, 56), VideoPath::builtin("TAVERN.BIK"), false);
  430. addInvite();
  431. }
  432. void CTavernWindow::addInvite()
  433. {
  434. OBJECT_CONSTRUCTION;
  435. if(!GAME->interface()->cb->getSettings().getBoolean(EGameSettings::HEROES_TAVERN_INVITE))
  436. return;
  437. const auto & heroesPool = GAME->server().client->gameState()->heroesPool;
  438. for(auto & elem : heroesPool->unusedHeroesFromPool())
  439. {
  440. bool heroAvailable = heroesPool->isHeroAvailableFor(elem.first, tavernObj->getOwner());
  441. if(heroAvailable)
  442. inviteableHeroes[elem.first] = elem.second;
  443. }
  444. if(!inviteableHeroes.empty())
  445. {
  446. int imageIndex = heroToInvite ? heroToInvite->getIconIndex() : 156; // 156 => special id for random
  447. if(!heroToInvite)
  448. heroToInvite = (*RandomGeneratorUtil::nextItem(inviteableHeroes, CRandomGenerator::getDefault())).second;
  449. inviteHero = std::make_shared<CLabel>(170, 444, EFonts::FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, LIBRARY->generaltexth->translate("vcmi.tavernWindow.inviteHero"));
  450. inviteHeroImage = std::make_shared<CAnimImage>(AnimationPath::builtin("PortraitsSmall"), imageIndex, 0, 245, 428);
  451. inviteHeroImageArea = std::make_shared<LRClickableArea>(Rect(245, 428, 48, 32), [this](){ ENGINE->windows().createAndPushWindow<HeroSelector>(inviteableHeroes, [this](CGHeroInstance* h){ heroToInvite = h; addInvite(); }); }, [this](){ ENGINE->windows().createAndPushWindow<CRClickPopupInt>(std::make_shared<CHeroWindow>(heroToInvite)); });
  452. }
  453. }
  454. void CTavernWindow::recruitb()
  455. {
  456. const CGHeroInstance *toBuy = (selected ? h2 : h1)->h;
  457. const CGObjectInstance *obj = tavernObj;
  458. GAME->interface()->cb->recruitHero(obj, toBuy, heroToInvite ? heroToInvite->getHeroTypeID() : HeroTypeID::NONE);
  459. close();
  460. }
  461. void CTavernWindow::thievesguildb()
  462. {
  463. ENGINE->windows().createAndPushWindow<CThievesGuildWindow>(tavernObj);
  464. }
  465. void CTavernWindow::close()
  466. {
  467. if (onWindowClosed)
  468. onWindowClosed();
  469. CStatusbarWindow::close();
  470. }
  471. void CTavernWindow::show(Canvas & to)
  472. {
  473. CWindowObject::show(to);
  474. if(selected >= 0)
  475. {
  476. auto sel = selected ? h2 : h1;
  477. if(selected != oldSelected)
  478. {
  479. // Selected hero just changed. Update RECRUIT button hover text if recruitment is allowed.
  480. oldSelected = selected;
  481. heroDescription->setText(sel->description);
  482. //Recruit %s the %s
  483. if (!recruit->isBlocked())
  484. recruit->addHoverText(EButtonState::NORMAL, boost::str(boost::format(LIBRARY->generaltexth->tavernInfo[3]) % sel->h->getNameTranslated() % sel->h->getClassNameTranslated()));
  485. }
  486. to.drawBorder(Rect::createAround(sel->pos, 2), Colors::BRIGHT_YELLOW, 2);
  487. }
  488. }
  489. void CTavernWindow::HeroPortrait::clickPressed(const Point & cursorPosition)
  490. {
  491. if(h)
  492. *_sel = _id;
  493. }
  494. void CTavernWindow::HeroPortrait::clickDouble(const Point & cursorPosition)
  495. {
  496. clickPressed(cursorPosition);
  497. if(onChoose)
  498. onChoose();
  499. }
  500. void CTavernWindow::HeroPortrait::showPopupWindow(const Point & cursorPosition)
  501. {
  502. // h3 behavior - right-click also selects hero
  503. clickPressed(cursorPosition);
  504. if(h)
  505. ENGINE->windows().createAndPushWindow<CRClickPopupInt>(std::make_shared<CHeroWindow>(h));
  506. }
  507. CTavernWindow::HeroPortrait::HeroPortrait(int & sel, int id, int x, int y, const CGHeroInstance * H, std::function<void()> OnChoose)
  508. : CIntObject(LCLICK | DOUBLECLICK | SHOW_POPUP | HOVER),
  509. h(H), _sel(&sel), _id(id), onChoose(OnChoose)
  510. {
  511. OBJECT_CONSTRUCTION;
  512. h = H;
  513. pos.x += x;
  514. pos.y += y;
  515. pos.w = 58;
  516. pos.h = 64;
  517. if(H)
  518. {
  519. hoverName = LIBRARY->generaltexth->tavernInfo[4];
  520. boost::algorithm::replace_first(hoverName,"%s",H->getNameTranslated());
  521. int artifs = (int)h->artifactsWorn.size() + (int)h->artifactsInBackpack.size();
  522. for(int i=13; i<=17; i++) //war machines and spellbook don't count
  523. if(vstd::contains(h->artifactsWorn, ArtifactPosition(i)))
  524. artifs--;
  525. description = LIBRARY->generaltexth->allTexts[215];
  526. boost::algorithm::replace_first(description, "%s", h->getNameTranslated());
  527. boost::algorithm::replace_first(description, "%d", std::to_string(h->level));
  528. boost::algorithm::replace_first(description, "%s", h->getClassNameTranslated());
  529. boost::algorithm::replace_first(description, "%d", std::to_string(artifs));
  530. portrait = std::make_shared<CAnimImage>(AnimationPath::builtin("portraitsLarge"), h->getIconIndex());
  531. }
  532. }
  533. void CTavernWindow::HeroPortrait::hover(bool on)
  534. {
  535. //Hoverable::hover(on);
  536. if(on)
  537. ENGINE->statusbar()->write(hoverName);
  538. else
  539. ENGINE->statusbar()->clear();
  540. }
  541. CTavernWindow::HeroSelector::HeroSelector(std::map<HeroTypeID, CGHeroInstance*> InviteableHeroes, std::function<void(CGHeroInstance*)> OnChoose)
  542. : CWindowObject(BORDERED), inviteableHeroes(InviteableHeroes), onChoose(OnChoose)
  543. {
  544. OBJECT_CONSTRUCTION;
  545. pos = Rect(
  546. pos.x,
  547. pos.y,
  548. ELEM_PER_LINES * 48,
  549. std::min((int)(inviteableHeroes.size() / ELEM_PER_LINES + (inviteableHeroes.size() % ELEM_PER_LINES != 0)), MAX_LINES) * 32
  550. );
  551. background = std::make_shared<CFilledTexture>(ImagePath::builtin("DIBOXBCK"), Rect(0, 0, pos.w, pos.h));
  552. if(inviteableHeroes.size() / ELEM_PER_LINES > MAX_LINES)
  553. {
  554. pos.w += 16;
  555. slider = std::make_shared<CSlider>(Point(pos.w - 16, 0), pos.h, std::bind(&CTavernWindow::HeroSelector::sliderMove, this, _1), MAX_LINES, std::ceil((double)inviteableHeroes.size() / ELEM_PER_LINES), 0, Orientation::VERTICAL, CSlider::BROWN);
  556. slider->setPanningStep(32);
  557. slider->setScrollBounds(Rect(-pos.w + slider->pos.w, 0, pos.w, pos.h));
  558. }
  559. recreate();
  560. center();
  561. }
  562. void CTavernWindow::HeroSelector::sliderMove(int slidPos)
  563. {
  564. if(!slider)
  565. return; // ignore spurious call when slider is being created
  566. recreate();
  567. redraw();
  568. }
  569. void CTavernWindow::HeroSelector::recreate()
  570. {
  571. OBJECT_CONSTRUCTION;
  572. int sliderLine = slider ? slider->getValue() : 0;
  573. int x = 0;
  574. int y = -sliderLine;
  575. portraits.clear();
  576. portraitAreas.clear();
  577. for(auto & h : inviteableHeroes)
  578. {
  579. if(y >= 0 && y <= MAX_LINES - 1)
  580. {
  581. portraits.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("PortraitsSmall"), (*LIBRARY->heroh)[h.first]->imageIndex, 0, x * 48, y * 32));
  582. portraitAreas.push_back(std::make_shared<LRClickableArea>(Rect(x * 48, y * 32, 48, 32), [this, h](){ close(); onChoose(inviteableHeroes[h.first]); }, [this, h](){ ENGINE->windows().createAndPushWindow<CRClickPopupInt>(std::make_shared<CHeroWindow>(inviteableHeroes[h.first])); }));
  583. }
  584. if(x > 0 && x % 15 == 0)
  585. {
  586. x = 0;
  587. y++;
  588. }
  589. else
  590. x++;
  591. }
  592. }
  593. CShipyardWindow::CShipyardWindow(const TResources & cost, int state, BoatId boatType, const std::function<void()> & onBuy)
  594. : CWindowObject(PLAYER_COLORED, ImagePath::builtin("TPSHIP"))
  595. {
  596. OBJECT_CONSTRUCTION;
  597. bgWater = std::make_shared<CPicture>(ImagePath::builtin("TPSHIPBK"), 100, 69);
  598. auto handler = LIBRARY->objtypeh->getHandlerFor(Obj::BOAT, boatType);
  599. auto boatConstructor = std::dynamic_pointer_cast<const BoatInstanceConstructor>(handler);
  600. assert(boatConstructor);
  601. if (boatConstructor)
  602. {
  603. AnimationPath boatFilename = boatConstructor->getBoatAnimationName();
  604. Point waterCenter = Point(bgWater->pos.x+bgWater->pos.w/2, bgWater->pos.y+bgWater->pos.h/2);
  605. bgShip = std::make_shared<CShowableAnim>(120, 96, boatFilename, CShowableAnim::MAP_OBJECT_MODE, 100, 7);
  606. bgShip->center(waterCenter);
  607. bgWater->needRefresh = true;
  608. }
  609. // Create resource icons and costs.
  610. std::string goldValue = std::to_string(cost[EGameResID::GOLD]);
  611. std::string woodValue = std::to_string(cost[EGameResID::WOOD]);
  612. goldCost = std::make_shared<CLabel>(118, 294, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, goldValue);
  613. woodCost = std::make_shared<CLabel>(212, 294, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, woodValue);
  614. goldPic = std::make_shared<CAnimImage>(AnimationPath::builtin("RESOURCE"), GameResID(EGameResID::GOLD), 0, 100, 244);
  615. woodPic = std::make_shared<CAnimImage>(AnimationPath::builtin("RESOURCE"), GameResID(EGameResID::WOOD), 0, 196, 244);
  616. quit = std::make_shared<CButton>(Point(224, 312), AnimationPath::builtin("ICANCEL"), CButton::tooltip(LIBRARY->generaltexth->allTexts[599]), std::bind(&CShipyardWindow::close, this), EShortcut::GLOBAL_CANCEL);
  617. build = std::make_shared<CButton>(Point(42, 312), AnimationPath::builtin("IBUY30"), CButton::tooltip(LIBRARY->generaltexth->allTexts[598]), std::bind(&CShipyardWindow::close, this), EShortcut::GLOBAL_ACCEPT);
  618. build->addCallback(onBuy);
  619. for(GameResID i = EGameResID::WOOD; i <= EGameResID::GOLD; ++i)
  620. {
  621. if(cost[i] > GAME->interface()->cb->getResourceAmount(i))
  622. {
  623. build->block(true);
  624. break;
  625. }
  626. }
  627. statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
  628. title = std::make_shared<CLabel>(164, 27, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, LIBRARY->generaltexth->jktexts[13]);
  629. costLabel = std::make_shared<CLabel>(164, 220, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, LIBRARY->generaltexth->jktexts[14]);
  630. }
  631. void CTransformerWindow::CItem::move()
  632. {
  633. if(left)
  634. moveBy(Point(289, 0));
  635. else
  636. moveBy(Point(-289, 0));
  637. left = !left;
  638. }
  639. void CTransformerWindow::CItem::clickPressed(const Point & cursorPosition)
  640. {
  641. move();
  642. parent->redraw();
  643. }
  644. void CTransformerWindow::CItem::update()
  645. {
  646. icon->setFrame(parent->army->getCreature(SlotID(id))->getId() + 2);
  647. }
  648. CTransformerWindow::CItem::CItem(CTransformerWindow * parent_, int size_, int id_)
  649. : CIntObject(LCLICK),
  650. id(id_),
  651. size(size_),
  652. parent(parent_)
  653. {
  654. OBJECT_CONSTRUCTION;
  655. left = true;
  656. pos.w = 58;
  657. pos.h = 64;
  658. pos.x += 45 + (id%3)*83 + id/6*83;
  659. pos.y += 109 + (id/3)*98;
  660. icon = std::make_shared<CAnimImage>(AnimationPath::builtin("TWCRPORT"), parent->army->getCreature(SlotID(id))->getId() + 2);
  661. count = std::make_shared<CLabel>(28, 76,FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, std::to_string(size));
  662. }
  663. void CTransformerWindow::makeDeal()
  664. {
  665. for(auto & elem : items)
  666. {
  667. if(!elem->left)
  668. GAME->interface()->cb->trade(market->getObjInstanceID(), EMarketMode::CREATURE_UNDEAD, SlotID(elem->id), {}, {}, hero);
  669. }
  670. }
  671. void CTransformerWindow::addAll()
  672. {
  673. for(auto & elem : items)
  674. {
  675. if(elem->left)
  676. elem->move();
  677. }
  678. redraw();
  679. }
  680. void CTransformerWindow::updateGarrisons()
  681. {
  682. for(auto & item : items)
  683. item->update();
  684. }
  685. bool CTransformerWindow::holdsGarrison(const CArmedInstance * army)
  686. {
  687. return army == hero;
  688. }
  689. CTransformerWindow::CTransformerWindow(const IMarket * _market, const CGHeroInstance * _hero, const std::function<void()> & onWindowClosed)
  690. : CWindowObject(PLAYER_COLORED, ImagePath::builtin("SKTRNBK")),
  691. hero(_hero),
  692. onWindowClosed(onWindowClosed),
  693. market(_market)
  694. {
  695. OBJECT_CONSTRUCTION;
  696. if(hero)
  697. army = hero;
  698. else
  699. army = dynamic_cast<const CArmedInstance *>(market); //for town only
  700. if(army)
  701. {
  702. for(int i = 0; i < GameConstants::ARMY_SIZE; i++)
  703. {
  704. if(army->getCreature(SlotID(i)))
  705. items.push_back(std::make_shared<CItem>(this, army->getStackCount(SlotID(i)), i));
  706. }
  707. }
  708. all = std::make_shared<CButton>(Point(146, 416), AnimationPath::builtin("ALTARMY.DEF"), LIBRARY->generaltexth->zelp[590], [&](){ addAll(); }, EShortcut::RECRUITMENT_UPGRADE_ALL);
  709. convert = std::make_shared<CButton>(Point(269, 416), AnimationPath::builtin("ALTSACR.DEF"), LIBRARY->generaltexth->zelp[591], [&](){ makeDeal(); }, EShortcut::GLOBAL_ACCEPT);
  710. cancel = std::make_shared<CButton>(Point(392, 416), AnimationPath::builtin("ICANCEL.DEF"), LIBRARY->generaltexth->zelp[592], [&](){ close(); },EShortcut::GLOBAL_CANCEL);
  711. statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
  712. titleLeft = std::make_shared<CLabel>(153, 29,FONT_SMALL, ETextAlignment::CENTER, Colors::YELLOW, LIBRARY->generaltexth->allTexts[485]);//holding area
  713. titleRight = std::make_shared<CLabel>(153+295, 29, FONT_SMALL, ETextAlignment::CENTER, Colors::YELLOW, LIBRARY->generaltexth->allTexts[486]);//transformer
  714. helpLeft = std::make_shared<CTextBox>(LIBRARY->generaltexth->allTexts[487], Rect(26, 56, 255, 40), 0, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW);//move creatures to create skeletons
  715. helpRight = std::make_shared<CTextBox>(LIBRARY->generaltexth->allTexts[488], Rect(320, 56, 255, 40), 0, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW);//creatures here will become skeletons
  716. }
  717. void CTransformerWindow::close()
  718. {
  719. if (onWindowClosed)
  720. onWindowClosed();
  721. CStatusbarWindow::close();
  722. }
  723. CUniversityWindow::CItem::CItem(CUniversityWindow * _parent, int _ID, int X, int Y)
  724. : CIntObject(LCLICK | SHOW_POPUP | HOVER),
  725. ID(_ID),
  726. parent(_parent)
  727. {
  728. OBJECT_CONSTRUCTION;
  729. pos.x += X;
  730. pos.y += Y;
  731. skill = std::make_shared<CSecSkillPlace>(Point(), CSecSkillPlace::ImageSize::MEDIUM, _ID, 1);
  732. skill->setClickPressedCallback([this](const CComponentHolder&, const Point& cursorPosition)
  733. {
  734. bool skillKnown = parent->hero->getSecSkillLevel(ID);
  735. bool canLearn = parent->hero->canLearnSkill(ID);
  736. if(!skillKnown && canLearn)
  737. ENGINE->windows().createAndPushWindow<CUnivConfirmWindow>(parent, ID, GAME->interface()->cb->getResourceAmount(EGameResID::GOLD) >= 2000);
  738. });
  739. update();
  740. }
  741. void CUniversityWindow::CItem::update()
  742. {
  743. bool skillKnown = parent->hero->getSecSkillLevel(ID);
  744. bool canLearn = parent->hero->canLearnSkill(ID);
  745. ImagePath image;
  746. if (skillKnown)
  747. image = ImagePath::builtin("UNIVGOLD");
  748. else if (canLearn)
  749. image = ImagePath::builtin("UNIVGREN");
  750. else
  751. image = ImagePath::builtin("UNIVRED");
  752. OBJECT_CONSTRUCTION;
  753. topBar = std::make_shared<CPicture>(image, Point(-28, -22));
  754. bottomBar = std::make_shared<CPicture>(image, Point(-28, 48));
  755. // needs to be on top of background bars
  756. name = std::make_shared<CLabel>(22, -13, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, ID.toEntity(LIBRARY)->getNameTranslated());
  757. level = std::make_shared<CLabel>(22, 57, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, LIBRARY->generaltexth->levels[0]);
  758. }
  759. CUniversityWindow::CUniversityWindow(const CGHeroInstance * _hero, BuildingID building, const IMarket * _market, const std::function<void()> & onWindowClosed)
  760. : CWindowObject(PLAYER_COLORED, ImagePath::builtin("UNIVERS1")),
  761. hero(_hero),
  762. onWindowClosed(onWindowClosed),
  763. market(_market)
  764. {
  765. OBJECT_CONSTRUCTION;
  766. std::string titleStr = LIBRARY->generaltexth->allTexts[602];
  767. std::string speechStr = LIBRARY->generaltexth->allTexts[603];
  768. if(auto town = dynamic_cast<const CGTownInstance *>(_market))
  769. {
  770. auto faction = town->getTown()->faction->getId();
  771. titlePic = std::make_shared<CAnimImage>((*LIBRARY->townh)[faction]->town->clientInfo.buildingsIcons, building);
  772. }
  773. else if(auto uni = dynamic_cast<const CGUniversity *>(_market); uni->appearance)
  774. {
  775. titlePic = std::make_shared<CAnimImage>(uni->appearance->animationFile, 0, 0, 0, 0, CShowableAnim::MAP_OBJECT_MODE);
  776. titleStr = uni->getObjectName();
  777. speechStr = uni->getSpeechTranslated();
  778. }
  779. else
  780. {
  781. titlePic = std::make_shared<CPicture>(ImagePath::builtin("UNIVBLDG"));
  782. }
  783. titlePic->center(Point(232 + pos.x, 76 + pos.y));
  784. clerkSpeech = std::make_shared<CTextBox>(speechStr, Rect(24, 129, 413, 70), 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  785. title = std::make_shared<CLabel>(231, 26, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW, titleStr);
  786. std::vector<TradeItemBuy> goods = market->availableItemsIds(EMarketMode::RESOURCE_SKILL);
  787. for(int i=0; i<goods.size(); i++)//prepare clickable items
  788. items.push_back(std::make_shared<CItem>(this, goods[i].as<SecondarySkill>(), 54+i*104, 234));
  789. cancel = std::make_shared<CButton>(Point(200, 313), AnimationPath::builtin("IOKAY.DEF"), LIBRARY->generaltexth->zelp[632], [&](){ close(); }, EShortcut::GLOBAL_ACCEPT);
  790. statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
  791. }
  792. void CUniversityWindow::close()
  793. {
  794. if (onWindowClosed)
  795. onWindowClosed();
  796. CStatusbarWindow::close();
  797. }
  798. void CUniversityWindow::updateSecondarySkills()
  799. {
  800. for (auto const & item : items)
  801. item->update();
  802. }
  803. void CUniversityWindow::makeDeal(SecondarySkill skill)
  804. {
  805. GAME->interface()->cb->trade(market->getObjInstanceID(), EMarketMode::RESOURCE_SKILL, GameResID(GameResID::GOLD), skill, 1, hero);
  806. }
  807. CUnivConfirmWindow::CUnivConfirmWindow(CUniversityWindow * owner_, SecondarySkill SKILL, bool available)
  808. : CWindowObject(PLAYER_COLORED, ImagePath::builtin("UNIVERS2.PCX")),
  809. owner(owner_)
  810. {
  811. OBJECT_CONSTRUCTION;
  812. std::string text = LIBRARY->generaltexth->allTexts[608];
  813. boost::replace_first(text, "%s", LIBRARY->generaltexth->levels[0]);
  814. boost::replace_first(text, "%s", LIBRARY->skillh->getByIndex(SKILL)->getNameTranslated());
  815. boost::replace_first(text, "%d", "2000");
  816. clerkSpeech = std::make_shared<CTextBox>(text, Rect(24, 129, 413, 70), 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  817. name = std::make_shared<CLabel>(230, 37, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, LIBRARY->skillh->getByIndex(SKILL)->getNameTranslated());
  818. icon = std::make_shared<CAnimImage>(AnimationPath::builtin("SECSKILL"), SKILL*3+3, 0, 211, 51);
  819. level = std::make_shared<CLabel>(230, 107, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, LIBRARY->generaltexth->levels[1]);
  820. costIcon = std::make_shared<CAnimImage>(AnimationPath::builtin("RESOURCE"), GameResID(EGameResID::GOLD), 0, 210, 210);
  821. cost = std::make_shared<CLabel>(230, 267, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, "2000");
  822. std::string hoverText = LIBRARY->generaltexth->allTexts[609];
  823. boost::replace_first(hoverText, "%s", LIBRARY->generaltexth->levels[0]+ " " + LIBRARY->skillh->getByIndex(SKILL)->getNameTranslated());
  824. text = LIBRARY->generaltexth->zelp[633].second;
  825. boost::replace_first(text, "%s", LIBRARY->generaltexth->levels[0]);
  826. boost::replace_first(text, "%s", LIBRARY->skillh->getByIndex(SKILL)->getNameTranslated());
  827. boost::replace_first(text, "%d", "2000");
  828. confirm = std::make_shared<CButton>(Point(148, 299), AnimationPath::builtin("IBY6432.DEF"), CButton::tooltip(hoverText, text), [this, SKILL](){makeDeal(SKILL);}, EShortcut::GLOBAL_ACCEPT);
  829. confirm->block(!available);
  830. cancel = std::make_shared<CButton>(Point(252,299), AnimationPath::builtin("ICANCEL.DEF"), LIBRARY->generaltexth->zelp[631], [&](){ close(); }, EShortcut::GLOBAL_CANCEL);
  831. statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
  832. }
  833. void CUnivConfirmWindow::makeDeal(SecondarySkill skill)
  834. {
  835. owner->makeDeal(skill);
  836. close();
  837. }
  838. CGarrisonWindow::CGarrisonWindow(const CArmedInstance * up, const CGHeroInstance * down, bool removableUnits)
  839. : CWindowObject(PLAYER_COLORED, ImagePath::builtin("GARRISON"))
  840. {
  841. OBJECT_CONSTRUCTION;
  842. garr = std::make_shared<CGarrisonInt>(Point(92, 127), 4, Point(0,96), up, down, removableUnits);
  843. {
  844. auto split = std::make_shared<CButton>(Point(88, 314), AnimationPath::builtin("IDV6432.DEF"), CButton::tooltip(LIBRARY->generaltexth->tcommands[3], ""), [this](){ garr->splitClick(); }, EShortcut::HERO_ARMY_SPLIT );
  845. garr->addSplitBtn(split);
  846. }
  847. quit = std::make_shared<CButton>(Point(399, 314), AnimationPath::builtin("IOK6432.DEF"), CButton::tooltip(LIBRARY->generaltexth->tcommands[8], ""), [this](){ close(); }, EShortcut::GLOBAL_ACCEPT);
  848. std::string titleText;
  849. if(down->tempOwner == up->tempOwner)
  850. {
  851. titleText = LIBRARY->generaltexth->allTexts[709];
  852. }
  853. else
  854. {
  855. //assume that this is joining monsters dialog
  856. if(up->Slots().size() > 0)
  857. {
  858. titleText = LIBRARY->generaltexth->allTexts[35];
  859. boost::algorithm::replace_first(titleText, "%s", up->Slots().begin()->second->getType()->getNamePluralTranslated());
  860. }
  861. else
  862. {
  863. logGlobal->error("Invalid armed instance for garrison window.");
  864. }
  865. }
  866. title = std::make_shared<CLabel>(275, 30, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, titleText);
  867. banner = std::make_shared<CAnimImage>(AnimationPath::builtin("CREST58"), up->getOwner().getNum(), 0, 28, 124);
  868. portrait = std::make_shared<CAnimImage>(AnimationPath::builtin("PortraitsLarge"), down->getIconIndex(), 0, 29, 222);
  869. }
  870. void CGarrisonWindow::updateGarrisons()
  871. {
  872. garr->recreateSlots();
  873. }
  874. bool CGarrisonWindow::holdsGarrison(const CArmedInstance * army)
  875. {
  876. return garr->upperArmy() == army || garr->lowerArmy() == army;
  877. }
  878. CHillFortWindow::CHillFortWindow(const CGHeroInstance * visitor, const CGObjectInstance * object)
  879. : CWindowObject(PLAYER_COLORED, ImagePath::builtin("APHLFTBK")),
  880. fort(object),
  881. hero(visitor)
  882. {
  883. OBJECT_CONSTRUCTION;
  884. title = std::make_shared<CLabel>(325, 32, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, fort->getObjectName());
  885. heroPic = std::make_shared<CHeroArea>(30, 60, hero);
  886. for(int i=0; i < resCount; i++)
  887. {
  888. totalIcons[i] = std::make_shared<CAnimImage>(AnimationPath::builtin("SMALRES"), i, 0, 104 + 76 * i, 237);
  889. totalLabels[i] = std::make_shared<CLabel>(166 + 76 * i, 253, FONT_SMALL, ETextAlignment::BOTTOMRIGHT);
  890. }
  891. for(int i = 0; i < slotsCount; i++)
  892. {
  893. upgrade[i] = std::make_shared<CButton>(Point(107 + i * 76, 171), AnimationPath::builtin("APHLF1R"), CButton::tooltip(getTextForSlot(SlotID(i))), [this, i](){ makeDeal(SlotID(i)); }, vstd::next(EShortcut::SELECT_INDEX_1, i));
  894. for(int j : {0,1})
  895. {
  896. slotIcons[i][j] = std::make_shared<CAnimImage>(AnimationPath::builtin("SMALRES"), 0, 0, 104 + 76 * i, 128 + 20 * j);
  897. slotLabels[i][j] = std::make_shared<CLabel>(168 + 76 * i, 144 + 20 * j, FONT_SMALL, ETextAlignment::BOTTOMRIGHT);
  898. }
  899. }
  900. upgradeAll = std::make_shared<CButton>(Point(30, 231), AnimationPath::builtin("APHLF4R"), CButton::tooltip(LIBRARY->generaltexth->allTexts[432]), [this](){ makeDeal(SlotID(slotsCount));}, EShortcut::RECRUITMENT_UPGRADE_ALL);
  901. quit = std::make_shared<CButton>(Point(294, 275), AnimationPath::builtin("IOKAY.DEF"), CButton::tooltip(), [this](){close();}, EShortcut::GLOBAL_ACCEPT);
  902. statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
  903. garr = std::make_shared<CGarrisonInt>(Point(108, 60), 18, Point(), hero, nullptr);
  904. statusbar->write(LIBRARY->generaltexth->translate(dynamic_cast<const HillFort *>(fort)->getDescriptionToolTip()));
  905. updateGarrisons();
  906. }
  907. bool CHillFortWindow::holdsGarrison(const CArmedInstance * army)
  908. {
  909. return hero == army;
  910. }
  911. void CHillFortWindow::updateGarrisons()
  912. {
  913. constexpr std::array slotImages = { "APHLF1R.DEF", "APHLF1Y.DEF", "APHLF1G.DEF" };
  914. constexpr std::array allImages = { "APHLF4R.DEF", "APHLF4Y.DEF", "APHLF4G.DEF" };
  915. std::array<TResources, slotsCount> costs;// costs [slot ID] [resource ID] = resource count for upgrade
  916. TResources totalSum; // totalSum[resource ID] = value
  917. auto getImgIdx = [](CHillFortWindow::State st) -> std::size_t
  918. {
  919. switch (st)
  920. {
  921. case State::EMPTY:
  922. return 0;
  923. case State::UNAVAILABLE:
  924. case State::ALREADY_UPGRADED:
  925. return 1;
  926. default:
  927. return static_cast<std::size_t>(st);
  928. }
  929. };
  930. for(int i=0; i<slotsCount; i++)
  931. {
  932. std::fill(costs[i].begin(), costs[i].end(), 0);
  933. State newState = getState(SlotID(i));
  934. if(newState != State::EMPTY)
  935. {
  936. if(const CStackInstance * s = hero->getStackPtr(SlotID(i)))
  937. {
  938. UpgradeInfo info(s->getCreature()->getId());
  939. GAME->interface()->cb->fillUpgradeInfo(hero, SlotID(i), info);
  940. if(info.canUpgrade()) //we have upgrades here - update costs
  941. {
  942. costs[i] = info.getUpgradeCosts() * hero->getStackCount(SlotID(i));
  943. totalSum += costs[i];
  944. }
  945. }
  946. }
  947. currState[i] = newState;
  948. upgrade[i]->setImage(AnimationPath::builtin(slotImages[getImgIdx(currState[i])]));
  949. upgrade[i]->block(currState[i] == State::EMPTY);
  950. upgrade[i]->addHoverText(EButtonState::NORMAL, getTextForSlot(SlotID(i)));
  951. }
  952. //"Upgrade all" slot
  953. State newState = State::MAKE_UPGRADE;
  954. {
  955. TResources myRes = GAME->interface()->cb->getResourceAmount();
  956. bool allUpgraded = true;//All creatures are upgraded?
  957. for(int i=0; i<slotsCount; i++)
  958. allUpgraded &= currState[i] == State::ALREADY_UPGRADED || currState[i] == State::EMPTY || currState[i] == State::UNAVAILABLE;
  959. if (allUpgraded)
  960. newState = State::ALREADY_UPGRADED;
  961. if(!totalSum.canBeAfforded(myRes))
  962. newState = State::UNAFFORDABLE;
  963. }
  964. currState[slotsCount] = newState;
  965. upgradeAll->setImage(AnimationPath::builtin(allImages[static_cast<std::size_t>(newState)]));
  966. garr->recreateSlots();
  967. for(int i = 0; i < slotsCount; i++)
  968. {
  969. //hide all first
  970. for(int j : {0,1})
  971. {
  972. slotIcons[i][j]->visible = false;
  973. slotLabels[i][j]->setText("");
  974. }
  975. //if can upgrade or can not afford, draw cost
  976. if(currState[i] == State::UNAFFORDABLE || currState[i] == State::MAKE_UPGRADE)
  977. {
  978. if(costs[i].nonZero())
  979. {
  980. //reverse iterator is used to display gold as first element
  981. int j = 0;
  982. for(int res = (int)costs[i].size()-1; (res >= 0) && (j < 2); res--)
  983. {
  984. int val = costs[i][res];
  985. if(!val)
  986. continue;
  987. slotIcons[i][j]->visible = true;
  988. slotIcons[i][j]->setFrame(res);
  989. slotLabels[i][j]->setText(std::to_string(val));
  990. j++;
  991. }
  992. }
  993. else//free upgrade - print gold image and "Free" text
  994. {
  995. slotIcons[i][0]->visible = true;
  996. slotIcons[i][0]->setFrame(GameResID(EGameResID::GOLD));
  997. slotLabels[i][0]->setText(LIBRARY->generaltexth->allTexts[344]);
  998. }
  999. }
  1000. }
  1001. for(int i = 0; i < resCount; i++)
  1002. {
  1003. if(totalSum[i] == 0)
  1004. {
  1005. totalIcons[i]->visible = false;
  1006. totalLabels[i]->setText("");
  1007. }
  1008. else
  1009. {
  1010. totalIcons[i]->visible = true;
  1011. totalLabels[i]->setText(std::to_string(totalSum[i]));
  1012. }
  1013. }
  1014. }
  1015. void CHillFortWindow::makeDeal(SlotID slot)
  1016. {
  1017. assert(slot.getNum() >= 0);
  1018. int offset = (slot.getNum() == slotsCount) ? 2 : 0;
  1019. switch(currState[slot.getNum()])
  1020. {
  1021. case State::ALREADY_UPGRADED:
  1022. GAME->interface()->showInfoDialog(LIBRARY->generaltexth->allTexts[313 + offset], std::vector<std::shared_ptr<CComponent>>(), soundBase::sound_todo);
  1023. break;
  1024. case State::UNAFFORDABLE:
  1025. GAME->interface()->showInfoDialog(LIBRARY->generaltexth->allTexts[314 + offset], std::vector<std::shared_ptr<CComponent>>(), soundBase::sound_todo);
  1026. break;
  1027. case State::UNAVAILABLE:
  1028. {
  1029. std::string message = LIBRARY->generaltexth->translate(dynamic_cast<const HillFort *>(fort)->getUnavailableUpgradeMessage());
  1030. GAME->interface()->showInfoDialog(message, std::vector<std::shared_ptr<CComponent>>(), soundBase::sound_todo);
  1031. break;
  1032. }
  1033. case State::MAKE_UPGRADE:
  1034. for(int i = 0; i < slotsCount; i++)
  1035. {
  1036. if(slot.getNum() == i || ( slot.getNum() == slotsCount && currState[i] == State::MAKE_UPGRADE ))//this is activated slot or "upgrade all"
  1037. {
  1038. if(const CStackInstance * s = hero->getStackPtr(SlotID(i)))
  1039. {
  1040. UpgradeInfo info(s->getCreatureID());
  1041. GAME->interface()->cb->fillUpgradeInfo(hero, SlotID(i), info);
  1042. GAME->interface()->cb->upgradeCreature(hero, SlotID(i), info.getUpgrade());
  1043. }
  1044. }
  1045. }
  1046. break;
  1047. }
  1048. }
  1049. std::string CHillFortWindow::getTextForSlot(SlotID slot)
  1050. {
  1051. if(!hero->getCreature(slot))//we don`t have creature here
  1052. return "";
  1053. std::string str = LIBRARY->generaltexth->allTexts[318];
  1054. int amount = hero->getStackCount(slot);
  1055. if(amount == 1)
  1056. boost::algorithm::replace_first(str,"%s",hero->getCreature(slot)->getNameSingularTranslated());
  1057. else
  1058. boost::algorithm::replace_first(str,"%s",hero->getCreature(slot)->getNamePluralTranslated());
  1059. return str;
  1060. }
  1061. CHillFortWindow::State CHillFortWindow::getState(SlotID slot)
  1062. {
  1063. TResources myRes = GAME->interface()->cb->getResourceAmount();
  1064. if(hero->slotEmpty(slot))
  1065. return State::EMPTY;
  1066. UpgradeInfo info(hero->getStackPtr(slot)->getCreatureID());
  1067. GAME->interface()->cb->fillUpgradeInfo(hero, slot, info);
  1068. if(info.hasUpgrades() && !info.canUpgrade())
  1069. return State::UNAVAILABLE; // Hill Fort may limit level of upgradeable creatures, e.g. mini Hill Fort from HOTA
  1070. if(!info.hasUpgrades())
  1071. return State::ALREADY_UPGRADED;
  1072. if(!(info.getUpgradeCosts() * hero->getStackCount(slot)).canBeAfforded(myRes))
  1073. return State::UNAFFORDABLE;
  1074. return State::MAKE_UPGRADE;
  1075. }
  1076. CThievesGuildWindow::CThievesGuildWindow(const CGObjectInstance * _owner):
  1077. CWindowObject(PLAYER_COLORED | BORDERED, ImagePath::builtin("TpRank")),
  1078. owner(_owner)
  1079. {
  1080. OBJECT_CONSTRUCTION;
  1081. SThievesGuildInfo tgi; //info to be displayed
  1082. GAME->interface()->cb->getThievesGuildInfo(tgi, owner);
  1083. exitb = std::make_shared<CButton>(Point(748, 556), AnimationPath::builtin("TPMAGE1"), CButton::tooltip(LIBRARY->generaltexth->allTexts[600]), [&](){ close();}, EShortcut::GLOBAL_RETURN);
  1084. statusbar = CGStatusBar::create(3, 555, ImagePath::builtin("TStatBar.bmp"), 742);
  1085. resdatabar = std::make_shared<CMinorResDataBar>();
  1086. resdatabar->moveBy(pos.topLeft(), true);
  1087. //data for information table:
  1088. // fields[row][column] = list of id's of players for this box
  1089. constexpr std::vector< std::vector< PlayerColor > > SThievesGuildInfo::* fields[] =
  1090. { &SThievesGuildInfo::numOfTowns, &SThievesGuildInfo::numOfHeroes, &SThievesGuildInfo::gold,
  1091. &SThievesGuildInfo::woodOre, &SThievesGuildInfo::mercSulfCrystGems, &SThievesGuildInfo::obelisks,
  1092. &SThievesGuildInfo::artifacts, &SThievesGuildInfo::army, &SThievesGuildInfo::income };
  1093. for(int g=0; g<12; ++g)
  1094. {
  1095. int posY[] = {400, 460, 510};
  1096. int y;
  1097. if(g < 9)
  1098. y = 52 + 32*g;
  1099. else
  1100. y = posY[g-9];
  1101. std::string text = LIBRARY->generaltexth->jktexts[24+g];
  1102. boost::algorithm::trim_if(text,boost::algorithm::is_any_of("\""));
  1103. if(settings["general"]["enableUiEnhancements"].Bool() && g >= 2 && g <= 4) // add icons instead of text (text is OH3 behavior)
  1104. {
  1105. auto addicon = [this, y](GameResID res, int x){ columnHeaderIcons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("SMALRES"), res, 0, x, y - 10)); };
  1106. if(g == 2) // gold
  1107. addicon(GameResID::GOLD, 125);
  1108. else if(g == 3) // wood, ore
  1109. {
  1110. addicon(GameResID::WOOD, 110);
  1111. addicon(GameResID::ORE, 140);
  1112. }
  1113. else if(g == 4) // mercury, sulfur, crystal, gems
  1114. {
  1115. addicon(GameResID::MERCURY, 80);
  1116. addicon(GameResID::SULFUR, 110);
  1117. addicon(GameResID::CRYSTAL, 140);
  1118. addicon(GameResID::GEMS, 170);
  1119. }
  1120. }
  1121. else
  1122. rowHeaders.push_back(std::make_shared<CLabel>(135, y, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW, text, 220));
  1123. }
  1124. for(int g=1; g<tgi.playerColors.size(); ++g)
  1125. columnBackgrounds.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("PRSTRIPS"), g-1, 0, 250 + 66*g, 7));
  1126. for(int g=0; g<tgi.playerColors.size(); ++g)
  1127. columnHeaders.push_back(std::make_shared<CLabel>(283 + 66*g, 21, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, LIBRARY->generaltexth->jktexts[16+g]));
  1128. //printing flags
  1129. for(int g = 0; g < std::size(fields); ++g) //by lines
  1130. {
  1131. for(int b=0; b<(tgi .* fields[g]).size(); ++b) //by places (1st, 2nd, ...)
  1132. {
  1133. std::vector<PlayerColor> &players = (tgi .* fields[g])[b]; //get players with this place in this line
  1134. //position of box
  1135. int xpos = 259 + 66 * b;
  1136. int ypos = 41 + 32 * g;
  1137. size_t rowLength[2]; //size of each row
  1138. rowLength[0] = std::min<size_t>(players.size(), 4);
  1139. rowLength[1] = players.size() - rowLength[0];
  1140. for(size_t j=0; j < 2; j++)
  1141. {
  1142. // origin of this row | offset for 2nd row| shift right for short rows
  1143. //if we have 2 rows, start either from mid or beginning (depending on count), otherwise center the flags
  1144. int rowStartX = xpos + (j ? 6 + ((int)rowLength[j] < 3 ? 12 : 0) : 24 - 6 * (int)rowLength[j]);
  1145. int rowStartY = ypos + (j ? 4 : 0);
  1146. for(size_t i=0; i < rowLength[j]; i++)
  1147. cells.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("itgflags"), players[i + j*4].getNum(), 0, rowStartX + (int)i*12, rowStartY));
  1148. }
  1149. }
  1150. }
  1151. static const std::string colorToBox[] = {"PRRED.BMP", "PRBLUE.BMP", "PRTAN.BMP", "PRGREEN.BMP", "PRORANGE.BMP", "PRPURPLE.BMP", "PRTEAL.BMP", "PRROSE.bmp"};
  1152. //printing best hero
  1153. int counter = 0;
  1154. for(auto & iter : tgi.colorToBestHero)
  1155. {
  1156. banners.push_back(std::make_shared<CPicture>(ImagePath::builtin(colorToBox[iter.first.getNum()]), 253 + 66 * counter, 334));
  1157. if(iter.second.portraitSource.isValid())
  1158. {
  1159. bestHeroes.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("PortraitsSmall"), iter.second.getIconIndex(), 0, 260 + 66 * counter, 360));
  1160. //TODO: r-click info:
  1161. // - r-click on hero
  1162. if(iter.second.details)
  1163. {
  1164. std::vector<std::string> lines;
  1165. boost::split(lines, LIBRARY->generaltexth->allTexts[184], boost::is_any_of("\n"));
  1166. for(int i=0; i<GameConstants::PRIMARY_SKILLS; ++i)
  1167. {
  1168. primSkillHeaders.push_back(std::make_shared<CLabel>(260 + 66 * counter, 407 + 11 * i, FONT_TINY, ETextAlignment::BOTTOMLEFT, Colors::WHITE, lines[i]));
  1169. primSkillHeadersArea.push_back(std::make_shared<LRClickableArea>(Rect(primSkillHeaders.back()->pos.x - pos.x, primSkillHeaders.back()->pos.y - pos.y - 11, 50, 11), nullptr, [i]{
  1170. CRClickPopup::createAndPush(LIBRARY->generaltexth->arraytxt[2 + i]);
  1171. }));
  1172. primSkillValues.push_back(std::make_shared<CLabel>(310 + 66 * counter, 407 + 11 * i, FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE,
  1173. std::to_string(iter.second.details->primskills[i])));
  1174. }
  1175. }
  1176. }
  1177. counter++;
  1178. }
  1179. //printing best creature
  1180. counter = 0;
  1181. for(auto & it : tgi.bestCreature)
  1182. {
  1183. if(it.second != CreatureID::NONE)
  1184. bestCreatures.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("TWCRPORT"), it.second+2, 0, 255 + 66 * counter, 479));
  1185. counter++;
  1186. }
  1187. //printing personality
  1188. counter = 0;
  1189. for(auto & it : tgi.personality)
  1190. {
  1191. std::string text;
  1192. if(it.second == EAiTactic::NONE)
  1193. {
  1194. text = LIBRARY->generaltexth->arraytxt[172];
  1195. }
  1196. else if(it.second != EAiTactic::RANDOM)
  1197. {
  1198. text = LIBRARY->generaltexth->arraytxt[168 + static_cast<int>(it.second)];
  1199. }
  1200. personalities.push_back(std::make_shared<CLabel>(283 + 66*counter, 459, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, text));
  1201. counter++;
  1202. }
  1203. }
  1204. CObjectListWindow::CItem::CItem(CObjectListWindow * _parent, size_t _id, std::string _text)
  1205. : CIntObject(LCLICK | DOUBLECLICK | RCLICK_POPUP),
  1206. parent(_parent),
  1207. index(_id)
  1208. {
  1209. OBJECT_CONSTRUCTION;
  1210. if(parent->images.size() > index)
  1211. icon = std::make_shared<CPicture>(parent->images[index], Point(1, 1));
  1212. border = std::make_shared<CPicture>(ImagePath::builtin("TPGATES"));
  1213. pos = border->pos;
  1214. setRedrawParent(true);
  1215. text = std::make_shared<CLabel>(pos.w/2, pos.h/2, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, _text, 256);
  1216. select(index == parent->selected);
  1217. }
  1218. void CObjectListWindow::CItem::select(bool on)
  1219. {
  1220. ui8 mask = UPDATE | SHOWALL;
  1221. if(on)
  1222. border->recActions |= mask;
  1223. else
  1224. border->recActions &= ~mask;
  1225. redraw();//???
  1226. }
  1227. void CObjectListWindow::CItem::clickPressed(const Point & cursorPosition)
  1228. {
  1229. parent->changeSelection(index);
  1230. if(parent->onClicked)
  1231. parent->onClicked(index);
  1232. }
  1233. void CObjectListWindow::CItem::clickDouble(const Point & cursorPosition)
  1234. {
  1235. if (parent->selected != index)
  1236. {
  1237. clickPressed(cursorPosition);
  1238. return;
  1239. }
  1240. parent->elementSelected();
  1241. }
  1242. void CObjectListWindow::CItem::showPopupWindow(const Point & cursorPosition)
  1243. {
  1244. if(parent->onPopup)
  1245. parent->onPopup(index);
  1246. }
  1247. CObjectListWindow::CObjectListWindow(const std::vector<int> & _items, std::shared_ptr<CIntObject> titleWidget_, std::string _title, std::string _descr, std::function<void(int)> Callback, size_t initialSelection, std::vector<std::shared_ptr<IImage>> images, bool searchBoxEnabled)
  1248. : CWindowObject(PLAYER_COLORED, ImagePath::builtin("TPGATE")),
  1249. onSelect(Callback),
  1250. selected(initialSelection),
  1251. images(images)
  1252. {
  1253. OBJECT_CONSTRUCTION;
  1254. addUsedEvents(KEYBOARD);
  1255. items.reserve(_items.size());
  1256. for(int id : _items)
  1257. {
  1258. std::string objectName = GAME->interface()->cb->getObjInstance(ObjectInstanceID(id))->getObjectName();
  1259. trimTextIfTooWide(objectName, id);
  1260. items.emplace_back(id, objectName);
  1261. }
  1262. itemsVisible = items;
  1263. init(titleWidget_, _title, _descr, searchBoxEnabled);
  1264. list->scrollTo(std::min(static_cast<int>(initialSelection + 4), static_cast<int>(items.size() - 1))); // 4 is for centering (list have 9 elements)
  1265. }
  1266. CObjectListWindow::CObjectListWindow(const std::vector<std::string> & _items, std::shared_ptr<CIntObject> titleWidget_, std::string _title, std::string _descr, std::function<void(int)> Callback, size_t initialSelection, std::vector<std::shared_ptr<IImage>> images, bool searchBoxEnabled)
  1267. : CWindowObject(PLAYER_COLORED, ImagePath::builtin("TPGATE")),
  1268. onSelect(Callback),
  1269. selected(initialSelection),
  1270. images(images)
  1271. {
  1272. OBJECT_CONSTRUCTION;
  1273. addUsedEvents(KEYBOARD);
  1274. items.reserve(_items.size());
  1275. for(size_t i = 0; i < _items.size(); i++)
  1276. {
  1277. std::string objectName = _items[i];
  1278. trimTextIfTooWide(objectName, static_cast<int>(i));
  1279. items.emplace_back(static_cast<int>(i), objectName);
  1280. }
  1281. itemsVisible = items;
  1282. init(titleWidget_, _title, _descr, searchBoxEnabled);
  1283. list->scrollTo(std::min(static_cast<int>(initialSelection + 4), static_cast<int>(items.size() - 1))); // 4 is for centering (list have 9 elements)
  1284. }
  1285. void CObjectListWindow::init(std::shared_ptr<CIntObject> titleWidget_, std::string _title, std::string _descr, bool searchBoxEnabled)
  1286. {
  1287. titleWidget = titleWidget_;
  1288. title = std::make_shared<CLabel>(152, 27, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, _title);
  1289. descr = std::make_shared<CLabel>(145, 133, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, _descr);
  1290. exit = std::make_shared<CButton>( Point(228, 402), AnimationPath::builtin("ICANCEL.DEF"), CButton::tooltip(), std::bind(&CObjectListWindow::exitPressed, this), EShortcut::GLOBAL_CANCEL);
  1291. if(titleWidget)
  1292. {
  1293. addChild(titleWidget.get());
  1294. titleWidget->pos.x = pos.w/2 + pos.x - titleWidget->pos.w/2;
  1295. titleWidget->pos.y = 75 + pos.y - titleWidget->pos.h/2;
  1296. }
  1297. list = std::make_shared<CListBox>(std::bind(&CObjectListWindow::genItem, this, _1),
  1298. Point(14, 151), Point(0, 25), 9, itemsVisible.size(), 0, 1, Rect(262, -32, 256, 256) );
  1299. list->setRedrawParent(true);
  1300. ok = std::make_shared<CButton>(Point(15, 402), AnimationPath::builtin("IOKAY.DEF"), CButton::tooltip(), std::bind(&CObjectListWindow::elementSelected, this), EShortcut::GLOBAL_ACCEPT);
  1301. ok->block(!list->size());
  1302. if(!searchBoxEnabled)
  1303. return;
  1304. Rect r(50, 90, pos.w - 100, 16);
  1305. const ColorRGBA rectangleColor = ColorRGBA(0, 0, 0, 75);
  1306. const ColorRGBA borderColor = ColorRGBA(128, 100, 75);
  1307. const ColorRGBA grayedColor = ColorRGBA(158, 130, 105);
  1308. searchBoxRectangle = std::make_shared<TransparentFilledRectangle>(r.resize(1), rectangleColor, borderColor);
  1309. searchBoxDescription = std::make_shared<CLabel>(r.center().x, r.center().y, FONT_SMALL, ETextAlignment::CENTER, grayedColor, LIBRARY->generaltexth->translate("vcmi.spellBook.search"));
  1310. searchBox = std::make_shared<CTextInput>(r, FONT_SMALL, ETextAlignment::CENTER, true);
  1311. searchBox->setCallback(std::bind(&CObjectListWindow::itemsSearchCallback, this, std::placeholders::_1));
  1312. }
  1313. void CObjectListWindow::trimTextIfTooWide(std::string & text, int id) const
  1314. {
  1315. int maxWidth = pos.w - 60; // 60 px for scrollbar and borders
  1316. std::string idStr = '(' + std::to_string(id) + ')';
  1317. const auto & font = ENGINE->renderHandler().loadFont(FONT_SMALL);
  1318. std::string suffix = " ... " + idStr;
  1319. if(font->getStringWidth(text) >= maxWidth)
  1320. {
  1321. logGlobal->warn("Mapobject name '%s' is too long and probably needs to be fixed! Trimming...",
  1322. text.substr(0, text.size() - idStr.size() + 1));
  1323. // Trim text until it fits
  1324. while(!text.empty())
  1325. {
  1326. std::string trimmedText = text + suffix;
  1327. if(font->getStringWidth(trimmedText) < maxWidth)
  1328. break;
  1329. TextOperations::trimRightUnicode(text);
  1330. }
  1331. text += suffix;
  1332. }
  1333. }
  1334. void CObjectListWindow::itemsSearchCallback(const std::string & text)
  1335. {
  1336. searchBoxDescription->setEnabled(text.empty());
  1337. itemsVisible.clear();
  1338. std::vector<std::pair<int, decltype(items)::value_type>> rankedItems; // Store (score, item)
  1339. for(const auto & item : items)
  1340. {
  1341. if(auto score = TextOperations::textSearchSimilarityScore(text, item.second)) // Keep only relevant items
  1342. rankedItems.emplace_back(score.value(), item);
  1343. }
  1344. // Sort: Lower score is better match
  1345. std::sort(rankedItems.begin(), rankedItems.end(), [](const auto & a, const auto & b)
  1346. {
  1347. return a.first < b.first;
  1348. });
  1349. for(const auto & rankedItem : rankedItems)
  1350. itemsVisible.push_back(rankedItem.second);
  1351. selected = 0;
  1352. list->resize(itemsVisible.size());
  1353. list->scrollTo(0);
  1354. ok->block(!itemsVisible.size());
  1355. redraw();
  1356. }
  1357. std::shared_ptr<CIntObject> CObjectListWindow::genItem(size_t index)
  1358. {
  1359. if(index < itemsVisible.size())
  1360. return std::make_shared<CItem>(this, index, itemsVisible[index].second);
  1361. return std::shared_ptr<CIntObject>();
  1362. }
  1363. void CObjectListWindow::elementSelected()
  1364. {
  1365. std::function<void(int)> toCall = onSelect;//save
  1366. int where = itemsVisible[selected].first; //required variables
  1367. close();//then destroy window
  1368. toCall(where);//and send selected object
  1369. }
  1370. void CObjectListWindow::exitPressed()
  1371. {
  1372. std::function<void()> toCall = onExit;//save
  1373. close();//then destroy window
  1374. if(toCall)
  1375. toCall();
  1376. }
  1377. void CObjectListWindow::changeSelection(size_t which)
  1378. {
  1379. ok->block(false);
  1380. if(selected == which)
  1381. return;
  1382. for(std::shared_ptr<CIntObject> element : list->getItems())
  1383. {
  1384. CItem * item = dynamic_cast<CItem*>(element.get());
  1385. if(item)
  1386. {
  1387. if(item->index == selected)
  1388. item->select(false);
  1389. if(item->index == which)
  1390. item->select(true);
  1391. }
  1392. }
  1393. selected = which;
  1394. }
  1395. void CObjectListWindow::keyPressed(EShortcut key)
  1396. {
  1397. int sel = static_cast<int>(selected);
  1398. switch(key)
  1399. {
  1400. break; case EShortcut::MOVE_UP:
  1401. sel -=1;
  1402. break; case EShortcut::MOVE_DOWN:
  1403. sel +=1;
  1404. break; case EShortcut::MOVE_PAGE_UP:
  1405. sel -=9;
  1406. break; case EShortcut::MOVE_PAGE_DOWN:
  1407. sel +=9;
  1408. break; case EShortcut::MOVE_FIRST:
  1409. sel = 0;
  1410. break; case EShortcut::MOVE_LAST:
  1411. sel = static_cast<int>(itemsVisible.size());
  1412. break; default:
  1413. return;
  1414. }
  1415. vstd::abetween<int>(sel, 0, itemsVisible.size()-1);
  1416. list->scrollTo(sel);
  1417. changeSelection(sel);
  1418. }
  1419. VideoWindow::VideoWindow(const VideoPath & video, const ImagePath & rim, bool showBackground, float scaleFactor, const std::function<void(bool skipped)> & closeCb)
  1420. : CWindowObject(BORDERED | SHADOW_DISABLED | NEEDS_ANIMATED_BACKGROUND)
  1421. , showBackground(showBackground)
  1422. , closeCb(closeCb)
  1423. {
  1424. OBJECT_CONSTRUCTION;
  1425. addUsedEvents(LCLICK | KEYBOARD);
  1426. if(!rim.empty())
  1427. {
  1428. setBackground(rim);
  1429. videoPlayer = std::make_shared<VideoWidgetOnce>(Point(80, 186), video, true, this);
  1430. pos = center(Rect(0, 0, 800, 600));
  1431. }
  1432. else
  1433. {
  1434. blackBackground = std::make_shared<GraphicalPrimitiveCanvas>(Rect(0, 0, ENGINE->screenDimensions().x, ENGINE->screenDimensions().y));
  1435. videoPlayer = std::make_shared<VideoWidgetOnce>(Point(0, 0), video, true, scaleFactor, this);
  1436. pos = center(Rect(0, 0, videoPlayer->pos.w, videoPlayer->pos.h));
  1437. blackBackground->addBox(Point(0, 0), Point(videoPlayer->pos.w, videoPlayer->pos.h), Colors::BLACK);
  1438. }
  1439. }
  1440. void VideoWindow::showAll(Canvas & to)
  1441. {
  1442. if(showBackground)
  1443. to.fillTexture(ENGINE->renderHandler().loadImage(ImagePath::builtin("DiBoxBck"), EImageBlitMode::OPAQUE));
  1444. CWindowObject::showAll(to);
  1445. }
  1446. void VideoWindow::onVideoPlaybackFinished()
  1447. {
  1448. exit(false);
  1449. }
  1450. void VideoWindow::exit(bool skipped)
  1451. {
  1452. close();
  1453. if(closeCb)
  1454. closeCb(skipped);
  1455. }
  1456. void VideoWindow::clickPressed(const Point & cursorPosition)
  1457. {
  1458. exit(true);
  1459. }
  1460. void VideoWindow::keyPressed(EShortcut key)
  1461. {
  1462. if(key == EShortcut::GLOBAL_RETURN)
  1463. exit(true);
  1464. }
  1465. void VideoWindow::notFocusedClick()
  1466. {
  1467. exit(true);
  1468. }