GUIClasses.cpp 75 KB

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