CCastleInterface.cpp 64 KB

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