GUIClasses.cpp 62 KB

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