BattleWindow.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. /*
  2. * BattleWindow.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "BattleWindow.h"
  12. #include "BattleInterface.h"
  13. #include "BattleInterfaceClasses.h"
  14. #include "BattleFieldController.h"
  15. #include "BattleStacksController.h"
  16. #include "BattleActionsController.h"
  17. #include "../CGameInfo.h"
  18. #include "../CPlayerInterface.h"
  19. #include "../CMusicHandler.h"
  20. #include "../gui/CursorHandler.h"
  21. #include "../gui/CGuiHandler.h"
  22. #include "../gui/Shortcut.h"
  23. #include "../gui/WindowHandler.h"
  24. #include "../windows/CSpellWindow.h"
  25. #include "../widgets/Buttons.h"
  26. #include "../widgets/Images.h"
  27. #include "../windows/CMessage.h"
  28. #include "../render/CAnimation.h"
  29. #include "../render/Canvas.h"
  30. #include "../adventureMap/CInGameConsole.h"
  31. #include "../../CCallback.h"
  32. #include "../../lib/CGeneralTextHandler.h"
  33. #include "../../lib/gameState/InfoAboutArmy.h"
  34. #include "../../lib/mapObjects/CGHeroInstance.h"
  35. #include "../../lib/CStack.h"
  36. #include "../../lib/CConfigHandler.h"
  37. #include "../../lib/filesystem/ResourceID.h"
  38. #include "../windows/settings/SettingsMainWindow.h"
  39. BattleWindow::BattleWindow(BattleInterface & owner):
  40. owner(owner),
  41. defaultAction(PossiblePlayerBattleAction::INVALID)
  42. {
  43. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  44. pos.w = 800;
  45. pos.h = 600;
  46. pos = center();
  47. REGISTER_BUILDER("battleConsole", &BattleWindow::buildBattleConsole);
  48. const JsonNode config(ResourceID("config/widgets/BattleWindow.json"));
  49. addShortcut(EShortcut::GLOBAL_OPTIONS, std::bind(&BattleWindow::bOptionsf, this));
  50. addShortcut(EShortcut::BATTLE_SURRENDER, std::bind(&BattleWindow::bSurrenderf, this));
  51. addShortcut(EShortcut::BATTLE_RETREAT, std::bind(&BattleWindow::bFleef, this));
  52. addShortcut(EShortcut::BATTLE_AUTOCOMBAT, std::bind(&BattleWindow::bAutofightf, this));
  53. addShortcut(EShortcut::BATTLE_CAST_SPELL, std::bind(&BattleWindow::bSpellf, this));
  54. addShortcut(EShortcut::BATTLE_WAIT, std::bind(&BattleWindow::bWaitf, this));
  55. addShortcut(EShortcut::BATTLE_DEFEND, std::bind(&BattleWindow::bDefencef, this));
  56. addShortcut(EShortcut::BATTLE_CONSOLE_UP, std::bind(&BattleWindow::bConsoleUpf, this));
  57. addShortcut(EShortcut::BATTLE_CONSOLE_DOWN, std::bind(&BattleWindow::bConsoleDownf, this));
  58. addShortcut(EShortcut::BATTLE_TACTICS_NEXT, std::bind(&BattleWindow::bTacticNextStack, this));
  59. addShortcut(EShortcut::BATTLE_TACTICS_END, std::bind(&BattleWindow::bTacticPhaseEnd, this));
  60. addShortcut(EShortcut::BATTLE_SELECT_ACTION, std::bind(&BattleWindow::bSwitchActionf, this));
  61. addShortcut(EShortcut::BATTLE_TOGGLE_QUEUE, [this](){ this->toggleQueueVisibility();});
  62. addShortcut(EShortcut::BATTLE_USE_CREATURE_SPELL, [this](){ this->owner.actionsController->enterCreatureCastingMode(); });
  63. addShortcut(EShortcut::GLOBAL_CANCEL, [this](){ this->owner.actionsController->endCastingSpell(); });
  64. build(config);
  65. console = widget<BattleConsole>("console");
  66. owner.console = console;
  67. owner.fieldController.reset( new BattleFieldController(owner));
  68. owner.fieldController->createHeroes();
  69. createQueue();
  70. if ( owner.tacticsMode )
  71. tacticPhaseStarted();
  72. else
  73. tacticPhaseEnded();
  74. addUsedEvents(KEYBOARD);
  75. }
  76. void BattleWindow::createQueue()
  77. {
  78. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  79. //create stack queue and adjust our own position
  80. bool embedQueue;
  81. bool showQueue = settings["battle"]["showQueue"].Bool();
  82. std::string queueSize = settings["battle"]["queueSize"].String();
  83. if(queueSize == "auto")
  84. embedQueue = GH.screenDimensions().y < 700;
  85. else
  86. embedQueue = GH.screenDimensions().y < 700 || queueSize == "small";
  87. queue = std::make_shared<StackQueue>(embedQueue, owner);
  88. if(!embedQueue && showQueue)
  89. {
  90. //re-center, taking into account stack queue position
  91. pos.y -= queue->pos.h;
  92. pos.h += queue->pos.h;
  93. pos = center();
  94. }
  95. if (!showQueue)
  96. queue->disable();
  97. }
  98. BattleWindow::~BattleWindow()
  99. {
  100. CPlayerInterface::battleInt = nullptr;
  101. }
  102. std::shared_ptr<BattleConsole> BattleWindow::buildBattleConsole(const JsonNode & config) const
  103. {
  104. auto rect = readRect(config["rect"]);
  105. auto offset = readPosition(config["imagePosition"]);
  106. auto background = widget<CPicture>("menuBattle");
  107. return std::make_shared<BattleConsole>(background, rect.topLeft(), offset, rect.dimensions() );
  108. }
  109. void BattleWindow::toggleQueueVisibility()
  110. {
  111. if(settings["battle"]["showQueue"].Bool())
  112. hideQueue();
  113. else
  114. showQueue();
  115. }
  116. void BattleWindow::hideQueue()
  117. {
  118. if(settings["battle"]["showQueue"].Bool() == false)
  119. return;
  120. Settings showQueue = settings.write["battle"]["showQueue"];
  121. showQueue->Bool() = false;
  122. queue->disable();
  123. if (!queue->embedded)
  124. {
  125. //re-center, taking into account stack queue position
  126. pos.y += queue->pos.h;
  127. pos.h -= queue->pos.h;
  128. pos = center();
  129. }
  130. GH.windows().totalRedraw();
  131. }
  132. void BattleWindow::showQueue()
  133. {
  134. if(settings["battle"]["showQueue"].Bool() == true)
  135. return;
  136. Settings showQueue = settings.write["battle"]["showQueue"];
  137. showQueue->Bool() = true;
  138. createQueue();
  139. updateQueue();
  140. GH.windows().totalRedraw();
  141. }
  142. void BattleWindow::updateQueue()
  143. {
  144. queue->update();
  145. }
  146. void BattleWindow::activate()
  147. {
  148. GH.setStatusbar(console);
  149. CIntObject::activate();
  150. LOCPLINT->cingconsole->activate();
  151. }
  152. void BattleWindow::deactivate()
  153. {
  154. GH.setStatusbar(nullptr);
  155. CIntObject::deactivate();
  156. LOCPLINT->cingconsole->deactivate();
  157. }
  158. bool BattleWindow::captureThisKey(EShortcut key)
  159. {
  160. return owner.openingPlaying();
  161. }
  162. void BattleWindow::keyPressed(EShortcut key)
  163. {
  164. if (owner.openingPlaying())
  165. {
  166. owner.openingEnd();
  167. return;
  168. }
  169. InterfaceObjectConfigurable::keyPressed(key);
  170. }
  171. void BattleWindow::tacticPhaseStarted()
  172. {
  173. auto menuBattle = widget<CIntObject>("menuBattle");
  174. auto console = widget<CIntObject>("console");
  175. auto menuTactics = widget<CIntObject>("menuTactics");
  176. auto tacticNext = widget<CIntObject>("tacticNext");
  177. auto tacticEnd = widget<CIntObject>("tacticEnd");
  178. auto alternativeAction = widget<CIntObject>("alternativeAction");
  179. menuBattle->disable();
  180. console->disable();
  181. if (alternativeAction)
  182. alternativeAction->disable();
  183. menuTactics->enable();
  184. tacticNext->enable();
  185. tacticEnd->enable();
  186. redraw();
  187. }
  188. void BattleWindow::tacticPhaseEnded()
  189. {
  190. auto menuBattle = widget<CIntObject>("menuBattle");
  191. auto console = widget<CIntObject>("console");
  192. auto menuTactics = widget<CIntObject>("menuTactics");
  193. auto tacticNext = widget<CIntObject>("tacticNext");
  194. auto tacticEnd = widget<CIntObject>("tacticEnd");
  195. auto alternativeAction = widget<CIntObject>("alternativeAction");
  196. menuBattle->enable();
  197. console->enable();
  198. if (alternativeAction)
  199. alternativeAction->enable();
  200. menuTactics->disable();
  201. tacticNext->disable();
  202. tacticEnd->disable();
  203. redraw();
  204. }
  205. void BattleWindow::bOptionsf()
  206. {
  207. if (owner.actionsController->spellcastingModeActive())
  208. return;
  209. CCS->curh->set(Cursor::Map::POINTER);
  210. GH.windows().createAndPushWindow<SettingsMainWindow>(&owner);
  211. }
  212. void BattleWindow::bSurrenderf()
  213. {
  214. if (owner.actionsController->spellcastingModeActive())
  215. return;
  216. int cost = owner.curInt->cb->battleGetSurrenderCost();
  217. if(cost >= 0)
  218. {
  219. std::string enemyHeroName = owner.curInt->cb->battleGetEnemyHero().name;
  220. if(enemyHeroName.empty())
  221. {
  222. logGlobal->warn("Surrender performed without enemy hero, should not happen!");
  223. enemyHeroName = "#ENEMY#";
  224. }
  225. 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."
  226. owner.curInt->showYesNoDialog(surrenderMessage, [this](){ reallySurrender(); }, nullptr);
  227. }
  228. }
  229. void BattleWindow::bFleef()
  230. {
  231. if (owner.actionsController->spellcastingModeActive())
  232. return;
  233. if ( owner.curInt->cb->battleCanFlee() )
  234. {
  235. CFunctionList<void()> ony = std::bind(&BattleWindow::reallyFlee,this);
  236. owner.curInt->showYesNoDialog(CGI->generaltexth->allTexts[28], ony, nullptr); //Are you sure you want to retreat?
  237. }
  238. else
  239. {
  240. std::vector<std::shared_ptr<CComponent>> comps;
  241. std::string heroName;
  242. //calculating fleeing hero's name
  243. if (owner.attackingHeroInstance)
  244. if (owner.attackingHeroInstance->tempOwner == owner.curInt->cb->getMyColor())
  245. heroName = owner.attackingHeroInstance->getNameTranslated();
  246. if (owner.defendingHeroInstance)
  247. if (owner.defendingHeroInstance->tempOwner == owner.curInt->cb->getMyColor())
  248. heroName = owner.defendingHeroInstance->getNameTranslated();
  249. //calculating text
  250. auto txt = boost::format(CGI->generaltexth->allTexts[340]) % heroName; //The Shackles of War are present. %s can not retreat!
  251. //printing message
  252. owner.curInt->showInfoDialog(boost::to_string(txt), comps);
  253. }
  254. }
  255. void BattleWindow::reallyFlee()
  256. {
  257. owner.giveCommand(EActionType::RETREAT);
  258. CCS->curh->set(Cursor::Map::POINTER);
  259. }
  260. void BattleWindow::reallySurrender()
  261. {
  262. if (owner.curInt->cb->getResourceAmount(EGameResID::GOLD) < owner.curInt->cb->battleGetSurrenderCost())
  263. {
  264. owner.curInt->showInfoDialog(CGI->generaltexth->allTexts[29]); //You don't have enough gold!
  265. }
  266. else
  267. {
  268. owner.giveCommand(EActionType::SURRENDER);
  269. CCS->curh->set(Cursor::Map::POINTER);
  270. }
  271. }
  272. void BattleWindow::showAlternativeActionIcon(PossiblePlayerBattleAction action)
  273. {
  274. auto w = widget<CButton>("alternativeAction");
  275. if(!w)
  276. return;
  277. std::string iconName = variables["actionIconDefault"].String();
  278. switch(action.get())
  279. {
  280. case PossiblePlayerBattleAction::ATTACK:
  281. iconName = variables["actionIconAttack"].String();
  282. break;
  283. case PossiblePlayerBattleAction::SHOOT:
  284. iconName = variables["actionIconShoot"].String();
  285. break;
  286. case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
  287. iconName = variables["actionIconSpell"].String();
  288. break;
  289. //TODO: figure out purpose of this icon
  290. //case PossiblePlayerBattleAction::???:
  291. //iconName = variables["actionIconWalk"].String();
  292. //break;
  293. case PossiblePlayerBattleAction::ATTACK_AND_RETURN:
  294. iconName = variables["actionIconReturn"].String();
  295. break;
  296. case PossiblePlayerBattleAction::WALK_AND_ATTACK:
  297. iconName = variables["actionIconNoReturn"].String();
  298. break;
  299. }
  300. auto anim = std::make_shared<CAnimation>(iconName);
  301. w->setImage(anim);
  302. w->redraw();
  303. }
  304. void BattleWindow::setAlternativeActions(const std::list<PossiblePlayerBattleAction> & actions)
  305. {
  306. alternativeActions = actions;
  307. defaultAction = PossiblePlayerBattleAction::INVALID;
  308. if(alternativeActions.size() > 1)
  309. defaultAction = alternativeActions.back();
  310. if(!alternativeActions.empty())
  311. showAlternativeActionIcon(alternativeActions.front());
  312. else
  313. showAlternativeActionIcon(defaultAction);
  314. }
  315. void BattleWindow::bAutofightf()
  316. {
  317. if (owner.actionsController->spellcastingModeActive())
  318. return;
  319. //Stop auto-fight mode
  320. if(owner.curInt->isAutoFightOn)
  321. {
  322. assert(owner.curInt->autofightingAI);
  323. owner.curInt->isAutoFightOn = false;
  324. logGlobal->trace("Stopping the autofight...");
  325. }
  326. else if(!owner.curInt->autofightingAI)
  327. {
  328. owner.curInt->isAutoFightOn = true;
  329. blockUI(true);
  330. auto ai = CDynLibHandler::getNewBattleAI(settings["server"]["friendlyAI"].String());
  331. ai->initBattleInterface(owner.curInt->env, owner.curInt->cb);
  332. ai->battleStart(owner.army1, owner.army2, int3(0,0,0), owner.attackingHeroInstance, owner.defendingHeroInstance, owner.curInt->cb->battleGetMySide());
  333. owner.curInt->autofightingAI = ai;
  334. owner.curInt->cb->registerBattleInterface(ai);
  335. owner.requestAutofightingAIToTakeAction();
  336. }
  337. }
  338. void BattleWindow::bSpellf()
  339. {
  340. if (owner.actionsController->spellcastingModeActive())
  341. return;
  342. if (!owner.makingTurn())
  343. return;
  344. auto myHero = owner.currentHero();
  345. if(!myHero)
  346. return;
  347. CCS->curh->set(Cursor::Map::POINTER);
  348. ESpellCastProblem::ESpellCastProblem spellCastProblem = owner.curInt->cb->battleCanCastSpell(myHero, spells::Mode::HERO);
  349. if(spellCastProblem == ESpellCastProblem::OK)
  350. {
  351. GH.windows().createAndPushWindow<CSpellWindow>(myHero, owner.curInt.get());
  352. }
  353. else if (spellCastProblem == ESpellCastProblem::MAGIC_IS_BLOCKED)
  354. {
  355. //TODO: move to spell mechanics, add more information to spell cast problem
  356. //Handle Orb of Inhibition-like effects -> we want to display dialog with info, why casting is impossible
  357. auto blockingBonus = owner.currentHero()->getBonusLocalFirst(Selector::type()(BonusType::BLOCK_ALL_MAGIC));
  358. if (!blockingBonus)
  359. return;
  360. if (blockingBonus->source == BonusSource::ARTIFACT)
  361. {
  362. const auto artID = ArtifactID(blockingBonus->sid);
  363. //If we have artifact, put name of our hero. Otherwise assume it's the enemy.
  364. //TODO check who *really* is source of bonus
  365. std::string heroName = myHero->hasArt(artID) ? myHero->getNameTranslated() : owner.enemyHero().name;
  366. //%s wields the %s, an ancient artifact which creates a p dead to all magic.
  367. LOCPLINT->showInfoDialog(boost::str(boost::format(CGI->generaltexth->allTexts[683])
  368. % heroName % CGI->artifacts()->getByIndex(artID)->getNameTranslated()));
  369. }
  370. }
  371. }
  372. void BattleWindow::bSwitchActionf()
  373. {
  374. if(alternativeActions.empty())
  375. return;
  376. if(alternativeActions.front() == defaultAction)
  377. {
  378. alternativeActions.push_back(alternativeActions.front());
  379. alternativeActions.pop_front();
  380. }
  381. auto actions = owner.actionsController->getPossibleActions();
  382. if(!actions.empty() && actions.front() == alternativeActions.front())
  383. {
  384. owner.actionsController->removePossibleAction(alternativeActions.front());
  385. showAlternativeActionIcon(defaultAction);
  386. }
  387. else
  388. {
  389. owner.actionsController->pushFrontPossibleAction(alternativeActions.front());
  390. showAlternativeActionIcon(alternativeActions.front());
  391. }
  392. alternativeActions.push_back(alternativeActions.front());
  393. alternativeActions.pop_front();
  394. }
  395. void BattleWindow::bWaitf()
  396. {
  397. if (owner.actionsController->spellcastingModeActive())
  398. return;
  399. if (owner.stacksController->getActiveStack() != nullptr)
  400. owner.giveCommand(EActionType::WAIT);
  401. }
  402. void BattleWindow::bDefencef()
  403. {
  404. if (owner.actionsController->spellcastingModeActive())
  405. return;
  406. if (owner.stacksController->getActiveStack() != nullptr)
  407. owner.giveCommand(EActionType::DEFEND);
  408. }
  409. void BattleWindow::bConsoleUpf()
  410. {
  411. if (owner.actionsController->spellcastingModeActive())
  412. return;
  413. console->scrollUp();
  414. }
  415. void BattleWindow::bConsoleDownf()
  416. {
  417. if (owner.actionsController->spellcastingModeActive())
  418. return;
  419. console->scrollDown();
  420. }
  421. void BattleWindow::bTacticNextStack()
  422. {
  423. owner.tacticNextStack(nullptr);
  424. }
  425. void BattleWindow::bTacticPhaseEnd()
  426. {
  427. owner.tacticPhaseEnd();
  428. }
  429. void BattleWindow::blockUI(bool on)
  430. {
  431. bool canCastSpells = false;
  432. auto hero = owner.curInt->cb->battleGetMyHero();
  433. if(hero)
  434. {
  435. ESpellCastProblem::ESpellCastProblem spellcastingProblem = owner.curInt->cb->battleCanCastSpell(hero, spells::Mode::HERO);
  436. //if magic is blocked, we leave button active, so the message can be displayed after button click
  437. canCastSpells = spellcastingProblem == ESpellCastProblem::OK || spellcastingProblem == ESpellCastProblem::MAGIC_IS_BLOCKED;
  438. }
  439. bool canWait = owner.stacksController->getActiveStack() ? !owner.stacksController->getActiveStack()->waitedThisTurn : false;
  440. setShortcutBlocked(EShortcut::GLOBAL_OPTIONS, on);
  441. setShortcutBlocked(EShortcut::BATTLE_RETREAT, on || !owner.curInt->cb->battleCanFlee());
  442. setShortcutBlocked(EShortcut::BATTLE_SURRENDER, on || owner.curInt->cb->battleGetSurrenderCost() < 0);
  443. setShortcutBlocked(EShortcut::BATTLE_CAST_SPELL, on || owner.tacticsMode || !canCastSpells);
  444. setShortcutBlocked(EShortcut::BATTLE_WAIT, on || owner.tacticsMode || !canWait);
  445. setShortcutBlocked(EShortcut::BATTLE_DEFEND, on || owner.tacticsMode);
  446. setShortcutBlocked(EShortcut::BATTLE_SELECT_ACTION, on || owner.tacticsMode);
  447. setShortcutBlocked(EShortcut::BATTLE_AUTOCOMBAT, owner.actionsController->spellcastingModeActive());
  448. setShortcutBlocked(EShortcut::BATTLE_TACTICS_END, on && owner.tacticsMode);
  449. setShortcutBlocked(EShortcut::BATTLE_TACTICS_NEXT, on && owner.tacticsMode);
  450. setShortcutBlocked(EShortcut::BATTLE_CONSOLE_DOWN, on && !owner.tacticsMode);
  451. setShortcutBlocked(EShortcut::BATTLE_CONSOLE_UP, on && !owner.tacticsMode);
  452. }
  453. std::optional<uint32_t> BattleWindow::getQueueHoveredUnitId()
  454. {
  455. return queue->getHoveredUnitIdIfAny();
  456. }
  457. void BattleWindow::showAll(Canvas & to)
  458. {
  459. CIntObject::showAll(to);
  460. if (GH.screenDimensions().x != 800 || GH.screenDimensions().y !=600)
  461. CMessage::drawBorder(owner.curInt->playerID, to.getInternalSurface(), pos.w+28, pos.h+29, pos.x-14, pos.y-15);
  462. }
  463. void BattleWindow::show(Canvas & to)
  464. {
  465. CIntObject::show(to);
  466. LOCPLINT->cingconsole->show(to);
  467. }
  468. void BattleWindow::close()
  469. {
  470. if(!GH.windows().isTopWindow(this))
  471. logGlobal->error("Only top interface must be closed");
  472. GH.windows().popWindows(1);
  473. }