CCastleInterface.cpp 63 KB

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