2
0

BattleInterfaceClasses.cpp 39 KB

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