BattleWindow.cpp 28 KB

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