BattleInterfaceClasses.cpp 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145
  1. /*
  2. * BattleInterfaceClasses.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 "BattleInterfaceClasses.h"
  12. #include "BattleInterface.h"
  13. #include "BattleActionsController.h"
  14. #include "BattleRenderer.h"
  15. #include "BattleSiegeController.h"
  16. #include "BattleFieldController.h"
  17. #include "BattleStacksController.h"
  18. #include "BattleWindow.h"
  19. #include "../CGameInfo.h"
  20. #include "../CPlayerInterface.h"
  21. #include "../gui/CursorHandler.h"
  22. #include "../gui/CGuiHandler.h"
  23. #include "../gui/Shortcut.h"
  24. #include "../gui/MouseButton.h"
  25. #include "../gui/WindowHandler.h"
  26. #include "../media/IMusicPlayer.h"
  27. #include "../render/Canvas.h"
  28. #include "../render/IImage.h"
  29. #include "../render/IFont.h"
  30. #include "../render/Graphics.h"
  31. #include "../widgets/Buttons.h"
  32. #include "../widgets/CComponent.h"
  33. #include "../widgets/Images.h"
  34. #include "../widgets/Slider.h"
  35. #include "../widgets/TextControls.h"
  36. #include "../widgets/VideoWidget.h"
  37. #include "../widgets/GraphicalPrimitiveCanvas.h"
  38. #include "../windows/CMessage.h"
  39. #include "../windows/CCreatureWindow.h"
  40. #include "../windows/CSpellWindow.h"
  41. #include "../windows/InfoWindows.h"
  42. #include "../render/CAnimation.h"
  43. #include "../render/IRenderHandler.h"
  44. #include "../adventureMap/CInGameConsole.h"
  45. #include "../eventsSDL/InputHandler.h"
  46. #include "../../CCallback.h"
  47. #include "../../lib/CStack.h"
  48. #include "../../lib/CConfigHandler.h"
  49. #include "../../lib/CCreatureHandler.h"
  50. #include "../../lib/gameState/InfoAboutArmy.h"
  51. #include "../../lib/CGeneralTextHandler.h"
  52. #include "../../lib/CTownHandler.h"
  53. #include "../../lib/CHeroHandler.h"
  54. #include "../../lib/StartInfo.h"
  55. #include "../../lib/mapObjects/CGTownInstance.h"
  56. #include "../../lib/networkPacks/PacksForClientBattle.h"
  57. #include "../../lib/TextOperations.h"
  58. #include "../../lib/json/JsonUtils.h"
  59. void BattleConsole::showAll(Canvas & to)
  60. {
  61. CIntObject::showAll(to);
  62. Point line1 (pos.x + pos.w/2, pos.y + 8);
  63. Point line2 (pos.x + pos.w/2, pos.y + 24);
  64. auto visibleText = getVisibleText();
  65. if(visibleText.size() > 0)
  66. to.drawText(line1, FONT_SMALL, Colors::WHITE, ETextAlignment::CENTER, visibleText[0]);
  67. if(visibleText.size() > 1)
  68. to.drawText(line2, FONT_SMALL, Colors::WHITE, ETextAlignment::CENTER, visibleText[1]);
  69. }
  70. std::vector<std::string> BattleConsole::getVisibleText() const
  71. {
  72. // high priority texts that hide battle log entries
  73. for(const auto & text : {consoleText, hoverText})
  74. {
  75. if (text.empty())
  76. continue;
  77. auto result = CMessage::breakText(text, pos.w, FONT_SMALL);
  78. if(result.size() > 2 && text.find('\n') != std::string::npos)
  79. {
  80. // Text has too many lines to fit into console, but has line breaks. Try ignore them and fit text that way
  81. std::string cleanText = boost::algorithm::replace_all_copy(text, "\n", " ");
  82. result = CMessage::breakText(cleanText, pos.w, FONT_SMALL);
  83. }
  84. if(result.size() > 2)
  85. result.resize(2);
  86. return result;
  87. }
  88. // log is small enough to fit entirely - display it as such
  89. if (logEntries.size() < 3)
  90. return logEntries;
  91. return { logEntries[scrollPosition - 1], logEntries[scrollPosition] };
  92. }
  93. std::vector<std::string> BattleConsole::splitText(const std::string &text)
  94. {
  95. std::vector<std::string> lines;
  96. std::vector<std::string> output;
  97. boost::split(lines, text, boost::is_any_of("\n"));
  98. for(const auto & line : lines)
  99. {
  100. if (graphics->fonts[FONT_SMALL]->getStringWidth(text) < pos.w)
  101. {
  102. output.push_back(line);
  103. }
  104. else
  105. {
  106. std::vector<std::string> substrings = CMessage::breakText(line, pos.w, FONT_SMALL);
  107. output.insert(output.end(), substrings.begin(), substrings.end());
  108. }
  109. }
  110. return output;
  111. }
  112. bool BattleConsole::addText(const std::string & text)
  113. {
  114. logGlobal->trace("CBattleConsole message: %s", text);
  115. auto newLines = splitText(text);
  116. logEntries.insert(logEntries.end(), newLines.begin(), newLines.end());
  117. scrollPosition = (int)logEntries.size()-1;
  118. redraw();
  119. return true;
  120. }
  121. void BattleConsole::scrollUp(ui32 by)
  122. {
  123. if(scrollPosition > static_cast<int>(by))
  124. scrollPosition -= by;
  125. redraw();
  126. }
  127. void BattleConsole::scrollDown(ui32 by)
  128. {
  129. if(scrollPosition + by < logEntries.size())
  130. scrollPosition += by;
  131. redraw();
  132. }
  133. BattleConsole::BattleConsole(const BattleInterface & owner, std::shared_ptr<CPicture> backgroundSource, const Point & objectPos, const Point & imagePos, const Point &size)
  134. : CIntObject(LCLICK)
  135. , owner(owner)
  136. , scrollPosition(-1)
  137. , enteringText(false)
  138. {
  139. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  140. pos += objectPos;
  141. pos.w = size.x;
  142. pos.h = size.y;
  143. background = std::make_shared<CPicture>(backgroundSource->getSurface(), Rect(imagePos, size), 0, 0 );
  144. }
  145. void BattleConsole::deactivate()
  146. {
  147. if (enteringText)
  148. LOCPLINT->cingconsole->endEnteringText(false);
  149. CIntObject::deactivate();
  150. }
  151. void BattleConsole::clickPressed(const Point & cursorPosition)
  152. {
  153. if(owner.makingTurn() && !owner.openingPlaying())
  154. {
  155. GH.windows().createAndPushWindow<BattleConsoleWindow>(boost::algorithm::join(logEntries, "\n"));
  156. }
  157. }
  158. void BattleConsole::setEnteringMode(bool on)
  159. {
  160. consoleText.clear();
  161. if (on)
  162. {
  163. assert(enteringText == false);
  164. GH.startTextInput(pos);
  165. }
  166. else
  167. {
  168. assert(enteringText == true);
  169. GH.stopTextInput();
  170. }
  171. enteringText = on;
  172. redraw();
  173. }
  174. void BattleConsole::setEnteredText(const std::string & text)
  175. {
  176. assert(enteringText == true);
  177. consoleText = text;
  178. redraw();
  179. }
  180. void BattleConsole::write(const std::string & Text)
  181. {
  182. hoverText = Text;
  183. redraw();
  184. }
  185. void BattleConsole::clearIfMatching(const std::string & Text)
  186. {
  187. if (hoverText == Text)
  188. clear();
  189. }
  190. void BattleConsole::clear()
  191. {
  192. write({});
  193. }
  194. BattleConsoleWindow::BattleConsoleWindow(const std::string & text)
  195. : CWindowObject(BORDERED)
  196. {
  197. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  198. pos.w = 429;
  199. pos.h = 434;
  200. updateShadow();
  201. center();
  202. backgroundTexture = std::make_shared<CFilledTexture>(ImagePath::builtin("DiBoxBck"), Rect(0, 0, pos.w, pos.h));
  203. buttonOk = std::make_shared<CButton>(Point(183, 388), AnimationPath::builtin("IOKAY"), CButton::tooltip(), [this](){ close(); }, EShortcut::GLOBAL_ACCEPT);
  204. Rect textArea(18, 17, 393, 354);
  205. textBoxBackgroundBorder = std::make_shared<TransparentFilledRectangle>(textArea, ColorRGBA(0, 0, 0, 75), ColorRGBA(128, 100, 75));
  206. textBox = std::make_shared<CTextBox>(text, textArea.resize(-5), CSlider::BROWN);
  207. if(textBox->slider)
  208. textBox->slider->scrollToMax();
  209. }
  210. const CGHeroInstance * BattleHero::instance()
  211. {
  212. return hero;
  213. }
  214. void BattleHero::tick(uint32_t msPassed)
  215. {
  216. size_t groupIndex = static_cast<size_t>(phase);
  217. float timePassed = msPassed / 1000.f;
  218. flagCurrentFrame += currentSpeed * timePassed;
  219. currentFrame += currentSpeed * timePassed;
  220. if(flagCurrentFrame >= flagAnimation->size(0))
  221. flagCurrentFrame -= flagAnimation->size(0);
  222. if(currentFrame >= animation->size(groupIndex))
  223. {
  224. currentFrame -= animation->size(groupIndex);
  225. switchToNextPhase();
  226. }
  227. }
  228. void BattleHero::render(Canvas & canvas)
  229. {
  230. size_t groupIndex = static_cast<size_t>(phase);
  231. auto flagFrame = flagAnimation->getImage(flagCurrentFrame, 0, true);
  232. auto heroFrame = animation->getImage(currentFrame, groupIndex, true);
  233. Point heroPosition = pos.center() - parent->pos.topLeft() - heroFrame->dimensions() / 2;
  234. Point flagPosition = pos.center() - parent->pos.topLeft() - flagFrame->dimensions() / 2;
  235. if(defender)
  236. flagPosition += Point(-4, -41);
  237. else
  238. flagPosition += Point(4, -41);
  239. canvas.draw(flagFrame, flagPosition);
  240. canvas.draw(heroFrame, heroPosition);
  241. }
  242. void BattleHero::pause()
  243. {
  244. currentSpeed = 0.f;
  245. }
  246. void BattleHero::play()
  247. {
  248. //H3 speed: 10 fps ( 100 ms per frame)
  249. currentSpeed = 10.f;
  250. }
  251. float BattleHero::getFrame() const
  252. {
  253. return currentFrame;
  254. }
  255. void BattleHero::collectRenderableObjects(BattleRenderer & renderer)
  256. {
  257. auto hex = defender ? BattleHex(GameConstants::BFIELD_WIDTH-1) : BattleHex(0);
  258. renderer.insert(EBattleFieldLayer::HEROES, hex, [this](BattleRenderer::RendererRef canvas)
  259. {
  260. render(canvas);
  261. });
  262. }
  263. void BattleHero::onPhaseFinished(const std::function<void()> & callback)
  264. {
  265. phaseFinishedCallback = callback;
  266. }
  267. void BattleHero::setPhase(EHeroAnimType newPhase)
  268. {
  269. nextPhase = newPhase;
  270. switchToNextPhase(); //immediately switch to next phase and then restore idling phase
  271. nextPhase = EHeroAnimType::HOLDING;
  272. }
  273. void BattleHero::heroLeftClicked()
  274. {
  275. if(owner.actionsController->spellcastingModeActive()) //we are casting a spell
  276. return;
  277. if(!hero || !owner.makingTurn())
  278. return;
  279. if(owner.getBattle()->battleCanCastSpell(hero, spells::Mode::HERO) == ESpellCastProblem::OK) //check conditions
  280. {
  281. CCS->curh->set(Cursor::Map::POINTER);
  282. GH.windows().createAndPushWindow<CSpellWindow>(hero, owner.getCurrentPlayerInterface());
  283. }
  284. }
  285. void BattleHero::heroRightClicked()
  286. {
  287. if(settings["battle"]["stickyHeroInfoWindows"].Bool())
  288. return;
  289. Point windowPosition;
  290. if(GH.screenDimensions().x < 1000)
  291. {
  292. windowPosition.x = (!defender) ? owner.fieldController->pos.left() + 1 : owner.fieldController->pos.right() - 79;
  293. windowPosition.y = owner.fieldController->pos.y + 135;
  294. }
  295. else
  296. {
  297. windowPosition.x = (!defender) ? owner.fieldController->pos.left() - 93 : owner.fieldController->pos.right() + 15;
  298. windowPosition.y = owner.fieldController->pos.y;
  299. }
  300. InfoAboutHero targetHero;
  301. if(owner.makingTurn() || settings["session"]["spectate"].Bool())
  302. {
  303. auto h = defender ? owner.defendingHeroInstance : owner.attackingHeroInstance;
  304. targetHero.initFromHero(h, InfoAboutHero::EInfoLevel::INBATTLE);
  305. GH.windows().createAndPushWindow<HeroInfoWindow>(targetHero, &windowPosition);
  306. }
  307. }
  308. void BattleHero::switchToNextPhase()
  309. {
  310. phase = nextPhase;
  311. currentFrame = 0.f;
  312. auto copy = phaseFinishedCallback;
  313. phaseFinishedCallback.clear();
  314. copy();
  315. }
  316. BattleHero::BattleHero(const BattleInterface & owner, const CGHeroInstance * hero, bool defender):
  317. defender(defender),
  318. hero(hero),
  319. owner(owner),
  320. phase(EHeroAnimType::HOLDING),
  321. nextPhase(EHeroAnimType::HOLDING),
  322. currentSpeed(0.f),
  323. currentFrame(0.f),
  324. flagCurrentFrame(0.f)
  325. {
  326. AnimationPath animationPath;
  327. if(!hero->type->battleImage.empty())
  328. animationPath = hero->type->battleImage;
  329. else
  330. if(hero->gender == EHeroGender::FEMALE)
  331. animationPath = hero->type->heroClass->imageBattleFemale;
  332. else
  333. animationPath = hero->type->heroClass->imageBattleMale;
  334. animation = GH.renderHandler().loadAnimation(animationPath);
  335. animation->preload();
  336. pos.w = 64;
  337. pos.h = 136;
  338. pos.x = owner.fieldController->pos.x + (defender ? (owner.fieldController->pos.w - pos.w) : 0);
  339. pos.y = owner.fieldController->pos.y;
  340. if(defender)
  341. animation->verticalFlip();
  342. if(defender)
  343. flagAnimation = GH.renderHandler().loadAnimation(AnimationPath::builtin("CMFLAGR"));
  344. else
  345. flagAnimation = GH.renderHandler().loadAnimation(AnimationPath::builtin("CMFLAGL"));
  346. flagAnimation->preload();
  347. flagAnimation->playerColored(hero->tempOwner);
  348. switchToNextPhase();
  349. play();
  350. addUsedEvents(TIME);
  351. }
  352. QuickSpellPanel::QuickSpellPanel(BattleInterface & owner)
  353. : CIntObject(0), owner(owner)
  354. {
  355. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  356. addUsedEvents(LCLICK | SHOW_POPUP | MOVE | INPUT_MODUS_CHANGE);
  357. pos = Rect(0, 0, 52, 600);
  358. background = std::make_shared<CFilledTexture>(ImagePath::builtin("DIBOXBCK"), pos);
  359. rect = std::make_shared<TransparentFilledRectangle>(Rect(0, 0, pos.w + 1, pos.h + 1), ColorRGBA(0, 0, 0, 0), ColorRGBA(241, 216, 120, 255));
  360. create();
  361. }
  362. void QuickSpellPanel::create()
  363. {
  364. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  365. const JsonNode config = JsonUtils::assembleFromFiles("config/shortcutsConfig");
  366. labels.clear();
  367. buttons.clear();
  368. buttonsDisabled.clear();
  369. auto hero = owner.getBattle()->battleGetMyHero();
  370. if(!hero)
  371. return;
  372. for(int i = 0; i < 12; i++) {
  373. std::string spellIdentifier = persistentStorage["quickSpell"][std::to_string(i)].String();
  374. SpellID id;
  375. try
  376. {
  377. id = SpellID::decode(spellIdentifier);
  378. }
  379. catch(const IdentifierResolutionException& e)
  380. {
  381. id = SpellID::NONE;
  382. }
  383. auto button = std::make_shared<CButton>(Point(2, 7 + 50 * i), AnimationPath::builtin("spellint"), CButton::tooltip(), [this, id, hero](){
  384. if(id.hasValue() && id.toSpell()->canBeCast(owner.getBattle().get(), spells::Mode::HERO, hero))
  385. {
  386. owner.castThisSpell(id);
  387. }
  388. });
  389. button->setOverlay(std::make_shared<CAnimImage>(AnimationPath::builtin("spellint"), !spellIdentifier.empty() ? id.num + 1 : 0));
  390. button->addPopupCallback([this, i, hero](){
  391. GH.input().hapticFeedback();
  392. GH.windows().createAndPushWindow<CSpellWindow>(hero, owner.curInt.get(), true, [this, i](SpellID spell){
  393. Settings configID = persistentStorage.write["quickSpell"][std::to_string(i)];
  394. configID->String() = spell.toSpell()->identifier;
  395. create();
  396. });
  397. });
  398. if(!id.hasValue() || !id.toSpell()->canBeCast(owner.getBattle().get(), spells::Mode::HERO, hero))
  399. {
  400. buttonsDisabled.push_back(std::make_shared<TransparentFilledRectangle>(Rect(2, 7 + 50 * i, 48, 36), ColorRGBA(0, 0, 0, 172)));
  401. }
  402. if(GH.input().getCurrentInputModus() == InputModus::MOUSE)
  403. labels.push_back(std::make_shared<CLabel>(7, 10 + 50 * i, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, config["keyboard"]["battleSpellShortcut" + std::to_string(i)].String()));
  404. buttons.push_back(button);
  405. }
  406. }
  407. void QuickSpellPanel::show(Canvas & to)
  408. {
  409. showAll(to);
  410. CIntObject::show(to);
  411. }
  412. void QuickSpellPanel::inputModusChanged(InputModus modi)
  413. {
  414. create();
  415. redraw();
  416. }
  417. HeroInfoBasicPanel::HeroInfoBasicPanel(const InfoAboutHero & hero, Point * position, bool initializeBackground)
  418. : CIntObject(0)
  419. {
  420. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  421. if (position != nullptr)
  422. moveTo(*position);
  423. if(initializeBackground)
  424. {
  425. background = std::make_shared<CPicture>(ImagePath::builtin("CHRPOP"));
  426. background->getSurface()->setBlitMode(EImageBlitMode::OPAQUE);
  427. background->colorize(hero.owner);
  428. }
  429. initializeData(hero);
  430. }
  431. void HeroInfoBasicPanel::initializeData(const InfoAboutHero & hero)
  432. {
  433. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  434. auto attack = hero.details->primskills[0];
  435. auto defense = hero.details->primskills[1];
  436. auto power = hero.details->primskills[2];
  437. auto knowledge = hero.details->primskills[3];
  438. auto morale = hero.details->morale;
  439. auto luck = hero.details->luck;
  440. auto currentSpellPoints = hero.details->mana;
  441. auto maxSpellPoints = hero.details->manaLimit;
  442. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("PortraitsLarge"), hero.getIconIndex(), 0, 10, 6));
  443. //primary stats
  444. labels.push_back(std::make_shared<CLabel>(9, 75, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[380] + ":"));
  445. labels.push_back(std::make_shared<CLabel>(9, 87, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[381] + ":"));
  446. labels.push_back(std::make_shared<CLabel>(9, 99, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[382] + ":"));
  447. labels.push_back(std::make_shared<CLabel>(9, 111, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[383] + ":"));
  448. labels.push_back(std::make_shared<CLabel>(69, 87, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(attack)));
  449. labels.push_back(std::make_shared<CLabel>(69, 99, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(defense)));
  450. labels.push_back(std::make_shared<CLabel>(69, 111, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(power)));
  451. labels.push_back(std::make_shared<CLabel>(69, 123, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(knowledge)));
  452. //morale+luck
  453. labels.push_back(std::make_shared<CLabel>(9, 131, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[384] + ":"));
  454. labels.push_back(std::make_shared<CLabel>(9, 143, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[385] + ":"));
  455. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("IMRL22"), morale + 3, 0, 47, 131));
  456. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("ILCK22"), luck + 3, 0, 47, 143));
  457. //spell points
  458. labels.push_back(std::make_shared<CLabel>(39, 174, EFonts::FONT_TINY, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[387]));
  459. labels.push_back(std::make_shared<CLabel>(39, 186, EFonts::FONT_TINY, ETextAlignment::CENTER, Colors::WHITE, std::to_string(currentSpellPoints) + "/" + std::to_string(maxSpellPoints)));
  460. }
  461. void HeroInfoBasicPanel::update(const InfoAboutHero & updatedInfo)
  462. {
  463. icons.clear();
  464. labels.clear();
  465. initializeData(updatedInfo);
  466. }
  467. void HeroInfoBasicPanel::show(Canvas & to)
  468. {
  469. showAll(to);
  470. CIntObject::show(to);
  471. }
  472. StackInfoBasicPanel::StackInfoBasicPanel(const CStack * stack, bool initializeBackground)
  473. : CIntObject(0)
  474. {
  475. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  476. if(initializeBackground)
  477. {
  478. background = std::make_shared<CPicture>(ImagePath::builtin("CCRPOP"));
  479. background->pos.y += 37;
  480. background->getSurface()->setBlitMode(EImageBlitMode::OPAQUE);
  481. background->colorize(stack->getOwner());
  482. background2 = std::make_shared<CPicture>(ImagePath::builtin("CHRPOP"));
  483. background2->getSurface()->setBlitMode(EImageBlitMode::OPAQUE);
  484. background2->colorize(stack->getOwner());
  485. }
  486. initializeData(stack);
  487. }
  488. void StackInfoBasicPanel::initializeData(const CStack * stack)
  489. {
  490. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  491. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("TWCRPORT"), stack->creatureId() + 2, 0, 10, 6));
  492. labels.push_back(std::make_shared<CLabel>(10 + 58, 6 + 64, FONT_MEDIUM, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, TextOperations::formatMetric(stack->getCount(), 4)));
  493. auto attack = std::to_string(CGI->creatures()->getByIndex(stack->creatureIndex())->getAttack(stack->isShooter())) + "(" + std::to_string(stack->getAttack(stack->isShooter())) + ")";
  494. auto defense = std::to_string(CGI->creatures()->getByIndex(stack->creatureIndex())->getDefense(stack->isShooter())) + "(" + std::to_string(stack->getDefense(stack->isShooter())) + ")";
  495. auto damage = std::to_string(CGI->creatures()->getByIndex(stack->creatureIndex())->getMinDamage(stack->isShooter())) + "-" + std::to_string(stack->getMaxDamage(stack->isShooter()));
  496. auto health = CGI->creatures()->getByIndex(stack->creatureIndex())->getMaxHealth();
  497. auto morale = stack->moraleVal();
  498. auto luck = stack->luckVal();
  499. auto killed = stack->getKilled();
  500. auto healthRemaining = TextOperations::formatMetric(std::max(stack->getAvailableHealth() - (stack->getCount() - 1) * health, (si64)0), 4);
  501. //primary stats*/
  502. labels.push_back(std::make_shared<CLabel>(9, 75, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[380] + ":"));
  503. labels.push_back(std::make_shared<CLabel>(9, 87, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[381] + ":"));
  504. labels.push_back(std::make_shared<CLabel>(9, 99, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[386] + ":"));
  505. labels.push_back(std::make_shared<CLabel>(9, 111, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[389] + ":"));
  506. labels.push_back(std::make_shared<CLabel>(69, 87, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, attack));
  507. labels.push_back(std::make_shared<CLabel>(69, 99, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, defense));
  508. labels.push_back(std::make_shared<CLabel>(69, 111, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, damage));
  509. labels.push_back(std::make_shared<CLabel>(69, 123, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(health)));
  510. //morale+luck
  511. labels.push_back(std::make_shared<CLabel>(9, 131, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[384] + ":"));
  512. labels.push_back(std::make_shared<CLabel>(9, 143, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[385] + ":"));
  513. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("IMRL22"), morale + 3, 0, 47, 131));
  514. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("ILCK22"), luck + 3, 0, 47, 143));
  515. //extra information
  516. labels.push_back(std::make_shared<CLabel>(9, 168, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, VLC->generaltexth->translate("vcmi.battleWindow.killed") + ":"));
  517. labels.push_back(std::make_shared<CLabel>(9, 180, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[389] + ":"));
  518. labels.push_back(std::make_shared<CLabel>(69, 180, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(killed)));
  519. labels.push_back(std::make_shared<CLabel>(69, 192, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, healthRemaining));
  520. //spells
  521. static const Point firstPos(15, 206); // position of 1st spell box
  522. static const Point offset(0, 38); // offset of each spell box from previous
  523. for(int i = 0; i < 3; i++)
  524. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("SpellInt"), 78, 0, firstPos.x + offset.x * i, firstPos.y + offset.y * i));
  525. int printed=0; //how many effect pics have been printed
  526. std::vector<SpellID> spells = stack->activeSpells();
  527. for(SpellID effect : spells)
  528. {
  529. //not all effects have graphics (for eg. Acid Breath)
  530. //for modded spells iconEffect is added to SpellInt.def
  531. const bool hasGraphics = (effect < SpellID::THUNDERBOLT) || (effect >= SpellID::AFTER_LAST);
  532. if (hasGraphics)
  533. {
  534. //FIXME: support permanent duration
  535. int duration = stack->getFirstBonus(Selector::source(BonusSource::SPELL_EFFECT, BonusSourceID(effect)))->turnsRemain;
  536. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("SpellInt"), effect + 1, 0, firstPos.x + offset.x * printed, firstPos.y + offset.y * printed));
  537. if(settings["general"]["enableUiEnhancements"].Bool())
  538. labels.push_back(std::make_shared<CLabel>(firstPos.x + offset.x * printed + 46, firstPos.y + offset.y * printed + 36, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(duration)));
  539. if(++printed >= 3 || (printed == 2 && spells.size() > 3)) // interface limit reached
  540. break;
  541. }
  542. }
  543. if(spells.size() == 0)
  544. labelsMultiline.push_back(std::make_shared<CMultiLineLabel>(Rect(firstPos.x, firstPos.y, 48, 36), EFonts::FONT_TINY, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[674]));
  545. if(spells.size() > 3)
  546. labelsMultiline.push_back(std::make_shared<CMultiLineLabel>(Rect(firstPos.x + offset.x * 2, firstPos.y + offset.y * 2 - 4, 48, 36), EFonts::FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, "..."));
  547. }
  548. void StackInfoBasicPanel::update(const CStack * updatedInfo)
  549. {
  550. icons.clear();
  551. labels.clear();
  552. labelsMultiline.clear();
  553. initializeData(updatedInfo);
  554. }
  555. void StackInfoBasicPanel::show(Canvas & to)
  556. {
  557. showAll(to);
  558. CIntObject::show(to);
  559. }
  560. HeroInfoWindow::HeroInfoWindow(const InfoAboutHero & hero, Point * position)
  561. : CWindowObject(RCLICK_POPUP | SHADOW_DISABLED, ImagePath::builtin("CHRPOP"))
  562. {
  563. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  564. if (position != nullptr)
  565. moveTo(*position);
  566. background->colorize(hero.owner); //maybe add this functionality to base class?
  567. content = std::make_shared<HeroInfoBasicPanel>(hero, nullptr, false);
  568. }
  569. BattleResultWindow::BattleResultWindow(const BattleResult & br, CPlayerInterface & _owner, bool allowReplay)
  570. : owner(_owner)
  571. {
  572. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  573. background = std::make_shared<CPicture>(ImagePath::builtin("CPRESULT"));
  574. background->colorize(owner.playerID);
  575. pos = center(background->pos);
  576. exit = std::make_shared<CButton>(Point(384, 505), AnimationPath::builtin("iok6432.def"), std::make_pair("", ""), [&](){ bExitf();}, EShortcut::GLOBAL_ACCEPT);
  577. exit->setBorderColor(Colors::METALLIC_GOLD);
  578. if(allowReplay || owner.cb->getStartInfo()->extraOptionsInfo.unlimitedReplay)
  579. {
  580. repeat = std::make_shared<CButton>(Point(24, 505), AnimationPath::builtin("icn6432.def"), std::make_pair("", ""), [&](){ bRepeatf();}, EShortcut::GLOBAL_CANCEL);
  581. repeat->setBorderColor(Colors::METALLIC_GOLD);
  582. labels.push_back(std::make_shared<CLabel>(232, 520, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->translate("vcmi.battleResultsWindow.applyResultsLabel")));
  583. }
  584. if(br.winner == 0) //attacker won
  585. {
  586. labels.push_back(std::make_shared<CLabel>(59, 124, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[410]));
  587. }
  588. else
  589. {
  590. labels.push_back(std::make_shared<CLabel>(59, 124, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[411]));
  591. }
  592. if(br.winner == 1)
  593. {
  594. labels.push_back(std::make_shared<CLabel>(412, 124, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[410]));
  595. }
  596. else
  597. {
  598. labels.push_back(std::make_shared<CLabel>(408, 124, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[411]));
  599. }
  600. labels.push_back(std::make_shared<CLabel>(232, 302, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[407]));
  601. labels.push_back(std::make_shared<CLabel>(232, 332, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[408]));
  602. labels.push_back(std::make_shared<CLabel>(232, 428, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[409]));
  603. std::string sideNames[2] = {"N/A", "N/A"};
  604. for(int i = 0; i < 2; i++)
  605. {
  606. auto heroInfo = owner.cb->getBattle(br.battleID)->battleGetHeroInfo(i);
  607. const int xs[] = {21, 392};
  608. if(heroInfo.portraitSource.isValid()) //attacking hero
  609. {
  610. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("PortraitsLarge"), heroInfo.getIconIndex(), 0, xs[i], 38));
  611. sideNames[i] = heroInfo.name;
  612. }
  613. else
  614. {
  615. auto stacks = owner.cb->getBattle(br.battleID)->battleGetAllStacks();
  616. vstd::erase_if(stacks, [i](const CStack * stack) //erase stack of other side and not coming from garrison
  617. {
  618. return stack->unitSide() != i || !stack->base;
  619. });
  620. auto best = vstd::maxElementByFun(stacks, [](const CStack * stack)
  621. {
  622. return stack->unitType()->getAIValue();
  623. });
  624. if(best != stacks.end()) //should be always but to be safe...
  625. {
  626. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("TWCRPORT"), (*best)->unitType()->getIconIndex(), 0, xs[i], 38));
  627. sideNames[i] = (*best)->unitType()->getNamePluralTranslated();
  628. }
  629. }
  630. }
  631. //printing attacker and defender's names
  632. labels.push_back(std::make_shared<CLabel>(89, 37, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE, sideNames[0]));
  633. labels.push_back(std::make_shared<CLabel>(381, 53, FONT_SMALL, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, sideNames[1]));
  634. //printing casualties
  635. for(int step = 0; step < 2; ++step)
  636. {
  637. if(br.casualties[step].size()==0)
  638. {
  639. labels.push_back(std::make_shared<CLabel>(235, 360 + 97 * step, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[523]));
  640. }
  641. else
  642. {
  643. int xPos = 235 - ((int)br.casualties[step].size()*32 + ((int)br.casualties[step].size() - 1)*10)/2; //increment by 42 with each picture
  644. int yPos = 344 + step * 97;
  645. for(auto & elem : br.casualties[step])
  646. {
  647. auto creature = CGI->creatures()->getByIndex(elem.first);
  648. if (creature->getId() == CreatureID::ARROW_TOWERS )
  649. continue; // do not show destroyed towers in battle results
  650. icons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("CPRSMALL"), creature->getIconIndex(), 0, xPos, yPos));
  651. std::ostringstream amount;
  652. amount<<elem.second;
  653. labels.push_back(std::make_shared<CLabel>(xPos + 16, yPos + 42, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, amount.str()));
  654. xPos += 42;
  655. }
  656. }
  657. }
  658. auto resources = getResources(br);
  659. description = std::make_shared<CTextBox>(resources.resultText.toString(), Rect(69, 203, 330, 68), 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  660. videoPlayer = std::make_shared<VideoWidget>(Point(107, 70), resources.prologueVideo, resources.loopedVideo, false);
  661. CCS->musich->playMusic(resources.musicName, false, true);
  662. }
  663. BattleResultResources BattleResultWindow::getResources(const BattleResult & br)
  664. {
  665. //printing result description
  666. bool weAreAttacker = !(owner.cb->getBattle(br.battleID)->battleGetMySide());
  667. bool weAreDefender = !weAreAttacker;
  668. bool weWon = (br.winner == 0 && weAreAttacker) || (br.winner == 1 && !weAreAttacker);
  669. bool isSiege = owner.cb->getBattle(br.battleID)->battleGetDefendedTown() != nullptr;
  670. BattleResultResources resources;
  671. if(weWon)
  672. {
  673. if(isSiege && weAreDefender)
  674. {
  675. resources.musicName = AudioPath::builtin("Music/Defend Castle");
  676. resources.prologueVideo = VideoPath::builtin("DEFENDALL.BIK");
  677. resources.loopedVideo = VideoPath::builtin("defendloop.bik");
  678. }
  679. else
  680. {
  681. resources.musicName = AudioPath::builtin("Music/Win Battle");
  682. resources.prologueVideo = VideoPath::builtin("WIN3.BIK");
  683. resources.loopedVideo = VideoPath::builtin("WIN3.BIK");
  684. }
  685. switch(br.result)
  686. {
  687. case EBattleResult::NORMAL:
  688. resources.resultText.appendTextID("core.genrltxt.304");
  689. break;
  690. case EBattleResult::ESCAPE:
  691. resources.resultText.appendTextID("core.genrltxt.303");
  692. break;
  693. case EBattleResult::SURRENDER:
  694. resources.resultText.appendTextID("core.genrltxt.302");
  695. break;
  696. default:
  697. throw std::runtime_error("Invalid battle result!");
  698. }
  699. const CGHeroInstance * ourHero = owner.cb->getBattle(br.battleID)->battleGetMyHero();
  700. if (ourHero)
  701. {
  702. resources.resultText.appendTextID("core.genrltxt.305");
  703. resources.resultText.replaceTextID(ourHero->getNameTranslated());
  704. resources.resultText.replaceNumber(br.exp[weAreAttacker ? 0 : 1]);
  705. }
  706. }
  707. else // we lose
  708. {
  709. switch(br.result)
  710. {
  711. case EBattleResult::NORMAL:
  712. resources.resultText.appendTextID("core.genrltxt.311");
  713. resources.musicName = AudioPath::builtin("Music/LoseCombat");
  714. resources.prologueVideo = VideoPath::builtin("LBSTART.BIK");
  715. resources.loopedVideo = VideoPath::builtin("LBLOOP.BIK");
  716. break;
  717. case EBattleResult::ESCAPE:
  718. resources.resultText.appendTextID("core.genrltxt.310");
  719. resources.musicName = AudioPath::builtin("Music/Retreat Battle");
  720. resources.prologueVideo = VideoPath::builtin("RTSTART.BIK");
  721. resources.loopedVideo = VideoPath::builtin("RTLOOP.BIK");
  722. break;
  723. case EBattleResult::SURRENDER:
  724. resources.resultText.appendTextID("core.genrltxt.309");
  725. resources.musicName = AudioPath::builtin("Music/Surrender Battle");
  726. resources.prologueVideo = VideoPath();
  727. resources.loopedVideo = VideoPath::builtin("SURRENDER.BIK");
  728. break;
  729. default:
  730. throw std::runtime_error("Invalid battle result!");
  731. }
  732. if(isSiege && weAreDefender)
  733. {
  734. resources.musicName = AudioPath::builtin("Music/LoseCastle");
  735. resources.prologueVideo = VideoPath::builtin("LOSECSTL.BIK");
  736. resources.loopedVideo = VideoPath::builtin("LOSECSLP.BIK");
  737. }
  738. }
  739. return resources;
  740. }
  741. void BattleResultWindow::activate()
  742. {
  743. owner.showingDialog->setBusy();
  744. CIntObject::activate();
  745. }
  746. void BattleResultWindow::buttonPressed(int button)
  747. {
  748. if (resultCallback)
  749. resultCallback(button);
  750. CPlayerInterface &intTmp = owner; //copy reference because "this" will be destructed soon
  751. close();
  752. if(GH.windows().topWindow<BattleWindow>())
  753. GH.windows().popWindows(1); //pop battle interface if present
  754. //Result window and battle interface are gone. We requested all dialogs to be closed before opening the battle,
  755. //so we can be sure that there is no dialogs left on GUI stack.
  756. intTmp.showingDialog->setFree();
  757. }
  758. void BattleResultWindow::bExitf()
  759. {
  760. buttonPressed(0);
  761. }
  762. void BattleResultWindow::bRepeatf()
  763. {
  764. buttonPressed(1);
  765. }
  766. StackQueue::StackQueue(bool Embedded, BattleInterface & owner)
  767. : embedded(Embedded),
  768. owner(owner)
  769. {
  770. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  771. uint32_t queueSize = QUEUE_SIZE_BIG;
  772. if(embedded)
  773. {
  774. int32_t queueSmallOutsideYOffset = 65;
  775. bool queueSmallOutside = settings["battle"]["queueSmallOutside"].Bool() && (pos.y - queueSmallOutsideYOffset) >= 0;
  776. queueSize = std::clamp(static_cast<int>(settings["battle"]["queueSmallSlots"].Float()), 1, queueSmallOutside ? GH.screenDimensions().x / 41 : 19);
  777. pos.w = queueSize * 41;
  778. pos.h = 49;
  779. pos.x += parent->pos.w/2 - pos.w/2;
  780. pos.y += queueSmallOutside ? -queueSmallOutsideYOffset : 10;
  781. icons = GH.renderHandler().loadAnimation(AnimationPath::builtin("CPRSMALL"));
  782. stateIcons = GH.renderHandler().loadAnimation(AnimationPath::builtin("VCMI/BATTLEQUEUE/STATESSMALL"));
  783. }
  784. else
  785. {
  786. pos.w = 800;
  787. pos.h = 85;
  788. pos.x += 0;
  789. pos.y -= pos.h;
  790. background = std::make_shared<CFilledTexture>(ImagePath::builtin("DIBOXBCK"), Rect(0, 0, pos.w, pos.h));
  791. icons = GH.renderHandler().loadAnimation(AnimationPath::builtin("TWCRPORT"));
  792. stateIcons = GH.renderHandler().loadAnimation(AnimationPath::builtin("VCMI/BATTLEQUEUE/STATESSMALL"));
  793. //TODO: where use big icons?
  794. //stateIcons = GH.renderHandler().loadAnimation("VCMI/BATTLEQUEUE/STATESBIG");
  795. }
  796. stateIcons->preload();
  797. stackBoxes.resize(queueSize);
  798. for (int i = 0; i < stackBoxes.size(); i++)
  799. {
  800. stackBoxes[i] = std::make_shared<StackBox>(this);
  801. stackBoxes[i]->moveBy(Point(1 + (embedded ? 41 : 80) * i, 0));
  802. }
  803. }
  804. void StackQueue::show(Canvas & to)
  805. {
  806. if (embedded)
  807. showAll(to);
  808. CIntObject::show(to);
  809. }
  810. void StackQueue::update()
  811. {
  812. std::vector<battle::Units> queueData;
  813. owner.getBattle()->battleGetTurnOrder(queueData, stackBoxes.size(), 0);
  814. size_t boxIndex = 0;
  815. ui32 tmpTurn = -1;
  816. for(size_t turn = 0; turn < queueData.size() && boxIndex < stackBoxes.size(); turn++)
  817. {
  818. for(size_t unitIndex = 0; unitIndex < queueData[turn].size() && boxIndex < stackBoxes.size(); boxIndex++, unitIndex++)
  819. {
  820. ui32 currentTurn = owner.round + turn;
  821. stackBoxes[boxIndex]->setUnit(queueData[turn][unitIndex], turn, tmpTurn != currentTurn && owner.round != 0 && (!embedded || tmpTurn != -1) ? (std::optional<ui32>)currentTurn : std::nullopt);
  822. tmpTurn = currentTurn;
  823. }
  824. }
  825. for(; boxIndex < stackBoxes.size(); boxIndex++)
  826. stackBoxes[boxIndex]->setUnit(nullptr);
  827. }
  828. int32_t StackQueue::getSiegeShooterIconID()
  829. {
  830. return owner.siegeController->getSiegedTown()->town->faction->getIndex();
  831. }
  832. std::optional<uint32_t> StackQueue::getHoveredUnitIdIfAny() const
  833. {
  834. for(const auto & stackBox : stackBoxes)
  835. {
  836. if(stackBox->isHovered())
  837. {
  838. return stackBox->getBoundUnitID();
  839. }
  840. }
  841. return std::nullopt;
  842. }
  843. StackQueue::StackBox::StackBox(StackQueue * owner):
  844. CIntObject(SHOW_POPUP | HOVER), owner(owner)
  845. {
  846. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  847. background = std::make_shared<CPicture>(ImagePath::builtin(owner->embedded ? "StackQueueSmall" : "StackQueueLarge"));
  848. pos.w = background->pos.w;
  849. pos.h = background->pos.h;
  850. if(owner->embedded)
  851. {
  852. icon = std::make_shared<CAnimImage>(owner->icons, 0, 0, 5, 2);
  853. amount = std::make_shared<CLabel>(pos.w/2, pos.h - 7, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  854. roundRect = std::make_shared<TransparentFilledRectangle>(Rect(0, 0, 2, 48), ColorRGBA(0, 0, 0, 255), ColorRGBA(0, 255, 0, 255));
  855. }
  856. else
  857. {
  858. icon = std::make_shared<CAnimImage>(owner->icons, 0, 0, 9, 1);
  859. amount = std::make_shared<CLabel>(pos.w/2, pos.h - 8, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE);
  860. roundRect = std::make_shared<TransparentFilledRectangle>(Rect(0, 0, 15, 18), ColorRGBA(0, 0, 0, 255), ColorRGBA(241, 216, 120, 255));
  861. round = std::make_shared<CLabel>(4, 2, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE);
  862. int icon_x = pos.w - 17;
  863. int icon_y = pos.h - 18;
  864. stateIcon = std::make_shared<CAnimImage>(owner->stateIcons, 0, 0, icon_x, icon_y);
  865. stateIcon->visible = false;
  866. }
  867. roundRect->disable();
  868. }
  869. void StackQueue::StackBox::setUnit(const battle::Unit * unit, size_t turn, std::optional<ui32> currentTurn)
  870. {
  871. if(unit)
  872. {
  873. boundUnitID = unit->unitId();
  874. background->colorize(unit->unitOwner());
  875. icon->visible = true;
  876. // temporary code for mod compatibility:
  877. // first, set icon that should definitely exist (arrow tower icon in base vcmi mod)
  878. // second, try to switch to icon that should be provided by mod
  879. // if mod is not up to date and does have arrow tower icon yet - second setFrame call will fail and retain previously set image
  880. // for 1.2 release & later next line should be moved into 'else' block
  881. icon->setFrame(unit->creatureIconIndex(), 0);
  882. if (unit->unitType()->getId() == CreatureID::ARROW_TOWERS)
  883. icon->setFrame(owner->getSiegeShooterIconID(), 1);
  884. roundRect->setEnabled(currentTurn.has_value());
  885. if(!owner->embedded)
  886. round->setEnabled(currentTurn.has_value());
  887. amount->setText(TextOperations::formatMetric(unit->getCount(), 4));
  888. if(currentTurn && !owner->embedded)
  889. {
  890. std::string tmp = std::to_string(*currentTurn);
  891. int len = graphics->fonts[FONT_SMALL]->getStringWidth(tmp);
  892. roundRect->pos.w = len + 6;
  893. round->setText(tmp);
  894. }
  895. if(stateIcon)
  896. {
  897. if(unit->defended((int)turn) || (turn > 0 && unit->defended((int)turn - 1)))
  898. {
  899. stateIcon->setFrame(0, 0);
  900. stateIcon->visible = true;
  901. }
  902. else if(unit->waited((int)turn))
  903. {
  904. stateIcon->setFrame(1, 0);
  905. stateIcon->visible = true;
  906. }
  907. else
  908. {
  909. stateIcon->visible = false;
  910. }
  911. }
  912. }
  913. else
  914. {
  915. boundUnitID = std::nullopt;
  916. background->colorize(PlayerColor::NEUTRAL);
  917. icon->visible = false;
  918. icon->setFrame(0);
  919. amount->setText("");
  920. if(stateIcon)
  921. stateIcon->visible = false;
  922. }
  923. }
  924. std::optional<uint32_t> StackQueue::StackBox::getBoundUnitID() const
  925. {
  926. return boundUnitID;
  927. }
  928. bool StackQueue::StackBox::isBoundUnitHighlighted() const
  929. {
  930. auto unitIdsToHighlight = owner->owner.stacksController->getHoveredStacksUnitIds();
  931. return vstd::contains(unitIdsToHighlight, getBoundUnitID());
  932. }
  933. void StackQueue::StackBox::showAll(Canvas & to)
  934. {
  935. CIntObject::showAll(to);
  936. if(isBoundUnitHighlighted())
  937. to.drawBorder(background->pos, Colors::CYAN, 2);
  938. }
  939. void StackQueue::StackBox::show(Canvas & to)
  940. {
  941. CIntObject::show(to);
  942. if(isBoundUnitHighlighted())
  943. to.drawBorder(background->pos, Colors::CYAN, 2);
  944. }
  945. void StackQueue::StackBox::showPopupWindow(const Point & cursorPosition)
  946. {
  947. auto stacks = owner->owner.getBattle()->battleGetAllStacks();
  948. for(const CStack * stack : stacks)
  949. if(boundUnitID.has_value() && stack->unitId() == *boundUnitID)
  950. GH.windows().createAndPushWindow<CStackWindow>(stack, true);
  951. }