GUIClasses.cpp 74 KB

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