CCastleInterface.cpp 62 KB

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