CCastleInterface.cpp 65 KB

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