BattleWindow.cpp 17 KB

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