BattleInterfaceClasses.cpp 40 KB

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