GUIClasses.cpp 76 KB

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