BattleWindow.cpp 16 KB

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