BattleWindow.cpp 24 KB

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