BattleWindow.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913
  1. /*
  2. * BattleWindow.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 "BattleWindow.h"
  12. #include "BattleActionsController.h"
  13. #include "BattleConsole.h"
  14. #include "BattleFieldController.h"
  15. #include "BattleInterface.h"
  16. #include "BattleStacksController.h"
  17. #include "HeroInfoWindow.h"
  18. #include "QuickSpellPanel.h"
  19. #include "StackInfoBasicPanel.h"
  20. #include "StackQueue.h"
  21. #include "UnitActionPanel.h"
  22. #include "../CPlayerInterface.h"
  23. #include "../GameEngine.h"
  24. #include "../GameInstance.h"
  25. #include "../adventureMap/CInGameConsole.h"
  26. #include "../adventureMap/TurnTimerWidget.h"
  27. #include "../gui/CursorHandler.h"
  28. #include "../gui/Shortcut.h"
  29. #include "../gui/WindowHandler.h"
  30. #include "../render/CAnimation.h"
  31. #include "../render/Canvas.h"
  32. #include "../render/IRenderHandler.h"
  33. #include "../widgets/Buttons.h"
  34. #include "../widgets/Images.h"
  35. #include "../windows/CCreatureWindow.h"
  36. #include "../windows/CMessage.h"
  37. #include "../windows/CSpellWindow.h"
  38. #include "../windows/settings/SettingsMainWindow.h"
  39. #include "../../lib/CConfigHandler.h"
  40. #include "../../lib/CPlayerState.h"
  41. #include "../../lib/CStack.h"
  42. #include "../../lib/GameLibrary.h"
  43. #include "../../lib/StartInfo.h"
  44. #include "../../lib/battle/BattleInfo.h"
  45. #include "../../lib/battle/CPlayerBattleCallback.h"
  46. #include "../../lib/callback/CCallback.h"
  47. #include "../../lib/callback/CDynLibHandler.h"
  48. #include "../../lib/entities/artifact/CArtHandler.h"
  49. #include "../../lib/filesystem/ResourcePath.h"
  50. #include "../../lib/gameState/InfoAboutArmy.h"
  51. #include "../../lib/mapObjects/CGHeroInstance.h"
  52. #include "../../lib/texts/CGeneralTextHandler.h"
  53. BattleWindow::BattleWindow(BattleInterface & Owner)
  54. : owner(Owner)
  55. {
  56. OBJECT_CONSTRUCTION;
  57. pos.w = 800;
  58. pos.h = 600;
  59. pos = center();
  60. PlayerColor defenderColor = owner.getBattle()->getBattle()->getSidePlayer(BattleSide::DEFENDER);
  61. PlayerColor attackerColor = owner.getBattle()->getBattle()->getSidePlayer(BattleSide::ATTACKER);
  62. bool isDefenderHuman = defenderColor.isValidPlayer() && GAME->interface()->cb->getStartInfo()->playerInfos.at(defenderColor).isControlledByHuman();
  63. bool isAttackerHuman = attackerColor.isValidPlayer() && GAME->interface()->cb->getStartInfo()->playerInfos.at(attackerColor).isControlledByHuman();
  64. onlyOnePlayerHuman = isDefenderHuman != isAttackerHuman;
  65. REGISTER_BUILDER("battleConsole", &BattleWindow::buildBattleConsole);
  66. const JsonNode config(JsonPath::builtin("config/widgets/BattleWindow2.json"));
  67. addShortcut(EShortcut::BATTLE_TOGGLE_QUICKSPELL, [this](){ this->toggleStickyQuickSpellVisibility();});
  68. addShortcut(EShortcut::BATTLE_SPELL_SHORTCUT_0, [this](){ useSpellIfPossible(0); });
  69. addShortcut(EShortcut::BATTLE_SPELL_SHORTCUT_1, [this](){ useSpellIfPossible(1); });
  70. addShortcut(EShortcut::BATTLE_SPELL_SHORTCUT_2, [this](){ useSpellIfPossible(2); });
  71. addShortcut(EShortcut::BATTLE_SPELL_SHORTCUT_3, [this](){ useSpellIfPossible(3); });
  72. addShortcut(EShortcut::BATTLE_SPELL_SHORTCUT_4, [this](){ useSpellIfPossible(4); });
  73. addShortcut(EShortcut::BATTLE_SPELL_SHORTCUT_5, [this](){ useSpellIfPossible(5); });
  74. addShortcut(EShortcut::BATTLE_SPELL_SHORTCUT_6, [this](){ useSpellIfPossible(6); });
  75. addShortcut(EShortcut::BATTLE_SPELL_SHORTCUT_7, [this](){ useSpellIfPossible(7); });
  76. addShortcut(EShortcut::BATTLE_SPELL_SHORTCUT_8, [this](){ useSpellIfPossible(8); });
  77. addShortcut(EShortcut::BATTLE_SPELL_SHORTCUT_9, [this](){ useSpellIfPossible(9); });
  78. addShortcut(EShortcut::BATTLE_SPELL_SHORTCUT_10, [this](){ useSpellIfPossible(10); });
  79. addShortcut(EShortcut::BATTLE_SPELL_SHORTCUT_11, [this](){ useSpellIfPossible(11); });
  80. addShortcut(EShortcut::GLOBAL_OPTIONS, std::bind(&BattleWindow::bOptionsf, this));
  81. addShortcut(EShortcut::BATTLE_SURRENDER, std::bind(&BattleWindow::bSurrenderf, this));
  82. addShortcut(EShortcut::BATTLE_RETREAT, std::bind(&BattleWindow::bFleef, this));
  83. addShortcut(EShortcut::BATTLE_AUTOCOMBAT, std::bind(&BattleWindow::bAutofightf, this));
  84. addShortcut(EShortcut::BATTLE_END_WITH_AUTOCOMBAT, std::bind(&BattleWindow::endWithAutocombat, this));
  85. addShortcut(EShortcut::BATTLE_CAST_SPELL, std::bind(&BattleWindow::bSpellf, this));
  86. addShortcut(EShortcut::BATTLE_WAIT, std::bind(&BattleWindow::bWaitf, this));
  87. addShortcut(EShortcut::BATTLE_DEFEND, std::bind(&BattleWindow::bDefencef, this));
  88. addShortcut(EShortcut::BATTLE_CONSOLE_UP, std::bind(&BattleWindow::bConsoleUpf, this));
  89. addShortcut(EShortcut::BATTLE_CONSOLE_DOWN, std::bind(&BattleWindow::bConsoleDownf, this));
  90. addShortcut(EShortcut::BATTLE_TACTICS_NEXT, std::bind(&BattleWindow::bTacticNextStack, this));
  91. addShortcut(EShortcut::BATTLE_TACTICS_END, std::bind(&BattleWindow::bTacticPhaseEnd, this));
  92. addShortcut(EShortcut::BATTLE_OPEN_ACTIVE_UNIT, std::bind(&BattleWindow::bOpenActiveUnit, this));
  93. addShortcut(EShortcut::BATTLE_OPEN_HOVERED_UNIT, std::bind(&BattleWindow::bOpenHoveredUnit, this));
  94. addShortcut(EShortcut::BATTLE_TOGGLE_QUEUE, [this](){ this->toggleQueueVisibility();});
  95. addShortcut(EShortcut::BATTLE_TOGGLE_HEROES_STATS, [this](){ this->toggleStickyHeroWindowsVisibility();});
  96. addShortcut(EShortcut::BATTLE_USE_CREATURE_SPELL, [this](){ this->owner.actionsController->enterCreatureCastingMode(); });
  97. addShortcut(EShortcut::GLOBAL_CANCEL, [this](){ this->owner.actionsController->endCastingSpell(); });
  98. build(config);
  99. console = widget<BattleConsole>("console");
  100. owner.console = console;
  101. owner.fieldController.reset( new BattleFieldController(owner));
  102. owner.fieldController->createHeroes();
  103. createQueue();
  104. createQuickSpellWindow();
  105. createStickyHeroInfoWindows();
  106. createTimerInfoWindows();
  107. if ( owner.tacticsMode )
  108. tacticPhaseStarted();
  109. else
  110. tacticPhaseEnded();
  111. addUsedEvents(LCLICK | KEYBOARD);
  112. }
  113. void BattleWindow::createQueue()
  114. {
  115. OBJECT_CONSTRUCTION;
  116. //create stack queue and adjust our own position
  117. bool embedQueue;
  118. bool showQueue = settings["battle"]["showQueue"].Bool();
  119. std::string queueSize = settings["battle"]["queueSize"].String();
  120. if(queueSize == "auto")
  121. embedQueue = ENGINE->screenDimensions().y < 700;
  122. else
  123. embedQueue = ENGINE->screenDimensions().y < 700 || queueSize == "small";
  124. queue = std::make_shared<StackQueue>(embedQueue, owner);
  125. if(!embedQueue && showQueue)
  126. {
  127. //re-center, taking into account stack queue position
  128. pos.y -= queue->pos.h;
  129. pos.h += queue->pos.h;
  130. }
  131. if(showQueue)
  132. pos = center();
  133. if (!showQueue)
  134. queue->disable();
  135. }
  136. void BattleWindow::createStickyHeroInfoWindows()
  137. {
  138. OBJECT_CONSTRUCTION;
  139. if(owner.defendingHeroInstance)
  140. {
  141. InfoAboutHero info;
  142. info.initFromHero(owner.defendingHeroInstance, InfoAboutHero::EInfoLevel::INBATTLE);
  143. defenderHeroWindow = std::make_shared<HeroInfoBasicPanel>(info, nullptr);
  144. }
  145. if(owner.attackingHeroInstance)
  146. {
  147. InfoAboutHero info;
  148. info.initFromHero(owner.attackingHeroInstance, InfoAboutHero::EInfoLevel::INBATTLE);
  149. attackerHeroWindow = std::make_shared<HeroInfoBasicPanel>(info, nullptr);
  150. }
  151. bool showInfoWindows = settings["battle"]["stickyHeroInfoWindows"].Bool();
  152. if(!showInfoWindows)
  153. {
  154. if(attackerHeroWindow)
  155. attackerHeroWindow->disable();
  156. if(defenderHeroWindow)
  157. defenderHeroWindow->disable();
  158. }
  159. setPositionInfoWindow();
  160. }
  161. void BattleWindow::createQuickSpellWindow()
  162. {
  163. OBJECT_CONSTRUCTION;
  164. quickSpellWindow = std::make_shared<QuickSpellPanel>(owner);
  165. quickSpellWindow->moveTo(Point(pos.x - 52, pos.y));
  166. unitActionWindow = std::make_shared<UnitActionPanel>(owner);
  167. unitActionWindow->moveTo(Point(pos.x + pos.w, pos.y));
  168. if(settings["battle"]["enableQuickSpellPanel"].Bool())
  169. showStickyQuickSpellWindow();
  170. else
  171. hideStickyQuickSpellWindow();
  172. }
  173. void BattleWindow::toggleStickyQuickSpellVisibility()
  174. {
  175. if(settings["battle"]["enableQuickSpellPanel"].Bool())
  176. hideStickyQuickSpellWindow();
  177. else
  178. showStickyQuickSpellWindow();
  179. }
  180. void BattleWindow::hideStickyQuickSpellWindow()
  181. {
  182. Settings showStickyQuickSpellWindow = settings.write["battle"]["enableQuickSpellPanel"];
  183. showStickyQuickSpellWindow->Bool() = false;
  184. quickSpellWindow->disable();
  185. unitActionWindow->disable();
  186. createTimerInfoWindows();
  187. setPositionInfoWindow();
  188. ENGINE->windows().totalRedraw();
  189. }
  190. void BattleWindow::showStickyQuickSpellWindow()
  191. {
  192. Settings showStickyQuickSpellWindow = settings.write["battle"]["enableQuickSpellPanel"];
  193. showStickyQuickSpellWindow->Bool() = true;
  194. auto hero = owner.getBattle()->battleGetMyHero();
  195. bool quickSpellWindowVisible = hasSpaceForQuickActions() && hero != nullptr && hero->hasSpellbook();
  196. bool unitActionWindowVisible = hasSpaceForQuickActions();
  197. quickSpellWindow->setEnabled(quickSpellWindowVisible);
  198. unitActionWindow->setEnabled(unitActionWindowVisible);
  199. if(owner.actionsController && unitActionWindowVisible) // needed after resize of window
  200. owner.actionsController->activateStack();
  201. createTimerInfoWindows();
  202. setPositionInfoWindow();
  203. ENGINE->windows().totalRedraw();
  204. }
  205. void BattleWindow::createTimerInfoWindows()
  206. {
  207. OBJECT_CONSTRUCTION;
  208. int xOffsetAttacker = quickSpellWindow->isDisabled() ? 0 : -51;
  209. int xOffsetDefender = unitActionWindow->isDisabled() ? 0 : 51;
  210. if(GAME->interface()->cb->getStartInfo()->turnTimerInfo.battleTimer != 0 || GAME->interface()->cb->getStartInfo()->turnTimerInfo.unitTimer != 0)
  211. {
  212. PlayerColor attacker = owner.getBattle()->sideToPlayer(BattleSide::ATTACKER);
  213. PlayerColor defender = owner.getBattle()->sideToPlayer(BattleSide::DEFENDER);
  214. if (attacker.isValidPlayer())
  215. {
  216. if (placeInfoWindowsOutside())
  217. attackerTimerWidget = std::make_shared<TurnTimerWidget>(Point(-76 + xOffsetAttacker, 0), attacker);
  218. else
  219. attackerTimerWidget = std::make_shared<TurnTimerWidget>(Point(1, 135), attacker);
  220. }
  221. if (defender.isValidPlayer())
  222. {
  223. if (placeInfoWindowsOutside())
  224. defenderTimerWidget = std::make_shared<TurnTimerWidget>(Point(pos.w + xOffsetDefender, 0), defender);
  225. else
  226. defenderTimerWidget = std::make_shared<TurnTimerWidget>(Point(pos.w - 78, 135), defender);
  227. }
  228. }
  229. }
  230. std::shared_ptr<BattleConsole> BattleWindow::buildBattleConsole(const JsonNode & config) const
  231. {
  232. auto rect = readRect(config["rect"]);
  233. auto offset = readPosition(config["imagePosition"]);
  234. auto background = widget<CPicture>("menuBattle");
  235. return std::make_shared<BattleConsole>(owner, background, rect.topLeft(), offset, rect.dimensions() );
  236. }
  237. void BattleWindow::useSpellIfPossible(int slot)
  238. {
  239. SpellID id;
  240. bool fromSettings;
  241. std::tie(id, fromSettings) = quickSpellWindow->getSpells()[slot];
  242. if(id == SpellID::NONE)
  243. return;
  244. if(id.hasValue() && owner.getBattle()->battleGetMyHero() && id.toSpell()->canBeCast(owner.getBattle().get(), spells::Mode::HERO, owner.getBattle()->battleGetMyHero()))
  245. {
  246. owner.castThisSpell(id);
  247. }
  248. };
  249. void BattleWindow::toggleQueueVisibility()
  250. {
  251. if(settings["battle"]["showQueue"].Bool())
  252. hideQueue();
  253. else
  254. showQueue();
  255. }
  256. void BattleWindow::hideQueue()
  257. {
  258. if(settings["battle"]["showQueue"].Bool() == false)
  259. return;
  260. Settings showQueue = settings.write["battle"]["showQueue"];
  261. showQueue->Bool() = false;
  262. queue->disable();
  263. if (!queue->embedded)
  264. {
  265. //re-center, taking into account stack queue position
  266. pos.y += queue->pos.h;
  267. pos.h -= queue->pos.h;
  268. }
  269. pos = center();
  270. setPositionInfoWindow();
  271. ENGINE->windows().totalRedraw();
  272. }
  273. void BattleWindow::showQueue()
  274. {
  275. if(settings["battle"]["showQueue"].Bool() == true)
  276. return;
  277. Settings showQueue = settings.write["battle"]["showQueue"];
  278. showQueue->Bool() = true;
  279. createQueue();
  280. updateQueue();
  281. setPositionInfoWindow();
  282. ENGINE->windows().totalRedraw();
  283. }
  284. void BattleWindow::toggleStickyHeroWindowsVisibility()
  285. {
  286. if(settings["battle"]["stickyHeroInfoWindows"].Bool())
  287. hideStickyHeroWindows();
  288. else
  289. showStickyHeroWindows();
  290. }
  291. void BattleWindow::hideStickyHeroWindows()
  292. {
  293. if(settings["battle"]["stickyHeroInfoWindows"].Bool() == false)
  294. return;
  295. Settings showStickyHeroInfoWindows = settings.write["battle"]["stickyHeroInfoWindows"];
  296. showStickyHeroInfoWindows->Bool() = false;
  297. if(attackerHeroWindow)
  298. attackerHeroWindow->disable();
  299. if(defenderHeroWindow)
  300. defenderHeroWindow->disable();
  301. ENGINE->windows().totalRedraw();
  302. }
  303. void BattleWindow::showStickyHeroWindows()
  304. {
  305. if(settings["battle"]["stickyHeroInfoWindows"].Bool() == true)
  306. return;
  307. Settings showStickyHeroInfoWindows = settings.write["battle"]["stickyHeroInfoWindows"];
  308. showStickyHeroInfoWindows->Bool() = true;
  309. createStickyHeroInfoWindows();
  310. ENGINE->windows().totalRedraw();
  311. }
  312. void BattleWindow::updateQueue()
  313. {
  314. queue->update();
  315. createQuickSpellWindow();
  316. }
  317. void BattleWindow::setPositionInfoWindow()
  318. {
  319. int xOffsetAttacker = quickSpellWindow->isDisabled() ? 0 : -51;
  320. int xOffsetDefender = unitActionWindow->isDisabled() ? 0 : 51;
  321. int yOffsetAttacker = attackerTimerWidget ? attackerTimerWidget->pos.h + 9 : 0;
  322. int yOffsetDefender = defenderTimerWidget ? defenderTimerWidget->pos.h + 9 : 0;
  323. if(defenderHeroWindow)
  324. {
  325. Point position = placeInfoWindowsOutside()
  326. ? Point(pos.x + pos.w - 1 + xOffsetDefender, pos.y - 1 + yOffsetDefender)
  327. : Point(pos.x + pos.w -79, pos.y + 195);
  328. defenderHeroWindow->moveTo(position);
  329. }
  330. if(attackerHeroWindow)
  331. {
  332. Point position = placeInfoWindowsOutside()
  333. ? Point(pos.x - 77 + xOffsetAttacker, pos.y - 1 + yOffsetAttacker)
  334. : Point(pos.x + 1, pos.y + 195);
  335. attackerHeroWindow->moveTo(position);
  336. }
  337. if(defenderStackWindow)
  338. {
  339. Point position = placeInfoWindowsOutside()
  340. ? Point(pos.x + pos.w - 1 + xOffsetDefender, defenderHeroWindow ? defenderHeroWindow->pos.y + 210 : pos.y - 1 + yOffsetDefender)
  341. : Point(pos.x + pos.w -79, defenderHeroWindow ? defenderHeroWindow->pos.y : pos.y + 195);
  342. defenderStackWindow->moveTo(position);
  343. }
  344. if(attackerStackWindow)
  345. {
  346. Point position = placeInfoWindowsOutside()
  347. ? Point(pos.x - 77 + xOffsetAttacker, attackerHeroWindow ? attackerHeroWindow->pos.y + 210 : pos.y - 1 + yOffsetAttacker)
  348. : Point(pos.x + 1, attackerHeroWindow ? attackerHeroWindow->pos.y : pos.y + 195);
  349. attackerStackWindow->moveTo(position);
  350. }
  351. }
  352. void BattleWindow::updateHeroInfoWindow(uint8_t side, const InfoAboutHero & hero)
  353. {
  354. std::shared_ptr<HeroInfoBasicPanel> panelToUpdate = side == 0 ? attackerHeroWindow : defenderHeroWindow;
  355. panelToUpdate->update(hero);
  356. }
  357. void BattleWindow::updateStackInfoWindow(const CStack * stack)
  358. {
  359. OBJECT_CONSTRUCTION;
  360. bool showInfoWindows = settings["battle"]["stickyHeroInfoWindows"].Bool();
  361. if(stack && stack->unitSide() == BattleSide::DEFENDER)
  362. {
  363. defenderStackWindow = std::make_shared<StackInfoBasicPanel>(stack, true);
  364. defenderStackWindow->setEnabled(showInfoWindows);
  365. }
  366. else
  367. defenderStackWindow = nullptr;
  368. if(stack && stack->unitSide() == BattleSide::ATTACKER)
  369. {
  370. attackerStackWindow = std::make_shared<StackInfoBasicPanel>(stack, true);
  371. attackerStackWindow->setEnabled(showInfoWindows);
  372. }
  373. else
  374. attackerStackWindow = nullptr;
  375. createTimerInfoWindows();
  376. setPositionInfoWindow();
  377. }
  378. void BattleWindow::heroManaPointsChanged(const CGHeroInstance * hero)
  379. {
  380. if(hero == owner.attackingHeroInstance || hero == owner.defendingHeroInstance)
  381. {
  382. InfoAboutHero heroInfo = InfoAboutHero();
  383. heroInfo.initFromHero(hero, InfoAboutHero::INBATTLE);
  384. updateHeroInfoWindow(hero == owner.attackingHeroInstance ? 0 : 1, heroInfo);
  385. }
  386. else
  387. {
  388. logGlobal->error("BattleWindow::heroManaPointsChanged: 'Mana points changed' called for hero not belonging to current battle window");
  389. }
  390. }
  391. void BattleWindow::activate()
  392. {
  393. ENGINE->setStatusbar(console);
  394. CIntObject::activate();
  395. GAME->interface()->cingconsole->activate();
  396. }
  397. void BattleWindow::deactivate()
  398. {
  399. ENGINE->setStatusbar(nullptr);
  400. CIntObject::deactivate();
  401. GAME->interface()->cingconsole->deactivate();
  402. }
  403. bool BattleWindow::captureThisKey(EShortcut key)
  404. {
  405. return owner.openingPlaying();
  406. }
  407. void BattleWindow::keyPressed(EShortcut key)
  408. {
  409. if (owner.openingPlaying())
  410. {
  411. owner.openingEnd();
  412. return;
  413. }
  414. InterfaceObjectConfigurable::keyPressed(key);
  415. }
  416. void BattleWindow::clickPressed(const Point & cursorPosition)
  417. {
  418. if (owner.openingPlaying())
  419. {
  420. owner.openingEnd();
  421. return;
  422. }
  423. InterfaceObjectConfigurable::clickPressed(cursorPosition);
  424. }
  425. void BattleWindow::tacticPhaseStarted()
  426. {
  427. auto menuBattle = widget<CIntObject>("menuBattle");
  428. auto console = widget<CIntObject>("console");
  429. auto menuTactics = widget<CIntObject>("menuTactics");
  430. auto tacticNext = widget<CIntObject>("tacticNext");
  431. auto tacticEnd = widget<CIntObject>("tacticEnd");
  432. menuBattle->disable();
  433. console->disable();
  434. menuTactics->enable();
  435. tacticNext->enable();
  436. tacticEnd->enable();
  437. redraw();
  438. }
  439. void BattleWindow::tacticPhaseEnded()
  440. {
  441. auto menuBattle = widget<CIntObject>("menuBattle");
  442. auto console = widget<CIntObject>("console");
  443. auto menuTactics = widget<CIntObject>("menuTactics");
  444. auto tacticNext = widget<CIntObject>("tacticNext");
  445. auto tacticEnd = widget<CIntObject>("tacticEnd");
  446. menuBattle->enable();
  447. console->enable();
  448. menuTactics->disable();
  449. tacticNext->disable();
  450. tacticEnd->disable();
  451. redraw();
  452. }
  453. void BattleWindow::bOptionsf()
  454. {
  455. if (owner.actionsController->heroSpellcastingModeActive())
  456. return;
  457. ENGINE->cursor().set(Cursor::Map::POINTER);
  458. ENGINE->windows().createAndPushWindow<SettingsMainWindow>(&owner);
  459. }
  460. void BattleWindow::bSurrenderf()
  461. {
  462. if (owner.actionsController->heroSpellcastingModeActive())
  463. return;
  464. int cost = owner.getBattle()->battleGetSurrenderCost();
  465. if(cost >= 0)
  466. {
  467. std::string enemyHeroName = owner.getBattle()->battleGetEnemyHero().name;
  468. if(enemyHeroName.empty())
  469. {
  470. logGlobal->warn("Surrender performed without enemy hero, should not happen!");
  471. enemyHeroName = "#ENEMY#";
  472. }
  473. std::string surrenderMessage = boost::str(boost::format(LIBRARY->generaltexth->allTexts[32]) % enemyHeroName % cost); //%s states: "I will accept your surrender and grant you and your troops safe passage for the price of %d gold."
  474. owner.curInt->showYesNoDialog(surrenderMessage, [this](){ reallySurrender(); }, nullptr);
  475. }
  476. }
  477. void BattleWindow::bFleef()
  478. {
  479. if (owner.actionsController->heroSpellcastingModeActive())
  480. return;
  481. if ( owner.getBattle()->battleCanFlee() )
  482. {
  483. auto ony = std::bind(&BattleWindow::reallyFlee,this);
  484. owner.curInt->showYesNoDialog(LIBRARY->generaltexth->allTexts[28], ony, nullptr); //Are you sure you want to retreat?
  485. }
  486. else
  487. {
  488. std::vector<std::shared_ptr<CComponent>> comps;
  489. std::string heroName;
  490. //calculating fleeing hero's name
  491. if (owner.attackingHeroInstance)
  492. if (owner.attackingHeroInstance->tempOwner == owner.curInt->cb->getPlayerID())
  493. heroName = owner.attackingHeroInstance->getNameTranslated();
  494. if (owner.defendingHeroInstance)
  495. if (owner.defendingHeroInstance->tempOwner == owner.curInt->cb->getPlayerID())
  496. heroName = owner.defendingHeroInstance->getNameTranslated();
  497. //calculating text
  498. auto txt = boost::format(LIBRARY->generaltexth->allTexts[340]) % heroName; //The Shackles of War are present. %s can not retreat!
  499. //printing message
  500. owner.curInt->showInfoDialog(boost::str(txt), comps);
  501. }
  502. }
  503. void BattleWindow::reallyFlee()
  504. {
  505. owner.giveCommand(EActionType::RETREAT);
  506. ENGINE->cursor().set(Cursor::Map::POINTER);
  507. }
  508. void BattleWindow::reallySurrender()
  509. {
  510. if (owner.curInt->cb->getResourceAmount(EGameResID::GOLD) < owner.getBattle()->battleGetSurrenderCost())
  511. {
  512. owner.curInt->showInfoDialog(LIBRARY->generaltexth->allTexts[29]); //You don't have enough gold!
  513. }
  514. else
  515. {
  516. owner.giveCommand(EActionType::SURRENDER);
  517. ENGINE->cursor().set(Cursor::Map::POINTER);
  518. }
  519. }
  520. void BattleWindow::setPossibleActions(const std::vector<PossiblePlayerBattleAction> & actions)
  521. {
  522. unitActionWindow->setPossibleActions(actions);
  523. }
  524. void BattleWindow::bAutofightf()
  525. {
  526. if (owner.actionsController->heroSpellcastingModeActive())
  527. return;
  528. if(settings["battle"]["endWithAutocombat"].Bool() && onlyOnePlayerHuman)
  529. {
  530. endWithAutocombat();
  531. return;
  532. }
  533. //Stop auto-fight mode
  534. if(owner.curInt->isAutoFightOn)
  535. {
  536. assert(owner.curInt->autofightingAI);
  537. owner.curInt->isAutoFightOn = false;
  538. logGlobal->trace("Stopping the autofight...");
  539. }
  540. else if(!owner.curInt->autofightingAI)
  541. {
  542. owner.curInt->isAutoFightOn = true;
  543. blockUI(true);
  544. auto ai = CDynLibHandler::getNewBattleAI(settings["server"]["friendlyAI"].String());
  545. AutocombatPreferences autocombatPreferences = AutocombatPreferences();
  546. autocombatPreferences.enableSpellsUsage = settings["battle"]["enableAutocombatSpells"].Bool();
  547. ai->initBattleInterface(owner.curInt->env, owner.curInt->cb, autocombatPreferences);
  548. ai->battleStart(owner.getBattleID(), owner.army1, owner.army2, int3(0,0,0), owner.attackingHeroInstance, owner.defendingHeroInstance, owner.getBattle()->battleGetMySide(), false);
  549. owner.curInt->registerBattleInterface(ai);
  550. owner.requestAutofightingAIToTakeAction();
  551. }
  552. }
  553. void BattleWindow::bSpellf()
  554. {
  555. if (owner.actionsController->heroSpellcastingModeActive())
  556. return;
  557. if (!owner.makingTurn())
  558. return;
  559. auto myHero = owner.currentHero();
  560. if(!myHero)
  561. return;
  562. ENGINE->cursor().set(Cursor::Map::POINTER);
  563. ESpellCastProblem spellCastProblem = owner.getBattle()->battleCanCastSpell(myHero, spells::Mode::HERO);
  564. if(spellCastProblem == ESpellCastProblem::OK)
  565. {
  566. ENGINE->windows().createAndPushWindow<CSpellWindow>(myHero, owner.curInt.get());
  567. }
  568. else if (spellCastProblem == ESpellCastProblem::MAGIC_IS_BLOCKED)
  569. {
  570. //TODO: move to spell mechanics, add more information to spell cast problem
  571. //Handle Orb of Inhibition-like effects -> we want to display dialog with info, why casting is impossible
  572. auto blockingBonus = owner.currentHero()->getFirstBonus(Selector::type()(BonusType::BLOCK_ALL_MAGIC));
  573. if (!blockingBonus)
  574. return;
  575. if (blockingBonus->source == BonusSource::ARTIFACT)
  576. {
  577. const auto artID = blockingBonus->sid.as<ArtifactID>();
  578. //If we have artifact, put name of our hero. Otherwise assume it's the enemy.
  579. //TODO check who *really* is source of bonus
  580. std::string heroName = myHero->hasArt(artID, true) ? myHero->getNameTranslated() : owner.enemyHero().name;
  581. //%s wields the %s, an ancient artifact which creates a p dead to all magic.
  582. GAME->interface()->showInfoDialog(boost::str(boost::format(LIBRARY->generaltexth->allTexts[683])
  583. % heroName % LIBRARY->artifacts()->getByIndex(artID)->getNameTranslated()));
  584. }
  585. else if(blockingBonus->source == BonusSource::OBJECT_TYPE)
  586. {
  587. if(blockingBonus->sid.as<MapObjectID>() == Obj::GARRISON || blockingBonus->sid.as<MapObjectID>() == Obj::GARRISON2)
  588. GAME->interface()->showInfoDialog(LIBRARY->generaltexth->allTexts[684]);
  589. }
  590. }
  591. else
  592. {
  593. logGlobal->warn("Unexpected problem with readiness to cast spell");
  594. }
  595. }
  596. void BattleWindow::bWaitf()
  597. {
  598. if (owner.actionsController->heroSpellcastingModeActive())
  599. return;
  600. if (owner.stacksController->getActiveStack() != nullptr)
  601. owner.giveCommand(EActionType::WAIT);
  602. }
  603. void BattleWindow::bDefencef()
  604. {
  605. if (owner.actionsController->heroSpellcastingModeActive())
  606. return;
  607. if (owner.stacksController->getActiveStack() != nullptr)
  608. owner.giveCommand(EActionType::DEFEND);
  609. }
  610. void BattleWindow::bConsoleUpf()
  611. {
  612. if (owner.actionsController->heroSpellcastingModeActive())
  613. return;
  614. console->scrollUp();
  615. }
  616. void BattleWindow::bConsoleDownf()
  617. {
  618. if (owner.actionsController->heroSpellcastingModeActive())
  619. return;
  620. console->scrollDown();
  621. }
  622. void BattleWindow::bTacticNextStack()
  623. {
  624. owner.tacticNextStack(nullptr);
  625. }
  626. void BattleWindow::bTacticPhaseEnd()
  627. {
  628. owner.tacticPhaseEnd();
  629. }
  630. void BattleWindow::blockUI(bool on)
  631. {
  632. bool canCastSpells = false;
  633. auto hero = owner.getBattle()->battleGetMyHero();
  634. if(hero)
  635. {
  636. ESpellCastProblem spellcastingProblem = owner.getBattle()->battleCanCastSpell(hero, spells::Mode::HERO);
  637. //if magic is blocked, we leave button active, so the message can be displayed after button click
  638. canCastSpells = spellcastingProblem == ESpellCastProblem::OK || spellcastingProblem == ESpellCastProblem::MAGIC_IS_BLOCKED;
  639. }
  640. bool canWait = owner.stacksController->getActiveStack() ? !owner.stacksController->getActiveStack()->waitedThisTurn : false;
  641. setShortcutBlocked(EShortcut::GLOBAL_OPTIONS, on);
  642. setShortcutBlocked(EShortcut::BATTLE_OPEN_ACTIVE_UNIT, on);
  643. setShortcutBlocked(EShortcut::BATTLE_OPEN_HOVERED_UNIT, on);
  644. setShortcutBlocked(EShortcut::BATTLE_RETREAT, on || !owner.getBattle()->battleCanFlee());
  645. setShortcutBlocked(EShortcut::BATTLE_SURRENDER, on || owner.getBattle()->battleGetSurrenderCost() < 0);
  646. setShortcutBlocked(EShortcut::BATTLE_CAST_SPELL, on || owner.tacticsMode || !canCastSpells);
  647. setShortcutBlocked(EShortcut::BATTLE_WAIT, on || owner.tacticsMode || !canWait);
  648. setShortcutBlocked(EShortcut::BATTLE_DEFEND, on || owner.tacticsMode);
  649. setShortcutBlocked(EShortcut::BATTLE_AUTOCOMBAT, (settings["battle"]["endWithAutocombat"].Bool() && onlyOnePlayerHuman) ? on || owner.tacticsMode || owner.actionsController->heroSpellcastingModeActive() : owner.actionsController->heroSpellcastingModeActive());
  650. setShortcutBlocked(EShortcut::BATTLE_END_WITH_AUTOCOMBAT, on || !onlyOnePlayerHuman || owner.actionsController->heroSpellcastingModeActive());
  651. setShortcutBlocked(EShortcut::BATTLE_TACTICS_END, on || !owner.tacticsMode);
  652. setShortcutBlocked(EShortcut::BATTLE_TACTICS_NEXT, on || !owner.tacticsMode);
  653. setShortcutBlocked(EShortcut::BATTLE_CONSOLE_DOWN, on && !owner.tacticsMode);
  654. setShortcutBlocked(EShortcut::BATTLE_CONSOLE_UP, on && !owner.tacticsMode);
  655. quickSpellWindow->setInputEnabled(!on);
  656. unitActionWindow->setInputEnabled(!on);
  657. }
  658. void BattleWindow::bOpenActiveUnit()
  659. {
  660. const auto * unit = owner.stacksController->getActiveStack();
  661. if (unit)
  662. ENGINE->windows().createAndPushWindow<CStackWindow>(unit, false);
  663. }
  664. void BattleWindow::bOpenHoveredUnit()
  665. {
  666. const auto units = owner.stacksController->getHoveredStacksUnitIds();
  667. if (!units.empty())
  668. {
  669. const auto * unit = owner.getBattle()->battleGetStackByID(units[0]);
  670. if (unit)
  671. ENGINE->windows().createAndPushWindow<CStackWindow>(unit, false);
  672. }
  673. }
  674. std::optional<uint32_t> BattleWindow::getQueueHoveredUnitId()
  675. {
  676. return queue->getHoveredUnitIdIfAny();
  677. }
  678. void BattleWindow::endWithAutocombat()
  679. {
  680. if(!owner.makingTurn())
  681. return;
  682. GAME->interface()->showYesNoDialog(
  683. LIBRARY->generaltexth->translate("vcmi.battleWindow.endWithAutocombat"),
  684. [this]()
  685. {
  686. owner.curInt->isAutoFightEndBattle = true;
  687. auto ai = CDynLibHandler::getNewBattleAI(settings["server"]["friendlyAI"].String());
  688. AutocombatPreferences autocombatPreferences = AutocombatPreferences();
  689. autocombatPreferences.enableSpellsUsage = settings["battle"]["enableAutocombatSpells"].Bool();
  690. ai->initBattleInterface(owner.curInt->env, owner.curInt->cb, autocombatPreferences);
  691. ai->battleStart(owner.getBattleID(), owner.army1, owner.army2, int3(0,0,0), owner.attackingHeroInstance, owner.defendingHeroInstance, owner.getBattle()->battleGetMySide(), false);
  692. owner.curInt->isAutoFightOn = true;
  693. owner.curInt->registerBattleInterface(ai);
  694. owner.requestAutofightingAIToTakeAction();
  695. close();
  696. owner.curInt->battleInt.reset();
  697. },
  698. nullptr
  699. );
  700. }
  701. void BattleWindow::showAll(Canvas & to)
  702. {
  703. CIntObject::showAll(to);
  704. if (ENGINE->screenDimensions().x != 800 || ENGINE->screenDimensions().y !=600)
  705. to.drawBorder(Rect(pos.x-1, pos.y - (queue && queue->embedded ? 1 : 0), pos.w+2, pos.h+1 + (queue && queue->embedded ? 1 : 0)), Colors::BRIGHT_YELLOW);
  706. }
  707. void BattleWindow::show(Canvas & to)
  708. {
  709. CIntObject::show(to);
  710. GAME->interface()->cingconsole->show(to);
  711. }
  712. void BattleWindow::onScreenResize()
  713. {
  714. if(settings["battle"]["showQueue"].Bool())
  715. {
  716. hideQueue();
  717. showQueue();
  718. }
  719. if(settings["battle"]["enableQuickSpellPanel"].Bool())
  720. {
  721. hideStickyQuickSpellWindow();
  722. showStickyQuickSpellWindow();
  723. }
  724. if(settings["battle"]["stickyHeroInfoWindows"].Bool())
  725. {
  726. hideStickyHeroWindows();
  727. showStickyHeroWindows();
  728. }
  729. }
  730. void BattleWindow::close()
  731. {
  732. if(!ENGINE->windows().isTopWindow(this))
  733. logGlobal->error("Only top interface must be closed");
  734. ENGINE->windows().popWindows(1);
  735. }
  736. bool BattleWindow::hasSpaceForQuickActions() const
  737. {
  738. constexpr int widthWithQuickActions = 800 + 50*2;
  739. return ENGINE->screenDimensions().x >= widthWithQuickActions;
  740. }
  741. bool BattleWindow::placeInfoWindowsOutside() const
  742. {
  743. constexpr int widthWithQuickActions = 800 + 50*2 + 75*2;
  744. constexpr int widthBaseWindow = 800 + 75*2;
  745. if (quickActionsPanelActive())
  746. return ENGINE->screenDimensions().x >= widthWithQuickActions;
  747. else
  748. return ENGINE->screenDimensions().x >= widthBaseWindow;
  749. }
  750. bool BattleWindow::quickActionsPanelActive() const
  751. {
  752. return unitActionWindow->isActive();
  753. }