CCastleInterface.cpp 76 KB

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