BattleWindow.cpp 29 KB

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