GUIClasses.cpp 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914
  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 "../CGameInfo.h"
  17. #include "../CMusicHandler.h"
  18. #include "../CPlayerInterface.h"
  19. #include "../CVideoHandler.h"
  20. #include "../CServerHandler.h"
  21. //#include "../adventureMap/CResDataBar.h"
  22. #include "../battle/BattleInterfaceClasses.h"
  23. #include "../battle/BattleInterface.h"
  24. #include "../gui/CGuiHandler.h"
  25. #include "../gui/CursorHandler.h"
  26. #include "../gui/TextAlignment.h"
  27. #include "../gui/Shortcut.h"
  28. #include "../widgets/CComponent.h"
  29. #include "../widgets/MiscWidgets.h"
  30. #include "../widgets/CreatureCostBox.h"
  31. #include "../widgets/Buttons.h"
  32. #include "../widgets/TextControls.h"
  33. #include "../widgets/ObjectLists.h"
  34. #include "../lobby/CSavingScreen.h"
  35. #include "../renderSDL/SDL_Extensions.h"
  36. #include "../render/CAnimation.h"
  37. #include "../CMT.h"
  38. #include "../../CCallback.h"
  39. #include "../lib/mapObjects/CGHeroInstance.h"
  40. #include "../lib/CArtHandler.h"
  41. #include "../lib/CBuildingHandler.h"
  42. #include "../lib/CConfigHandler.h"
  43. #include "../lib/CCreatureHandler.h"
  44. #include "../lib/CGameState.h"
  45. #include "../lib/CGeneralTextHandler.h"
  46. #include "../lib/CHeroHandler.h"
  47. #include "../lib/CModHandler.h"
  48. #include "../lib/GameSettings.h"
  49. #include "../lib/CondSh.h"
  50. #include "../lib/CSkillHandler.h"
  51. #include "../lib/spells/CSpellHandler.h"
  52. #include "../lib/filesystem/Filesystem.h"
  53. #include "../lib/CStopWatch.h"
  54. #include "../lib/CTownHandler.h"
  55. #include "../lib/GameConstants.h"
  56. #include "../lib/bonuses/Bonus.h"
  57. #include "../lib/mapping/CMap.h"
  58. #include "../lib/NetPacksBase.h"
  59. #include "../lib/StartInfo.h"
  60. #include "../lib/TextOperations.h"
  61. #include <SDL_surface.h>
  62. CRecruitmentWindow::CCreatureCard::CCreatureCard(CRecruitmentWindow * window, const CCreature * crea, int totalAmount)
  63. : CIntObject(LCLICK | RCLICK),
  64. parent(window),
  65. selected(false),
  66. creature(crea),
  67. amount(totalAmount)
  68. {
  69. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  70. animation = std::make_shared<CCreaturePic>(1, 1, creature, true, true);
  71. // 1 + 1 px for borders
  72. pos.w = animation->pos.w + 2;
  73. pos.h = animation->pos.h + 2;
  74. }
  75. void CRecruitmentWindow::CCreatureCard::select(bool on)
  76. {
  77. selected = on;
  78. redraw();
  79. }
  80. void CRecruitmentWindow::CCreatureCard::clickLeft(tribool down, bool previousState)
  81. {
  82. if(down)
  83. parent->select(this->shared_from_this());
  84. }
  85. void CRecruitmentWindow::CCreatureCard::clickRight(tribool down, bool previousState)
  86. {
  87. if(down)
  88. GH.pushIntT<CStackWindow>(creature, true);
  89. }
  90. void CRecruitmentWindow::CCreatureCard::showAll(SDL_Surface * to)
  91. {
  92. CIntObject::showAll(to);
  93. if(selected)
  94. CSDL_Ext::drawBorder(to, pos, Colors::RED);
  95. else
  96. CSDL_Ext::drawBorder(to, pos, Colors::YELLOW);
  97. }
  98. void CRecruitmentWindow::select(std::shared_ptr<CCreatureCard> card)
  99. {
  100. if(card == selected)
  101. return;
  102. if(selected)
  103. selected->select(false);
  104. selected = card;
  105. if(selected)
  106. selected->select(true);
  107. if(card)
  108. {
  109. si32 maxAmount = card->creature->maxAmount(LOCPLINT->cb->getResourceAmount());
  110. vstd::amin(maxAmount, card->amount);
  111. slider->setAmount(maxAmount);
  112. if(slider->getValue() != maxAmount)
  113. slider->moveTo(maxAmount);
  114. else // if slider already at 0 - emulate call to sliderMoved()
  115. sliderMoved(maxAmount);
  116. costPerTroopValue->createItems(card->creature->getFullRecruitCost());
  117. totalCostValue->createItems(card->creature->getFullRecruitCost());
  118. costPerTroopValue->set(card->creature->getFullRecruitCost());
  119. totalCostValue->set(card->creature->getFullRecruitCost() * maxAmount);
  120. //Recruit %s
  121. title->setText(boost::str(boost::format(CGI->generaltexth->tcommands[21]) % card->creature->getNamePluralTranslated()));
  122. maxButton->block(maxAmount == 0);
  123. slider->block(maxAmount == 0);
  124. }
  125. }
  126. void CRecruitmentWindow::buy()
  127. {
  128. CreatureID crid = selected->creature->getId();
  129. SlotID dstslot = dst-> getSlotFor(crid);
  130. if(!dstslot.validSlot() && (selected->creature->warMachine == ArtifactID::NONE)) //no available slot
  131. {
  132. std::string txt;
  133. if(dst->ID == Obj::HERO)
  134. {
  135. txt = CGI->generaltexth->allTexts[425]; //The %s would join your hero, but there aren't enough provisions to support them.
  136. boost::algorithm::replace_first(txt, "%s", slider->getValue() > 1 ? CGI->creh->objects[crid]->getNamePluralTranslated() : CGI->creh->objects[crid]->getNameSingularTranslated());
  137. }
  138. else
  139. {
  140. txt = CGI->generaltexth->allTexts[17]; //There is no room in the garrison for this army.
  141. }
  142. LOCPLINT->showInfoDialog(txt);
  143. return;
  144. }
  145. onRecruit(crid, slider->getValue());
  146. if(level >= 0)
  147. close();
  148. }
  149. void CRecruitmentWindow::showAll(SDL_Surface * to)
  150. {
  151. CWindowObject::showAll(to);
  152. // recruit\total values
  153. CSDL_Ext::drawBorder(to, pos.x + 172, pos.y + 222, 67, 42, Colors::YELLOW);
  154. CSDL_Ext::drawBorder(to, pos.x + 246, pos.y + 222, 67, 42, Colors::YELLOW);
  155. //cost boxes
  156. CSDL_Ext::drawBorder(to, pos.x + 64, pos.y + 222, 99, 76, Colors::YELLOW);
  157. CSDL_Ext::drawBorder(to, pos.x + 322, pos.y + 222, 99, 76, Colors::YELLOW);
  158. //buttons borders
  159. CSDL_Ext::drawBorder(to, pos.x + 133, pos.y + 312, 66, 34, Colors::METALLIC_GOLD);
  160. CSDL_Ext::drawBorder(to, pos.x + 211, pos.y + 312, 66, 34, Colors::METALLIC_GOLD);
  161. CSDL_Ext::drawBorder(to, pos.x + 289, pos.y + 312, 66, 34, Colors::METALLIC_GOLD);
  162. }
  163. CRecruitmentWindow::CRecruitmentWindow(const CGDwelling * Dwelling, int Level, const CArmedInstance * Dst, const std::function<void(CreatureID,int)> & Recruit, int y_offset):
  164. CStatusbarWindow(PLAYER_COLORED, "TPRCRT"),
  165. onRecruit(Recruit),
  166. level(Level),
  167. dst(Dst),
  168. selected(nullptr),
  169. dwelling(Dwelling)
  170. {
  171. moveBy(Point(0, y_offset));
  172. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  173. statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
  174. slider = std::make_shared<CSlider>(Point(176,279),135,std::bind(&CRecruitmentWindow::sliderMoved,this, _1),0,0,0,true);
  175. maxButton = std::make_shared<CButton>(Point(134, 313), "IRCBTNS.DEF", CGI->generaltexth->zelp[553], std::bind(&CSlider::moveToMax, slider), EShortcut::RECRUITMENT_MAX);
  176. buyButton = std::make_shared<CButton>(Point(212, 313), "IBY6432.DEF", CGI->generaltexth->zelp[554], std::bind(&CRecruitmentWindow::buy, this), EShortcut::GLOBAL_ACCEPT);
  177. cancelButton = std::make_shared<CButton>(Point(290, 313), "ICN6432.DEF", CGI->generaltexth->zelp[555], std::bind(&CRecruitmentWindow::close, this), EShortcut::GLOBAL_CANCEL);
  178. title = std::make_shared<CLabel>(243, 32, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW);
  179. availableValue = std::make_shared<CLabel>(205, 253, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  180. toRecruitValue = std::make_shared<CLabel>(279, 253, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  181. costPerTroopValue = std::make_shared<CreatureCostBox>(Rect(65, 222, 97, 74), CGI->generaltexth->allTexts[346]);
  182. totalCostValue = std::make_shared<CreatureCostBox>(Rect(323, 222, 97, 74), CGI->generaltexth->allTexts[466]);
  183. availableTitle = std::make_shared<CLabel>(205, 233, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[465]);
  184. toRecruitTitle = std::make_shared<CLabel>(279, 233, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[16]);
  185. availableCreaturesChanged();
  186. }
  187. void CRecruitmentWindow::availableCreaturesChanged()
  188. {
  189. OBJECT_CONSTRUCTION_CUSTOM_CAPTURING(255-DISPOSE);
  190. size_t selectedIndex = 0;
  191. if(!cards.empty() && selected) // find position of selected item
  192. selectedIndex = std::find(cards.begin(), cards.end(), selected) - cards.begin();
  193. select(nullptr);
  194. cards.clear();
  195. for(int i=0; i<dwelling->creatures.size(); i++)
  196. {
  197. //find appropriate level
  198. if(level >= 0 && i != level)
  199. continue;
  200. int amount = dwelling->creatures[i].first;
  201. //create new cards
  202. for(auto & creature : boost::adaptors::reverse(dwelling->creatures[i].second))
  203. cards.push_back(std::make_shared<CCreatureCard>(this, CGI->creh->objects[creature], amount));
  204. }
  205. const int creatureWidth = 102;
  206. //normal distance between cards - 18px
  207. int requiredSpace = 18;
  208. //maximum distance we can use without reaching window borders
  209. int availableSpace = pos.w - 50 - creatureWidth * (int)cards.size();
  210. if (cards.size() > 1) // avoid division by zero
  211. availableSpace /= (int)cards.size() - 1;
  212. else
  213. availableSpace = 0;
  214. assert(availableSpace >= 0);
  215. const int spaceBetween = std::min(requiredSpace, availableSpace);
  216. const int totalCreatureWidth = spaceBetween + creatureWidth;
  217. //now we know total amount of cards and can move them to correct position
  218. int curx = pos.w / 2 - (creatureWidth*(int)cards.size()/2) - (spaceBetween*((int)cards.size()-1)/2);
  219. for(auto & card : cards)
  220. {
  221. card->moveBy(Point(curx, 64));
  222. curx += totalCreatureWidth;
  223. }
  224. //restore selection
  225. select(cards[selectedIndex]);
  226. if(slider->getValue() == slider->getAmount())
  227. slider->moveToMax();
  228. else // if slider already at 0 - emulate call to sliderMoved()
  229. sliderMoved(slider->getAmount());
  230. }
  231. void CRecruitmentWindow::sliderMoved(int to)
  232. {
  233. if(!selected)
  234. return;
  235. buyButton->block(!to);
  236. availableValue->setText(std::to_string(selected->amount - to));
  237. toRecruitValue->setText(std::to_string(to));
  238. totalCostValue->set(selected->creature->getFullRecruitCost() * to);
  239. }
  240. CSplitWindow::CSplitWindow(const CCreature * creature, std::function<void(int, int)> callback_, int leftMin_, int rightMin_, int leftAmount_, int rightAmount_)
  241. : CWindowObject(PLAYER_COLORED, "GPUCRDIV"),
  242. callback(callback_),
  243. leftAmount(leftAmount_),
  244. rightAmount(rightAmount_),
  245. leftMin(leftMin_),
  246. rightMin(rightMin_)
  247. {
  248. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  249. int total = leftAmount + rightAmount;
  250. int leftMax = total - rightMin;
  251. int rightMax = total - leftMin;
  252. ok = std::make_shared<CButton>(Point(20, 263), "IOK6432", CButton::tooltip(), std::bind(&CSplitWindow::apply, this), EShortcut::GLOBAL_ACCEPT);
  253. cancel = std::make_shared<CButton>(Point(214, 263), "ICN6432", CButton::tooltip(), std::bind(&CSplitWindow::close, this), EShortcut::GLOBAL_CANCEL);
  254. int sliderPosition = total - leftMin - rightMin;
  255. leftInput = std::make_shared<CTextInput>(Rect(20, 218, 100, 36), FONT_BIG, std::bind(&CSplitWindow::setAmountText, this, _1, true));
  256. rightInput = std::make_shared<CTextInput>(Rect(176, 218, 100, 36), FONT_BIG, std::bind(&CSplitWindow::setAmountText, this, _1, false));
  257. //add filters to allow only number input
  258. leftInput->filters += std::bind(&CTextInput::numberFilter, _1, _2, leftMin, leftMax);
  259. rightInput->filters += std::bind(&CTextInput::numberFilter, _1, _2, rightMin, rightMax);
  260. leftInput->setText(std::to_string(leftAmount), false);
  261. rightInput->setText(std::to_string(rightAmount), false);
  262. animLeft = std::make_shared<CCreaturePic>(20, 54, creature, true, false);
  263. animRight = std::make_shared<CCreaturePic>(177, 54,creature, true, false);
  264. slider = std::make_shared<CSlider>(Point(21, 194), 257, std::bind(&CSplitWindow::sliderMoved, this, _1), 0, sliderPosition, rightAmount - rightMin, true);
  265. std::string titleStr = CGI->generaltexth->allTexts[256];
  266. boost::algorithm::replace_first(titleStr,"%s", creature->getNamePluralTranslated());
  267. title = std::make_shared<CLabel>(150, 34, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, titleStr);
  268. }
  269. void CSplitWindow::setAmountText(std::string text, bool left)
  270. {
  271. int amount = 0;
  272. if(text.length())
  273. {
  274. try
  275. {
  276. amount = boost::lexical_cast<int>(text);
  277. }
  278. catch(boost::bad_lexical_cast &)
  279. {
  280. amount = left ? leftAmount : rightAmount;
  281. }
  282. int total = leftAmount + rightAmount;
  283. if(amount > total)
  284. amount = total;
  285. }
  286. setAmount(amount, left);
  287. slider->moveTo(rightAmount - rightMin);
  288. }
  289. void CSplitWindow::setAmount(int value, bool left)
  290. {
  291. int total = leftAmount + rightAmount;
  292. leftAmount = left ? value : total - value;
  293. rightAmount = left ? total - value : value;
  294. leftInput->setText(std::to_string(leftAmount));
  295. rightInput->setText(std::to_string(rightAmount));
  296. }
  297. void CSplitWindow::apply()
  298. {
  299. callback(leftAmount, rightAmount);
  300. close();
  301. }
  302. void CSplitWindow::sliderMoved(int to)
  303. {
  304. setAmount(rightMin + to, false);
  305. }
  306. CLevelWindow::CLevelWindow(const CGHeroInstance * hero, PrimarySkill::PrimarySkill pskill, std::vector<SecondarySkill> & skills, std::function<void(ui32)> callback)
  307. : CWindowObject(PLAYER_COLORED, "LVLUPBKG"),
  308. cb(callback)
  309. {
  310. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  311. LOCPLINT->showingDialog->setn(true);
  312. if(!skills.empty())
  313. {
  314. std::vector<std::shared_ptr<CSelectableComponent>> comps;
  315. for(auto & skill : skills)
  316. {
  317. auto comp = std::make_shared<CSelectableComponent>(CComponent::secskill, skill, hero->getSecSkillLevel(SecondarySkill(skill))+1, CComponent::medium);
  318. comps.push_back(comp);
  319. }
  320. box = std::make_shared<CComponentBox>(comps, Rect(75, 300, pos.w - 150, 100));
  321. }
  322. portrait = std::make_shared<CAnimImage>("PortraitsLarge", hero->portrait, 0, 170, 66);
  323. ok = std::make_shared<CButton>(Point(297, 413), "IOKAY", CButton::tooltip(), std::bind(&CLevelWindow::close, this), EShortcut::GLOBAL_ACCEPT);
  324. //%s has gained a level.
  325. mainTitle = std::make_shared<CLabel>(192, 33, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, boost::str(boost::format(CGI->generaltexth->allTexts[444]) % hero->getNameTranslated()));
  326. //%s is now a level %d %s.
  327. std::string levelTitleText = CGI->generaltexth->translate("core.genrltxt.445");
  328. boost::replace_first(levelTitleText, "%s", hero->getNameTranslated());
  329. boost::replace_first(levelTitleText, "%d", std::to_string(hero->level));
  330. boost::replace_first(levelTitleText, "%s", hero->type->heroClass->getNameTranslated());
  331. levelTitle = std::make_shared<CLabel>(192, 162, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, levelTitleText);
  332. skillIcon = std::make_shared<CAnimImage>("PSKIL42", pskill, 0, 174, 190);
  333. skillValue = std::make_shared<CLabel>(192, 253, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->primarySkillNames[pskill] + " +1");
  334. }
  335. CLevelWindow::~CLevelWindow()
  336. {
  337. //FIXME: call callback if there was nothing to select?
  338. if (box && box->selectedIndex() != -1)
  339. cb(box->selectedIndex());
  340. LOCPLINT->showingDialog->setn(false);
  341. }
  342. CTavernWindow::CTavernWindow(const CGObjectInstance * TavernObj)
  343. : CStatusbarWindow(PLAYER_COLORED, "TPTAVERN"),
  344. tavernObj(TavernObj)
  345. {
  346. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  347. std::vector<const CGHeroInstance*> h = LOCPLINT->cb->getAvailableHeroes(TavernObj);
  348. if(h.size() < 2)
  349. h.resize(2, nullptr);
  350. selected = 0;
  351. if(!h[0])
  352. selected = 1;
  353. if(!h[0] && !h[1])
  354. selected = -1;
  355. oldSelected = -1;
  356. h1 = std::make_shared<HeroPortrait>(selected, 0, 72, 299, h[0]);
  357. h2 = std::make_shared<HeroPortrait>(selected, 1, 162, 299, h[1]);
  358. title = std::make_shared<CLabel>(200, 35, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->jktexts[37]);
  359. cost = std::make_shared<CLabel>(320, 328, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, std::to_string(GameConstants::HERO_GOLD_COST));
  360. auto rumorText = boost::str(boost::format(CGI->generaltexth->allTexts[216]) % LOCPLINT->cb->getTavernRumor(tavernObj));
  361. rumor = std::make_shared<CTextBox>(rumorText, Rect(32, 190, 330, 68), 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  362. statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
  363. cancel = std::make_shared<CButton>(Point(310, 428), "ICANCEL.DEF", CButton::tooltip(CGI->generaltexth->tavernInfo[7]), std::bind(&CTavernWindow::close, this), EShortcut::GLOBAL_CANCEL);
  364. recruit = std::make_shared<CButton>(Point(272, 355), "TPTAV01.DEF", CButton::tooltip(), std::bind(&CTavernWindow::recruitb, this), EShortcut::GLOBAL_ACCEPT);
  365. thiefGuild = std::make_shared<CButton>(Point(22, 428), "TPTAV02.DEF", CButton::tooltip(CGI->generaltexth->tavernInfo[5]), std::bind(&CTavernWindow::thievesguildb, this), EShortcut::ADVENTURE_THIEVES_GUILD);
  366. if(LOCPLINT->cb->getResourceAmount(EGameResID::GOLD) < GameConstants::HERO_GOLD_COST) //not enough gold
  367. {
  368. recruit->addHoverText(CButton::NORMAL, CGI->generaltexth->tavernInfo[0]); //Cannot afford a Hero
  369. recruit->block(true);
  370. }
  371. else if(LOCPLINT->cb->howManyHeroes(true) >= CGI->settings()->getInteger(EGameSettings::HEROES_PER_PLAYER_TOTAL_CAP))
  372. {
  373. //Cannot recruit. You already have %d Heroes.
  374. recruit->addHoverText(CButton::NORMAL, boost::str(boost::format(CGI->generaltexth->tavernInfo[1]) % LOCPLINT->cb->howManyHeroes(true)));
  375. recruit->block(true);
  376. }
  377. else if(LOCPLINT->cb->howManyHeroes(false) >= CGI->settings()->getInteger(EGameSettings::HEROES_PER_PLAYER_ON_MAP_CAP))
  378. {
  379. //Cannot recruit. You already have %d Heroes.
  380. recruit->addHoverText(CButton::NORMAL, boost::str(boost::format(CGI->generaltexth->tavernInfo[1]) % LOCPLINT->cb->howManyHeroes(false)));
  381. recruit->block(true);
  382. }
  383. else if(LOCPLINT->castleInt && LOCPLINT->castleInt->town->visitingHero)
  384. {
  385. recruit->addHoverText(CButton::NORMAL, CGI->generaltexth->tavernInfo[2]); //Cannot recruit. You already have a Hero in this town.
  386. recruit->block(true);
  387. }
  388. else
  389. {
  390. if(selected == -1)
  391. recruit->block(true);
  392. }
  393. if(LOCPLINT->castleInt)
  394. CCS->videoh->open(LOCPLINT->castleInt->town->town->clientInfo.tavernVideo);
  395. else
  396. CCS->videoh->open("TAVERN.BIK");
  397. }
  398. void CTavernWindow::recruitb()
  399. {
  400. const CGHeroInstance *toBuy = (selected ? h2 : h1)->h;
  401. const CGObjectInstance *obj = tavernObj;
  402. close();
  403. LOCPLINT->cb->recruitHero(obj, toBuy);
  404. }
  405. void CTavernWindow::thievesguildb()
  406. {
  407. GH.pushIntT<CThievesGuildWindow>(tavernObj);
  408. }
  409. CTavernWindow::~CTavernWindow()
  410. {
  411. CCS->videoh->close();
  412. }
  413. void CTavernWindow::show(SDL_Surface * to)
  414. {
  415. CWindowObject::show(to);
  416. CCS->videoh->update(pos.x+70, pos.y+56, to, true, false);
  417. if(selected >= 0)
  418. {
  419. auto sel = selected ? h2 : h1;
  420. if (selected != oldSelected && !recruit->isBlocked())
  421. {
  422. // Selected hero just changed. Update RECRUIT button hover text if recruitment is allowed.
  423. oldSelected = selected;
  424. //Recruit %s the %s
  425. recruit->addHoverText(CButton::NORMAL, boost::str(boost::format(CGI->generaltexth->tavernInfo[3]) % sel->h->getNameTranslated() % sel->h->type->heroClass->getNameTranslated()));
  426. }
  427. printAtMiddleWBLoc(sel->description, 146, 395, FONT_SMALL, 200, Colors::WHITE, to);
  428. CSDL_Ext::drawBorder(to,sel->pos.x-2,sel->pos.y-2,sel->pos.w+4,sel->pos.h+4,Colors::BRIGHT_YELLOW);
  429. }
  430. }
  431. void CTavernWindow::HeroPortrait::clickLeft(tribool down, bool previousState)
  432. {
  433. if(h && previousState && !down)
  434. *_sel = _id;
  435. }
  436. void CTavernWindow::HeroPortrait::clickRight(tribool down, bool previousState)
  437. {
  438. if(h && down)
  439. GH.pushIntT<CRClickPopupInt>(std::make_shared<CHeroWindow>(h));
  440. }
  441. CTavernWindow::HeroPortrait::HeroPortrait(int & sel, int id, int x, int y, const CGHeroInstance * H)
  442. : CIntObject(LCLICK | RCLICK | HOVER),
  443. h(H), _sel(&sel), _id(id)
  444. {
  445. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  446. h = H;
  447. pos.x += x;
  448. pos.y += y;
  449. pos.w = 58;
  450. pos.h = 64;
  451. if(H)
  452. {
  453. hoverName = CGI->generaltexth->tavernInfo[4];
  454. boost::algorithm::replace_first(hoverName,"%s",H->getNameTranslated());
  455. int artifs = (int)h->artifactsWorn.size() + (int)h->artifactsInBackpack.size();
  456. for(int i=13; i<=17; i++) //war machines and spellbook don't count
  457. if(vstd::contains(h->artifactsWorn, ArtifactPosition(i)))
  458. artifs--;
  459. description = CGI->generaltexth->allTexts[215];
  460. boost::algorithm::replace_first(description, "%s", h->getNameTranslated());
  461. boost::algorithm::replace_first(description, "%d", std::to_string(h->level));
  462. boost::algorithm::replace_first(description, "%s", h->type->heroClass->getNameTranslated());
  463. boost::algorithm::replace_first(description, "%d", std::to_string(artifs));
  464. portrait = std::make_shared<CAnimImage>("portraitsLarge", h->portrait);
  465. }
  466. }
  467. void CTavernWindow::HeroPortrait::hover(bool on)
  468. {
  469. //Hoverable::hover(on);
  470. if(on)
  471. GH.statusbar->write(hoverName);
  472. else
  473. GH.statusbar->clear();
  474. }
  475. static const std::string QUICK_EXCHANGE_MOD_PREFIX = "quick-exchange";
  476. static const std::string QUICK_EXCHANGE_BG = QUICK_EXCHANGE_MOD_PREFIX + "/TRADEQE";
  477. static bool isQuickExchangeLayoutAvailable()
  478. {
  479. return CResourceHandler::get()->existsResource(ResourceID(std::string("SPRITES/") + QUICK_EXCHANGE_BG, EResType::IMAGE));
  480. }
  481. // Runs a task asynchronously with gamestate locking and waitTillRealize set to true
  482. class GsThread
  483. {
  484. private:
  485. std::function<void()> action;
  486. std::shared_ptr<CCallback> cb;
  487. public:
  488. static void run(std::function<void()> action)
  489. {
  490. std::shared_ptr<GsThread> instance(new GsThread(action));
  491. boost::thread(std::bind(&GsThread::staticRun, instance));
  492. }
  493. private:
  494. GsThread(std::function<void()> action)
  495. :action(action), cb(LOCPLINT->cb)
  496. {
  497. }
  498. static void staticRun(std::shared_ptr<GsThread> instance)
  499. {
  500. instance->run();
  501. }
  502. void run()
  503. {
  504. boost::shared_lock<boost::shared_mutex> gsLock(CGameState::mutex);
  505. auto originalWaitTillRealize = cb->waitTillRealize;
  506. auto originalUnlockGsWhenWating = cb->unlockGsWhenWaiting;
  507. cb->waitTillRealize = true;
  508. cb->unlockGsWhenWaiting = true;
  509. action();
  510. cb->waitTillRealize = originalWaitTillRealize;
  511. cb->unlockGsWhenWaiting = originalUnlockGsWhenWating;
  512. }
  513. };
  514. CExchangeController::CExchangeController(CExchangeWindow * view, ObjectInstanceID hero1, ObjectInstanceID hero2)
  515. :left(LOCPLINT->cb->getHero(hero1)), right(LOCPLINT->cb->getHero(hero2)), cb(LOCPLINT->cb), view(view)
  516. {
  517. }
  518. std::function<void()> CExchangeController::onMoveArmyToLeft()
  519. {
  520. return [&]() { moveArmy(false); };
  521. }
  522. std::function<void()> CExchangeController::onMoveArmyToRight()
  523. {
  524. return [&]() { moveArmy(true); };
  525. }
  526. std::vector<CArtifactInstance *> getBackpackArts(const CGHeroInstance * hero)
  527. {
  528. std::vector<CArtifactInstance *> result;
  529. for(auto slot : hero->artifactsInBackpack)
  530. {
  531. result.push_back(slot.artifact);
  532. }
  533. return result;
  534. }
  535. std::function<void()> CExchangeController::onSwapArtifacts()
  536. {
  537. return [&]()
  538. {
  539. GsThread::run([=]
  540. {
  541. cb->bulkMoveArtifacts(left->id, right->id, true);
  542. });
  543. };
  544. }
  545. std::function<void()> CExchangeController::onMoveArtifactsToLeft()
  546. {
  547. return [&]() { moveArtifacts(false); };
  548. }
  549. std::function<void()> CExchangeController::onMoveArtifactsToRight()
  550. {
  551. return [&]() { moveArtifacts(true); };
  552. }
  553. std::vector<std::pair<SlotID, CStackInstance *>> getStacks(const CArmedInstance * source)
  554. {
  555. auto slots = source->Slots();
  556. return std::vector<std::pair<SlotID, CStackInstance *>>(slots.begin(), slots.end());
  557. }
  558. std::function<void()> CExchangeController::onSwapArmy()
  559. {
  560. return [&]()
  561. {
  562. GsThread::run([=]
  563. {
  564. if(left->tempOwner != cb->getMyColor()
  565. || right->tempOwner != cb->getMyColor())
  566. {
  567. return;
  568. }
  569. auto leftSlots = getStacks(left);
  570. auto rightSlots = getStacks(right);
  571. auto i = leftSlots.begin(), j = rightSlots.begin();
  572. for(; i != leftSlots.end() && j != rightSlots.end(); i++, j++)
  573. {
  574. cb->swapCreatures(left, right, i->first, j->first);
  575. }
  576. if(i != leftSlots.end())
  577. {
  578. for(; i != leftSlots.end(); i++)
  579. {
  580. cb->swapCreatures(left, right, i->first, right->getFreeSlot());
  581. }
  582. }
  583. else if(j != rightSlots.end())
  584. {
  585. for(; j != rightSlots.end(); j++)
  586. {
  587. cb->swapCreatures(left, right, left->getFreeSlot(), j->first);
  588. }
  589. }
  590. });
  591. };
  592. }
  593. std::function<void()> CExchangeController::onMoveStackToLeft(SlotID slotID)
  594. {
  595. return [=]()
  596. {
  597. if(right->tempOwner != cb->getMyColor())
  598. {
  599. return;
  600. }
  601. moveStack(right, left, slotID);
  602. };
  603. }
  604. std::function<void()> CExchangeController::onMoveStackToRight(SlotID slotID)
  605. {
  606. return [=]()
  607. {
  608. if(left->tempOwner != cb->getMyColor())
  609. {
  610. return;
  611. }
  612. moveStack(left, right, slotID);
  613. };
  614. }
  615. void CExchangeController::moveStack(
  616. const CGHeroInstance * source,
  617. const CGHeroInstance * target,
  618. SlotID sourceSlot)
  619. {
  620. auto creature = source->getCreature(sourceSlot);
  621. SlotID targetSlot = target->getSlotFor(creature);
  622. if(targetSlot.validSlot())
  623. {
  624. if(source->stacksCount() == 1 && source->needsLastStack())
  625. {
  626. cb->splitStack(
  627. source,
  628. target,
  629. sourceSlot,
  630. targetSlot,
  631. target->getStackCount(targetSlot) + source->getStackCount(sourceSlot) - 1);
  632. }
  633. else
  634. {
  635. cb->mergeOrSwapStacks(source, target, sourceSlot, targetSlot);
  636. }
  637. }
  638. }
  639. void CExchangeController::moveArmy(bool leftToRight)
  640. {
  641. const CGHeroInstance * source = leftToRight ? left : right;
  642. const CGHeroInstance * target = leftToRight ? right : left;
  643. const CGarrisonSlot * selection = this->view->getSelectedSlotID();
  644. SlotID slot;
  645. if(source->tempOwner != cb->getMyColor())
  646. {
  647. return;
  648. }
  649. if(selection && selection->our() && selection->getObj() == source)
  650. {
  651. slot = selection->getSlot();
  652. }
  653. else
  654. {
  655. auto weakestSlot = vstd::minElementByFun(
  656. source->Slots(),
  657. [](const std::pair<SlotID, CStackInstance *> & s) -> int
  658. {
  659. return s.second->getCreatureID().toCreature()->getAIValue();
  660. });
  661. slot = weakestSlot->first;
  662. }
  663. cb->bulkMoveArmy(source->id, target->id, slot);
  664. }
  665. void CExchangeController::moveArtifacts(bool leftToRight)
  666. {
  667. const CGHeroInstance * source = leftToRight ? left : right;
  668. const CGHeroInstance * target = leftToRight ? right : left;
  669. if(source->tempOwner != cb->getMyColor())
  670. {
  671. return;
  672. }
  673. GsThread::run([=]
  674. {
  675. cb->bulkMoveArtifacts(source->id, target->id, false);
  676. });
  677. }
  678. void CExchangeController::moveArtifact(
  679. const CGHeroInstance * source,
  680. const CGHeroInstance * target,
  681. ArtifactPosition srcPosition)
  682. {
  683. auto srcLocation = ArtifactLocation(source, srcPosition);
  684. auto dstLocation = ArtifactLocation(target,
  685. ArtifactUtils::getArtAnyPosition(target, source->getArt(srcPosition)->getTypeId()));
  686. cb->swapArtifacts(srcLocation, dstLocation);
  687. }
  688. CExchangeWindow::CExchangeWindow(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID queryID)
  689. : CStatusbarWindow(PLAYER_COLORED | BORDERED, isQuickExchangeLayoutAvailable() ? QUICK_EXCHANGE_BG : "TRADE2"),
  690. controller(this, hero1, hero2),
  691. moveStackLeftButtons(),
  692. moveStackRightButtons()
  693. {
  694. const bool qeLayout = isQuickExchangeLayoutAvailable();
  695. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  696. heroInst[0] = LOCPLINT->cb->getHero(hero1);
  697. heroInst[1] = LOCPLINT->cb->getHero(hero2);
  698. auto genTitle = [](const CGHeroInstance * h)
  699. {
  700. boost::format fmt(CGI->generaltexth->allTexts[138]);
  701. fmt % h->getNameTranslated() % h->level % h->type->heroClass->getNameTranslated();
  702. return boost::str(fmt);
  703. };
  704. titles[0] = std::make_shared<CLabel>(147, 25, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, genTitle(heroInst[0]));
  705. titles[1] = std::make_shared<CLabel>(653, 25, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, genTitle(heroInst[1]));
  706. auto PSKIL32 = std::make_shared<CAnimation>("PSKIL32");
  707. PSKIL32->preload();
  708. auto SECSK32 = std::make_shared<CAnimation>("SECSK32");
  709. for(int g = 0; g < 4; ++g)
  710. {
  711. if (qeLayout)
  712. primSkillImages.push_back(std::make_shared<CAnimImage>(PSKIL32, g, Rect(389, 12 + 26 * g, 22, 22)));
  713. else
  714. primSkillImages.push_back(std::make_shared<CAnimImage>(PSKIL32, g, 0, 385, 19 + 36 * g));
  715. }
  716. for(int leftRight : {0, 1})
  717. {
  718. const CGHeroInstance * hero = heroInst.at(leftRight);
  719. herosWArt[leftRight] = std::make_shared<CHeroWithMaybePickedArtifact>(this, hero);
  720. for(int m=0; m<GameConstants::PRIMARY_SKILLS; ++m)
  721. primSkillValues[leftRight].push_back(std::make_shared<CLabel>(352 + (qeLayout ? 96 : 93) * leftRight, (qeLayout ? 22 : 35) + (qeLayout ? 26 : 36) * m, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE));
  722. for(int m=0; m < hero->secSkills.size(); ++m)
  723. secSkillIcons[leftRight].push_back(std::make_shared<CAnimImage>(SECSK32, 0, 0, 32 + 36 * m + 454 * leftRight, qeLayout ? 83 : 88));
  724. specImages[leftRight] = std::make_shared<CAnimImage>("UN32", hero->type->imageIndex, 0, 67 + 490 * leftRight, qeLayout ? 41 : 45);
  725. expImages[leftRight] = std::make_shared<CAnimImage>(PSKIL32, 4, 0, 103 + 490 * leftRight, qeLayout ? 41 : 45);
  726. expValues[leftRight] = std::make_shared<CLabel>(119 + 490 * leftRight, qeLayout ? 66 : 71, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  727. manaImages[leftRight] = std::make_shared<CAnimImage>(PSKIL32, 5, 0, 139 + 490 * leftRight, qeLayout ? 41 : 45);
  728. manaValues[leftRight] = std::make_shared<CLabel>(155 + 490 * leftRight, qeLayout ? 66 : 71, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  729. }
  730. portraits[0] = std::make_shared<CAnimImage>("PortraitsLarge", heroInst[0]->portrait, 0, 257, 13);
  731. portraits[1] = std::make_shared<CAnimImage>("PortraitsLarge", heroInst[1]->portrait, 0, 485, 13);
  732. artifs[0] = std::make_shared<CArtifactsOfHeroMain>(Point(-334, 150));
  733. artifs[0]->setHero(heroInst[0]);
  734. artifs[1] = std::make_shared<CArtifactsOfHeroMain>(Point(98, 150));
  735. artifs[1]->setHero(heroInst[1]);
  736. addSet(artifs[0]);
  737. addSet(artifs[1]);
  738. for(int g=0; g<4; ++g)
  739. {
  740. primSkillAreas.push_back(std::make_shared<LRClickableAreaWTextComp>());
  741. if (qeLayout)
  742. primSkillAreas[g]->pos = Rect(Point(pos.x + 324, pos.y + 12 + 26 * g), Point(152, 22));
  743. else
  744. primSkillAreas[g]->pos = Rect(Point(pos.x + 329, pos.y + 19 + 36 * g), Point(140, 32));
  745. primSkillAreas[g]->text = CGI->generaltexth->arraytxt[2+g];
  746. primSkillAreas[g]->type = g;
  747. primSkillAreas[g]->bonusValue = 0;
  748. primSkillAreas[g]->baseType = 0;
  749. primSkillAreas[g]->hoverText = CGI->generaltexth->heroscrn[1];
  750. boost::replace_first(primSkillAreas[g]->hoverText, "%s", CGI->generaltexth->primarySkillNames[g]);
  751. }
  752. //heroes related thing
  753. for(int b=0; b < heroInst.size(); b++)
  754. {
  755. const CGHeroInstance * hero = heroInst.at(b);
  756. //secondary skill's clickable areas
  757. for(int g=0; g<hero->secSkills.size(); ++g)
  758. {
  759. int skill = hero->secSkills[g].first,
  760. level = hero->secSkills[g].second; // <1, 3>
  761. secSkillAreas[b].push_back(std::make_shared<LRClickableAreaWTextComp>());
  762. secSkillAreas[b][g]->pos = Rect(Point(pos.x + 32 + g * 36 + b * 454 , pos.y + (qeLayout ? 83 : 88)), Point(32, 32) );
  763. secSkillAreas[b][g]->baseType = 1;
  764. secSkillAreas[b][g]->type = skill;
  765. secSkillAreas[b][g]->bonusValue = level;
  766. secSkillAreas[b][g]->text = CGI->skillh->getByIndex(skill)->getDescriptionTranslated(level);
  767. secSkillAreas[b][g]->hoverText = CGI->generaltexth->heroscrn[21];
  768. boost::algorithm::replace_first(secSkillAreas[b][g]->hoverText, "%s", CGI->generaltexth->levels[level - 1]);
  769. boost::algorithm::replace_first(secSkillAreas[b][g]->hoverText, "%s", CGI->skillh->getByIndex(skill)->getNameTranslated());
  770. }
  771. heroAreas[b] = std::make_shared<CHeroArea>(257 + 228*b, 13, hero);
  772. specialtyAreas[b] = std::make_shared<LRClickableAreaWText>();
  773. specialtyAreas[b]->pos = Rect(Point(pos.x + 69 + 490 * b, pos.y + (qeLayout ? 41 : 45)), Point(32, 32));
  774. specialtyAreas[b]->hoverText = CGI->generaltexth->heroscrn[27];
  775. specialtyAreas[b]->text = hero->type->getSpecialtyDescriptionTranslated();
  776. experienceAreas[b] = std::make_shared<LRClickableAreaWText>();
  777. experienceAreas[b]->pos = Rect(Point(pos.x + 105 + 490 * b, pos.y + (qeLayout ? 41 : 45)), Point(32, 32));
  778. experienceAreas[b]->hoverText = CGI->generaltexth->heroscrn[9];
  779. experienceAreas[b]->text = CGI->generaltexth->allTexts[2];
  780. boost::algorithm::replace_first(experienceAreas[b]->text, "%d", std::to_string(hero->level));
  781. boost::algorithm::replace_first(experienceAreas[b]->text, "%d", std::to_string(CGI->heroh->reqExp(hero->level+1)));
  782. boost::algorithm::replace_first(experienceAreas[b]->text, "%d", std::to_string(hero->exp));
  783. spellPointsAreas[b] = std::make_shared<LRClickableAreaWText>();
  784. spellPointsAreas[b]->pos = Rect(Point(pos.x + 141 + 490 * b, pos.y + (qeLayout ? 41 : 45)), Point(32, 32));
  785. spellPointsAreas[b]->hoverText = CGI->generaltexth->heroscrn[22];
  786. spellPointsAreas[b]->text = CGI->generaltexth->allTexts[205];
  787. boost::algorithm::replace_first(spellPointsAreas[b]->text, "%s", hero->getNameTranslated());
  788. boost::algorithm::replace_first(spellPointsAreas[b]->text, "%d", std::to_string(hero->mana));
  789. boost::algorithm::replace_first(spellPointsAreas[b]->text, "%d", std::to_string(hero->manaLimit()));
  790. morale[b] = std::make_shared<MoraleLuckBox>(true, Rect(Point(176 + 490 * b, 39), Point(32, 32)), true);
  791. luck[b] = std::make_shared<MoraleLuckBox>(false, Rect(Point(212 + 490 * b, 39), Point(32, 32)), true);
  792. }
  793. quit = std::make_shared<CButton>(Point(732, 567), "IOKAY.DEF", CGI->generaltexth->zelp[600], std::bind(&CExchangeWindow::close, this), EShortcut::GLOBAL_ACCEPT);
  794. if(queryID.getNum() > 0)
  795. quit->addCallback([=](){ LOCPLINT->cb->selectionMade(0, queryID); });
  796. questlogButton[0] = std::make_shared<CButton>(Point( 10, qeLayout ? 39 : 44), "hsbtns4.def", CButton::tooltip(CGI->generaltexth->heroscrn[0]), std::bind(&CExchangeWindow::questlog, this, 0));
  797. questlogButton[1] = std::make_shared<CButton>(Point(740, qeLayout ? 39 : 44), "hsbtns4.def", CButton::tooltip(CGI->generaltexth->heroscrn[0]), std::bind(&CExchangeWindow::questlog, this, 1));
  798. Rect barRect(5, 578, 725, 18);
  799. statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), barRect, 5, 578));
  800. //garrison interface
  801. garr = std::make_shared<CGarrisonInt>(69, qeLayout ? 122 : 131, 4, Point(418,0), heroInst[0], heroInst[1], true, true);
  802. auto splitButtonCallback = [&](){ garr->splitClick(); };
  803. garr->addSplitBtn(std::make_shared<CButton>( Point( 10, qeLayout ? 122 : 132), "TSBTNS.DEF", CButton::tooltip(CGI->generaltexth->tcommands[3]), splitButtonCallback));
  804. garr->addSplitBtn(std::make_shared<CButton>( Point(744, qeLayout ? 122 : 132), "TSBTNS.DEF", CButton::tooltip(CGI->generaltexth->tcommands[3]), splitButtonCallback));
  805. if(qeLayout)
  806. {
  807. moveAllGarrButtonLeft = std::make_shared<CButton>(Point(325, 118), QUICK_EXCHANGE_MOD_PREFIX + "/armRight.DEF", CButton::tooltip(CGI->generaltexth->qeModCommands[1]), controller.onMoveArmyToRight());
  808. echangeGarrButton = std::make_shared<CButton>(Point(377, 118), QUICK_EXCHANGE_MOD_PREFIX + "/swapAll.DEF", CButton::tooltip(CGI->generaltexth->qeModCommands[2]), controller.onSwapArmy());
  809. moveAllGarrButtonRight = std::make_shared<CButton>(Point(425, 118), QUICK_EXCHANGE_MOD_PREFIX + "/armLeft.DEF", CButton::tooltip(CGI->generaltexth->qeModCommands[1]), controller.onMoveArmyToLeft());
  810. moveArtifactsButtonLeft = std::make_shared<CButton>(Point(325, 154), QUICK_EXCHANGE_MOD_PREFIX + "/artRight.DEF", CButton::tooltip(CGI->generaltexth->qeModCommands[3]), controller.onMoveArtifactsToRight());
  811. echangeArtifactsButton = std::make_shared<CButton>(Point(377, 154), QUICK_EXCHANGE_MOD_PREFIX + "/swapAll.DEF", CButton::tooltip(CGI->generaltexth->qeModCommands[4]), controller.onSwapArtifacts());
  812. moveArtifactsButtonRight = std::make_shared<CButton>(Point(425, 154), QUICK_EXCHANGE_MOD_PREFIX + "/artLeft.DEF", CButton::tooltip(CGI->generaltexth->qeModCommands[3]), controller.onMoveArtifactsToLeft());
  813. for(int i = 0; i < GameConstants::ARMY_SIZE; i++)
  814. {
  815. moveStackLeftButtons.push_back(
  816. std::make_shared<CButton>(
  817. Point(484 + 35 * i, 154),
  818. QUICK_EXCHANGE_MOD_PREFIX + "/unitLeft.DEF",
  819. CButton::tooltip(CGI->generaltexth->qeModCommands[1]),
  820. controller.onMoveStackToLeft(SlotID(i))));
  821. moveStackRightButtons.push_back(
  822. std::make_shared<CButton>(
  823. Point(66 + 35 * i, 154),
  824. QUICK_EXCHANGE_MOD_PREFIX + "/unitRight.DEF",
  825. CButton::tooltip(CGI->generaltexth->qeModCommands[1]),
  826. controller.onMoveStackToRight(SlotID(i))));
  827. }
  828. }
  829. updateWidgets();
  830. }
  831. const CGarrisonSlot * CExchangeWindow::getSelectedSlotID() const
  832. {
  833. return garr->getSelection();
  834. }
  835. void CExchangeWindow::updateGarrisons()
  836. {
  837. garr->recreateSlots();
  838. updateWidgets();
  839. }
  840. void CExchangeWindow::questlog(int whichHero)
  841. {
  842. CCS->curh->dragAndDropCursor(nullptr);
  843. LOCPLINT->showQuestLog();
  844. }
  845. void CExchangeWindow::updateWidgets()
  846. {
  847. for(size_t leftRight : {0, 1})
  848. {
  849. const CGHeroInstance * hero = heroInst.at(leftRight);
  850. for(int m=0; m<GameConstants::PRIMARY_SKILLS; ++m)
  851. {
  852. auto value = herosWArt[leftRight]->getPrimSkillLevel(static_cast<PrimarySkill::PrimarySkill>(m));
  853. primSkillValues[leftRight][m]->setText(std::to_string(value));
  854. }
  855. for(int m=0; m < hero->secSkills.size(); ++m)
  856. {
  857. int id = hero->secSkills[m].first;
  858. int level = hero->secSkills[m].second;
  859. secSkillIcons[leftRight][m]->setFrame(2 + id * 3 + level);
  860. }
  861. expValues[leftRight]->setText(TextOperations::formatMetric(hero->exp, 3));
  862. manaValues[leftRight]->setText(TextOperations::formatMetric(hero->mana, 3));
  863. morale[leftRight]->set(hero);
  864. luck[leftRight]->set(hero);
  865. }
  866. }
  867. CShipyardWindow::CShipyardWindow(const TResources & cost, int state, BoatId boatType, const std::function<void()> & onBuy)
  868. : CStatusbarWindow(PLAYER_COLORED, "TPSHIP")
  869. {
  870. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  871. bgWater = std::make_shared<CPicture>("TPSHIPBK", 100, 69);
  872. std::string boatFilenames[3] = {"AB01_", "AB02_", "AB03_"};
  873. Point waterCenter = Point(bgWater->pos.x+bgWater->pos.w/2, bgWater->pos.y+bgWater->pos.h/2);
  874. bgShip = std::make_shared<CAnimImage>(boatFilenames[boatType.getNum()], 0, 7, 120, 96, 0);
  875. bgShip->center(waterCenter);
  876. // Create resource icons and costs.
  877. std::string goldValue = std::to_string(cost[EGameResID::GOLD]);
  878. std::string woodValue = std::to_string(cost[EGameResID::WOOD]);
  879. goldCost = std::make_shared<CLabel>(118, 294, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, goldValue);
  880. woodCost = std::make_shared<CLabel>(212, 294, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, woodValue);
  881. goldPic = std::make_shared<CAnimImage>("RESOURCE",GameResID(EGameResID::GOLD), 0, 100, 244);
  882. woodPic = std::make_shared<CAnimImage>("RESOURCE", GameResID(EGameResID::WOOD), 0, 196, 244);
  883. quit = std::make_shared<CButton>(Point(224, 312), "ICANCEL", CButton::tooltip(CGI->generaltexth->allTexts[599]), std::bind(&CShipyardWindow::close, this), EShortcut::GLOBAL_CANCEL);
  884. build = std::make_shared<CButton>(Point(42, 312), "IBUY30", CButton::tooltip(CGI->generaltexth->allTexts[598]), std::bind(&CShipyardWindow::close, this), EShortcut::GLOBAL_ACCEPT);
  885. build->addCallback(onBuy);
  886. for(GameResID i = EGameResID::WOOD; i <= EGameResID::GOLD; ++i)
  887. {
  888. if(cost[i] > LOCPLINT->cb->getResourceAmount(i))
  889. {
  890. build->block(true);
  891. break;
  892. }
  893. }
  894. statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
  895. title = std::make_shared<CLabel>(164, 27, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->jktexts[13]);
  896. costLabel = std::make_shared<CLabel>(164, 220, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->jktexts[14]);
  897. }
  898. void CTransformerWindow::CItem::move()
  899. {
  900. if(left)
  901. moveBy(Point(289, 0));
  902. else
  903. moveBy(Point(-289, 0));
  904. left = !left;
  905. }
  906. void CTransformerWindow::CItem::clickLeft(tribool down, bool previousState)
  907. {
  908. if(previousState && (!down))
  909. {
  910. move();
  911. parent->redraw();
  912. }
  913. }
  914. void CTransformerWindow::CItem::update()
  915. {
  916. icon->setFrame(parent->army->getCreature(SlotID(id))->getId() + 2);
  917. }
  918. CTransformerWindow::CItem::CItem(CTransformerWindow * parent_, int size_, int id_)
  919. : CIntObject(LCLICK),
  920. id(id_),
  921. size(size_),
  922. parent(parent_)
  923. {
  924. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  925. left = true;
  926. pos.w = 58;
  927. pos.h = 64;
  928. pos.x += 45 + (id%3)*83 + id/6*83;
  929. pos.y += 109 + (id/3)*98;
  930. icon = std::make_shared<CAnimImage>("TWCRPORT", parent->army->getCreature(SlotID(id))->getId() + 2);
  931. count = std::make_shared<CLabel>(28, 76,FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, std::to_string(size));
  932. }
  933. void CTransformerWindow::makeDeal()
  934. {
  935. for(auto & elem : items)
  936. {
  937. if(!elem->left)
  938. LOCPLINT->cb->trade(market, EMarketMode::CREATURE_UNDEAD, elem->id, 0, 0, hero);
  939. }
  940. }
  941. void CTransformerWindow::addAll()
  942. {
  943. for(auto & elem : items)
  944. {
  945. if(elem->left)
  946. elem->move();
  947. }
  948. redraw();
  949. }
  950. void CTransformerWindow::updateGarrisons()
  951. {
  952. for(auto & item : items)
  953. item->update();
  954. }
  955. CTransformerWindow::CTransformerWindow(const IMarket * _market, const CGHeroInstance * _hero)
  956. : CStatusbarWindow(PLAYER_COLORED, "SKTRNBK"),
  957. hero(_hero),
  958. market(_market)
  959. {
  960. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  961. if(hero)
  962. army = hero;
  963. else
  964. army = dynamic_cast<const CArmedInstance *>(market); //for town only
  965. if(army)
  966. {
  967. for(int i = 0; i < GameConstants::ARMY_SIZE; i++)
  968. {
  969. if(army->getCreature(SlotID(i)))
  970. items.push_back(std::make_shared<CItem>(this, army->getStackCount(SlotID(i)), i));
  971. }
  972. }
  973. all = std::make_shared<CButton>(Point(146, 416), "ALTARMY.DEF", CGI->generaltexth->zelp[590], [&](){ addAll(); }, EShortcut::RECRUITMENT_UPGRADE_ALL);
  974. convert = std::make_shared<CButton>(Point(269, 416), "ALTSACR.DEF", CGI->generaltexth->zelp[591], [&](){ makeDeal(); }, EShortcut::GLOBAL_ACCEPT);
  975. cancel = std::make_shared<CButton>(Point(392, 416), "ICANCEL.DEF", CGI->generaltexth->zelp[592], [&](){ close(); },EShortcut::GLOBAL_CANCEL);
  976. statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
  977. titleLeft = std::make_shared<CLabel>(153, 29,FONT_SMALL, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[485]);//holding area
  978. titleRight = std::make_shared<CLabel>(153+295, 29, FONT_SMALL, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[486]);//transformer
  979. helpLeft = std::make_shared<CTextBox>(CGI->generaltexth->allTexts[487], Rect(26, 56, 255, 40), 0, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW);//move creatures to create skeletons
  980. helpRight = std::make_shared<CTextBox>(CGI->generaltexth->allTexts[488], Rect(320, 56, 255, 40), 0, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW);//creatures here will become skeletons
  981. }
  982. CUniversityWindow::CItem::CItem(CUniversityWindow * _parent, int _ID, int X, int Y)
  983. : CIntObject(LCLICK | RCLICK | HOVER),
  984. ID(_ID),
  985. parent(_parent)
  986. {
  987. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  988. pos.x += X;
  989. pos.y += Y;
  990. topBar = std::make_shared<CAnimImage>(parent->bars, 0, 0, -28, -22);
  991. bottomBar = std::make_shared<CAnimImage>(parent->bars, 0, 0, -28, 48);
  992. icon = std::make_shared<CAnimImage>("SECSKILL", _ID * 3 + 3, 0);
  993. name = std::make_shared<CLabel>(22, -13, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->skillh->getByIndex(ID)->getNameTranslated());
  994. level = std::make_shared<CLabel>(22, 57, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->levels[0]);
  995. pos.h = icon->pos.h;
  996. pos.w = icon->pos.w;
  997. }
  998. void CUniversityWindow::CItem::clickLeft(tribool down, bool previousState)
  999. {
  1000. if(previousState && (!down))
  1001. {
  1002. if(state() == 2)
  1003. GH.pushIntT<CUnivConfirmWindow>(parent, ID, LOCPLINT->cb->getResourceAmount(EGameResID::GOLD) >= 2000);
  1004. }
  1005. }
  1006. void CUniversityWindow::CItem::clickRight(tribool down, bool previousState)
  1007. {
  1008. if(down)
  1009. {
  1010. CRClickPopup::createAndPush(CGI->skillh->getByIndex(ID)->getDescriptionTranslated(1), std::make_shared<CComponent>(CComponent::secskill, ID, 1));
  1011. }
  1012. }
  1013. void CUniversityWindow::CItem::hover(bool on)
  1014. {
  1015. if(on)
  1016. GH.statusbar->write(CGI->skillh->getByIndex(ID)->getNameTranslated());
  1017. else
  1018. GH.statusbar->clear();
  1019. }
  1020. int CUniversityWindow::CItem::state()
  1021. {
  1022. if(parent->hero->getSecSkillLevel(SecondarySkill(ID)))//hero know this skill
  1023. return 1;
  1024. if(!parent->hero->canLearnSkill(SecondarySkill(ID)))//can't learn more skills
  1025. return 0;
  1026. return 2;
  1027. }
  1028. void CUniversityWindow::CItem::showAll(SDL_Surface * to)
  1029. {
  1030. //TODO: update when state actually changes
  1031. auto stateIndex = state();
  1032. topBar->setFrame(stateIndex);
  1033. bottomBar->setFrame(stateIndex);
  1034. CIntObject::showAll(to);
  1035. }
  1036. CUniversityWindow::CUniversityWindow(const CGHeroInstance * _hero, const IMarket * _market)
  1037. : CStatusbarWindow(PLAYER_COLORED, "UNIVERS1"),
  1038. hero(_hero),
  1039. market(_market)
  1040. {
  1041. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  1042. bars = std::make_shared<CAnimation>();
  1043. bars->setCustom("UNIVRED", 0, 0);
  1044. bars->setCustom("UNIVGOLD", 1, 0);
  1045. bars->setCustom("UNIVGREN", 2, 0);
  1046. bars->preload();
  1047. std::string titleStr = CGI->generaltexth->allTexts[602];
  1048. std::string speechStr = CGI->generaltexth->allTexts[603];
  1049. if(auto town = dynamic_cast<const CGTownInstance *>(_market))
  1050. {
  1051. auto faction = town->town->faction->getId();
  1052. auto bid = town->town->getSpecialBuilding(BuildingSubID::MAGIC_UNIVERSITY)->bid;
  1053. titlePic = std::make_shared<CAnimImage>((*CGI->townh)[faction]->town->clientInfo.buildingsIcons, bid);
  1054. }
  1055. else if(auto uni = dynamic_cast<const CGUniversity *>(_market); uni->appearance)
  1056. {
  1057. titlePic = std::make_shared<CAnimImage>(uni->appearance->animationFile, 0);
  1058. titleStr = uni->title;
  1059. speechStr = uni->speech;
  1060. }
  1061. else
  1062. {
  1063. titlePic = std::make_shared<CPicture>("UNIVBLDG");
  1064. }
  1065. titlePic->center(Point(232 + pos.x, 76 + pos.y));
  1066. clerkSpeech = std::make_shared<CTextBox>(speechStr, Rect(24, 129, 413, 70), 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  1067. title = std::make_shared<CLabel>(231, 26, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW, titleStr);
  1068. std::vector<int> goods = market->availableItemsIds(EMarketMode::RESOURCE_SKILL);
  1069. for(int i=0; i<goods.size(); i++)//prepare clickable items
  1070. items.push_back(std::make_shared<CItem>(this, goods[i], 54+i*104, 234));
  1071. cancel = std::make_shared<CButton>(Point(200, 313), "IOKAY.DEF", CGI->generaltexth->zelp[632], [&](){ close(); }, EShortcut::GLOBAL_ACCEPT);
  1072. statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
  1073. }
  1074. void CUniversityWindow::makeDeal(int skill)
  1075. {
  1076. LOCPLINT->cb->trade(market, EMarketMode::RESOURCE_SKILL, 6, skill, 1, hero);
  1077. }
  1078. CUnivConfirmWindow::CUnivConfirmWindow(CUniversityWindow * owner_, int SKILL, bool available)
  1079. : CStatusbarWindow(PLAYER_COLORED, "UNIVERS2.PCX"),
  1080. owner(owner_)
  1081. {
  1082. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  1083. std::string text = CGI->generaltexth->allTexts[608];
  1084. boost::replace_first(text, "%s", CGI->generaltexth->levels[0]);
  1085. boost::replace_first(text, "%s", CGI->skillh->getByIndex(SKILL)->getNameTranslated());
  1086. boost::replace_first(text, "%d", "2000");
  1087. clerkSpeech = std::make_shared<CTextBox>(text, Rect(24, 129, 413, 70), 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  1088. name = std::make_shared<CLabel>(230, 37, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->skillh->getByIndex(SKILL)->getNameTranslated());
  1089. icon = std::make_shared<CAnimImage>("SECSKILL", SKILL*3+3, 0, 211, 51);
  1090. level = std::make_shared<CLabel>(230, 107, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->levels[1]);
  1091. costIcon = std::make_shared<CAnimImage>("RESOURCE", GameResID(EGameResID::GOLD), 0, 210, 210);
  1092. cost = std::make_shared<CLabel>(230, 267, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, "2000");
  1093. std::string hoverText = CGI->generaltexth->allTexts[609];
  1094. boost::replace_first(hoverText, "%s", CGI->generaltexth->levels[0]+ " " + CGI->skillh->getByIndex(SKILL)->getNameTranslated());
  1095. text = CGI->generaltexth->zelp[633].second;
  1096. boost::replace_first(text, "%s", CGI->generaltexth->levels[0]);
  1097. boost::replace_first(text, "%s", CGI->skillh->getByIndex(SKILL)->getNameTranslated());
  1098. boost::replace_first(text, "%d", "2000");
  1099. confirm = std::make_shared<CButton>(Point(148, 299), "IBY6432.DEF", CButton::tooltip(hoverText, text), [=](){makeDeal(SKILL);}, EShortcut::GLOBAL_ACCEPT);
  1100. confirm->block(!available);
  1101. cancel = std::make_shared<CButton>(Point(252,299), "ICANCEL.DEF", CGI->generaltexth->zelp[631], [&](){ close(); }, EShortcut::GLOBAL_CANCEL);
  1102. statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
  1103. }
  1104. void CUnivConfirmWindow::makeDeal(int skill)
  1105. {
  1106. owner->makeDeal(skill);
  1107. close();
  1108. }
  1109. CGarrisonWindow::CGarrisonWindow(const CArmedInstance * up, const CGHeroInstance * down, bool removableUnits)
  1110. : CWindowObject(PLAYER_COLORED, "GARRISON")
  1111. {
  1112. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  1113. garr = std::make_shared<CGarrisonInt>(92, 127, 4, Point(0,96), up, down, removableUnits);
  1114. {
  1115. auto split = std::make_shared<CButton>(Point(88, 314), "IDV6432.DEF", CButton::tooltip(CGI->generaltexth->tcommands[3], ""), [&](){ garr->splitClick(); } );
  1116. garr->addSplitBtn(split);
  1117. }
  1118. quit = std::make_shared<CButton>(Point(399, 314), "IOK6432.DEF", CButton::tooltip(CGI->generaltexth->tcommands[8], ""), [&](){ close(); }, EShortcut::GLOBAL_ACCEPT);
  1119. std::string titleText;
  1120. if(down->tempOwner == up->tempOwner)
  1121. {
  1122. titleText = CGI->generaltexth->allTexts[709];
  1123. }
  1124. else
  1125. {
  1126. //assume that this is joining monsters dialog
  1127. if(up->Slots().size() > 0)
  1128. {
  1129. titleText = CGI->generaltexth->allTexts[35];
  1130. boost::algorithm::replace_first(titleText, "%s", up->Slots().begin()->second->type->getNamePluralTranslated());
  1131. }
  1132. else
  1133. {
  1134. logGlobal->error("Invalid armed instance for garrison window.");
  1135. }
  1136. }
  1137. title = std::make_shared<CLabel>(275, 30, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, titleText);
  1138. banner = std::make_shared<CAnimImage>("CREST58", up->getOwner().getNum(), 0, 28, 124);
  1139. portrait = std::make_shared<CAnimImage>("PortraitsLarge", down->portrait, 0, 29, 222);
  1140. }
  1141. void CGarrisonWindow::updateGarrisons()
  1142. {
  1143. garr->recreateSlots();
  1144. }
  1145. CHillFortWindow::CHillFortWindow(const CGHeroInstance * visitor, const CGObjectInstance * object)
  1146. : CStatusbarWindow(PLAYER_COLORED, "APHLFTBK"),
  1147. fort(object),
  1148. hero(visitor)
  1149. {
  1150. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  1151. title = std::make_shared<CLabel>(325, 32, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, fort->getObjectName());
  1152. heroPic = std::make_shared<CHeroArea>(30, 60, hero);
  1153. for(int i=0; i < resCount; i++)
  1154. {
  1155. totalIcons[i] = std::make_shared<CAnimImage>("SMALRES", i, 0, 104 + 76 * i, 237);
  1156. totalLabels[i] = std::make_shared<CLabel>(166 + 76 * i, 253, FONT_SMALL, ETextAlignment::BOTTOMRIGHT);
  1157. }
  1158. for(int i = 0; i < slotsCount; i++)
  1159. {
  1160. upgrade[i] = std::make_shared<CButton>(Point(107 + i * 76, 171), "", CButton::tooltip(getTextForSlot(SlotID(i))), [=](){ makeDeal(SlotID(i)); }, vstd::next(EShortcut::SELECT_INDEX_1, i));
  1161. for(auto image : { "APHLF1R.DEF", "APHLF1Y.DEF", "APHLF1G.DEF" })
  1162. upgrade[i]->addImage(image);
  1163. for(int j : {0,1})
  1164. {
  1165. slotIcons[i][j] = std::make_shared<CAnimImage>("SMALRES", 0, 0, 104 + 76 * i, 128 + 20 * j);
  1166. slotLabels[i][j] = std::make_shared<CLabel>(168 + 76 * i, 144 + 20 * j, FONT_SMALL, ETextAlignment::BOTTOMRIGHT);
  1167. }
  1168. }
  1169. upgradeAll = std::make_shared<CButton>(Point(30, 231), "", CButton::tooltip(CGI->generaltexth->allTexts[432]), [&](){ makeDeal(SlotID(slotsCount));}, EShortcut::RECRUITMENT_UPGRADE_ALL);
  1170. for(auto image : { "APHLF4R.DEF", "APHLF4Y.DEF", "APHLF4G.DEF" })
  1171. upgradeAll->addImage(image);
  1172. quit = std::make_shared<CButton>(Point(294, 275), "IOKAY.DEF", CButton::tooltip(), std::bind(&CHillFortWindow::close, this), EShortcut::GLOBAL_ACCEPT);
  1173. statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
  1174. garr = std::make_shared<CGarrisonInt>(108, 60, 18, Point(), hero, nullptr);
  1175. updateGarrisons();
  1176. }
  1177. void CHillFortWindow::updateGarrisons()
  1178. {
  1179. std::array<TResources, slotsCount> costs;// costs [slot ID] [resource ID] = resource count for upgrade
  1180. TResources totalSum; // totalSum[resource ID] = value
  1181. for(int i=0; i<slotsCount; i++)
  1182. {
  1183. std::fill(costs[i].begin(), costs[i].end(), 0);
  1184. int newState = getState(SlotID(i));
  1185. if(newState != -1)
  1186. {
  1187. UpgradeInfo info;
  1188. LOCPLINT->cb->fillUpgradeInfo(hero, SlotID(i), info);
  1189. if(info.newID.size())//we have upgrades here - update costs
  1190. {
  1191. costs[i] = info.cost[0] * hero->getStackCount(SlotID(i));
  1192. totalSum += costs[i];
  1193. }
  1194. }
  1195. currState[i] = newState;
  1196. upgrade[i]->setIndex(currState[i] == -1 ? 0 : currState[i]);
  1197. upgrade[i]->block(currState[i] == -1);
  1198. upgrade[i]->addHoverText(CButton::NORMAL, getTextForSlot(SlotID(i)));
  1199. }
  1200. //"Upgrade all" slot
  1201. int newState = 2;
  1202. {
  1203. TResources myRes = LOCPLINT->cb->getResourceAmount();
  1204. bool allUpgraded = true;//All creatures are upgraded?
  1205. for(int i=0; i<slotsCount; i++)
  1206. allUpgraded &= currState[i] == 1 || currState[i] == -1;
  1207. if(allUpgraded)
  1208. newState = 1;
  1209. if(!totalSum.canBeAfforded(myRes))
  1210. newState = 0;
  1211. }
  1212. currState[slotsCount] = newState;
  1213. upgradeAll->setIndex(newState);
  1214. garr->recreateSlots();
  1215. for(int i = 0; i < slotsCount; i++)
  1216. {
  1217. //hide all first
  1218. for(int j : {0,1})
  1219. {
  1220. slotIcons[i][j]->visible = false;
  1221. slotLabels[i][j]->setText("");
  1222. }
  1223. //if can upgrade or can not afford, draw cost
  1224. if(currState[i] == 0 || currState[i] == 2)
  1225. {
  1226. if(costs[i].nonZero())
  1227. {
  1228. //reverse iterator is used to display gold as first element
  1229. int j = 0;
  1230. for(int res = (int)costs[i].size()-1; (res >= 0) && (j < 2); res--)
  1231. {
  1232. int val = costs[i][res];
  1233. if(!val)
  1234. continue;
  1235. slotIcons[i][j]->visible = true;
  1236. slotIcons[i][j]->setFrame(res);
  1237. slotLabels[i][j]->setText(std::to_string(val));
  1238. j++;
  1239. }
  1240. }
  1241. else//free upgrade - print gold image and "Free" text
  1242. {
  1243. slotIcons[i][0]->visible = true;
  1244. slotIcons[i][0]->setFrame(GameResID(EGameResID::GOLD));
  1245. slotLabels[i][0]->setText(CGI->generaltexth->allTexts[344]);
  1246. }
  1247. }
  1248. }
  1249. for(int i = 0; i < resCount; i++)
  1250. {
  1251. if(totalSum[i] == 0)
  1252. {
  1253. totalIcons[i]->visible = false;
  1254. totalLabels[i]->setText("");
  1255. }
  1256. else
  1257. {
  1258. totalIcons[i]->visible = true;
  1259. totalLabels[i]->setText(std::to_string(totalSum[i]));
  1260. }
  1261. }
  1262. }
  1263. void CHillFortWindow::makeDeal(SlotID slot)
  1264. {
  1265. assert(slot.getNum()>=0);
  1266. int offset = (slot.getNum() == slotsCount)?2:0;
  1267. switch(currState[slot.getNum()])
  1268. {
  1269. case 0:
  1270. LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[314 + offset], std::vector<std::shared_ptr<CComponent>>(), soundBase::sound_todo);
  1271. break;
  1272. case 1:
  1273. LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[313 + offset], std::vector<std::shared_ptr<CComponent>>(), soundBase::sound_todo);
  1274. break;
  1275. case 2:
  1276. for(int i=0; i<slotsCount; i++)
  1277. {
  1278. if(slot.getNum() ==i || ( slot.getNum() == slotsCount && currState[i] == 2 ))//this is activated slot or "upgrade all"
  1279. {
  1280. UpgradeInfo info;
  1281. LOCPLINT->cb->fillUpgradeInfo(hero, SlotID(i), info);
  1282. LOCPLINT->cb->upgradeCreature(hero, SlotID(i), info.newID[0]);
  1283. }
  1284. }
  1285. break;
  1286. }
  1287. }
  1288. std::string CHillFortWindow::getTextForSlot(SlotID slot)
  1289. {
  1290. if(!hero->getCreature(slot))//we don`t have creature here
  1291. return "";
  1292. std::string str = CGI->generaltexth->allTexts[318];
  1293. int amount = hero->getStackCount(slot);
  1294. if(amount == 1)
  1295. boost::algorithm::replace_first(str,"%s",hero->getCreature(slot)->getNameSingularTranslated());
  1296. else
  1297. boost::algorithm::replace_first(str,"%s",hero->getCreature(slot)->getNamePluralTranslated());
  1298. return str;
  1299. }
  1300. int CHillFortWindow::getState(SlotID slot)
  1301. {
  1302. TResources myRes = LOCPLINT->cb->getResourceAmount();
  1303. if(hero->slotEmpty(slot))//no creature here
  1304. return -1;
  1305. UpgradeInfo info;
  1306. LOCPLINT->cb->fillUpgradeInfo(hero, slot, info);
  1307. if(!info.newID.size())//already upgraded
  1308. return 1;
  1309. if(!(info.cost[0] * hero->getStackCount(slot)).canBeAfforded(myRes))
  1310. return 0;
  1311. return 2;//can upgrade
  1312. }
  1313. CThievesGuildWindow::CThievesGuildWindow(const CGObjectInstance * _owner):
  1314. CStatusbarWindow(PLAYER_COLORED | BORDERED, "TpRank"),
  1315. owner(_owner)
  1316. {
  1317. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  1318. SThievesGuildInfo tgi; //info to be displayed
  1319. LOCPLINT->cb->getThievesGuildInfo(tgi, owner);
  1320. exitb = std::make_shared<CButton>(Point(748, 556), "TPMAGE1", CButton::tooltip(CGI->generaltexth->allTexts[600]), [&](){ close();}, EShortcut::GLOBAL_RETURN);
  1321. statusbar = CGStatusBar::create(3, 555, "TStatBar.bmp", 742);
  1322. resdatabar = std::make_shared<CMinorResDataBar>();
  1323. resdatabar->moveBy(pos.topLeft(), true);
  1324. //data for information table:
  1325. // fields[row][column] = list of id's of players for this box
  1326. static std::vector< std::vector< PlayerColor > > SThievesGuildInfo::* fields[] =
  1327. { &SThievesGuildInfo::numOfTowns, &SThievesGuildInfo::numOfHeroes, &SThievesGuildInfo::gold,
  1328. &SThievesGuildInfo::woodOre, &SThievesGuildInfo::mercSulfCrystGems, &SThievesGuildInfo::obelisks,
  1329. &SThievesGuildInfo::artifacts, &SThievesGuildInfo::army, &SThievesGuildInfo::income };
  1330. for(int g=0; g<12; ++g)
  1331. {
  1332. int posY[] = {400, 460, 510};
  1333. int y;
  1334. if(g < 9)
  1335. y = 52 + 32*g;
  1336. else
  1337. y = posY[g-9];
  1338. std::string text = CGI->generaltexth->jktexts[24+g];
  1339. boost::algorithm::trim_if(text,boost::algorithm::is_any_of("\""));
  1340. rowHeaders.push_back(std::make_shared<CLabel>(135, y, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW, text));
  1341. }
  1342. auto PRSTRIPS = std::make_shared<CAnimation>("PRSTRIPS");
  1343. PRSTRIPS->preload();
  1344. for(int g=1; g<tgi.playerColors.size(); ++g)
  1345. columnBackgrounds.push_back(std::make_shared<CAnimImage>(PRSTRIPS, g-1, 0, 250 + 66*g, 7));
  1346. for(int g=0; g<tgi.playerColors.size(); ++g)
  1347. columnHeaders.push_back(std::make_shared<CLabel>(283 + 66*g, 24, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->jktexts[16+g]));
  1348. auto itgflags = std::make_shared<CAnimation>("itgflags");
  1349. itgflags->preload();
  1350. //printing flags
  1351. for(int g = 0; g < std::size(fields); ++g) //by lines
  1352. {
  1353. for(int b=0; b<(tgi .* fields[g]).size(); ++b) //by places (1st, 2nd, ...)
  1354. {
  1355. std::vector<PlayerColor> &players = (tgi .* fields[g])[b]; //get players with this place in this line
  1356. //position of box
  1357. int xpos = 259 + 66 * b;
  1358. int ypos = 41 + 32 * g;
  1359. size_t rowLength[2]; //size of each row
  1360. rowLength[0] = std::min<size_t>(players.size(), 4);
  1361. rowLength[1] = players.size() - rowLength[0];
  1362. for(size_t j=0; j < 2; j++)
  1363. {
  1364. // origin of this row | offset for 2nd row| shift right for short rows
  1365. //if we have 2 rows, start either from mid or beginning (depending on count), otherwise center the flags
  1366. int rowStartX = xpos + (j ? 6 + ((int)rowLength[j] < 3 ? 12 : 0) : 24 - 6 * (int)rowLength[j]);
  1367. int rowStartY = ypos + (j ? 4 : 0);
  1368. for(size_t i=0; i < rowLength[j]; i++)
  1369. cells.push_back(std::make_shared<CAnimImage>(itgflags, players[i + j*4].getNum(), 0, rowStartX + (int)i*12, rowStartY));
  1370. }
  1371. }
  1372. }
  1373. static const std::string colorToBox[] = {"PRRED.BMP", "PRBLUE.BMP", "PRTAN.BMP", "PRGREEN.BMP", "PRORANGE.BMP", "PRPURPLE.BMP", "PRTEAL.BMP", "PRROSE.bmp"};
  1374. //printing best hero
  1375. int counter = 0;
  1376. for(auto & iter : tgi.colorToBestHero)
  1377. {
  1378. banners.push_back(std::make_shared<CPicture>(colorToBox[iter.first.getNum()], 253 + 66 * counter, 334));
  1379. if(iter.second.portrait >= 0)
  1380. {
  1381. bestHeroes.push_back(std::make_shared<CAnimImage>("PortraitsSmall", iter.second.portrait, 0, 260 + 66 * counter, 360));
  1382. //TODO: r-click info:
  1383. // - r-click on hero
  1384. // - r-click on primary skill label
  1385. if(iter.second.details)
  1386. {
  1387. primSkillHeaders.push_back(std::make_shared<CTextBox>(CGI->generaltexth->allTexts[184], Rect(260 + 66*counter, 396, 52, 64),
  1388. 0, FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE));
  1389. for(int i=0; i<iter.second.details->primskills.size(); ++i)
  1390. {
  1391. primSkillValues.push_back(std::make_shared<CLabel>(310 + 66 * counter, 407 + 11*i, FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE,
  1392. std::to_string(iter.second.details->primskills[i])));
  1393. }
  1394. }
  1395. }
  1396. counter++;
  1397. }
  1398. //printing best creature
  1399. counter = 0;
  1400. for(auto & it : tgi.bestCreature)
  1401. {
  1402. if(it.second >= 0)
  1403. bestCreatures.push_back(std::make_shared<CAnimImage>("TWCRPORT", it.second+2, 0, 255 + 66 * counter, 479));
  1404. counter++;
  1405. }
  1406. //printing personality
  1407. counter = 0;
  1408. for(auto & it : tgi.personality)
  1409. {
  1410. std::string text;
  1411. if(it.second == EAiTactic::NONE)
  1412. {
  1413. text = CGI->generaltexth->arraytxt[172];
  1414. }
  1415. else if(it.second != EAiTactic::RANDOM)
  1416. {
  1417. text = CGI->generaltexth->arraytxt[168 + it.second];
  1418. }
  1419. personalities.push_back(std::make_shared<CLabel>(283 + 66*counter, 459, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, text));
  1420. counter++;
  1421. }
  1422. }
  1423. CObjectListWindow::CItem::CItem(CObjectListWindow * _parent, size_t _id, std::string _text)
  1424. : CIntObject(LCLICK | DOUBLECLICK),
  1425. parent(_parent),
  1426. index(_id)
  1427. {
  1428. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  1429. border = std::make_shared<CPicture>("TPGATES");
  1430. pos = border->pos;
  1431. type |= REDRAW_PARENT;
  1432. text = std::make_shared<CLabel>(pos.w/2, pos.h/2, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, _text);
  1433. select(index == parent->selected);
  1434. }
  1435. void CObjectListWindow::CItem::select(bool on)
  1436. {
  1437. ui8 mask = UPDATE | SHOWALL;
  1438. if(on)
  1439. border->recActions |= mask;
  1440. else
  1441. border->recActions &= ~mask;
  1442. redraw();//???
  1443. }
  1444. void CObjectListWindow::CItem::clickLeft(tribool down, bool previousState)
  1445. {
  1446. if( previousState && !down)
  1447. parent->changeSelection(index);
  1448. }
  1449. void CObjectListWindow::CItem::onDoubleClick()
  1450. {
  1451. parent->elementSelected();
  1452. }
  1453. 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)
  1454. : CWindowObject(PLAYER_COLORED, "TPGATE"),
  1455. onSelect(Callback),
  1456. selected(initialSelection)
  1457. {
  1458. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  1459. items.reserve(_items.size());
  1460. for(int id : _items)
  1461. {
  1462. items.push_back(std::make_pair(id, LOCPLINT->cb->getObjInstance(ObjectInstanceID(id))->getObjectName()));
  1463. }
  1464. init(titleWidget_, _title, _descr);
  1465. }
  1466. 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)
  1467. : CWindowObject(PLAYER_COLORED, "TPGATE"),
  1468. onSelect(Callback),
  1469. selected(initialSelection)
  1470. {
  1471. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  1472. items.reserve(_items.size());
  1473. for(size_t i=0; i<_items.size(); i++)
  1474. items.push_back(std::make_pair(int(i), _items[i]));
  1475. init(titleWidget_, _title, _descr);
  1476. }
  1477. void CObjectListWindow::init(std::shared_ptr<CIntObject> titleWidget_, std::string _title, std::string _descr)
  1478. {
  1479. titleWidget = titleWidget_;
  1480. title = std::make_shared<CLabel>(152, 27, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, _title);
  1481. descr = std::make_shared<CLabel>(145, 133, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, _descr);
  1482. exit = std::make_shared<CButton>( Point(228, 402), "ICANCEL.DEF", CButton::tooltip(), std::bind(&CObjectListWindow::exitPressed, this), EShortcut::GLOBAL_CANCEL);
  1483. if(titleWidget)
  1484. {
  1485. addChild(titleWidget.get());
  1486. titleWidget->recActions = 255-DISPOSE;
  1487. titleWidget->pos.x = pos.w/2 + pos.x - titleWidget->pos.w/2;
  1488. titleWidget->pos.y =75 + pos.y - titleWidget->pos.h/2;
  1489. }
  1490. list = std::make_shared<CListBox>(std::bind(&CObjectListWindow::genItem, this, _1),
  1491. Point(14, 151), Point(0, 25), 9, items.size(), 0, 1, Rect(262, -32, 256, 256) );
  1492. list->type |= REDRAW_PARENT;
  1493. ok = std::make_shared<CButton>(Point(15, 402), "IOKAY.DEF", CButton::tooltip(), std::bind(&CObjectListWindow::elementSelected, this), EShortcut::GLOBAL_ACCEPT);
  1494. ok->block(!list->size());
  1495. }
  1496. std::shared_ptr<CIntObject> CObjectListWindow::genItem(size_t index)
  1497. {
  1498. if(index < items.size())
  1499. return std::make_shared<CItem>(this, index, items[index].second);
  1500. return std::shared_ptr<CIntObject>();
  1501. }
  1502. void CObjectListWindow::elementSelected()
  1503. {
  1504. std::function<void(int)> toCall = onSelect;//save
  1505. int where = items[selected].first; //required variables
  1506. close();//then destroy window
  1507. toCall(where);//and send selected object
  1508. }
  1509. void CObjectListWindow::exitPressed()
  1510. {
  1511. std::function<void()> toCall = onExit;//save
  1512. close();//then destroy window
  1513. if(toCall)
  1514. toCall();
  1515. }
  1516. void CObjectListWindow::changeSelection(size_t which)
  1517. {
  1518. ok->block(false);
  1519. if(selected == which)
  1520. return;
  1521. for(std::shared_ptr<CIntObject> element : list->getItems())
  1522. {
  1523. CItem * item = dynamic_cast<CItem*>(element.get());
  1524. if(item)
  1525. {
  1526. if(item->index == selected)
  1527. item->select(false);
  1528. if(item->index == which)
  1529. item->select(true);
  1530. }
  1531. }
  1532. selected = which;
  1533. }
  1534. void CObjectListWindow::keyPressed (EShortcut key)
  1535. {
  1536. int sel = static_cast<int>(selected);
  1537. switch(key)
  1538. {
  1539. break; case EShortcut::MOVE_UP:
  1540. sel -=1;
  1541. break; case EShortcut::MOVE_DOWN:
  1542. sel +=1;
  1543. break; case EShortcut::MOVE_PAGE_UP:
  1544. sel -=9;
  1545. break; case EShortcut::MOVE_PAGE_DOWN:
  1546. sel +=9;
  1547. break; case EShortcut::MOVE_FIRST:
  1548. sel = 0;
  1549. break; case EShortcut::MOVE_LAST:
  1550. sel = static_cast<int>(items.size());
  1551. break; default:
  1552. return;
  1553. }
  1554. vstd::abetween<int>(sel, 0, items.size()-1);
  1555. list->scrollTo(sel);
  1556. changeSelection(sel);
  1557. }