BattleInterfaceClasses.cpp 40 KB

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