2
0

CCastleInterface.cpp 74 KB

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