BattleInterfaceClasses.cpp 40 KB

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