BattleWindow.cpp 26 KB

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