CCastleInterface.cpp 78 KB

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