BattleWindow.cpp 17 KB

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