BattleInterfaceClasses.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916
  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 "../CMusicHandler.h"
  21. #include "../CPlayerInterface.h"
  22. #include "../CVideoHandler.h"
  23. #include "../gui/CursorHandler.h"
  24. #include "../gui/CGuiHandler.h"
  25. #include "../render/Canvas.h"
  26. #include "../render/IImage.h"
  27. #include "../widgets/Buttons.h"
  28. #include "../widgets/Images.h"
  29. #include "../widgets/TextControls.h"
  30. #include "../windows/CMessage.h"
  31. #include "../windows/CCreatureWindow.h"
  32. #include "../windows/CSpellWindow.h"
  33. #include "../render/CAnimation.h"
  34. #include "../adventureMap/CInGameConsole.h"
  35. #include "../../CCallback.h"
  36. #include "../../lib/CStack.h"
  37. #include "../../lib/CConfigHandler.h"
  38. #include "../../lib/CCreatureHandler.h"
  39. #include "../../lib/CGameState.h"
  40. #include "../../lib/CGeneralTextHandler.h"
  41. #include "../../lib/CTownHandler.h"
  42. #include "../../lib/CHeroHandler.h"
  43. #include "../../lib/NetPacks.h"
  44. #include "../../lib/StartInfo.h"
  45. #include "../../lib/CondSh.h"
  46. #include "../../lib/mapObjects/CGTownInstance.h"
  47. #include <SDL_surface.h>
  48. #include <SDL_events.h>
  49. void BattleConsole::showAll(SDL_Surface * to)
  50. {
  51. CIntObject::showAll(to);
  52. Point line1 (pos.x + pos.w/2, pos.y + 8);
  53. Point line2 (pos.x + pos.w/2, pos.y + 24);
  54. auto visibleText = getVisibleText();
  55. if(visibleText.size() > 0)
  56. graphics->fonts[FONT_SMALL]->renderTextCenter(to, visibleText[0], Colors::WHITE, line1);
  57. if(visibleText.size() > 1)
  58. graphics->fonts[FONT_SMALL]->renderTextCenter(to, visibleText[1], Colors::WHITE, line2);
  59. }
  60. std::vector<std::string> BattleConsole::getVisibleText()
  61. {
  62. // high priority texts that hide battle log entries
  63. for (auto const & text : {consoleText, hoverText} )
  64. {
  65. if (text.empty())
  66. continue;
  67. auto result = CMessage::breakText(text, pos.w, FONT_SMALL);
  68. if(result.size() > 2)
  69. result.resize(2);
  70. return result;
  71. }
  72. // log is small enough to fit entirely - display it as such
  73. if (logEntries.size() < 3)
  74. return logEntries;
  75. return { logEntries[scrollPosition - 1], logEntries[scrollPosition] };
  76. }
  77. std::vector<std::string> BattleConsole::splitText(const std::string &text)
  78. {
  79. std::vector<std::string> lines;
  80. std::vector<std::string> output;
  81. boost::split(lines, text, boost::is_any_of("\n"));
  82. for (auto const & line : lines)
  83. {
  84. if (graphics->fonts[FONT_SMALL]->getStringWidth(text) < pos.w)
  85. {
  86. output.push_back(line);
  87. }
  88. else
  89. {
  90. std::vector<std::string> substrings = CMessage::breakText(line, pos.w, FONT_SMALL);
  91. output.insert(output.end(), substrings.begin(), substrings.end());
  92. }
  93. }
  94. return output;
  95. }
  96. bool BattleConsole::addText(const std::string & text)
  97. {
  98. logGlobal->trace("CBattleConsole message: %s", text);
  99. auto newLines = splitText(text);
  100. logEntries.insert(logEntries.end(), newLines.begin(), newLines.end());
  101. scrollPosition = (int)logEntries.size()-1;
  102. redraw();
  103. return true;
  104. }
  105. void BattleConsole::scrollUp(ui32 by)
  106. {
  107. if(scrollPosition > static_cast<int>(by))
  108. scrollPosition -= by;
  109. redraw();
  110. }
  111. void BattleConsole::scrollDown(ui32 by)
  112. {
  113. if(scrollPosition + by < logEntries.size())
  114. scrollPosition += by;
  115. redraw();
  116. }
  117. BattleConsole::BattleConsole(std::shared_ptr<CPicture> backgroundSource, const Point & objectPos, const Point & imagePos, const Point &size)
  118. : scrollPosition(-1)
  119. , enteringText(false)
  120. {
  121. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  122. pos += objectPos;
  123. pos.w = size.x;
  124. pos.h = size.y;
  125. background = std::make_shared<CPicture>(backgroundSource->getSurface(), Rect(imagePos, size), 0, 0 );
  126. }
  127. void BattleConsole::deactivate()
  128. {
  129. if (enteringText)
  130. LOCPLINT->cingconsole->endEnteringText(false);
  131. CIntObject::deactivate();
  132. }
  133. void BattleConsole::setEnteringMode(bool on)
  134. {
  135. consoleText.clear();
  136. if (on)
  137. {
  138. assert(enteringText == false);
  139. CSDL_Ext::startTextInput(pos);
  140. }
  141. else
  142. {
  143. assert(enteringText == true);
  144. CSDL_Ext::stopTextInput();
  145. }
  146. enteringText = on;
  147. redraw();
  148. }
  149. void BattleConsole::setEnteredText(const std::string & text)
  150. {
  151. assert(enteringText == true);
  152. consoleText = text;
  153. redraw();
  154. }
  155. void BattleConsole::write(const std::string & Text)
  156. {
  157. hoverText = Text;
  158. redraw();
  159. }
  160. void BattleConsole::clearIfMatching(const std::string & Text)
  161. {
  162. if (hoverText == Text)
  163. clear();
  164. }
  165. void BattleConsole::clear()
  166. {
  167. write({});
  168. }
  169. const CGHeroInstance * BattleHero::instance()
  170. {
  171. return hero;
  172. }
  173. void BattleHero::render(Canvas & canvas)
  174. {
  175. size_t groupIndex = static_cast<size_t>(phase);
  176. auto flagFrame = flagAnimation->getImage(flagCurrentFrame, 0, true);
  177. auto heroFrame = animation->getImage(currentFrame, groupIndex, true);
  178. Point heroPosition = pos.center() - parent->pos.topLeft() - heroFrame->dimensions() / 2;
  179. Point flagPosition = pos.center() - parent->pos.topLeft() - flagFrame->dimensions() / 2;
  180. if(defender)
  181. flagPosition += Point(-4, -41);
  182. else
  183. flagPosition += Point(4, -41);
  184. canvas.draw(flagFrame, flagPosition);
  185. canvas.draw(heroFrame, heroPosition);
  186. float timePassed = float(GH.mainFPSmng->getElapsedMilliseconds()) / 1000.f;
  187. flagCurrentFrame += currentSpeed * timePassed;
  188. currentFrame += currentSpeed * timePassed;
  189. if(flagCurrentFrame >= flagAnimation->size(0))
  190. flagCurrentFrame -= flagAnimation->size(0);
  191. if(currentFrame >= animation->size(groupIndex))
  192. {
  193. currentFrame -= animation->size(groupIndex);
  194. switchToNextPhase();
  195. }
  196. }
  197. void BattleHero::pause()
  198. {
  199. currentSpeed = 0.f;
  200. }
  201. void BattleHero::play()
  202. {
  203. //H3 speed: 10 fps ( 100 ms per frame)
  204. currentSpeed = 10.f;
  205. }
  206. float BattleHero::getFrame() const
  207. {
  208. return currentFrame;
  209. }
  210. void BattleHero::collectRenderableObjects(BattleRenderer & renderer)
  211. {
  212. auto hex = defender ? BattleHex(GameConstants::BFIELD_WIDTH-1) : BattleHex(0);
  213. renderer.insert(EBattleFieldLayer::HEROES, hex, [this](BattleRenderer::RendererRef canvas)
  214. {
  215. render(canvas);
  216. });
  217. }
  218. void BattleHero::onPhaseFinished(const std::function<void()> & callback)
  219. {
  220. phaseFinishedCallback = callback;
  221. }
  222. void BattleHero::setPhase(EHeroAnimType newPhase)
  223. {
  224. nextPhase = newPhase;
  225. switchToNextPhase(); //immediately switch to next phase and then restore idling phase
  226. nextPhase = EHeroAnimType::HOLDING;
  227. }
  228. void BattleHero::hover(bool on)
  229. {
  230. //TODO: BROKEN CODE
  231. if (on)
  232. CCS->curh->set(Cursor::Combat::HERO);
  233. else
  234. CCS->curh->set(Cursor::Combat::POINTER);
  235. }
  236. void BattleHero::clickLeft(tribool down, bool previousState)
  237. {
  238. if(owner.actionsController->spellcastingModeActive()) //we are casting a spell
  239. return;
  240. if(boost::logic::indeterminate(down))
  241. return;
  242. if(!hero || down || !owner.myTurn)
  243. return;
  244. if(owner.getCurrentPlayerInterface()->cb->battleCanCastSpell(hero, spells::Mode::HERO) == ESpellCastProblem::OK) //check conditions
  245. {
  246. BattleHex hoveredHex = owner.fieldController->getHoveredHex();
  247. //do nothing when any hex is hovered - hero's animation overlaps battlefield
  248. if ( hoveredHex != BattleHex::INVALID )
  249. return;
  250. CCS->curh->set(Cursor::Map::POINTER);
  251. GH.pushIntT<CSpellWindow>(hero, owner.getCurrentPlayerInterface());
  252. }
  253. }
  254. void BattleHero::clickRight(tribool down, bool previousState)
  255. {
  256. if(boost::logic::indeterminate(down))
  257. return;
  258. Point windowPosition;
  259. windowPosition.x = (!defender) ? owner.fieldController->pos.left() + 1 : owner.fieldController->pos.right() - 79;
  260. windowPosition.y = owner.fieldController->pos.y + 135;
  261. InfoAboutHero targetHero;
  262. if(down && (owner.myTurn || settings["session"]["spectate"].Bool()))
  263. {
  264. auto h = defender ? owner.defendingHeroInstance : owner.attackingHeroInstance;
  265. targetHero.initFromHero(h, InfoAboutHero::EInfoLevel::INBATTLE);
  266. GH.pushIntT<HeroInfoWindow>(targetHero, &windowPosition);
  267. }
  268. }
  269. void BattleHero::switchToNextPhase()
  270. {
  271. phase = nextPhase;
  272. currentFrame = 0.f;
  273. auto copy = phaseFinishedCallback;
  274. phaseFinishedCallback.clear();
  275. copy();
  276. }
  277. BattleHero::BattleHero(const BattleInterface & owner, const CGHeroInstance * hero, bool defender):
  278. defender(defender),
  279. hero(hero),
  280. owner(owner),
  281. phase(EHeroAnimType::HOLDING),
  282. nextPhase(EHeroAnimType::HOLDING),
  283. currentSpeed(0.f),
  284. currentFrame(0.f),
  285. flagCurrentFrame(0.f)
  286. {
  287. std::string animationPath;
  288. if(!hero->type->battleImage.empty())
  289. animationPath = hero->type->battleImage;
  290. else
  291. if(hero->sex)
  292. animationPath = hero->type->heroClass->imageBattleFemale;
  293. else
  294. animationPath = hero->type->heroClass->imageBattleMale;
  295. animation = std::make_shared<CAnimation>(animationPath);
  296. animation->preload();
  297. pos.w = 64;
  298. pos.h = 136;
  299. pos.x = owner.fieldController->pos.x + (defender ? (owner.fieldController->pos.w - pos.w) : 0);
  300. pos.y = owner.fieldController->pos.y;
  301. if(defender)
  302. animation->verticalFlip();
  303. if(defender)
  304. flagAnimation = std::make_shared<CAnimation>("CMFLAGR");
  305. else
  306. flagAnimation = std::make_shared<CAnimation>("CMFLAGL");
  307. flagAnimation->preload();
  308. flagAnimation->playerColored(hero->tempOwner);
  309. addUsedEvents(LCLICK | RCLICK | HOVER);
  310. switchToNextPhase();
  311. play();
  312. }
  313. HeroInfoWindow::HeroInfoWindow(const InfoAboutHero & hero, Point * position)
  314. : CWindowObject(RCLICK_POPUP | SHADOW_DISABLED, "CHRPOP")
  315. {
  316. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  317. if (position != nullptr)
  318. moveTo(*position);
  319. background->colorize(hero.owner); //maybe add this functionality to base class?
  320. auto attack = hero.details->primskills[0];
  321. auto defense = hero.details->primskills[1];
  322. auto power = hero.details->primskills[2];
  323. auto knowledge = hero.details->primskills[3];
  324. auto morale = hero.details->morale;
  325. auto luck = hero.details->luck;
  326. auto currentSpellPoints = hero.details->mana;
  327. auto maxSpellPoints = hero.details->manaLimit;
  328. icons.push_back(std::make_shared<CAnimImage>("PortraitsLarge", hero.portrait, 0, 10, 6));
  329. //primary stats
  330. labels.push_back(std::make_shared<CLabel>(9, 75, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[380] + ":"));
  331. labels.push_back(std::make_shared<CLabel>(9, 87, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[381] + ":"));
  332. labels.push_back(std::make_shared<CLabel>(9, 99, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[382] + ":"));
  333. labels.push_back(std::make_shared<CLabel>(9, 111, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[383] + ":"));
  334. labels.push_back(std::make_shared<CLabel>(69, 87, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(attack)));
  335. labels.push_back(std::make_shared<CLabel>(69, 99, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(defense)));
  336. labels.push_back(std::make_shared<CLabel>(69, 111, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(power)));
  337. labels.push_back(std::make_shared<CLabel>(69, 123, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(knowledge)));
  338. //morale+luck
  339. labels.push_back(std::make_shared<CLabel>(9, 131, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[384] + ":"));
  340. labels.push_back(std::make_shared<CLabel>(9, 143, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[385] + ":"));
  341. icons.push_back(std::make_shared<CAnimImage>("IMRL22", morale + 3, 0, 47, 131));
  342. icons.push_back(std::make_shared<CAnimImage>("ILCK22", luck + 3, 0, 47, 143));
  343. //spell points
  344. labels.push_back(std::make_shared<CLabel>(39, 174, EFonts::FONT_TINY, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[387]));
  345. labels.push_back(std::make_shared<CLabel>(39, 186, EFonts::FONT_TINY, ETextAlignment::CENTER, Colors::WHITE, std::to_string(currentSpellPoints) + "/" + std::to_string(maxSpellPoints)));
  346. }
  347. BattleOptionsWindow::BattleOptionsWindow(BattleInterface * owner):
  348. CWindowObject(PLAYER_COLORED, "comopbck.bmp")
  349. {
  350. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  351. auto viewGrid = std::make_shared<CToggleButton>(Point(25, 56), "sysopchk.def", CGI->generaltexth->zelp[427], [=](bool on)
  352. {
  353. Settings cellBorders = settings.write["battle"]["cellBorders"];
  354. cellBorders->Bool() = on;
  355. if(owner)
  356. owner->redrawBattlefield();
  357. });
  358. viewGrid->setSelected(settings["battle"]["cellBorders"].Bool());
  359. toggles.push_back(viewGrid);
  360. auto movementShadow = std::make_shared<CToggleButton>(Point(25, 89), "sysopchk.def", CGI->generaltexth->zelp[428], [=](bool on)
  361. {
  362. Settings stackRange = settings.write["battle"]["stackRange"];
  363. stackRange->Bool() = on;
  364. if(owner)
  365. owner->redrawBattlefield();
  366. });
  367. movementShadow->setSelected(settings["battle"]["stackRange"].Bool());
  368. toggles.push_back(movementShadow);
  369. auto mouseShadow = std::make_shared<CToggleButton>(Point(25, 122), "sysopchk.def", CGI->generaltexth->zelp[429], [&](bool on)
  370. {
  371. Settings shadow = settings.write["battle"]["mouseShadow"];
  372. shadow->Bool() = on;
  373. });
  374. mouseShadow->setSelected(settings["battle"]["mouseShadow"].Bool());
  375. toggles.push_back(mouseShadow);
  376. animSpeeds = std::make_shared<CToggleGroup>([&](int value)
  377. {
  378. Settings speed = settings.write["battle"]["speedFactor"];
  379. speed->Float() = float(value);
  380. });
  381. std::shared_ptr<CToggleButton> toggle;
  382. toggle = std::make_shared<CToggleButton>(Point( 28, 225), "sysopb9.def", CGI->generaltexth->zelp[422]);
  383. animSpeeds->addToggle(1, toggle);
  384. toggle = std::make_shared<CToggleButton>(Point( 92, 225), "sysob10.def", CGI->generaltexth->zelp[423]);
  385. animSpeeds->addToggle(2, toggle);
  386. toggle = std::make_shared<CToggleButton>(Point(156, 225), "sysob11.def", CGI->generaltexth->zelp[424]);
  387. animSpeeds->addToggle(3, toggle);
  388. animSpeeds->setSelected(getAnimSpeed());
  389. setToDefault = std::make_shared<CButton>(Point(246, 359), "codefaul.def", CGI->generaltexth->zelp[393], [&](){ bDefaultf(); });
  390. setToDefault->setImageOrder(1, 0, 2, 3);
  391. exit = std::make_shared<CButton>(Point(357, 359), "soretrn.def", CGI->generaltexth->zelp[392], [&](){ bExitf();}, SDLK_RETURN);
  392. exit->setImageOrder(1, 0, 2, 3);
  393. //creating labels
  394. labels.push_back(std::make_shared<CLabel>(242, 32, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[392]));//window title
  395. labels.push_back(std::make_shared<CLabel>(122, 214, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[393]));//animation speed
  396. labels.push_back(std::make_shared<CLabel>(122, 293, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[394]));//music volume
  397. labels.push_back(std::make_shared<CLabel>(122, 359, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[395]));//effects' volume
  398. labels.push_back(std::make_shared<CLabel>(353, 66, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[396]));//auto - combat options
  399. labels.push_back(std::make_shared<CLabel>(353, 265, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[397]));//creature info
  400. //auto - combat options
  401. labels.push_back(std::make_shared<CLabel>(283, 86, FONT_MEDIUM, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[398]));//creatures
  402. labels.push_back(std::make_shared<CLabel>(283, 116, FONT_MEDIUM, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[399]));//spells
  403. labels.push_back(std::make_shared<CLabel>(283, 146, FONT_MEDIUM, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[400]));//catapult
  404. labels.push_back(std::make_shared<CLabel>(283, 176, FONT_MEDIUM, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[151]));//ballista
  405. labels.push_back(std::make_shared<CLabel>(283, 206, FONT_MEDIUM, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[401]));//first aid tent
  406. //creature info
  407. labels.push_back(std::make_shared<CLabel>(283, 285, FONT_MEDIUM, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[402]));//all stats
  408. labels.push_back(std::make_shared<CLabel>(283, 315, FONT_MEDIUM, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[403]));//spells only
  409. //general options
  410. labels.push_back(std::make_shared<CLabel>(61, 57, FONT_MEDIUM, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[404]));
  411. labels.push_back(std::make_shared<CLabel>(61, 90, FONT_MEDIUM, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[405]));
  412. labels.push_back(std::make_shared<CLabel>(61, 123, FONT_MEDIUM, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[406]));
  413. labels.push_back(std::make_shared<CLabel>(61, 156, FONT_MEDIUM, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[407]));
  414. }
  415. int BattleOptionsWindow::getAnimSpeed() const
  416. {
  417. if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-battle-speed"].isNull())
  418. return static_cast<int>(vstd::round(settings["session"]["spectate-battle-speed"].Float()));
  419. return static_cast<int>(vstd::round(settings["battle"]["speedFactor"].Float()));
  420. }
  421. void BattleOptionsWindow::bDefaultf()
  422. {
  423. //TODO: implement
  424. }
  425. void BattleOptionsWindow::bExitf()
  426. {
  427. close();
  428. }
  429. BattleResultWindow::BattleResultWindow(const BattleResult & br, CPlayerInterface & _owner)
  430. : owner(_owner)
  431. {
  432. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  433. pos = CSDL_Ext::genRect(561, 470, (screen->w - 800)/2 + 165, (screen->h - 600)/2 + 19);
  434. background = std::make_shared<CPicture>("CPRESULT");
  435. background->colorize(owner.playerID);
  436. exit = std::make_shared<CButton>(Point(384, 505), "iok6432.def", std::make_pair("", ""), [&](){ bExitf();}, SDLK_RETURN);
  437. exit->setBorderColor(Colors::METALLIC_GOLD);
  438. if(br.winner == 0) //attacker won
  439. {
  440. labels.push_back(std::make_shared<CLabel>(59, 124, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[410]));
  441. }
  442. else
  443. {
  444. labels.push_back(std::make_shared<CLabel>(59, 124, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[411]));
  445. }
  446. if(br.winner == 1)
  447. {
  448. labels.push_back(std::make_shared<CLabel>(412, 124, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[410]));
  449. }
  450. else
  451. {
  452. labels.push_back(std::make_shared<CLabel>(408, 124, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[411]));
  453. }
  454. labels.push_back(std::make_shared<CLabel>(232, 302, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[407]));
  455. labels.push_back(std::make_shared<CLabel>(232, 332, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[408]));
  456. labels.push_back(std::make_shared<CLabel>(232, 428, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[409]));
  457. std::string sideNames[2] = {"N/A", "N/A"};
  458. for(int i = 0; i < 2; i++)
  459. {
  460. auto heroInfo = owner.cb->battleGetHeroInfo(i);
  461. const int xs[] = {21, 392};
  462. if(heroInfo.portrait >= 0) //attacking hero
  463. {
  464. icons.push_back(std::make_shared<CAnimImage>("PortraitsLarge", heroInfo.portrait, 0, xs[i], 38));
  465. sideNames[i] = heroInfo.name;
  466. }
  467. else
  468. {
  469. auto stacks = owner.cb->battleGetAllStacks();
  470. vstd::erase_if(stacks, [i](const CStack * stack) //erase stack of other side and not coming from garrison
  471. {
  472. return stack->side != i || !stack->base;
  473. });
  474. auto best = vstd::maxElementByFun(stacks, [](const CStack * stack)
  475. {
  476. return stack->type->AIValue;
  477. });
  478. if(best != stacks.end()) //should be always but to be safe...
  479. {
  480. icons.push_back(std::make_shared<CAnimImage>("TWCRPORT", (*best)->type->getIconIndex(), 0, xs[i], 38));
  481. sideNames[i] = (*best)->type->getNamePluralTranslated();
  482. }
  483. }
  484. }
  485. //printing attacker and defender's names
  486. labels.push_back(std::make_shared<CLabel>(89, 37, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE, sideNames[0]));
  487. labels.push_back(std::make_shared<CLabel>(381, 53, FONT_SMALL, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, sideNames[1]));
  488. //printing casualties
  489. for(int step = 0; step < 2; ++step)
  490. {
  491. if(br.casualties[step].size()==0)
  492. {
  493. labels.push_back(std::make_shared<CLabel>(235, 360 + 97 * step, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[523]));
  494. }
  495. else
  496. {
  497. int xPos = 235 - ((int)br.casualties[step].size()*32 + ((int)br.casualties[step].size() - 1)*10)/2; //increment by 42 with each picture
  498. int yPos = 344 + step * 97;
  499. for(auto & elem : br.casualties[step])
  500. {
  501. auto creature = CGI->creatures()->getByIndex(elem.first);
  502. if (creature->getId() == CreatureID::ARROW_TOWERS )
  503. continue; // do not show destroyed towers in battle results
  504. icons.push_back(std::make_shared<CAnimImage>("CPRSMALL", creature->getIconIndex(), 0, xPos, yPos));
  505. std::ostringstream amount;
  506. amount<<elem.second;
  507. labels.push_back(std::make_shared<CLabel>(xPos + 16, yPos + 42, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, amount.str()));
  508. xPos += 42;
  509. }
  510. }
  511. }
  512. //printing result description
  513. bool weAreAttacker = !(owner.cb->battleGetMySide());
  514. if((br.winner == 0 && weAreAttacker) || (br.winner == 1 && !weAreAttacker)) //we've won
  515. {
  516. int text = 304;
  517. switch(br.result)
  518. {
  519. case BattleResult::NORMAL:
  520. break;
  521. case BattleResult::ESCAPE:
  522. text = 303;
  523. break;
  524. case BattleResult::SURRENDER:
  525. text = 302;
  526. break;
  527. default:
  528. logGlobal->error("Invalid battle result code %d. Assumed normal.", static_cast<int>(br.result));
  529. break;
  530. }
  531. CCS->musich->playMusic("Music/Win Battle", false, true);
  532. CCS->videoh->open("WIN3.BIK");
  533. std::string str = CGI->generaltexth->allTexts[text];
  534. const CGHeroInstance * ourHero = owner.cb->battleGetMyHero();
  535. if (ourHero)
  536. {
  537. str += CGI->generaltexth->allTexts[305];
  538. boost::algorithm::replace_first(str, "%s", ourHero->getNameTranslated());
  539. boost::algorithm::replace_first(str, "%d", boost::lexical_cast<std::string>(br.exp[weAreAttacker ? 0 : 1]));
  540. }
  541. description = std::make_shared<CTextBox>(str, Rect(69, 203, 330, 68), 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  542. }
  543. else // we lose
  544. {
  545. int text = 311;
  546. std::string musicName = "Music/LoseCombat";
  547. std::string videoName = "LBSTART.BIK";
  548. switch(br.result)
  549. {
  550. case BattleResult::NORMAL:
  551. break;
  552. case BattleResult::ESCAPE:
  553. musicName = "Music/Retreat Battle";
  554. videoName = "RTSTART.BIK";
  555. text = 310;
  556. break;
  557. case BattleResult::SURRENDER:
  558. musicName = "Music/Surrender Battle";
  559. videoName = "SURRENDER.BIK";
  560. text = 309;
  561. break;
  562. default:
  563. logGlobal->error("Invalid battle result code %d. Assumed normal.", static_cast<int>(br.result));
  564. break;
  565. }
  566. CCS->musich->playMusic(musicName, false, true);
  567. CCS->videoh->open(videoName);
  568. labels.push_back(std::make_shared<CLabel>(235, 235, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[text]));
  569. }
  570. }
  571. void BattleResultWindow::activate()
  572. {
  573. owner.showingDialog->set(true);
  574. CIntObject::activate();
  575. }
  576. void BattleResultWindow::show(SDL_Surface * to)
  577. {
  578. CIntObject::show(to);
  579. CCS->videoh->update(pos.x + 107, pos.y + 70, screen, true, false);
  580. }
  581. void BattleResultWindow::bExitf()
  582. {
  583. CPlayerInterface &intTmp = owner; //copy reference because "this" will be destructed soon
  584. close();
  585. if(dynamic_cast<BattleWindow*>(GH.topInt().get()))
  586. GH.popInts(1); //pop battle interface if present
  587. //Result window and battle interface are gone. We requested all dialogs to be closed before opening the battle,
  588. //so we can be sure that there is no dialogs left on GUI stack.
  589. intTmp.showingDialog->setn(false);
  590. CCS->videoh->close();
  591. }
  592. void ClickableHex::hover(bool on)
  593. {
  594. hovered = on;
  595. //Hoverable::hover(on);
  596. if(!on && setAlterText)
  597. {
  598. GH.statusbar->clear();
  599. setAlterText = false;
  600. }
  601. }
  602. ClickableHex::ClickableHex() : setAlterText(false), myNumber(-1), strictHovered(false), myInterface(nullptr)
  603. {
  604. addUsedEvents(LCLICK | RCLICK | HOVER | MOVE);
  605. }
  606. void ClickableHex::mouseMoved(const SDL_MouseMotionEvent &sEvent)
  607. {
  608. strictHovered = myInterface->fieldController->isPixelInHex(Point(sEvent.x-pos.x, sEvent.y-pos.y));
  609. if(hovered && strictHovered) //print attacked creature to console
  610. {
  611. const CStack * attackedStack = myInterface->getCurrentPlayerInterface()->cb->battleGetStackByPos(myNumber);
  612. if( attackedStack != nullptr &&
  613. attackedStack->owner != myInterface->getCurrentPlayerInterface()->playerID &&
  614. attackedStack->alive())
  615. {
  616. MetaString text;
  617. text.addTxt(MetaString::GENERAL_TXT, 220);
  618. attackedStack->addNameReplacement(text);
  619. GH.statusbar->write(text.toString());
  620. setAlterText = true;
  621. }
  622. }
  623. else if(setAlterText)
  624. {
  625. GH.statusbar->clear();
  626. setAlterText = false;
  627. }
  628. }
  629. void ClickableHex::clickLeft(tribool down, bool previousState)
  630. {
  631. if(!down && hovered && strictHovered) //we've been really clicked!
  632. {
  633. myInterface->actionsController->handleHex(myNumber, LCLICK);
  634. }
  635. }
  636. void ClickableHex::clickRight(tribool down, bool previousState)
  637. {
  638. const CStack * myst = myInterface->getCurrentPlayerInterface()->cb->battleGetStackByPos(myNumber); //stack info
  639. if(hovered && strictHovered && myst!=nullptr)
  640. {
  641. if(!myst->alive()) return;
  642. if(down)
  643. {
  644. GH.pushIntT<CStackWindow>(myst, true);
  645. }
  646. }
  647. }
  648. StackQueue::StackQueue(bool Embedded, BattleInterface & owner)
  649. : embedded(Embedded),
  650. owner(owner)
  651. {
  652. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  653. if(embedded)
  654. {
  655. pos.w = QUEUE_SIZE * 41;
  656. pos.h = 49;
  657. pos.x += parent->pos.w/2 - pos.w/2;
  658. pos.y += 10;
  659. icons = std::make_shared<CAnimation>("CPRSMALL");
  660. stateIcons = std::make_shared<CAnimation>("VCMI/BATTLEQUEUE/STATESSMALL");
  661. }
  662. else
  663. {
  664. pos.w = 800;
  665. pos.h = 85;
  666. pos.x += 0;
  667. pos.y -= pos.h;
  668. background = std::make_shared<CFilledTexture>("DIBOXBCK", Rect(0, 0, pos.w, pos.h));
  669. icons = std::make_shared<CAnimation>("TWCRPORT");
  670. stateIcons = std::make_shared<CAnimation>("VCMI/BATTLEQUEUE/STATESSMALL");
  671. //TODO: where use big icons?
  672. //stateIcons = std::make_shared<CAnimation>("VCMI/BATTLEQUEUE/STATESBIG");
  673. }
  674. stateIcons->preload();
  675. stackBoxes.resize(QUEUE_SIZE);
  676. for (int i = 0; i < stackBoxes.size(); i++)
  677. {
  678. stackBoxes[i] = std::make_shared<StackBox>(this);
  679. stackBoxes[i]->moveBy(Point(1 + (embedded ? 41 : 80) * i, 0));
  680. }
  681. }
  682. void StackQueue::show(SDL_Surface * to)
  683. {
  684. if (embedded)
  685. showAll(to);
  686. CIntObject::show(to);
  687. }
  688. void StackQueue::update()
  689. {
  690. std::vector<battle::Units> queueData;
  691. owner.getCurrentPlayerInterface()->cb->battleGetTurnOrder(queueData, stackBoxes.size(), 0);
  692. size_t boxIndex = 0;
  693. for(size_t turn = 0; turn < queueData.size() && boxIndex < stackBoxes.size(); turn++)
  694. {
  695. for(size_t unitIndex = 0; unitIndex < queueData[turn].size() && boxIndex < stackBoxes.size(); boxIndex++, unitIndex++)
  696. stackBoxes[boxIndex]->setUnit(queueData[turn][unitIndex], turn);
  697. }
  698. for(; boxIndex < stackBoxes.size(); boxIndex++)
  699. stackBoxes[boxIndex]->setUnit(nullptr);
  700. }
  701. int32_t StackQueue::getSiegeShooterIconID()
  702. {
  703. return owner.siegeController->getSiegedTown()->town->faction->getIndex();
  704. }
  705. StackQueue::StackBox::StackBox(StackQueue * owner):
  706. owner(owner)
  707. {
  708. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  709. background = std::make_shared<CPicture>(owner->embedded ? "StackQueueSmall" : "StackQueueLarge");
  710. pos.w = background->pos.w;
  711. pos.h = background->pos.h;
  712. if(owner->embedded)
  713. {
  714. icon = std::make_shared<CAnimImage>(owner->icons, 0, 0, 5, 2);
  715. amount = std::make_shared<CLabel>(pos.w/2, pos.h - 7, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
  716. }
  717. else
  718. {
  719. icon = std::make_shared<CAnimImage>(owner->icons, 0, 0, 9, 1);
  720. amount = std::make_shared<CLabel>(pos.w/2, pos.h - 8, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE);
  721. int icon_x = pos.w - 17;
  722. int icon_y = pos.h - 18;
  723. stateIcon = std::make_shared<CAnimImage>(owner->stateIcons, 0, 0, icon_x, icon_y);
  724. stateIcon->visible = false;
  725. }
  726. }
  727. void StackQueue::StackBox::setUnit(const battle::Unit * unit, size_t turn)
  728. {
  729. if(unit)
  730. {
  731. background->colorize(unit->unitOwner());
  732. icon->visible = true;
  733. // temporary code for mod compatibility:
  734. // first, set icon that should definitely exist (arrow tower icon in base vcmi mod)
  735. // second, try to switch to icon that should be provided by mod
  736. // if mod is not up to date and does have arrow tower icon yet - second setFrame call will fail and retain previously set image
  737. // for 1.2 release & later next line should be moved into 'else' block
  738. icon->setFrame(unit->creatureIconIndex(), 0);
  739. if (unit->unitType()->idNumber == CreatureID::ARROW_TOWERS)
  740. icon->setFrame(owner->getSiegeShooterIconID(), 1);
  741. amount->setText(CSDL_Ext::makeNumberShort(unit->getCount(), 4));
  742. if(stateIcon)
  743. {
  744. if(unit->defended((int)turn) || (turn > 0 && unit->defended((int)turn - 1)))
  745. {
  746. stateIcon->setFrame(0, 0);
  747. stateIcon->visible = true;
  748. }
  749. else if(unit->waited((int)turn))
  750. {
  751. stateIcon->setFrame(1, 0);
  752. stateIcon->visible = true;
  753. }
  754. else
  755. {
  756. stateIcon->visible = false;
  757. }
  758. }
  759. }
  760. else
  761. {
  762. background->colorize(PlayerColor::NEUTRAL);
  763. icon->visible = false;
  764. icon->setFrame(0);
  765. amount->setText("");
  766. if(stateIcon)
  767. stateIcon->visible = false;
  768. }
  769. }