CCastleInterface.cpp 77 KB

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