GUIClasses.cpp 78 KB

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