BattleWindow.cpp 25 KB

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