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