CCastleInterface.cpp 81 KB

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