CCastleInterface.cpp 71 KB

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