BattleWindow.cpp 26 KB

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