CCastleInterface.cpp 63 KB

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