GUIClasses.cpp 62 KB

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