GUIClasses.cpp 64 KB

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