CCastleInterface.cpp 65 KB

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