CCastleInterface.cpp 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211
  1. /*
  2. * CCastleInterface.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 "CCastleInterface.h"
  12. #include "CHeroWindow.h"
  13. #include "CMarketWindow.h"
  14. #include "InfoWindows.h"
  15. #include "GUIClasses.h"
  16. #include "QuickRecruitmentWindow.h"
  17. #include "CCreatureWindow.h"
  18. #include "../CGameInfo.h"
  19. #include "../CPlayerInterface.h"
  20. #include "../PlayerLocalState.h"
  21. #include "../gui/CGuiHandler.h"
  22. #include "../gui/Shortcut.h"
  23. #include "../gui/WindowHandler.h"
  24. #include "../media/IMusicPlayer.h"
  25. #include "../media/ISoundPlayer.h"
  26. #include "../widgets/MiscWidgets.h"
  27. #include "../widgets/CComponent.h"
  28. #include "../widgets/CGarrisonInt.h"
  29. #include "../widgets/Buttons.h"
  30. #include "../widgets/TextControls.h"
  31. #include "../widgets/RadialMenu.h"
  32. #include "../widgets/CExchangeController.h"
  33. #include "../render/Canvas.h"
  34. #include "../render/IImage.h"
  35. #include "../render/IRenderHandler.h"
  36. #include "../render/CAnimation.h"
  37. #include "../render/ColorFilter.h"
  38. #include "../render/IFont.h"
  39. #include "../adventureMap/AdventureMapInterface.h"
  40. #include "../adventureMap/CList.h"
  41. #include "../adventureMap/CResDataBar.h"
  42. #include "../../CCallback.h"
  43. #include "../../lib/CArtHandler.h"
  44. #include "../../lib/CConfigHandler.h"
  45. #include "../../lib/CSoundBase.h"
  46. #include "../../lib/CCreatureHandler.h"
  47. #include "../../lib/texts/CGeneralTextHandler.h"
  48. #include "../../lib/IGameSettings.h"
  49. #include "../../lib/spells/CSpellHandler.h"
  50. #include "../../lib/GameConstants.h"
  51. #include "../../lib/StartInfo.h"
  52. #include "../../lib/campaign/CampaignState.h"
  53. #include "../../lib/entities/building/CBuilding.h"
  54. #include "../../lib/mapObjects/CGHeroInstance.h"
  55. #include "../../lib/mapObjects/CGTownInstance.h"
  56. #include "../../lib/mapObjects/TownBuildingInstance.h"
  57. static bool useCompactCreatureBox()
  58. {
  59. return settings["gameTweaks"]["compactTownCreatureInfo"].Bool();
  60. }
  61. static bool useAvailableAmountAsCreatureLabel()
  62. {
  63. return settings["gameTweaks"]["availableCreaturesAsDwellingLabel"].Bool();
  64. }
  65. CBuildingRect::CBuildingRect(CCastleBuildings * Par, const CGTownInstance * Town, const CStructure * Str)
  66. : CShowableAnim(0, 0, Str->defName, CShowableAnim::BASE, BUILDING_FRAME_TIME),
  67. parent(Par),
  68. town(Town),
  69. str(Str),
  70. border(nullptr),
  71. area(nullptr),
  72. stateTimeCounter(BUILD_ANIMATION_FINISHED_TIMEPOINT)
  73. {
  74. addUsedEvents(LCLICK | SHOW_POPUP | MOVE | HOVER | TIME);
  75. pos.x += str->pos.x;
  76. pos.y += str->pos.y;
  77. // special animation frame manipulation for castle shipyard with and without ship
  78. // done due to .def used in special way, not to animate building - first image is for shipyard without citadel moat, 2nd image is for including moat
  79. if(Town->getFactionID() == FactionID::CASTLE && Str->building &&
  80. (Str->building->bid == BuildingID::SHIPYARD || Str->building->bid == BuildingID::SHIP))
  81. {
  82. if(Town->hasBuilt(BuildingID::CITADEL))
  83. {
  84. this->first = 1;
  85. this->frame = 1;
  86. }
  87. else
  88. this->last = 0;
  89. }
  90. if(!str->borderName.empty())
  91. border = GH.renderHandler().loadImage(str->borderName, EImageBlitMode::COLORKEY);
  92. if(!str->areaName.empty())
  93. area = GH.renderHandler().loadImage(str->areaName, EImageBlitMode::SIMPLE);
  94. }
  95. const CBuilding * CBuildingRect::getBuilding()
  96. {
  97. if (!str->building)
  98. return nullptr;
  99. if (str->hiddenUpgrade) // hidden upgrades, e.g. hordes - return base (dwelling for hordes)
  100. return town->getTown()->buildings.at(str->building->getBase());
  101. return str->building;
  102. }
  103. bool CBuildingRect::operator<(const CBuildingRect & p2) const
  104. {
  105. return (str->pos.z) < (p2.str->pos.z);
  106. }
  107. void CBuildingRect::hover(bool on)
  108. {
  109. if (!area)
  110. return;
  111. if(on)
  112. {
  113. if(! parent->selectedBuilding //no building hovered
  114. || (*parent->selectedBuilding)<(*this)) //or we are on top
  115. {
  116. parent->selectedBuilding = this;
  117. GH.statusbar()->write(getSubtitle());
  118. }
  119. }
  120. else
  121. {
  122. if(parent->selectedBuilding == this)
  123. {
  124. parent->selectedBuilding = nullptr;
  125. GH.statusbar()->clear();
  126. }
  127. }
  128. }
  129. void CBuildingRect::clickPressed(const Point & cursorPosition)
  130. {
  131. if(getBuilding() && area && (parent->selectedBuilding==this))
  132. {
  133. auto building = getBuilding();
  134. parent->buildingClicked(building->bid);
  135. }
  136. }
  137. void CBuildingRect::showPopupWindow(const Point & cursorPosition)
  138. {
  139. if((!area) || (this!=parent->selectedBuilding) || getBuilding() == nullptr)
  140. return;
  141. BuildingID bid = getBuilding()->bid;
  142. const CBuilding *bld = town->getTown()->buildings.at(bid);
  143. if (!bid.IsDwelling())
  144. {
  145. CRClickPopup::createAndPush(CInfoWindow::genText(bld->getNameTranslated(), bld->getDescriptionTranslated()),
  146. std::make_shared<CComponent>(ComponentType::BUILDING, BuildingTypeUniqueID(bld->town->faction->getId(), bld->bid)));
  147. }
  148. else
  149. {
  150. int level = BuildingID::getLevelFromDwelling(bid);
  151. GH.windows().createAndPushWindow<CDwellingInfoBox>(parent->pos.x+parent->pos.w / 2, parent->pos.y+parent->pos.h /2, town, level);
  152. }
  153. }
  154. void CBuildingRect::show(Canvas & to)
  155. {
  156. uint32_t stageDelay = BUILDING_APPEAR_TIMEPOINT;
  157. bool showTextOverlay = GH.isKeyboardAltDown();
  158. if(stateTimeCounter < BUILDING_APPEAR_TIMEPOINT)
  159. {
  160. setAlpha(255 * stateTimeCounter / stageDelay);
  161. CShowableAnim::show(to);
  162. }
  163. else
  164. {
  165. setAlpha(255);
  166. CShowableAnim::show(to);
  167. }
  168. if(border && stateTimeCounter > BUILDING_APPEAR_TIMEPOINT)
  169. {
  170. if(stateTimeCounter >= BUILD_ANIMATION_FINISHED_TIMEPOINT)
  171. {
  172. if(parent->selectedBuilding == this || showTextOverlay)
  173. to.draw(border, pos.topLeft());
  174. return;
  175. }
  176. auto darkBorder = ColorFilter::genRangeShifter(0.f, 0.f, 0.f, 0.5f, 0.5f, 0.5f );
  177. auto lightBorder = ColorFilter::genRangeShifter(0.f, 0.f, 0.f, 2.0f, 2.0f, 2.0f );
  178. auto baseBorder = ColorFilter::genEmptyShifter();
  179. float progress = float(stateTimeCounter % stageDelay) / stageDelay;
  180. if (stateTimeCounter < BUILDING_WHITE_BORDER_TIMEPOINT)
  181. border->adjustPalette(ColorFilter::genInterpolated(lightBorder, darkBorder, progress), 0);
  182. else
  183. if (stateTimeCounter < BUILDING_YELLOW_BORDER_TIMEPOINT)
  184. border->adjustPalette(ColorFilter::genInterpolated(darkBorder, baseBorder, progress), 0);
  185. else
  186. border->adjustPalette(baseBorder, 0);
  187. to.draw(border, pos.topLeft());
  188. }
  189. }
  190. void CBuildingRect::tick(uint32_t msPassed)
  191. {
  192. CShowableAnim::tick(msPassed);
  193. stateTimeCounter += msPassed;
  194. }
  195. void CBuildingRect::showAll(Canvas & to)
  196. {
  197. if (stateTimeCounter == 0)
  198. return;
  199. CShowableAnim::showAll(to);
  200. if(!isActive() && parent->selectedBuilding == this && border)
  201. to.draw(border, pos.topLeft());
  202. }
  203. std::string CBuildingRect::getSubtitle()//hover text for building
  204. {
  205. if (!getBuilding())
  206. return "";
  207. auto bid = getBuilding()->bid;
  208. if (!bid.IsDwelling())//non-dwellings - only building name
  209. return town->getTown()->buildings.at(getBuilding()->bid)->getNameTranslated();
  210. else//dwellings - recruit %creature%
  211. {
  212. int level = BuildingID::getLevelFromDwelling(getBuilding()->bid);
  213. auto & availableCreatures = town->creatures[level].second;
  214. if(availableCreatures.size())
  215. {
  216. int creaID = availableCreatures.back();//taking last of available creatures
  217. return CGI->generaltexth->allTexts[16] + " " + CGI->creh->objects.at(creaID)->getNamePluralTranslated();
  218. }
  219. else
  220. {
  221. logGlobal->warn("Dwelling with id %d offers no creatures!", bid);
  222. return "#ERROR#";
  223. }
  224. }
  225. }
  226. void CBuildingRect::mouseMoved (const Point & cursorPosition, const Point & lastUpdateDistance)
  227. {
  228. hover(true);
  229. }
  230. bool CBuildingRect::receiveEvent(const Point & position, int eventType) const
  231. {
  232. if (!pos.isInside(position.x, position.y))
  233. return false;
  234. if(area && area->isTransparent(position - pos.topLeft()))
  235. return false;
  236. return CIntObject::receiveEvent(position, eventType);
  237. }
  238. CDwellingInfoBox::CDwellingInfoBox(int centerX, int centerY, const CGTownInstance * Town, int level)
  239. : CWindowObject(RCLICK_POPUP, ImagePath::builtin("CRTOINFO"), Point(centerX, centerY))
  240. {
  241. OBJECT_CONSTRUCTION;
  242. background->setPlayerColor(Town->tempOwner);
  243. const CCreature * creature = Town->creatures.at(level).second.back().toCreature();
  244. title = std::make_shared<CLabel>(80, 30, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, creature->getNamePluralTranslated());
  245. animation = std::make_shared<CCreaturePic>(30, 44, creature, true, true);
  246. std::string text = std::to_string(Town->creatures.at(level).first);
  247. available = std::make_shared<CLabel>(80,190, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[217] + text);
  248. costPerTroop = std::make_shared<CLabel>(80, 227, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[346]);
  249. for(int i = 0; i<GameConstants::RESOURCE_QUANTITY; i++)
  250. {
  251. auto res = static_cast<EGameResID>(i);
  252. if(creature->getRecruitCost(res))
  253. {
  254. resPicture.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("RESOURCE"), i, 0, 0, 0));
  255. resAmount.push_back(std::make_shared<CLabel>(0,0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, std::to_string(creature->getRecruitCost(res))));
  256. }
  257. }
  258. int posY = 238;
  259. int posX = pos.w/2 - (int)resAmount.size() * 25 + 5;
  260. for (size_t i=0; i<resAmount.size(); i++)
  261. {
  262. resPicture[i]->moveBy(Point(posX, posY));
  263. resAmount[i]->moveBy(Point(posX+16, posY+43));
  264. posX += 50;
  265. }
  266. }
  267. CDwellingInfoBox::~CDwellingInfoBox() = default;
  268. CHeroGSlot::CHeroGSlot(int x, int y, int updown, const CGHeroInstance * h, HeroSlots * Owner)
  269. {
  270. OBJECT_CONSTRUCTION;
  271. owner = Owner;
  272. pos.x += x;
  273. pos.y += y;
  274. pos.w = 58;
  275. pos.h = 64;
  276. upg = updown;
  277. portrait = std::make_shared<CAnimImage>(AnimationPath::builtin("PortraitsLarge"), 0, 0, 0, 0);
  278. portrait->visible = false;
  279. flag = std::make_shared<CAnimImage>(AnimationPath::builtin("CREST58"), 0, 0, 0, 0);
  280. flag->visible = false;
  281. selection = std::make_shared<CAnimImage>(AnimationPath::builtin("TWCRPORT"), 1, 0);
  282. selection->visible = false;
  283. set(h);
  284. addUsedEvents(LCLICK | SHOW_POPUP | GESTURE | HOVER);
  285. }
  286. CHeroGSlot::~CHeroGSlot() = default;
  287. void CHeroGSlot::gesture(bool on, const Point & initialPosition, const Point & finalPosition)
  288. {
  289. if(!on)
  290. return;
  291. if(!hero)
  292. return;
  293. if (!settings["input"]["radialWheelGarrisonSwipe"].Bool())
  294. return;
  295. std::shared_ptr<CHeroGSlot> other = upg ? owner->garrisonedHero : owner->visitingHero;
  296. bool twoHeroes = hero && other->hero;
  297. ObjectInstanceID heroId = hero->id;
  298. ObjectInstanceID heroOtherId = twoHeroes ? other->hero->id : ObjectInstanceID::NONE;
  299. std::vector<RadialMenuConfig> menuElements = {
  300. { RadialMenuConfig::ITEM_NW, twoHeroes, "moveTroops", "vcmi.radialWheel.heroGetArmy", [heroId, heroOtherId](){CExchangeController(heroId, heroOtherId).moveArmy(false, std::nullopt);} },
  301. { RadialMenuConfig::ITEM_NE, twoHeroes, "stackSplitDialog", "vcmi.radialWheel.heroSwapArmy", [heroId, heroOtherId](){CExchangeController(heroId, heroOtherId).swapArmy();} },
  302. { RadialMenuConfig::ITEM_EE, twoHeroes, "tradeHeroes", "vcmi.radialWheel.heroExchange", [heroId, heroOtherId](){LOCPLINT->showHeroExchange(heroId, heroOtherId);} },
  303. { RadialMenuConfig::ITEM_SW, twoHeroes, "moveArtifacts", "vcmi.radialWheel.heroGetArtifacts", [heroId, heroOtherId](){CExchangeController(heroId, heroOtherId).moveArtifacts(false, true, true);} },
  304. { RadialMenuConfig::ITEM_SE, twoHeroes, "swapArtifacts", "vcmi.radialWheel.heroSwapArtifacts", [heroId, heroOtherId](){CExchangeController(heroId, heroOtherId).swapArtifacts(true, true);} },
  305. { RadialMenuConfig::ITEM_WW, true, "dismissHero", "vcmi.radialWheel.heroDismiss", [this]()
  306. {
  307. CFunctionList<void()> ony = [=](){ };
  308. ony += [=](){ LOCPLINT->cb->dismissHero(hero); };
  309. LOCPLINT->showYesNoDialog(CGI->generaltexth->allTexts[22], ony, nullptr);
  310. } },
  311. };
  312. GH.windows().createAndPushWindow<RadialMenu>(pos.center(), menuElements);
  313. }
  314. void CHeroGSlot::hover(bool on)
  315. {
  316. if(!on)
  317. {
  318. GH.statusbar()->clear();
  319. return;
  320. }
  321. std::shared_ptr<CHeroGSlot> other = upg ? owner->garrisonedHero : owner->visitingHero;
  322. std::string temp;
  323. if(hero)
  324. {
  325. if(isSelected())//view NNN
  326. {
  327. temp = CGI->generaltexth->tcommands[4];
  328. boost::algorithm::replace_first(temp,"%s",hero->getNameTranslated());
  329. }
  330. else if(other->hero && other->isSelected())//exchange
  331. {
  332. temp = CGI->generaltexth->tcommands[7];
  333. boost::algorithm::replace_first(temp,"%s",hero->getNameTranslated());
  334. boost::algorithm::replace_first(temp,"%s",other->hero->getNameTranslated());
  335. }
  336. else// select NNN (in ZZZ)
  337. {
  338. if(upg)//down - visiting
  339. {
  340. temp = CGI->generaltexth->tcommands[32];
  341. boost::algorithm::replace_first(temp,"%s",hero->getNameTranslated());
  342. }
  343. else //up - garrison
  344. {
  345. temp = CGI->generaltexth->tcommands[12];
  346. boost::algorithm::replace_first(temp,"%s",hero->getNameTranslated());
  347. }
  348. }
  349. }
  350. else //we are empty slot
  351. {
  352. if(other->isSelected() && other->hero) //move NNNN
  353. {
  354. temp = CGI->generaltexth->tcommands[6];
  355. boost::algorithm::replace_first(temp,"%s",other->hero->getNameTranslated());
  356. }
  357. else //empty
  358. {
  359. temp = CGI->generaltexth->allTexts[507];
  360. }
  361. }
  362. if(temp.size())
  363. GH.statusbar()->write(temp);
  364. }
  365. void CHeroGSlot::clickPressed(const Point & cursorPosition)
  366. {
  367. std::shared_ptr<CHeroGSlot> other = upg ? owner->garrisonedHero : owner->visitingHero;
  368. owner->garr->setSplittingMode(false);
  369. owner->garr->selectSlot(nullptr);
  370. if(hero && isSelected())
  371. {
  372. setHighlight(false);
  373. if(other->hero && !GH.isKeyboardShiftDown())
  374. LOCPLINT->showHeroExchange(hero->id, other->hero->id);
  375. else
  376. LOCPLINT->openHeroWindow(hero);
  377. }
  378. else if(other->hero && other->isSelected())
  379. {
  380. owner->swapArmies();
  381. }
  382. else if(hero)
  383. {
  384. setHighlight(true);
  385. owner->garr->selectSlot(nullptr);
  386. redraw();
  387. }
  388. //refresh statusbar
  389. hover(false);
  390. hover(true);
  391. }
  392. void CHeroGSlot::showPopupWindow(const Point & cursorPosition)
  393. {
  394. if(hero)
  395. {
  396. GH.windows().createAndPushWindow<CInfoBoxPopup>(pos.center(), hero);
  397. }
  398. }
  399. void CHeroGSlot::deactivate()
  400. {
  401. selection->visible = false;
  402. CIntObject::deactivate();
  403. }
  404. bool CHeroGSlot::isSelected() const
  405. {
  406. return selection->visible;
  407. }
  408. void CHeroGSlot::setHighlight(bool on)
  409. {
  410. selection->visible = on;
  411. if(owner->garrisonedHero->hero && owner->visitingHero->hero) //two heroes in town
  412. {
  413. for(auto & elem : owner->garr->splitButtons) //splitting enabled when slot highlighted
  414. elem->block(!on);
  415. }
  416. }
  417. void CHeroGSlot::set(const CGHeroInstance * newHero)
  418. {
  419. OBJECT_CONSTRUCTION;
  420. hero = newHero;
  421. selection->visible = false;
  422. portrait->visible = false;
  423. flag->visible = false;
  424. if(newHero)
  425. {
  426. portrait->visible = true;
  427. portrait->setFrame(newHero->getIconIndex());
  428. }
  429. else if(!upg && owner->showEmpty) //up garrison
  430. {
  431. flag->visible = true;
  432. flag->setFrame(LOCPLINT->castleInt->town->getOwner().getNum());
  433. }
  434. }
  435. HeroSlots::HeroSlots(const CGTownInstance * Town, Point garrPos, Point visitPos, std::shared_ptr<CGarrisonInt> Garrison, bool ShowEmpty):
  436. showEmpty(ShowEmpty),
  437. town(Town),
  438. garr(Garrison)
  439. {
  440. OBJECT_CONSTRUCTION;
  441. garrisonedHero = std::make_shared<CHeroGSlot>(garrPos.x, garrPos.y, 0, town->garrisonHero, this);
  442. visitingHero = std::make_shared<CHeroGSlot>(visitPos.x, visitPos.y, 1, town->visitingHero, this);
  443. }
  444. HeroSlots::~HeroSlots() = default;
  445. void HeroSlots::update()
  446. {
  447. garrisonedHero->set(town->garrisonHero);
  448. visitingHero->set(town->visitingHero);
  449. }
  450. void HeroSlots::swapArmies()
  451. {
  452. bool allow = true;
  453. //moving hero out of town - check if it is allowed
  454. if (town->garrisonHero)
  455. {
  456. if (!town->visitingHero && LOCPLINT->cb->howManyHeroes(false) >= LOCPLINT->cb->getSettings().getInteger(EGameSettings::HEROES_PER_PLAYER_ON_MAP_CAP))
  457. {
  458. std::string text = CGI->generaltexth->translate("core.genrltxt.18"); //You already have %d adventuring heroes under your command.
  459. boost::algorithm::replace_first(text,"%d",std::to_string(LOCPLINT->cb->howManyHeroes(false)));
  460. LOCPLINT->showInfoDialog(text, std::vector<std::shared_ptr<CComponent>>(), soundBase::sound_todo);
  461. allow = false;
  462. }
  463. else if (town->garrisonHero->stacksCount() == 0)
  464. {
  465. //This hero has no creatures. A hero must have creatures before he can brave the dangers of the countryside.
  466. LOCPLINT->showInfoDialog(CGI->generaltexth->translate("core.genrltxt.19"), {}, soundBase::sound_todo);
  467. allow = false;
  468. }
  469. }
  470. if(!town->garrisonHero && town->visitingHero) //visiting => garrison, merge armies: town army => hero army
  471. {
  472. if(!town->visitingHero->canBeMergedWith(*town))
  473. {
  474. LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[275], std::vector<std::shared_ptr<CComponent>>(), soundBase::sound_todo);
  475. allow = false;
  476. }
  477. }
  478. garrisonedHero->setHighlight(false);
  479. visitingHero->setHighlight(false);
  480. if (allow)
  481. LOCPLINT->cb->swapGarrisonHero(town);
  482. }
  483. CCastleBuildings::CCastleBuildings(const CGTownInstance* Town):
  484. town(Town),
  485. selectedBuilding(nullptr)
  486. {
  487. OBJECT_CONSTRUCTION;
  488. background = std::make_shared<CPicture>(town->getTown()->clientInfo.townBackground, Point(0,0), EImageBlitMode::OPAQUE);
  489. background->needRefresh = true;
  490. pos.w = background->pos.w;
  491. pos.h = background->pos.h;
  492. recreate();
  493. }
  494. CCastleBuildings::~CCastleBuildings() = default;
  495. void CCastleBuildings::recreate()
  496. {
  497. selectedBuilding = nullptr;
  498. OBJECT_CONSTRUCTION;
  499. buildings.clear();
  500. groups.clear();
  501. //Generate buildings list
  502. auto buildingsCopy = town->getBuildings();// a bit modified copy of built buildings
  503. if(town->hasBuilt(BuildingID::SHIPYARD))
  504. {
  505. auto bayPos = town->bestLocation();
  506. if(!bayPos.valid())
  507. logGlobal->warn("Shipyard in non-coastal town!");
  508. std::vector <const CGObjectInstance *> vobjs = LOCPLINT->cb->getVisitableObjs(bayPos, false);
  509. //there is visitable obj at shipyard output tile and it's a boat or hero (on boat)
  510. if(!vobjs.empty() && (vobjs.front()->ID == Obj::BOAT || vobjs.front()->ID == Obj::HERO))
  511. {
  512. buildingsCopy.insert(BuildingID::SHIP);
  513. }
  514. }
  515. for(const CStructure * structure : town->getTown()->clientInfo.structures)
  516. {
  517. if(!structure->building)
  518. {
  519. buildings.push_back(std::make_shared<CBuildingRect>(this, town, structure));
  520. continue;
  521. }
  522. if(vstd::contains(buildingsCopy, structure->building->bid))
  523. {
  524. groups[structure->building->getBase()].push_back(structure);
  525. }
  526. }
  527. for(auto & entry : groups)
  528. {
  529. const CBuilding * build = town->getTown()->buildings.at(entry.first);
  530. const CStructure * toAdd = *boost::max_element(entry.second, [=](const CStructure * a, const CStructure * b)
  531. {
  532. return build->getDistance(a->building->bid) < build->getDistance(b->building->bid);
  533. });
  534. buildings.push_back(std::make_shared<CBuildingRect>(this, town, toAdd));
  535. }
  536. const auto & buildSorter = [](const CIntObject * a, const CIntObject * b)
  537. {
  538. auto b1 = dynamic_cast<const CBuildingRect *>(a);
  539. auto b2 = dynamic_cast<const CBuildingRect *>(b);
  540. if(!b1 && !b2)
  541. return intptr_t(a) < intptr_t(b);
  542. if(b1 && !b2)
  543. return false;
  544. if(!b1 && b2)
  545. return true;
  546. return (*b1)<(*b2);
  547. };
  548. boost::sort(children, buildSorter); //TODO: create building in blit order
  549. }
  550. void CCastleBuildings::drawOverlays(Canvas & to, std::vector<std::shared_ptr<CBuildingRect>> buildingRects)
  551. {
  552. std::vector<Rect> textRects;
  553. for(auto & buildingRect : buildingRects)
  554. {
  555. if(!buildingRect->border)
  556. continue;
  557. auto building = buildingRect->getBuilding();
  558. if (!building)
  559. continue;
  560. auto bid = building->bid;
  561. auto overlay = town->getTown()->buildings.at(bid)->getNameTranslated();
  562. const auto & font = GH.renderHandler().loadFont(FONT_TINY);
  563. auto backColor = Colors::GREEN; // Other
  564. if(bid.IsDwelling())
  565. backColor = Colors::PURPLE; // dwelling
  566. auto contentRect = buildingRect->border->contentRect();
  567. auto center = Rect(buildingRect->pos.x + contentRect.x, buildingRect->pos.y + contentRect.y, contentRect.w, contentRect.h).center();
  568. Point dimensions(font->getStringWidth(overlay), font->getLineHeight());
  569. Rect textRect = Rect(center - dimensions / 2, dimensions).resize(2);
  570. while(!pos.resize(-5).isInside(Point(textRect.topLeft().x, textRect.center().y)))
  571. textRect.x++;
  572. while(!pos.resize(-5).isInside(Point(textRect.topRight().x, textRect.center().y)))
  573. textRect.x--;
  574. while(std::any_of(textRects.begin(), textRects.end(), [textRect](Rect existingTextRect) { return existingTextRect.resize(3).intersectionTest(textRect); }))
  575. textRect.y++;
  576. textRects.push_back(textRect);
  577. to.drawColor(textRect, backColor);
  578. to.drawBorder(textRect, Colors::BRIGHT_YELLOW);
  579. to.drawText(textRect.center(), EFonts::FONT_TINY, Colors::BLACK, ETextAlignment::CENTER, overlay);
  580. }
  581. }
  582. void CCastleBuildings::show(Canvas & to)
  583. {
  584. CIntObject::show(to);
  585. bool showTextOverlay = GH.isKeyboardAltDown();
  586. if(showTextOverlay)
  587. drawOverlays(to, buildings);
  588. }
  589. void CCastleBuildings::addBuilding(BuildingID building)
  590. {
  591. //FIXME: implement faster method without complete recreation of town
  592. BuildingID base = town->getTown()->buildings.at(building)->getBase();
  593. recreate();
  594. auto & structures = groups.at(base);
  595. for(auto buildingRect : buildings)
  596. {
  597. if(vstd::contains(structures, buildingRect->str))
  598. {
  599. //reset animation
  600. if(structures.size() == 1)
  601. buildingRect->stateTimeCounter = 0; // transparency -> fully visible stage
  602. else
  603. buildingRect->stateTimeCounter = CBuildingRect::BUILDING_APPEAR_TIMEPOINT; // already in fully visible stage
  604. break;
  605. }
  606. }
  607. }
  608. void CCastleBuildings::removeBuilding(BuildingID building)
  609. {
  610. //FIXME: implement faster method without complete recreation of town
  611. recreate();
  612. }
  613. const CGHeroInstance * CCastleBuildings::getHero()
  614. {
  615. if(town->visitingHero)
  616. return town->visitingHero;
  617. else
  618. return town->garrisonHero;
  619. }
  620. void CCastleBuildings::buildingClicked(BuildingID building)
  621. {
  622. BuildingID buildingToEnter = building;
  623. for(;;)
  624. {
  625. const CBuilding *b = town->getTown()->buildings.find(buildingToEnter)->second;
  626. if (buildingTryActivateCustomUI(buildingToEnter, building))
  627. return;
  628. if (!b->upgrade.hasValue())
  629. {
  630. enterBuilding(building);
  631. return;
  632. }
  633. buildingToEnter = b->upgrade;
  634. }
  635. }
  636. bool CCastleBuildings::buildingTryActivateCustomUI(BuildingID buildingToTest, BuildingID buildingTarget)
  637. {
  638. logGlobal->trace("You've clicked on %d", (int)buildingToTest.toEnum());
  639. const CBuilding *b = town->getTown()->buildings.at(buildingToTest);
  640. if (town->getWarMachineInBuilding(buildingToTest).hasValue())
  641. {
  642. enterBlacksmith(buildingTarget, town->getWarMachineInBuilding(buildingToTest));
  643. return true;
  644. }
  645. if (!b->marketModes.empty())
  646. {
  647. switch (*b->marketModes.begin())
  648. {
  649. case EMarketMode::CREATURE_UNDEAD:
  650. GH.windows().createAndPushWindow<CTransformerWindow>(town, getHero(), nullptr);
  651. return true;
  652. case EMarketMode::RESOURCE_SKILL:
  653. if (getHero())
  654. GH.windows().createAndPushWindow<CUniversityWindow>(getHero(), buildingTarget, town, nullptr);
  655. return true;
  656. case EMarketMode::RESOURCE_RESOURCE:
  657. // can't use allied marketplace
  658. if (town->getOwner() == LOCPLINT->playerID)
  659. {
  660. GH.windows().createAndPushWindow<CMarketWindow>(town, getHero(), nullptr, *b->marketModes.begin());
  661. return true;
  662. }
  663. else
  664. return false;
  665. default:
  666. if(getHero())
  667. GH.windows().createAndPushWindow<CMarketWindow>(town, getHero(), nullptr, *b->marketModes.begin());
  668. else
  669. LOCPLINT->showInfoDialog(boost::str(boost::format(CGI->generaltexth->allTexts[273]) % b->getNameTranslated())); //Only visiting heroes may use the %s.
  670. return true;
  671. }
  672. }
  673. if (town->rewardableBuildings.count(buildingToTest) && town->getTown()->buildings.at(buildingToTest)->manualHeroVisit)
  674. {
  675. enterRewardable(buildingToTest);
  676. return true;
  677. }
  678. if (buildingToTest.IsDwelling())
  679. {
  680. enterDwelling((BuildingID::getLevelFromDwelling(buildingToTest)));
  681. return true;
  682. }
  683. else
  684. {
  685. switch(buildingToTest)
  686. {
  687. case BuildingID::MAGES_GUILD_1:
  688. case BuildingID::MAGES_GUILD_2:
  689. case BuildingID::MAGES_GUILD_3:
  690. case BuildingID::MAGES_GUILD_4:
  691. case BuildingID::MAGES_GUILD_5:
  692. enterMagesGuild();
  693. return true;
  694. case BuildingID::TAVERN:
  695. LOCPLINT->showTavernWindow(town, nullptr, QueryID::NONE);
  696. return true;
  697. case BuildingID::SHIPYARD:
  698. if(town->shipyardStatus() == IBoatGenerator::GOOD)
  699. {
  700. LOCPLINT->showShipyardDialog(town);
  701. return true;
  702. }
  703. else if(town->shipyardStatus() == IBoatGenerator::BOAT_ALREADY_BUILT)
  704. {
  705. LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[51]);
  706. return true;
  707. }
  708. return false;
  709. case BuildingID::FORT:
  710. case BuildingID::CITADEL:
  711. case BuildingID::CASTLE:
  712. GH.windows().createAndPushWindow<CFortScreen>(town);
  713. return true;
  714. case BuildingID::VILLAGE_HALL:
  715. case BuildingID::CITY_HALL:
  716. case BuildingID::TOWN_HALL:
  717. case BuildingID::CAPITOL:
  718. enterTownHall();
  719. return true;
  720. case BuildingID::SHIP:
  721. LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[51]); //Cannot build another boat
  722. return true;
  723. case BuildingID::SPECIAL_1:
  724. case BuildingID::SPECIAL_2:
  725. case BuildingID::SPECIAL_3:
  726. case BuildingID::SPECIAL_4:
  727. switch (b->subId)
  728. {
  729. case BuildingSubID::MYSTIC_POND:
  730. enterFountain(buildingToTest, b->subId, buildingTarget);
  731. return true;
  732. case BuildingSubID::CASTLE_GATE:
  733. if (LOCPLINT->makingTurn)
  734. {
  735. enterCastleGate(buildingToTest);
  736. return true;
  737. }
  738. return false;
  739. case BuildingSubID::PORTAL_OF_SUMMONING:
  740. if (town->creatures[town->getTown()->creatures.size()].second.empty())//No creatures
  741. LOCPLINT->showInfoDialog(CGI->generaltexth->tcommands[30]);
  742. else
  743. enterDwelling(town->getTown()->creatures.size());
  744. return true;
  745. case BuildingSubID::BANK:
  746. enterBank(buildingTarget);
  747. return true;
  748. }
  749. }
  750. }
  751. for (auto const & bonus : b->buildingBonuses)
  752. {
  753. if (bonus->type == BonusType::THIEVES_GUILD_ACCESS)
  754. {
  755. enterAnyThievesGuild();
  756. return true;
  757. }
  758. }
  759. return false;
  760. }
  761. void CCastleBuildings::enterRewardable(BuildingID building)
  762. {
  763. if (town->visitingHero == nullptr)
  764. {
  765. MetaString message;
  766. message.appendTextID("core.genrltxt.273"); // only visiting heroes may visit %s
  767. message.replaceTextID(town->getTown()->buildings.at(building)->getNameTextID());
  768. LOCPLINT->showInfoDialog(message.toString());
  769. }
  770. else
  771. {
  772. if (town->rewardableBuildings.at(building)->wasVisited(town->visitingHero))
  773. enterBuilding(building);
  774. else
  775. LOCPLINT->cb->visitTownBuilding(town, building);
  776. }
  777. }
  778. void CCastleBuildings::enterBlacksmith(BuildingID building, ArtifactID artifactID)
  779. {
  780. const CGHeroInstance *hero = town->visitingHero;
  781. if(!hero)
  782. {
  783. LOCPLINT->showInfoDialog(boost::str(boost::format(CGI->generaltexth->allTexts[273]) % town->getTown()->buildings.find(building)->second->getNameTranslated()));
  784. return;
  785. }
  786. auto art = artifactID.toArtifact();
  787. int price = art->getPrice();
  788. bool possible = LOCPLINT->cb->getResourceAmount(EGameResID::GOLD) >= price;
  789. if(possible)
  790. {
  791. for(auto slot : art->getPossibleSlots().at(ArtBearer::HERO))
  792. {
  793. if(hero->getArt(slot) == nullptr || hero->getArt(slot)->getTypeId() != artifactID)
  794. {
  795. possible = true;
  796. break;
  797. }
  798. else
  799. {
  800. possible = false;
  801. }
  802. }
  803. }
  804. CreatureID creatureID = artifactID.toArtifact()->getWarMachine();
  805. GH.windows().createAndPushWindow<CBlacksmithDialog>(possible, creatureID, artifactID, hero->id);
  806. }
  807. void CCastleBuildings::enterBuilding(BuildingID building)
  808. {
  809. std::vector<std::shared_ptr<CComponent>> comps(1, std::make_shared<CComponent>(ComponentType::BUILDING, BuildingTypeUniqueID(town->getFactionID(), building)));
  810. LOCPLINT->showInfoDialog( town->getTown()->buildings.find(building)->second->getDescriptionTranslated(), comps);
  811. }
  812. void CCastleBuildings::enterCastleGate(BuildingID building)
  813. {
  814. if (!town->visitingHero)
  815. {
  816. LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[126]);
  817. return;//only visiting hero can use castle gates
  818. }
  819. std::vector <int> availableTowns;
  820. std::vector<std::shared_ptr<IImage>> images;
  821. std::vector <const CGTownInstance*> Towns = LOCPLINT->localState->getOwnedTowns();
  822. for(auto & Town : Towns)
  823. {
  824. const CGTownInstance *t = Town;
  825. if (t->id != this->town->id && t->visitingHero == nullptr && //another town, empty and this is
  826. t->getFactionID() == town->getFactionID() && //the town of the same faction
  827. t->hasBuilt(BuildingSubID::CASTLE_GATE)) //and the town has a castle gate
  828. {
  829. availableTowns.push_back(t->id.getNum());//add to the list
  830. if(settings["general"]["enableUiEnhancements"].Bool())
  831. {
  832. auto image = GH.renderHandler().loadImage(AnimationPath::builtin("ITPA"), t->getTown()->clientInfo.icons[t->hasFort()][false] + 2, 0, EImageBlitMode::OPAQUE);
  833. image->scaleTo(Point(35, 23), EScalingAlgorithm::NEAREST);
  834. images.push_back(image);
  835. }
  836. }
  837. }
  838. auto gateIcon = std::make_shared<CAnimImage>(town->getTown()->clientInfo.buildingsIcons, building);//will be deleted by selection window
  839. auto wnd = std::make_shared<CObjectListWindow>(availableTowns, gateIcon, CGI->generaltexth->jktexts[40],
  840. CGI->generaltexth->jktexts[41], std::bind (&CCastleInterface::castleTeleport, LOCPLINT->castleInt, _1), 0, images);
  841. wnd->onPopup = [availableTowns](int index) { CRClickPopup::createAndPush(LOCPLINT->cb->getObjInstance(ObjectInstanceID(availableTowns[index])), GH.getCursorPosition()); };
  842. GH.windows().pushWindow(wnd);
  843. }
  844. void CCastleBuildings::enterDwelling(int level)
  845. {
  846. if (level < 0 || level >= town->creatures.size() || town->creatures[level].second.empty())
  847. {
  848. assert(0);
  849. logGlobal->error("Attempt to enter into invalid dwelling of level %d in town %s (%s)", level, town->getNameTranslated(), town->getFaction()->getNameTranslated());
  850. return;
  851. }
  852. auto recruitCb = [=](CreatureID id, int count)
  853. {
  854. LOCPLINT->cb->recruitCreatures(town, town->getUpperArmy(), id, count, level);
  855. };
  856. GH.windows().createAndPushWindow<CRecruitmentWindow>(town, level, town->getUpperArmy(), recruitCb, nullptr, -87);
  857. }
  858. void CCastleBuildings::enterToTheQuickRecruitmentWindow()
  859. {
  860. const auto beginIt = town->creatures.cbegin();
  861. const auto afterLastIt = town->creatures.size() > town->getTown()->creatures.size()
  862. ? std::next(beginIt, town->getTown()->creatures.size())
  863. : town->creatures.cend();
  864. const auto hasSomeoneToRecruit = std::any_of(beginIt, afterLastIt,
  865. [](const auto & creatureInfo) { return creatureInfo.first > 0; });
  866. if(hasSomeoneToRecruit)
  867. GH.windows().createAndPushWindow<QuickRecruitmentWindow>(town, pos);
  868. else
  869. CInfoWindow::showInfoDialog(CGI->generaltexth->translate("vcmi.townHall.noCreaturesToRecruit"), {});
  870. }
  871. void CCastleBuildings::enterFountain(const BuildingID & building, BuildingSubID::EBuildingSubID subID, BuildingID upgrades)
  872. {
  873. std::vector<std::shared_ptr<CComponent>> comps(1, std::make_shared<CComponent>(ComponentType::BUILDING, BuildingTypeUniqueID(town->getFactionID(), building)));
  874. std::string descr = town->getTown()->buildings.find(building)->second->getDescriptionTranslated();
  875. std::string hasNotProduced;
  876. std::string hasProduced;
  877. hasNotProduced = CGI->generaltexth->allTexts[677];
  878. hasProduced = CGI->generaltexth->allTexts[678];
  879. bool isMysticPondOrItsUpgrade = subID == BuildingSubID::MYSTIC_POND
  880. || (upgrades != BuildingID::NONE
  881. && town->getTown()->buildings.find(BuildingID(upgrades))->second->subId == BuildingSubID::MYSTIC_POND);
  882. if(upgrades != BuildingID::NONE)
  883. descr += "\n\n"+town->getTown()->buildings.find(BuildingID(upgrades))->second->getDescriptionTranslated();
  884. if(isMysticPondOrItsUpgrade) //for vanila Rampart like towns
  885. {
  886. if(town->bonusValue.first == 0) //Mystic Pond produced nothing;
  887. descr += "\n\n" + hasNotProduced;
  888. else //Mystic Pond produced something;
  889. {
  890. descr += "\n\n" + hasProduced;
  891. boost::algorithm::replace_first(descr,"%s",CGI->generaltexth->restypes[town->bonusValue.first]);
  892. boost::algorithm::replace_first(descr,"%d",std::to_string(town->bonusValue.second));
  893. }
  894. }
  895. LOCPLINT->showInfoDialog(descr, comps);
  896. }
  897. void CCastleBuildings::enterMagesGuild()
  898. {
  899. const CGHeroInstance *hero = getHero();
  900. // hero doesn't have spellbok
  901. // or it is not our turn and we can't make actions
  902. if(hero && !hero->hasSpellbook() && LOCPLINT->makingTurn)
  903. {
  904. if(hero->isCampaignYog())
  905. {
  906. // "Yog has given up magic in all its forms..."
  907. LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[736]);
  908. }
  909. else if(LOCPLINT->cb->getResourceAmount(EGameResID::GOLD) < 500) //not enough gold to buy spellbook
  910. {
  911. openMagesGuild();
  912. LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[213]);
  913. }
  914. else
  915. {
  916. CFunctionList<void()> onYes = [this](){ openMagesGuild(); };
  917. CFunctionList<void()> onNo = onYes;
  918. onYes += [hero](){ LOCPLINT->cb->buyArtifact(hero, ArtifactID::SPELLBOOK); };
  919. std::vector<std::shared_ptr<CComponent>> components(1, std::make_shared<CComponent>(ComponentType::ARTIFACT, ArtifactID(ArtifactID::SPELLBOOK)));
  920. LOCPLINT->showYesNoDialog(CGI->generaltexth->allTexts[214], onYes, onNo, components);
  921. }
  922. }
  923. else
  924. {
  925. openMagesGuild();
  926. }
  927. }
  928. void CCastleBuildings::enterTownHall()
  929. {
  930. if(town->visitingHero && town->visitingHero->hasArt(ArtifactID::GRAIL) &&
  931. !town->hasBuilt(BuildingID::GRAIL)) //hero has grail, but town does not have it
  932. {
  933. if(!vstd::contains(town->forbiddenBuildings, BuildingID::GRAIL))
  934. {
  935. LOCPLINT->showYesNoDialog(CGI->generaltexth->allTexts[597], //Do you wish this to be the permanent home of the Grail?
  936. [&](){ LOCPLINT->cb->buildBuilding(town, BuildingID::GRAIL); },
  937. [&](){ openTownHall(); });
  938. }
  939. else
  940. {
  941. LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[673]);
  942. assert(GH.windows().topWindow<CInfoWindow>() != nullptr);
  943. GH.windows().topWindow<CInfoWindow>()->buttons[0]->addCallback(std::bind(&CCastleBuildings::openTownHall, this));
  944. }
  945. }
  946. else
  947. {
  948. openTownHall();
  949. }
  950. }
  951. void CCastleBuildings::openMagesGuild()
  952. {
  953. auto mageGuildBackground = LOCPLINT->castleInt->town->getTown()->clientInfo.guildBackground;
  954. GH.windows().createAndPushWindow<CMageGuildScreen>(LOCPLINT->castleInt, mageGuildBackground);
  955. }
  956. void CCastleBuildings::openTownHall()
  957. {
  958. GH.windows().createAndPushWindow<CHallInterface>(town);
  959. }
  960. void CCastleBuildings::enterAnyThievesGuild()
  961. {
  962. std::vector<const CGTownInstance*> towns = LOCPLINT->cb->getTownsInfo(true);
  963. for(auto & ownedTown : towns)
  964. {
  965. if(ownedTown->hasBuilt(BuildingID::TAVERN))
  966. {
  967. LOCPLINT->showThievesGuildWindow(ownedTown);
  968. return;
  969. }
  970. }
  971. LOCPLINT->showInfoDialog(CGI->generaltexth->translate("vcmi.adventureMap.noTownWithTavern"));
  972. }
  973. void CCastleBuildings::enterBank(BuildingID building)
  974. {
  975. std::vector<std::shared_ptr<CComponent>> components;
  976. if(town->bonusValue.second > 0)
  977. {
  978. components.push_back(std::make_shared<CComponent>(ComponentType::RESOURCE_PER_DAY, GameResID(GameResID::GOLD), -500));
  979. LOCPLINT->showInfoDialog(CGI->generaltexth->translate("vcmi.townStructure.bank.payBack"), components);
  980. }
  981. else{
  982. components.push_back(std::make_shared<CComponent>(ComponentType::RESOURCE, GameResID(GameResID::GOLD), 2500));
  983. LOCPLINT->showYesNoDialog(CGI->generaltexth->translate("vcmi.townStructure.bank.borrow"), [this, building](){ LOCPLINT->cb->visitTownBuilding(town, building); }, nullptr, components);
  984. }
  985. }
  986. void CCastleBuildings::enterAnyMarket()
  987. {
  988. if(town->hasBuilt(BuildingID::MARKETPLACE))
  989. {
  990. GH.windows().createAndPushWindow<CMarketWindow>(town, nullptr, nullptr, EMarketMode::RESOURCE_RESOURCE);
  991. return;
  992. }
  993. std::vector<const CGTownInstance*> towns = LOCPLINT->cb->getTownsInfo(true);
  994. for(auto & town : towns)
  995. {
  996. if(town->hasBuilt(BuildingID::MARKETPLACE))
  997. {
  998. GH.windows().createAndPushWindow<CMarketWindow>(town, nullptr, nullptr, EMarketMode::RESOURCE_RESOURCE);
  999. return;
  1000. }
  1001. }
  1002. LOCPLINT->showInfoDialog(CGI->generaltexth->translate("vcmi.adventureMap.noTownWithMarket"));
  1003. }
  1004. CCreaInfo::CCreaInfo(Point position, const CGTownInstance * Town, int Level, bool compact, bool _showAvailable):
  1005. town(Town),
  1006. level(Level),
  1007. showAvailable(_showAvailable)
  1008. {
  1009. OBJECT_CONSTRUCTION;
  1010. pos += position;
  1011. if(town->creatures.size() <= level || town->creatures[level].second.empty())
  1012. {
  1013. level = -1;
  1014. return;//No creature
  1015. }
  1016. addUsedEvents(LCLICK | SHOW_POPUP | HOVER);
  1017. creature = town->creatures[level].second.back();
  1018. picture = std::make_shared<CAnimImage>(AnimationPath::builtin("CPRSMALL"), creature.toEntity(VLC)->getIconIndex(), 0, 8, 0);
  1019. std::string value;
  1020. if(showAvailable)
  1021. value = std::to_string(town->creatures[level].first);
  1022. else
  1023. value = std::string("+") + std::to_string(town->creatureGrowth(level));
  1024. if(compact)
  1025. {
  1026. label = std::make_shared<CLabel>(40, 32, FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, value);
  1027. pos.x += 8;
  1028. pos.w = 32;
  1029. pos.h = 32;
  1030. }
  1031. else
  1032. {
  1033. label = std::make_shared<CLabel>(24, 40, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, value);
  1034. pos.w = 48;
  1035. pos.h = 48;
  1036. }
  1037. }
  1038. void CCreaInfo::update()
  1039. {
  1040. if(label)
  1041. {
  1042. std::string value;
  1043. if(showAvailable)
  1044. value = std::to_string(town->creatures[level].first);
  1045. else
  1046. value = std::string("+") + std::to_string(town->creatureGrowth(level));
  1047. if(value != label->getText())
  1048. label->setText(value);
  1049. }
  1050. }
  1051. void CCreaInfo::hover(bool on)
  1052. {
  1053. MetaString message;
  1054. message.appendTextID("core.genrltxt.588");
  1055. message.replaceNameSingular(creature);
  1056. if(on)
  1057. {
  1058. GH.statusbar()->write(message.toString());
  1059. }
  1060. else
  1061. {
  1062. GH.statusbar()->clearIfMatching(message.toString());
  1063. }
  1064. }
  1065. void CCreaInfo::clickPressed(const Point & cursorPosition)
  1066. {
  1067. int offset = LOCPLINT->castleInt? (-87) : 0;
  1068. auto recruitCb = [=](CreatureID id, int count)
  1069. {
  1070. LOCPLINT->cb->recruitCreatures(town, town->getUpperArmy(), id, count, level);
  1071. };
  1072. GH.windows().createAndPushWindow<CRecruitmentWindow>(town, level, town->getUpperArmy(), recruitCb, nullptr, offset);
  1073. }
  1074. std::string CCreaInfo::genGrowthText()
  1075. {
  1076. GrowthInfo gi = town->getGrowthInfo(level);
  1077. MetaString descr;
  1078. descr.appendTextID("core.genrltxt.589");
  1079. descr.replaceNameSingular(creature);
  1080. descr.replaceNumber(gi.totalGrowth());
  1081. for(const GrowthInfo::Entry & entry : gi.entries)
  1082. {
  1083. descr.appendEOL();
  1084. descr.appendRawString(entry.description);
  1085. }
  1086. return descr.toString();
  1087. }
  1088. void CCreaInfo::showPopupWindow(const Point & cursorPosition)
  1089. {
  1090. if (showAvailable)
  1091. GH.windows().createAndPushWindow<CDwellingInfoBox>(GH.screenDimensions().x / 2, GH.screenDimensions().y / 2, town, level);
  1092. else
  1093. CRClickPopup::createAndPush(genGrowthText(), std::make_shared<CComponent>(ComponentType::CREATURE, creature));
  1094. }
  1095. bool CCreaInfo::getShowAvailable()
  1096. {
  1097. return showAvailable;
  1098. }
  1099. CTownInfo::CTownInfo(int posX, int posY, const CGTownInstance * Town, bool townHall)
  1100. : town(Town),
  1101. building(nullptr)
  1102. {
  1103. OBJECT_CONSTRUCTION;
  1104. addUsedEvents(SHOW_POPUP | HOVER);
  1105. pos.x += posX;
  1106. pos.y += posY;
  1107. int buildID;
  1108. if(townHall)
  1109. {
  1110. buildID = 10 + town->hallLevel();
  1111. picture = std::make_shared<CAnimImage>(AnimationPath::builtin("ITMTL.DEF"), town->hallLevel());
  1112. }
  1113. else
  1114. {
  1115. buildID = 6 + town->fortLevel();
  1116. if(buildID == 6)
  1117. return;//FIXME: suspicious statement, fix or comment
  1118. picture = std::make_shared<CAnimImage>(AnimationPath::builtin("ITMCL.DEF"), town->fortLevel()-1);
  1119. }
  1120. building = town->getTown()->buildings.at(BuildingID(buildID));
  1121. pos = picture->pos;
  1122. }
  1123. void CTownInfo::hover(bool on)
  1124. {
  1125. if(on)
  1126. {
  1127. if(building )
  1128. GH.statusbar()->write(building->getNameTranslated());
  1129. }
  1130. else
  1131. {
  1132. GH.statusbar()->clear();
  1133. }
  1134. }
  1135. void CTownInfo::showPopupWindow(const Point & cursorPosition)
  1136. {
  1137. if(building)
  1138. {
  1139. auto c = std::make_shared<CComponent>(ComponentType::BUILDING, BuildingTypeUniqueID(building->town->faction->getId(), building->bid));
  1140. CRClickPopup::createAndPush(CInfoWindow::genText(building->getNameTranslated(), building->getDescriptionTranslated()), c);
  1141. }
  1142. }
  1143. CCastleInterface::CCastleInterface(const CGTownInstance * Town, const CGTownInstance * from):
  1144. CWindowObject(PLAYER_COLORED | BORDERED),
  1145. town(Town)
  1146. {
  1147. OBJECT_CONSTRUCTION;
  1148. LOCPLINT->castleInt = this;
  1149. addUsedEvents(KEYBOARD);
  1150. builds = std::make_shared<CCastleBuildings>(town);
  1151. panel = std::make_shared<CPicture>(ImagePath::builtin("TOWNSCRN"), 0, builds->pos.h);
  1152. panel->setPlayerColor(LOCPLINT->playerID);
  1153. pos.w = panel->pos.w;
  1154. pos.h = builds->pos.h + panel->pos.h;
  1155. center();
  1156. updateShadow();
  1157. garr = std::make_shared<CGarrisonInt>(Point(305, 387), 4, Point(0,96), town->getUpperArmy(), town->visitingHero);
  1158. garr->setRedrawParent(true);
  1159. heroes = std::make_shared<HeroSlots>(town, Point(241, 387), Point(241, 483), garr, true);
  1160. title = std::make_shared<CLabel>(85, 387, FONT_MEDIUM, ETextAlignment::TOPLEFT, Colors::WHITE, town->getNameTranslated());
  1161. income = std::make_shared<CLabel>(195, 443, FONT_SMALL, ETextAlignment::CENTER);
  1162. icon = std::make_shared<CAnimImage>(AnimationPath::builtin("ITPT"), 0, 0, 15, 387);
  1163. exit = std::make_shared<CButton>(Point(744, 544), AnimationPath::builtin("TSBTNS"), CButton::tooltip(CGI->generaltexth->tcommands[8]), [&](){close();}, EShortcut::GLOBAL_RETURN);
  1164. exit->setImageOrder(4, 5, 6, 7);
  1165. auto split = std::make_shared<CButton>(Point(744, 382), AnimationPath::builtin("TSBTNS"), CButton::tooltip(CGI->generaltexth->tcommands[3]), [this]() { garr->splitClick(); }, EShortcut::HERO_ARMY_SPLIT);
  1166. garr->addSplitBtn(split);
  1167. Rect barRect(9, 182, 732, 18);
  1168. auto statusbarBackground = std::make_shared<CPicture>(panel->getSurface(), barRect, 9, 555);
  1169. statusbar = CGStatusBar::create(statusbarBackground);
  1170. resdatabar = std::make_shared<CResDataBar>(ImagePath::builtin("ARESBAR"), 3, 575, 37, 3, 84, 78);
  1171. townlist = std::make_shared<CTownList>(3, Rect(Point(743, 414), Point(48, 128)), Point(1,16), Point(0, 32), LOCPLINT->localState->getOwnedTowns().size() );
  1172. townlist->setScrollUpButton( std::make_shared<CButton>( Point(744, 414), AnimationPath::builtin("IAM014"), CButton::tooltipLocalized("core.help.306"), 0));
  1173. townlist->setScrollDownButton( std::make_shared<CButton>( Point(744, 526), AnimationPath::builtin("IAM015"), CButton::tooltipLocalized("core.help.307"), 0));
  1174. if(from)
  1175. townlist->select(from);
  1176. townlist->select(town); //this will scroll list to select current town
  1177. townlist->onSelect = std::bind(&CCastleInterface::townChange, this);
  1178. recreateIcons();
  1179. if (!from)
  1180. adventureInt->onAudioPaused();
  1181. CCS->musich->playMusicFromSet("faction", town->getFaction()->getJsonKey(), true, false);
  1182. }
  1183. CCastleInterface::~CCastleInterface()
  1184. {
  1185. // resume map audio if:
  1186. // adventureInt exists (may happen on exiting client with open castle interface)
  1187. // castleInt has not been replaced (happens on switching between towns inside castle interface)
  1188. if (adventureInt && LOCPLINT->castleInt == this)
  1189. adventureInt->onAudioResumed();
  1190. if(LOCPLINT->castleInt == this)
  1191. LOCPLINT->castleInt = nullptr;
  1192. }
  1193. void CCastleInterface::updateGarrisons()
  1194. {
  1195. garr->setArmy(town->getUpperArmy(), EGarrisonType::UPPER);
  1196. garr->setArmy(town->visitingHero, EGarrisonType::LOWER);
  1197. garr->recreateSlots();
  1198. heroes->update();
  1199. redraw();
  1200. }
  1201. bool CCastleInterface::holdsGarrison(const CArmedInstance * army)
  1202. {
  1203. return army == town || army == town->getUpperArmy() || army == town->visitingHero;
  1204. }
  1205. void CCastleInterface::close()
  1206. {
  1207. if(town->tempOwner == LOCPLINT->playerID) //we may have opened window for an allied town
  1208. {
  1209. if(town->visitingHero && town->visitingHero->tempOwner == LOCPLINT->playerID)
  1210. LOCPLINT->localState->setSelection(town->visitingHero);
  1211. else
  1212. LOCPLINT->localState->setSelection(town);
  1213. }
  1214. CWindowObject::close();
  1215. }
  1216. void CCastleInterface::castleTeleport(int where)
  1217. {
  1218. const CGTownInstance * dest = LOCPLINT->cb->getTown(ObjectInstanceID(where));
  1219. LOCPLINT->localState->setSelection(town->visitingHero);//according to assert(ho == adventureInt->selection) in the eraseCurrentPathOf
  1220. LOCPLINT->cb->teleportHero(town->visitingHero, dest);
  1221. LOCPLINT->localState->erasePath(town->visitingHero);
  1222. }
  1223. void CCastleInterface::townChange()
  1224. {
  1225. //TODO: do not recreate window
  1226. const CGTownInstance * dest = LOCPLINT->localState->getOwnedTown(townlist->getSelectedIndex());
  1227. const CGTownInstance * town = this->town;// "this" is going to be deleted
  1228. if ( dest == town )
  1229. return;
  1230. close();
  1231. GH.windows().createAndPushWindow<CCastleInterface>(dest, town);
  1232. }
  1233. void CCastleInterface::addBuilding(BuildingID bid)
  1234. {
  1235. if (town->getTown()->buildings.at(bid)->mode != CBuilding::BUILD_AUTO)
  1236. CCS->soundh->playSound(soundBase::newBuilding);
  1237. deactivate();
  1238. builds->addBuilding(bid);
  1239. recreateIcons();
  1240. activate();
  1241. redraw();
  1242. }
  1243. void CCastleInterface::removeBuilding(BuildingID bid)
  1244. {
  1245. deactivate();
  1246. builds->removeBuilding(bid);
  1247. recreateIcons();
  1248. activate();
  1249. redraw();
  1250. }
  1251. void CCastleInterface::recreateIcons()
  1252. {
  1253. OBJECT_CONSTRUCTION;
  1254. size_t iconIndex = town->getTown()->clientInfo.icons[town->hasFort()][town->built >= LOCPLINT->cb->getSettings().getInteger(EGameSettings::TOWNS_BUILDINGS_PER_TURN_CAP)];
  1255. icon->setFrame(iconIndex);
  1256. TResources townIncome = town->dailyIncome();
  1257. income->setText(std::to_string(townIncome[EGameResID::GOLD]));
  1258. hall = std::make_shared<CTownInfo>(80, 413, town, true);
  1259. fort = std::make_shared<CTownInfo>(122, 413, town, false);
  1260. fastTownHall = std::make_shared<CButton>(Point(80, 413), AnimationPath::builtin("castleInterfaceQuickAccess"), CButton::tooltip(), [this](){ builds->enterTownHall(); }, EShortcut::TOWN_OPEN_HALL);
  1261. fastTownHall->setOverlay(std::make_shared<CAnimImage>(AnimationPath::builtin("ITMTL"), town->hallLevel()));
  1262. int imageIndex = town->fortLevel() == CGTownInstance::EFortLevel::NONE ? 3 : town->fortLevel() - 1;
  1263. fastArmyPurchase = std::make_shared<CButton>(Point(122, 413), AnimationPath::builtin("castleInterfaceQuickAccess"), CButton::tooltip(), [this](){ builds->enterToTheQuickRecruitmentWindow(); }, EShortcut::TOWN_OPEN_RECRUITMENT);
  1264. fastArmyPurchase->setOverlay(std::make_shared<CAnimImage>(AnimationPath::builtin("itmcl"), imageIndex));
  1265. fastMarket = std::make_shared<LRClickableArea>(Rect(163, 410, 64, 42), [this]() { builds->enterAnyMarket(); });
  1266. fastTavern = std::make_shared<LRClickableArea>(Rect(15, 387, 58, 64), [&]()
  1267. {
  1268. if(town->hasBuilt(BuildingID::TAVERN))
  1269. LOCPLINT->showTavernWindow(town, nullptr, QueryID::NONE);
  1270. }, [this]{
  1271. if(!town->getFaction()->getDescriptionTranslated().empty())
  1272. CRClickPopup::createAndPush(town->getFaction()->getDescriptionTranslated());
  1273. });
  1274. creainfo.clear();
  1275. bool compactCreatureInfo = useCompactCreatureBox();
  1276. bool useAvailableCreaturesForLabel = useAvailableAmountAsCreatureLabel();
  1277. for(size_t i=0; i<4; i++)
  1278. creainfo.push_back(std::make_shared<CCreaInfo>(Point(14 + 55 * (int)i, 459), town, (int)i, compactCreatureInfo, useAvailableCreaturesForLabel));
  1279. for(size_t i=0; i<4; i++)
  1280. creainfo.push_back(std::make_shared<CCreaInfo>(Point(14 + 55 * (int)i, 507), town, (int)i + 4, compactCreatureInfo, useAvailableCreaturesForLabel));
  1281. }
  1282. void CCastleInterface::keyPressed(EShortcut key)
  1283. {
  1284. switch(key)
  1285. {
  1286. case EShortcut::MOVE_UP:
  1287. townlist->selectPrev();
  1288. break;
  1289. case EShortcut::MOVE_DOWN:
  1290. townlist->selectNext();
  1291. break;
  1292. case EShortcut::TOWN_OPEN_FORT:
  1293. GH.windows().createAndPushWindow<CFortScreen>(town);
  1294. break;
  1295. case EShortcut::TOWN_OPEN_MARKET:
  1296. builds->enterAnyMarket();
  1297. break;
  1298. case EShortcut::TOWN_OPEN_MAGE_GUILD:
  1299. if(town->hasBuilt(BuildingID::MAGES_GUILD_1))
  1300. builds->enterMagesGuild();
  1301. break;
  1302. case EShortcut::TOWN_OPEN_THIEVES_GUILD:
  1303. break;
  1304. case EShortcut::TOWN_OPEN_HERO_EXCHANGE:
  1305. if (town->visitingHero && town->garrisonHero)
  1306. LOCPLINT->showHeroExchange(town->visitingHero->id, town->garrisonHero->id);
  1307. break;
  1308. case EShortcut::TOWN_OPEN_HERO:
  1309. if (town->visitingHero)
  1310. LOCPLINT->openHeroWindow(town->visitingHero);
  1311. else if (town->garrisonHero)
  1312. LOCPLINT->openHeroWindow(town->garrisonHero);
  1313. break;
  1314. case EShortcut::TOWN_OPEN_VISITING_HERO:
  1315. if (town->visitingHero)
  1316. LOCPLINT->openHeroWindow(town->visitingHero);
  1317. break;
  1318. case EShortcut::TOWN_OPEN_GARRISONED_HERO:
  1319. if (town->garrisonHero)
  1320. LOCPLINT->openHeroWindow(town->garrisonHero);
  1321. break;
  1322. case EShortcut::TOWN_SWAP_ARMIES:
  1323. heroes->swapArmies();
  1324. break;
  1325. case EShortcut::TOWN_OPEN_TAVERN:
  1326. if(town->hasBuilt(BuildingID::TAVERN))
  1327. LOCPLINT->showTavernWindow(town, nullptr, QueryID::NONE);
  1328. break;
  1329. default:
  1330. break;
  1331. }
  1332. }
  1333. void CCastleInterface::creaturesChangedEventHandler()
  1334. {
  1335. for(auto creatureInfoBox : creainfo)
  1336. {
  1337. if(creatureInfoBox->getShowAvailable())
  1338. {
  1339. creatureInfoBox->update();
  1340. }
  1341. }
  1342. }
  1343. CHallInterface::CBuildingBox::CBuildingBox(int x, int y, const CGTownInstance * Town, const CBuilding * Building):
  1344. town(Town),
  1345. building(Building)
  1346. {
  1347. OBJECT_CONSTRUCTION;
  1348. addUsedEvents(LCLICK | SHOW_POPUP | HOVER);
  1349. pos.x += x;
  1350. pos.y += y;
  1351. pos.w = 154;
  1352. pos.h = 92;
  1353. state = LOCPLINT->cb->canBuildStructure(town, building->bid);
  1354. constexpr std::array panelIndex =
  1355. {
  1356. 3, 3, 3, 0, 0, 2, 2, 1, 2, 2, 3, 3
  1357. };
  1358. constexpr std::array iconIndex =
  1359. {
  1360. -1, -1, -1, 0, 0, 1, 2, -1, 1, 1, -1, -1
  1361. };
  1362. icon = std::make_shared<CAnimImage>(town->getTown()->clientInfo.buildingsIcons, building->bid, 0, 2, 2);
  1363. header = std::make_shared<CAnimImage>(AnimationPath::builtin("TPTHBAR"), panelIndex[static_cast<int>(state)], 0, 1, 73);
  1364. if(iconIndex[static_cast<int>(state)] >=0)
  1365. mark = std::make_shared<CAnimImage>(AnimationPath::builtin("TPTHCHK"), iconIndex[static_cast<int>(state)], 0, 136, 56);
  1366. name = std::make_shared<CLabel>(78, 81, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, building->getNameTranslated(), 150);
  1367. //todo: add support for all possible states
  1368. if(state >= EBuildingState::BUILDING_ERROR)
  1369. state = EBuildingState::FORBIDDEN;
  1370. }
  1371. void CHallInterface::CBuildingBox::hover(bool on)
  1372. {
  1373. if(on)
  1374. {
  1375. std::string toPrint;
  1376. if(state==EBuildingState::PREREQUIRES || state == EBuildingState::MISSING_BASE)
  1377. toPrint = CGI->generaltexth->hcommands[5];
  1378. else if(state==EBuildingState::CANT_BUILD_TODAY)
  1379. toPrint = CGI->generaltexth->allTexts[223];
  1380. else
  1381. toPrint = CGI->generaltexth->hcommands[static_cast<int>(state)];
  1382. boost::algorithm::replace_first(toPrint,"%s",building->getNameTranslated());
  1383. GH.statusbar()->write(toPrint);
  1384. }
  1385. else
  1386. {
  1387. GH.statusbar()->clear();
  1388. }
  1389. }
  1390. void CHallInterface::CBuildingBox::clickPressed(const Point & cursorPosition)
  1391. {
  1392. GH.windows().createAndPushWindow<CBuildWindow>(town,building,state,0);
  1393. }
  1394. void CHallInterface::CBuildingBox::showPopupWindow(const Point & cursorPosition)
  1395. {
  1396. GH.windows().createAndPushWindow<CBuildWindow>(town,building,state,1);
  1397. }
  1398. CHallInterface::CHallInterface(const CGTownInstance * Town):
  1399. CWindowObject(PLAYER_COLORED | BORDERED, Town->getTown()->clientInfo.hallBackground),
  1400. town(Town)
  1401. {
  1402. OBJECT_CONSTRUCTION;
  1403. resdatabar = std::make_shared<CMinorResDataBar>();
  1404. resdatabar->moveBy(pos.topLeft(), true);
  1405. Rect barRect(5, 556, 740, 18);
  1406. auto statusbarBackground = std::make_shared<CPicture>(background->getSurface(), barRect, 5, 556);
  1407. statusbar = CGStatusBar::create(statusbarBackground);
  1408. title = std::make_shared<CLabel>(399, 12, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, town->getTown()->buildings.at(BuildingID(town->hallLevel()+BuildingID::VILLAGE_HALL))->getNameTranslated());
  1409. exit = std::make_shared<CButton>(Point(748, 556), AnimationPath::builtin("TPMAGE1.DEF"), CButton::tooltip(CGI->generaltexth->hcommands[8]), [&](){close();}, EShortcut::GLOBAL_RETURN);
  1410. auto & boxList = town->getTown()->clientInfo.hallSlots;
  1411. boxes.resize(boxList.size());
  1412. for(size_t row=0; row<boxList.size(); row++) //for each row
  1413. {
  1414. for(size_t col=0; col<boxList[row].size(); col++) //for each box
  1415. {
  1416. const CBuilding * building = nullptr;
  1417. for(auto & buildingID : boxList[row][col])//we are looking for the first not built structure
  1418. {
  1419. if (!buildingID.hasValue())
  1420. {
  1421. logMod->warn("Invalid building ID found in hallSlots of town '%s'", town->getFaction()->getJsonKey() );
  1422. continue;
  1423. }
  1424. const CBuilding * current = town->getTown()->buildings.at(buildingID);
  1425. if(town->hasBuilt(buildingID))
  1426. {
  1427. building = current;
  1428. }
  1429. else
  1430. {
  1431. if(current->mode == CBuilding::BUILD_NORMAL)
  1432. {
  1433. building = current;
  1434. break;
  1435. }
  1436. }
  1437. }
  1438. int posX = pos.w/2 - (int)boxList[row].size()*154/2 - ((int)boxList[row].size()-1)*20 + 194*(int)col;
  1439. int posY = 35 + 104*(int)row;
  1440. if(building)
  1441. boxes[row].push_back(std::make_shared<CBuildingBox>(posX, posY, town, building));
  1442. }
  1443. }
  1444. }
  1445. CBuildWindow::CBuildWindow(const CGTownInstance *Town, const CBuilding * Building, EBuildingState state, bool rightClick):
  1446. CWindowObject(PLAYER_COLORED | (rightClick ? RCLICK_POPUP : 0), ImagePath::builtin("TPUBUILD")),
  1447. town(Town),
  1448. building(Building)
  1449. {
  1450. OBJECT_CONSTRUCTION;
  1451. icon = std::make_shared<CAnimImage>(town->getTown()->clientInfo.buildingsIcons, building->bid, 0, 125, 50);
  1452. auto statusbarBackground = std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26);
  1453. statusbar = CGStatusBar::create(statusbarBackground);
  1454. MetaString nameString;
  1455. nameString.appendTextID("core.hallinfo.7");
  1456. nameString.replaceTextID(building->getNameTextID());
  1457. name = std::make_shared<CLabel>(197, 30, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, nameString.toString());
  1458. description = std::make_shared<CTextBox>(building->getDescriptionTranslated(), Rect(33, 135, 329, 67), 0, FONT_MEDIUM, ETextAlignment::CENTER);
  1459. stateText = std::make_shared<CTextBox>(getTextForState(state), Rect(33, 216, 329, 67), 0, FONT_SMALL, ETextAlignment::CENTER);
  1460. //Create components for all required resources
  1461. std::vector<std::shared_ptr<CComponent>> components;
  1462. for(GameResID i : GameResID::ALL_RESOURCES())
  1463. {
  1464. if(building->resources[i])
  1465. {
  1466. MetaString message;
  1467. int resourceAmount = LOCPLINT->cb->getResourceAmount(i);
  1468. bool canAfford = resourceAmount >= building->resources[i];
  1469. if(!canAfford && state != EBuildingState::ALREADY_PRESENT && settings["general"]["enableUiEnhancements"].Bool())
  1470. {
  1471. message.appendRawString("{H3Red|%d}/%d");
  1472. message.replaceNumber(resourceAmount);
  1473. }
  1474. else
  1475. message.appendRawString("%d");
  1476. message.replaceNumber(building->resources[i]);
  1477. components.push_back(std::make_shared<CComponent>(ComponentType::RESOURCE, i, message.toString(), CComponent::small));
  1478. }
  1479. }
  1480. cost = std::make_shared<CComponentBox>(components, Rect(25, 300, pos.w - 50, 130));
  1481. if(!rightClick)
  1482. { //normal window
  1483. MetaString tooltipYes;
  1484. tooltipYes.appendTextID("core.genrltxt.595");
  1485. tooltipYes.replaceTextID(building->getNameTextID());
  1486. MetaString tooltipNo;
  1487. tooltipNo.appendTextID("core.genrltxt.596");
  1488. tooltipNo.replaceTextID(building->getNameTextID());
  1489. buy = std::make_shared<CButton>(Point(45, 446), AnimationPath::builtin("IBUY30"), CButton::tooltip(tooltipYes.toString()), [&](){ buyFunc(); }, EShortcut::GLOBAL_ACCEPT);
  1490. buy->setBorderColor(Colors::METALLIC_GOLD);
  1491. buy->block(state != EBuildingState::ALLOWED || LOCPLINT->playerID != town->tempOwner || !LOCPLINT->makingTurn);
  1492. cancel = std::make_shared<CButton>(Point(290, 445), AnimationPath::builtin("ICANCEL"), CButton::tooltip(tooltipNo.toString()), [&](){ close();}, EShortcut::GLOBAL_CANCEL);
  1493. cancel->setBorderColor(Colors::METALLIC_GOLD);
  1494. }
  1495. }
  1496. void CBuildWindow::buyFunc()
  1497. {
  1498. LOCPLINT->cb->buildBuilding(town,building->bid);
  1499. GH.windows().popWindows(2); //we - build window and hall screen
  1500. }
  1501. std::string CBuildWindow::getTextForState(EBuildingState state)
  1502. {
  1503. std::string ret;
  1504. if(state < EBuildingState::ALLOWED)
  1505. ret = CGI->generaltexth->hcommands[static_cast<int>(state)];
  1506. switch (state)
  1507. {
  1508. case EBuildingState::ALREADY_PRESENT:
  1509. case EBuildingState::CANT_BUILD_TODAY:
  1510. case EBuildingState::NO_RESOURCES:
  1511. ret.replace(ret.find_first_of("%s"), 2, building->getNameTranslated());
  1512. break;
  1513. case EBuildingState::ALLOWED:
  1514. return CGI->generaltexth->allTexts[219]; //all prereq. are met
  1515. case EBuildingState::PREREQUIRES:
  1516. {
  1517. auto toStr = [&](const BuildingID build) -> std::string
  1518. {
  1519. return town->getTown()->buildings.at(build)->getNameTranslated();
  1520. };
  1521. ret = CGI->generaltexth->allTexts[52];
  1522. ret += "\n" + town->genBuildingRequirements(building->bid).toString(toStr);
  1523. break;
  1524. }
  1525. case EBuildingState::MISSING_BASE:
  1526. {
  1527. std::string msg = CGI->generaltexth->translate("vcmi.townHall.missingBase");
  1528. ret = boost::str(boost::format(msg) % town->getTown()->buildings.at(building->upgrade)->getNameTranslated());
  1529. break;
  1530. }
  1531. }
  1532. return ret;
  1533. }
  1534. LabeledValue::LabeledValue(Rect size, std::string name, std::string descr, int min, int max)
  1535. {
  1536. OBJECT_CONSTRUCTION;
  1537. pos.x+=size.x;
  1538. pos.y+=size.y;
  1539. pos.w = size.w;
  1540. pos.h = size.h;
  1541. init(name, descr, min, max);
  1542. }
  1543. LabeledValue::LabeledValue(Rect size, std::string name, std::string descr, int val)
  1544. {
  1545. OBJECT_CONSTRUCTION;
  1546. pos.x+=size.x;
  1547. pos.y+=size.y;
  1548. pos.w = size.w;
  1549. pos.h = size.h;
  1550. init(name, descr, val, val);
  1551. }
  1552. void LabeledValue::init(std::string nameText, std::string descr, int min, int max)
  1553. {
  1554. addUsedEvents(HOVER);
  1555. hoverText = descr;
  1556. std::string valueText;
  1557. if(min && max)
  1558. {
  1559. valueText = std::to_string(min);
  1560. if(min != max)
  1561. valueText += '-' + std::to_string(max);
  1562. }
  1563. name = std::make_shared<CLabel>(3, 0, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE, nameText);
  1564. value = std::make_shared<CLabel>(pos.w-3, pos.h-2, FONT_SMALL, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, valueText);
  1565. }
  1566. void LabeledValue::hover(bool on)
  1567. {
  1568. if(on)
  1569. {
  1570. GH.statusbar()->write(hoverText);
  1571. }
  1572. else
  1573. {
  1574. GH.statusbar()->clear();
  1575. }
  1576. }
  1577. CFortScreen::CFortScreen(const CGTownInstance * town):
  1578. CWindowObject(PLAYER_COLORED | BORDERED, getBgName(town))
  1579. {
  1580. OBJECT_CONSTRUCTION;
  1581. ui32 fortSize = static_cast<ui32>(town->creatures.size());
  1582. if(fortSize > town->getTown()->creatures.size() && town->creatures.back().second.empty())
  1583. fortSize--;
  1584. fortSize = std::min(fortSize, static_cast<ui32>(GameConstants::CREATURES_PER_TOWN)); // for 8 creatures + portal of summoning
  1585. const CBuilding * fortBuilding = town->getTown()->buildings.at(BuildingID(town->fortLevel()+6));
  1586. title = std::make_shared<CLabel>(400, 12, FONT_BIG, ETextAlignment::CENTER, Colors::WHITE, fortBuilding->getNameTranslated());
  1587. std::string text = boost::str(boost::format(CGI->generaltexth->fcommands[6]) % fortBuilding->getNameTranslated());
  1588. exit = std::make_shared<CButton>(Point(748, 556), AnimationPath::builtin("TPMAGE1"), CButton::tooltip(text), [&](){ close(); }, EShortcut::GLOBAL_RETURN);
  1589. std::vector<Point> positions =
  1590. {
  1591. Point(10, 22), Point(404, 22),
  1592. Point(10, 155), Point(404,155),
  1593. Point(10, 288), Point(404,288)
  1594. };
  1595. if(fortSize == GameConstants::CREATURES_PER_TOWN)
  1596. {
  1597. positions.push_back(Point(10, 421));
  1598. positions.push_back(Point(404,421));
  1599. }
  1600. else
  1601. {
  1602. positions.push_back(Point(206,421));
  1603. }
  1604. for(ui32 i=0; i<fortSize; i++)
  1605. {
  1606. BuildingID buildingID;
  1607. if(fortSize == town->getTown()->creatures.size())
  1608. {
  1609. BuildingID buildID = BuildingID(BuildingID::getDwellingFromLevel(i, 0));
  1610. for(; town->getBuildings().count(buildID); BuildingID::advanceDwelling(buildID))
  1611. {
  1612. if(town->hasBuilt(buildID))
  1613. buildingID = buildID;
  1614. }
  1615. }
  1616. else
  1617. {
  1618. buildingID = BuildingID::SPECIAL_3;
  1619. }
  1620. recAreas.push_back(std::make_shared<RecruitArea>(positions[i].x, positions[i].y, town, i));
  1621. }
  1622. resdatabar = std::make_shared<CMinorResDataBar>();
  1623. resdatabar->moveBy(pos.topLeft(), true);
  1624. Rect barRect(4, 554, 740, 18);
  1625. auto statusbarBackground = std::make_shared<CPicture>(background->getSurface(), barRect, 4, 554);
  1626. statusbar = CGStatusBar::create(statusbarBackground);
  1627. }
  1628. ImagePath CFortScreen::getBgName(const CGTownInstance * town)
  1629. {
  1630. ui32 fortSize = static_cast<ui32>(town->creatures.size());
  1631. if(fortSize > town->getTown()->creatures.size() && town->creatures.back().second.empty())
  1632. fortSize--;
  1633. fortSize = std::min(fortSize, static_cast<ui32>(GameConstants::CREATURES_PER_TOWN)); // for 8 creatures + portal of summoning
  1634. if(fortSize == GameConstants::CREATURES_PER_TOWN)
  1635. return ImagePath::builtin("TPCASTL8");
  1636. else
  1637. return ImagePath::builtin("TPCASTL7");
  1638. }
  1639. void CFortScreen::creaturesChangedEventHandler()
  1640. {
  1641. for(auto & elem : recAreas)
  1642. elem->creaturesChangedEventHandler();
  1643. LOCPLINT->castleInt->creaturesChangedEventHandler();
  1644. }
  1645. CFortScreen::RecruitArea::RecruitArea(int posX, int posY, const CGTownInstance * Town, int Level):
  1646. town(Town),
  1647. level(Level),
  1648. availableCount(nullptr)
  1649. {
  1650. OBJECT_CONSTRUCTION;
  1651. pos.x +=posX;
  1652. pos.y +=posY;
  1653. pos.w = 386;
  1654. pos.h = 126;
  1655. if(!town->creatures[level].second.empty())
  1656. addUsedEvents(LCLICK | HOVER);//Activate only if dwelling is present
  1657. addUsedEvents(SHOW_POPUP);
  1658. icons = std::make_shared<CPicture>(ImagePath::builtin("TPCAINFO"), 261, 3);
  1659. if(getMyBuilding() != nullptr)
  1660. {
  1661. buildingIcon = std::make_shared<CAnimImage>(town->getTown()->clientInfo.buildingsIcons, getMyBuilding()->bid, 0, 4, 21);
  1662. buildingName = std::make_shared<CLabel>(78, 101, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, getMyBuilding()->getNameTranslated(), 152);
  1663. if(town->hasBuilt(getMyBuilding()->bid))
  1664. {
  1665. ui32 available = town->creatures[level].first;
  1666. std::string availableText = CGI->generaltexth->allTexts[217]+ std::to_string(available);
  1667. availableCount = std::make_shared<CLabel>(78, 119, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, availableText);
  1668. }
  1669. }
  1670. if(getMyCreature() != nullptr)
  1671. {
  1672. hoverText = boost::str(boost::format(CGI->generaltexth->tcommands[21]) % getMyCreature()->getNamePluralTranslated());
  1673. new CCreaturePic(159, 4, getMyCreature(), false);
  1674. new CLabel(78, 11, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, getMyCreature()->getNamePluralTranslated(), 152);
  1675. Rect sizes(287, 4, 96, 18);
  1676. values.push_back(std::make_shared<LabeledValue>(sizes, CGI->generaltexth->allTexts[190], CGI->generaltexth->fcommands[0], getMyCreature()->getAttack(false)));
  1677. sizes.y+=20;
  1678. values.push_back(std::make_shared<LabeledValue>(sizes, CGI->generaltexth->allTexts[191], CGI->generaltexth->fcommands[1], getMyCreature()->getDefense(false)));
  1679. sizes.y+=21;
  1680. values.push_back(std::make_shared<LabeledValue>(sizes, CGI->generaltexth->allTexts[199], CGI->generaltexth->fcommands[2], getMyCreature()->getMinDamage(false), getMyCreature()->getMaxDamage(false)));
  1681. sizes.y+=20;
  1682. values.push_back(std::make_shared<LabeledValue>(sizes, CGI->generaltexth->allTexts[388], CGI->generaltexth->fcommands[3], getMyCreature()->getMaxHealth()));
  1683. sizes.y+=21;
  1684. values.push_back(std::make_shared<LabeledValue>(sizes, CGI->generaltexth->allTexts[193], CGI->generaltexth->fcommands[4], getMyCreature()->valOfBonuses(BonusType::STACKS_SPEED)));
  1685. sizes.y+=20;
  1686. values.push_back(std::make_shared<LabeledValue>(sizes, CGI->generaltexth->allTexts[194], CGI->generaltexth->fcommands[5], town->creatureGrowth(level)));
  1687. }
  1688. }
  1689. const CCreature * CFortScreen::RecruitArea::getMyCreature()
  1690. {
  1691. if(!town->creatures.at(level).second.empty()) // built
  1692. return town->creatures.at(level).second.back().toCreature();
  1693. if(!town->getTown()->creatures.at(level).empty()) // there are creatures on this level
  1694. return town->getTown()->creatures.at(level).front().toCreature();
  1695. return nullptr;
  1696. }
  1697. const CBuilding * CFortScreen::RecruitArea::getMyBuilding()
  1698. {
  1699. BuildingID myID = BuildingID(BuildingID::getDwellingFromLevel(level, 0));
  1700. if (level == town->getTown()->creatures.size())
  1701. return town->getTown()->getSpecialBuilding(BuildingSubID::PORTAL_OF_SUMMONING);
  1702. if (!town->getTown()->buildings.count(myID))
  1703. return nullptr;
  1704. const CBuilding * build = town->getTown()->buildings.at(myID);
  1705. while (town->getTown()->buildings.count(myID))
  1706. {
  1707. if (town->hasBuilt(myID))
  1708. build = town->getTown()->buildings.at(myID);
  1709. BuildingID::advanceDwelling(myID);
  1710. }
  1711. return build;
  1712. }
  1713. void CFortScreen::RecruitArea::hover(bool on)
  1714. {
  1715. if(on)
  1716. GH.statusbar()->write(hoverText);
  1717. else
  1718. GH.statusbar()->clear();
  1719. }
  1720. void CFortScreen::RecruitArea::creaturesChangedEventHandler()
  1721. {
  1722. if(availableCount)
  1723. {
  1724. std::string availableText = CGI->generaltexth->allTexts[217] + std::to_string(town->creatures[level].first);
  1725. availableCount->setText(availableText);
  1726. }
  1727. }
  1728. void CFortScreen::RecruitArea::clickPressed(const Point & cursorPosition)
  1729. {
  1730. LOCPLINT->castleInt->builds->enterDwelling(level);
  1731. }
  1732. void CFortScreen::RecruitArea::showPopupWindow(const Point & cursorPosition)
  1733. {
  1734. if (getMyCreature() != nullptr)
  1735. GH.windows().createAndPushWindow<CStackWindow>(getMyCreature(), true);
  1736. }
  1737. CMageGuildScreen::CMageGuildScreen(CCastleInterface * owner, const ImagePath & imagename)
  1738. : CWindowObject(BORDERED, imagename), townId(owner->town->id)
  1739. {
  1740. OBJECT_CONSTRUCTION;
  1741. window = std::make_shared<CPicture>(owner->town->getTown()->clientInfo.guildWindow, 332, 76);
  1742. resdatabar = std::make_shared<CMinorResDataBar>();
  1743. resdatabar->moveBy(pos.topLeft(), true);
  1744. Rect barRect(7, 556, 737, 18);
  1745. auto statusbarBackground = std::make_shared<CPicture>(background->getSurface(), barRect, 7, 556);
  1746. statusbar = CGStatusBar::create(statusbarBackground);
  1747. exit = std::make_shared<CButton>(Point(748, 556), AnimationPath::builtin("TPMAGE1.DEF"), CButton::tooltip(CGI->generaltexth->allTexts[593]), [&](){ close(); }, EShortcut::GLOBAL_RETURN);
  1748. updateSpells(townId);
  1749. }
  1750. void CMageGuildScreen::updateSpells(ObjectInstanceID tID)
  1751. {
  1752. if(tID != townId)
  1753. return;
  1754. OBJECT_CONSTRUCTION;
  1755. static const std::vector<std::vector<Point> > positions =
  1756. {
  1757. {Point(222,445), Point(312,445), Point(402,445), Point(520,445), Point(610,445), Point(700,445)},
  1758. {Point(48,53), Point(48,147), Point(48,241), Point(48,335), Point(48,429)},
  1759. {Point(570,82), Point(672,82), Point(570,157), Point(672,157)},
  1760. {Point(183,42), Point(183,148), Point(183,253)},
  1761. {Point(491,325), Point(591,325)}
  1762. };
  1763. spells.clear();
  1764. emptyScrolls.clear();
  1765. const CGTownInstance * town = LOCPLINT->cb->getTown(townId);
  1766. for(uint32_t i=0; i<town->getTown()->mageLevel; i++)
  1767. {
  1768. uint32_t spellCount = town->spellsAtLevel(i+1,false); //spell at level with -1 hmmm?
  1769. for(uint32_t j=0; j<spellCount; j++)
  1770. {
  1771. if(i<town->mageGuildLevel() && town->spells[i].size()>j)
  1772. spells.push_back(std::make_shared<Scroll>(positions[i][j], town->spells[i][j].toSpell(), townId));
  1773. else
  1774. emptyScrolls.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("TPMAGES.DEF"), 1, 0, positions[i][j].x, positions[i][j].y));
  1775. }
  1776. }
  1777. redraw();
  1778. }
  1779. CMageGuildScreen::Scroll::Scroll(Point position, const CSpell *Spell, ObjectInstanceID townId)
  1780. : spell(Spell), townId(townId)
  1781. {
  1782. OBJECT_CONSTRUCTION;
  1783. addUsedEvents(LCLICK | SHOW_POPUP | HOVER);
  1784. pos += position;
  1785. image = std::make_shared<CAnimImage>(AnimationPath::builtin("SPELLSCR"), spell->id);
  1786. pos = image->pos;
  1787. }
  1788. void CMageGuildScreen::Scroll::clickPressed(const Point & cursorPosition)
  1789. {
  1790. const CGTownInstance * town = LOCPLINT->cb->getTown(townId);
  1791. if(LOCPLINT->cb->getSettings().getBoolean(EGameSettings::TOWNS_SPELL_RESEARCH) && town->spellResearchAllowed)
  1792. {
  1793. int level = -1;
  1794. for(int i = 0; i < town->spells.size(); i++)
  1795. if(vstd::find_pos(town->spells[i], spell->id) != -1)
  1796. level = i;
  1797. if(town->spellResearchCounterDay >= LOCPLINT->cb->getSettings().getValue(EGameSettings::TOWNS_SPELL_RESEARCH_PER_DAY).Vector()[level].Float())
  1798. {
  1799. LOCPLINT->showInfoDialog(CGI->generaltexth->translate("vcmi.spellResearch.comeAgain"));
  1800. return;
  1801. }
  1802. auto costBase = TResources(LOCPLINT->cb->getSettings().getValue(EGameSettings::TOWNS_SPELL_RESEARCH_COST).Vector()[level]);
  1803. auto costExponent = LOCPLINT->cb->getSettings().getValue(EGameSettings::TOWNS_SPELL_RESEARCH_COST_EXPONENT_PER_RESEARCH).Vector()[level].Float();
  1804. auto cost = costBase * std::pow(town->spellResearchAcceptedCounter + 1, costExponent);
  1805. std::vector<std::shared_ptr<CComponent>> resComps;
  1806. int index = town->spellsAtLevel(level, false);
  1807. if (index >= town->spells[level].size())
  1808. {
  1809. LOCPLINT->showInfoDialog(CGI->generaltexth->translate("vcmi.spellResearch.noMoreSpells"));
  1810. return;
  1811. }
  1812. auto newSpell = town->spells[level].at(index);
  1813. resComps.push_back(std::make_shared<CComponent>(ComponentType::SPELL, spell->id));
  1814. resComps.push_back(std::make_shared<CComponent>(ComponentType::SPELL, newSpell));
  1815. resComps.back()->newLine = true;
  1816. for(TResources::nziterator i(cost); i.valid(); i++)
  1817. {
  1818. resComps.push_back(std::make_shared<CComponent>(ComponentType::RESOURCE, i->resType, i->resVal, CComponent::ESize::medium));
  1819. }
  1820. std::vector<std::pair<AnimationPath, CFunctionList<void()>>> pom;
  1821. for(int i = 0; i < 3; i++)
  1822. pom.emplace_back(AnimationPath::builtin("settingsWindow/button80"), nullptr);
  1823. auto text = CGI->generaltexth->translate(LOCPLINT->cb->getResourceAmount().canAfford(cost) ? "vcmi.spellResearch.pay" : "vcmi.spellResearch.canNotAfford");
  1824. boost::replace_first(text, "%SPELL1", spell->id.toSpell()->getNameTranslated());
  1825. boost::replace_first(text, "%SPELL2", newSpell.toSpell()->getNameTranslated());
  1826. auto temp = std::make_shared<CInfoWindow>(text, LOCPLINT->playerID, resComps, pom);
  1827. temp->buttons[0]->setOverlay(std::make_shared<CPicture>(ImagePath::builtin("spellResearch/accept")));
  1828. temp->buttons[0]->addCallback([this, town](){ LOCPLINT->cb->spellResearch(town, spell->id, true); });
  1829. temp->buttons[0]->addPopupCallback([](){ CRClickPopup::createAndPush(CGI->generaltexth->translate("vcmi.spellResearch.research")); });
  1830. temp->buttons[0]->setEnabled(LOCPLINT->cb->getResourceAmount().canAfford(cost));
  1831. temp->buttons[1]->setOverlay(std::make_shared<CPicture>(ImagePath::builtin("spellResearch/reroll")));
  1832. temp->buttons[1]->addCallback([this, town](){ LOCPLINT->cb->spellResearch(town, spell->id, false); });
  1833. temp->buttons[1]->addPopupCallback([](){ CRClickPopup::createAndPush(CGI->generaltexth->translate("vcmi.spellResearch.skip")); });
  1834. temp->buttons[2]->setOverlay(std::make_shared<CPicture>(ImagePath::builtin("spellResearch/close")));
  1835. temp->buttons[2]->addPopupCallback([](){ CRClickPopup::createAndPush(CGI->generaltexth->translate("vcmi.spellResearch.abort")); });
  1836. GH.windows().pushWindow(temp);
  1837. }
  1838. else
  1839. LOCPLINT->showInfoDialog(spell->getDescriptionTranslated(0), std::make_shared<CComponent>(ComponentType::SPELL, spell->id));
  1840. }
  1841. void CMageGuildScreen::Scroll::showPopupWindow(const Point & cursorPosition)
  1842. {
  1843. CRClickPopup::createAndPush(spell->getDescriptionTranslated(0), std::make_shared<CComponent>(ComponentType::SPELL, spell->id));
  1844. }
  1845. void CMageGuildScreen::Scroll::hover(bool on)
  1846. {
  1847. if(on)
  1848. GH.statusbar()->write(spell->getNameTranslated());
  1849. else
  1850. GH.statusbar()->clear();
  1851. }
  1852. CBlacksmithDialog::CBlacksmithDialog(bool possible, CreatureID creMachineID, ArtifactID aid, ObjectInstanceID hid):
  1853. CWindowObject(PLAYER_COLORED, ImagePath::builtin("TPSMITH"))
  1854. {
  1855. OBJECT_CONSTRUCTION;
  1856. Rect barRect(8, pos.h - 26, pos.w - 16, 19);
  1857. auto statusbarBackground = std::make_shared<CPicture>(background->getSurface(), barRect, 8, pos.h - 26);
  1858. statusbar = CGStatusBar::create(statusbarBackground);
  1859. animBG = std::make_shared<CPicture>(ImagePath::builtin("TPSMITBK"), 64, 50);
  1860. animBG->needRefresh = true;
  1861. const CCreature * creature = creMachineID.toCreature();
  1862. anim = std::make_shared<CCreatureAnim>(64, 50, creature->animDefName);
  1863. anim->clipRect(113,125,200,150);
  1864. MetaString titleString;
  1865. titleString.appendTextID("core.genrltxt.274");
  1866. titleString.replaceTextID(creature->getNameSingularTextID());
  1867. MetaString buyText;
  1868. buyText.appendTextID("core.genrltxt.595");
  1869. buyText.replaceTextID(creature->getNameSingularTextID());
  1870. MetaString cancelText;
  1871. cancelText.appendTextID("core.genrltxt.596");
  1872. cancelText.replaceTextID(creature->getNameSingularTextID());
  1873. std::string costString = std::to_string(aid.toEntity(CGI)->getPrice());
  1874. title = std::make_shared<CLabel>(165, 28, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, titleString.toString());
  1875. costText = std::make_shared<CLabel>(165, 218, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->jktexts[43]);
  1876. costValue = std::make_shared<CLabel>(165, 292, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, costString);
  1877. buy = std::make_shared<CButton>(Point(42, 312), AnimationPath::builtin("IBUY30.DEF"), CButton::tooltip(buyText.toString()), [&](){ close(); }, EShortcut::GLOBAL_ACCEPT);
  1878. cancel = std::make_shared<CButton>(Point(224, 312), AnimationPath::builtin("ICANCEL.DEF"), CButton::tooltip(cancelText.toString()), [&](){ close(); }, EShortcut::GLOBAL_CANCEL);
  1879. if(possible)
  1880. buy->addCallback([=](){ LOCPLINT->cb->buyArtifact(LOCPLINT->cb->getHero(hid),aid); });
  1881. else
  1882. buy->block(true);
  1883. costIcon = std::make_shared<CAnimImage>(AnimationPath::builtin("RESOURCE"), GameResID(EGameResID::GOLD), 0, 148, 244);
  1884. }