CCastleInterface.cpp 79 KB

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