2
0

BattleWindow.cpp 29 KB

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