GUIClasses.cpp 79 KB

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