BattleWindow.cpp 16 KB

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