BattleInterface.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871
  1. /*
  2. * BattleInterface.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 "BattleInterface.h"
  12. #include "BattleAnimationClasses.h"
  13. #include "BattleActionsController.h"
  14. #include "BattleInterfaceClasses.h"
  15. #include "CreatureAnimation.h"
  16. #include "BattleProjectileController.h"
  17. #include "BattleEffectsController.h"
  18. #include "BattleObstacleController.h"
  19. #include "BattleSiegeController.h"
  20. #include "BattleFieldController.h"
  21. #include "BattleWindow.h"
  22. #include "BattleStacksController.h"
  23. #include "BattleRenderer.h"
  24. #include "../CPlayerInterface.h"
  25. #include "../gui/CursorHandler.h"
  26. #include "../GameEngine.h"
  27. #include "../GameInstance.h"
  28. #include "../gui/WindowHandler.h"
  29. #include "../media/IMusicPlayer.h"
  30. #include "../media/ISoundPlayer.h"
  31. #include "../windows/CTutorialWindow.h"
  32. #include "../render/Canvas.h"
  33. #include "../adventureMap/AdventureMapInterface.h"
  34. #include "../../lib/BattleFieldHandler.h"
  35. #include "../../lib/CConfigHandler.h"
  36. #include "../../lib/CStack.h"
  37. #include "../../lib/CThreadHelper.h"
  38. #include "../../lib/GameLibrary.h"
  39. #include "../../lib/TerrainHandler.h"
  40. #include "../../lib/UnlockGuard.h"
  41. #include "../../lib/battle/CPlayerBattleCallback.h"
  42. #include "../../lib/callback/CCallback.h"
  43. #include "../../lib/gameState/InfoAboutArmy.h"
  44. #include "../../lib/mapObjects/CGTownInstance.h"
  45. #include "../../lib/networkPacks/PacksForClientBattle.h"
  46. #include "../../lib/texts/CGeneralTextHandler.h"
  47. BattleInterface::BattleInterface(const BattleID & battleID, const CCreatureSet *army1, const CCreatureSet *army2,
  48. const CGHeroInstance *hero1, const CGHeroInstance *hero2,
  49. std::shared_ptr<CPlayerInterface> att,
  50. std::shared_ptr<CPlayerInterface> defen,
  51. std::shared_ptr<CPlayerInterface> spectatorInt)
  52. : attackingHeroInstance(hero1)
  53. , defendingHeroInstance(hero2)
  54. , attackerInt(att)
  55. , defenderInt(defen)
  56. , curInt(att)
  57. , battleID(battleID)
  58. , battleOpeningDelayActive(true)
  59. , round(0)
  60. {
  61. if(spectatorInt)
  62. {
  63. curInt = spectatorInt;
  64. }
  65. else if(!curInt)
  66. {
  67. //May happen when we are defending during network MP game -> attacker interface is just not present
  68. curInt = defenderInt;
  69. }
  70. //hot-seat -> check tactics for both players (defender may be local human)
  71. if(attackerInt && attackerInt->cb->getBattle(getBattleID())->battleGetTacticDist())
  72. tacticianInterface = attackerInt;
  73. else if(defenderInt && defenderInt->cb->getBattle(getBattleID())->battleGetTacticDist())
  74. tacticianInterface = defenderInt;
  75. //if we found interface of player with tactics, then enter tactics mode
  76. tacticsMode = static_cast<bool>(tacticianInterface);
  77. //initializing armies
  78. this->army1 = army1;
  79. this->army2 = army2;
  80. const CGTownInstance *town = getBattle()->battleGetDefendedTown();
  81. if(town && town->fortificationsLevel().wallsHealth > 0)
  82. siegeController.reset(new BattleSiegeController(*this, town));
  83. windowObject = std::make_shared<BattleWindow>(*this);
  84. projectilesController.reset(new BattleProjectileController(*this));
  85. stacksController.reset( new BattleStacksController(*this));
  86. actionsController.reset( new BattleActionsController(*this));
  87. effectsController.reset(new BattleEffectsController(*this));
  88. obstacleController.reset(new BattleObstacleController(*this));
  89. adventureInt->onAudioPaused();
  90. ongoingAnimationsState.setBusy();
  91. ENGINE->windows().pushWindow(windowObject);
  92. windowObject->blockUI(true);
  93. windowObject->updateQueue();
  94. playIntroSoundAndUnlockInterface();
  95. }
  96. void BattleInterface::playIntroSoundAndUnlockInterface()
  97. {
  98. auto onIntroPlayed = [this]()
  99. {
  100. // Make sure that battle have not ended while intro was playing AND that a different one has not started
  101. if(GAME->interface()->battleInt.get() == this)
  102. onIntroSoundPlayed();
  103. };
  104. auto bfieldType = getBattle()->battleGetBattlefieldType();
  105. const auto & battlefieldSound = bfieldType.getInfo()->musicFilename;
  106. std::vector<soundBase::soundID> battleIntroSounds =
  107. {
  108. soundBase::battle00, soundBase::battle01,
  109. soundBase::battle02, soundBase::battle03, soundBase::battle04,
  110. soundBase::battle05, soundBase::battle06, soundBase::battle07
  111. };
  112. int battleIntroSoundChannel = -1;
  113. if (!battlefieldSound.empty())
  114. battleIntroSoundChannel = ENGINE->sound().playSound(battlefieldSound);
  115. else
  116. battleIntroSoundChannel = ENGINE->sound().playSoundFromSet(battleIntroSounds);
  117. if (battleIntroSoundChannel != -1)
  118. {
  119. ENGINE->sound().setCallback(battleIntroSoundChannel, onIntroPlayed);
  120. if (settings["gameTweaks"]["skipBattleIntroMusic"].Bool())
  121. openingEnd();
  122. }
  123. else // failed to play sound
  124. {
  125. onIntroSoundPlayed();
  126. }
  127. }
  128. bool BattleInterface::openingPlaying() const
  129. {
  130. return battleOpeningDelayActive;
  131. }
  132. void BattleInterface::onIntroSoundPlayed()
  133. {
  134. if (openingPlaying())
  135. openingEnd();
  136. auto bfieldType = getBattle()->battleGetBattlefieldType();
  137. const auto & battlefieldMusic = bfieldType.getInfo()->musicFilename;
  138. if (!battlefieldMusic.empty())
  139. ENGINE->music().playMusic(battlefieldMusic, true, true);
  140. else
  141. ENGINE->music().playMusicFromSet("battle", true, true);
  142. }
  143. void BattleInterface::openingEnd()
  144. {
  145. assert(openingPlaying());
  146. if (!openingPlaying())
  147. return;
  148. onAnimationsFinished();
  149. if(tacticsMode)
  150. tacticNextStack(nullptr);
  151. activateStack();
  152. battleOpeningDelayActive = false;
  153. CTutorialWindow::openWindowFirstTime(TutorialMode::TOUCH_BATTLE);
  154. }
  155. BattleInterface::~BattleInterface()
  156. {
  157. CPlayerInterface::battleInt = nullptr;
  158. if (adventureInt)
  159. adventureInt->onAudioResumed();
  160. awaitingEvents.clear();
  161. onAnimationsFinished();
  162. }
  163. void BattleInterface::redrawBattlefield()
  164. {
  165. fieldController->redrawBackgroundWithHexes();
  166. ENGINE->windows().totalRedraw();
  167. }
  168. void BattleInterface::stackReset(const CStack * stack)
  169. {
  170. stacksController->stackReset(stack);
  171. }
  172. void BattleInterface::stackAdded(const CStack * stack)
  173. {
  174. stacksController->stackAdded(stack, false);
  175. }
  176. void BattleInterface::stackRemoved(uint32_t stackID)
  177. {
  178. stacksController->stackRemoved(stackID);
  179. fieldController->redrawBackgroundWithHexes();
  180. windowObject->updateQueue();
  181. }
  182. void BattleInterface::stackActivated(const CStack *stack)
  183. {
  184. stacksController->stackActivated(stack);
  185. }
  186. void BattleInterface::stackMoved(const CStack *stack, const BattleHexArray & destHex, int distance, bool teleport)
  187. {
  188. if (teleport)
  189. stacksController->stackTeleported(stack, destHex, distance);
  190. else
  191. stacksController->stackMoved(stack, destHex, distance);
  192. }
  193. void BattleInterface::stacksAreAttacked(std::vector<StackAttackedInfo> attackedInfos)
  194. {
  195. stacksController->stacksAreAttacked(attackedInfos);
  196. BattleSideArray<int> killedBySide{0,0};
  197. for(const StackAttackedInfo & attackedInfo : attackedInfos)
  198. {
  199. BattleSide side = attackedInfo.defender->unitSide();
  200. killedBySide.at(side) += attackedInfo.amountKilled;
  201. }
  202. for(BattleSide side : { BattleSide::ATTACKER, BattleSide::DEFENDER })
  203. {
  204. if(killedBySide.at(side) > killedBySide.at(getBattle()->otherSide(side)))
  205. setHeroAnimation(side, EHeroAnimType::DEFEAT);
  206. else if(killedBySide.at(side) < killedBySide.at(getBattle()->otherSide(side)))
  207. setHeroAnimation(side, EHeroAnimType::VICTORY);
  208. }
  209. }
  210. void BattleInterface::stackAttacking( const StackAttackInfo & attackInfo )
  211. {
  212. stacksController->stackAttacking(attackInfo);
  213. }
  214. void BattleInterface::newRoundFirst()
  215. {
  216. waitForAnimations();
  217. }
  218. void BattleInterface::newRound()
  219. {
  220. console->addText(LIBRARY->generaltexth->allTexts[412]);
  221. round++;
  222. }
  223. void BattleInterface::giveCommand(EActionType action, const BattleHex & tile, SpellID spell)
  224. {
  225. const CStack * actor = nullptr;
  226. if(action != EActionType::HERO_SPELL && action != EActionType::RETREAT && action != EActionType::SURRENDER)
  227. {
  228. actor = stacksController->getActiveStack();
  229. }
  230. auto side = getBattle()->playerToSide(curInt->playerID);
  231. if(side == BattleSide::NONE)
  232. {
  233. logGlobal->error("Player %s is not in battle", curInt->playerID.toString());
  234. return;
  235. }
  236. BattleAction ba;
  237. ba.side = side;
  238. ba.actionType = action;
  239. ba.aimToHex(tile);
  240. ba.spell = spell;
  241. sendCommand(ba, actor);
  242. }
  243. void BattleInterface::sendCommand(BattleAction command, const CStack * actor)
  244. {
  245. command.stackNumber = actor ? actor->unitId() : ((command.side == BattleSide::ATTACKER) ? -1 : -2);
  246. if(!tacticsMode)
  247. {
  248. logGlobal->trace("Setting command for %s", (actor ? actor->nodeName() : "hero"));
  249. stacksController->setActiveStack(nullptr);
  250. curInt->cb->battleMakeUnitAction(battleID, command);
  251. }
  252. else
  253. {
  254. curInt->cb->battleMakeTacticAction(battleID, command);
  255. stacksController->setActiveStack(nullptr);
  256. //next stack will be activated when action ends
  257. }
  258. ENGINE->cursor().set(Cursor::Combat::POINTER);
  259. }
  260. const CGHeroInstance * BattleInterface::getActiveHero()
  261. {
  262. const CStack *attacker = stacksController->getActiveStack();
  263. if(!attacker)
  264. {
  265. return nullptr;
  266. }
  267. if(attacker->unitSide() == BattleSide::ATTACKER)
  268. {
  269. return attackingHeroInstance;
  270. }
  271. return defendingHeroInstance;
  272. }
  273. void BattleInterface::stackIsCatapulting(const CatapultAttack & ca)
  274. {
  275. if (siegeController)
  276. siegeController->stackIsCatapulting(ca);
  277. }
  278. void BattleInterface::gateStateChanged(const EGateState state)
  279. {
  280. if (siegeController)
  281. siegeController->gateStateChanged(state);
  282. }
  283. void BattleInterface::battleFinished(const BattleResult& br, QueryID queryID)
  284. {
  285. checkForAnimations();
  286. stacksController->setActiveStack(nullptr);
  287. ENGINE->cursor().set(Cursor::Map::POINTER);
  288. curInt->waitWhileDialog();
  289. if(settings["session"]["spectate"].Bool() && settings["session"]["spectate-skip-battle-result"].Bool())
  290. {
  291. curInt->cb->selectionMade(0, queryID);
  292. windowObject->close();
  293. return;
  294. }
  295. auto wnd = std::make_shared<BattleResultWindow>(br, *(this->curInt));
  296. wnd->resultCallback = [this, queryID](ui32 selection)
  297. {
  298. curInt->cb->selectionMade(selection, queryID);
  299. };
  300. ENGINE->windows().pushWindow(wnd);
  301. curInt->waitWhileDialog(); // Avoid freeze when AI end turn after battle. Check bug #1897
  302. CPlayerInterface::battleInt.reset();
  303. }
  304. void BattleInterface::spellCast(const BattleSpellCast * sc)
  305. {
  306. // Do not deactivate anything in tactics mode
  307. // This is battlefield setup spells
  308. if(!tacticsMode)
  309. {
  310. windowObject->blockUI(true);
  311. // Disable current active stack duing the cast
  312. // Store the current activeStack to stackToActivate
  313. stacksController->deactivateStack();
  314. }
  315. ENGINE->cursor().set(Cursor::Combat::BLOCKED);
  316. const SpellID spellID = sc->spellID;
  317. if(!spellID.hasValue())
  318. return;
  319. const CSpell * spell = spellID.toSpell();
  320. auto targetedTile = sc->tile;
  321. const AudioPath & castSoundPath = spell->getCastSound();
  322. if (!castSoundPath.empty())
  323. {
  324. auto group = spell->animationInfo.projectile.empty() ?
  325. EAnimationEvents::HIT:
  326. EAnimationEvents::BEFORE_HIT;//FIXME: recheck whether this should be on projectile spawning
  327. addToAnimationStage(group, [=]() {
  328. ENGINE->sound().playSound(castSoundPath);
  329. });
  330. }
  331. if ( sc->activeCast )
  332. {
  333. const CStack * casterStack = getBattle()->battleGetStackByID(sc->casterStack);
  334. if(casterStack != nullptr )
  335. {
  336. addToAnimationStage(EAnimationEvents::BEFORE_HIT, [this, casterStack, targetedTile, spell]()
  337. {
  338. stacksController->addNewAnim(new CastAnimation(*this, casterStack, targetedTile, getBattle()->battleGetStackByPos(targetedTile), spell));
  339. displaySpellCast(spell, casterStack->getPosition());
  340. });
  341. }
  342. else
  343. {
  344. auto hero = sc->side == BattleSide::DEFENDER ? defendingHero : attackingHero;
  345. assert(hero);
  346. addToAnimationStage(EAnimationEvents::BEFORE_HIT, [this, hero, targetedTile, spell]()
  347. {
  348. stacksController->addNewAnim(new HeroCastAnimation(*this, hero, targetedTile, getBattle()->battleGetStackByPos(targetedTile), spell));
  349. });
  350. }
  351. }
  352. addToAnimationStage(EAnimationEvents::HIT, [this, spell, targetedTile](){
  353. displaySpellHit(spell, targetedTile);
  354. });
  355. //queuing affect animation
  356. for(auto & elem : sc->affectedCres)
  357. {
  358. auto stack = getBattle()->battleGetStackByID(elem, false);
  359. assert(stack);
  360. if(stack)
  361. {
  362. addToAnimationStage(EAnimationEvents::HIT, [this, stack, spell](){
  363. displaySpellEffect(spell, stack->getPosition());
  364. });
  365. }
  366. }
  367. for(auto & elem : sc->reflectedCres)
  368. {
  369. auto stack = getBattle()->battleGetStackByID(elem, false);
  370. assert(stack);
  371. addToAnimationStage(EAnimationEvents::HIT, [this, stack](){
  372. effectsController->displayEffect(EBattleEffect::MAGIC_MIRROR, stack->getPosition());
  373. });
  374. }
  375. if (!sc->resistedCres.empty())
  376. {
  377. addToAnimationStage(EAnimationEvents::HIT, [](){
  378. ENGINE->sound().playSound(AudioPath::builtin("MAGICRES"));
  379. });
  380. }
  381. for(auto & elem : sc->resistedCres)
  382. {
  383. auto stack = getBattle()->battleGetStackByID(elem, false);
  384. assert(stack);
  385. addToAnimationStage(EAnimationEvents::HIT, [this, stack](){
  386. effectsController->displayEffect(EBattleEffect::RESISTANCE, stack->getPosition());
  387. });
  388. }
  389. //mana absorption
  390. if (sc->manaGained > 0)
  391. {
  392. Point leftHero = Point(15, 30);
  393. Point rightHero = Point(755, 30);
  394. BattleSide side = sc->side;
  395. addToAnimationStage(EAnimationEvents::AFTER_HIT, [this, side, leftHero, rightHero](){
  396. stacksController->addNewAnim(new EffectAnimation(*this, AnimationPath::builtin(side == BattleSide::DEFENDER ? "SP07_A.DEF" : "SP07_B.DEF"), leftHero));
  397. stacksController->addNewAnim(new EffectAnimation(*this, AnimationPath::builtin(side == BattleSide::DEFENDER ? "SP07_B.DEF" : "SP07_A.DEF"), rightHero));
  398. });
  399. }
  400. // animations will be executed by spell effects
  401. }
  402. void BattleInterface::battleStacksEffectsSet(const SetStackEffect & sse)
  403. {
  404. if(stacksController->getActiveStack() != nullptr)
  405. fieldController->redrawBackgroundWithHexes();
  406. }
  407. void BattleInterface::setHeroAnimation(BattleSide side, EHeroAnimType phase)
  408. {
  409. if(side == BattleSide::ATTACKER)
  410. {
  411. if(attackingHero)
  412. attackingHero->setPhase(phase);
  413. }
  414. else
  415. {
  416. if(defendingHero)
  417. defendingHero->setPhase(phase);
  418. }
  419. }
  420. void BattleInterface::displayBattleLog(const std::vector<MetaString> & battleLog)
  421. {
  422. for(const auto & line : battleLog)
  423. {
  424. std::string formatted = line.toString();
  425. boost::algorithm::trim(formatted);
  426. appendBattleLog(formatted);
  427. }
  428. }
  429. void BattleInterface::displaySpellAnimationQueue(const CSpell * spell, const CSpell::TAnimationQueue & q, const BattleHex & destinationTile, bool isHit)
  430. {
  431. for(const CSpell::TAnimation & animation : q)
  432. {
  433. if(animation.pause > 0)
  434. stacksController->addNewAnim(new DummyAnimation(*this, animation.pause));
  435. if (!animation.effectName.empty())
  436. {
  437. const CStack * destStack = getBattle()->battleGetStackByPos(destinationTile, false);
  438. if (destStack)
  439. stacksController->addNewAnim(new ColorTransformAnimation(*this, destStack, animation.effectName, spell ));
  440. }
  441. if(!animation.resourceName.empty())
  442. {
  443. int flags = 0;
  444. if (isHit)
  445. flags |= EffectAnimation::FORCE_ON_TOP;
  446. if (animation.verticalPosition == VerticalPosition::BOTTOM)
  447. flags |= EffectAnimation::ALIGN_TO_BOTTOM;
  448. if (!destinationTile.isValid())
  449. flags |= EffectAnimation::SCREEN_FILL;
  450. if (!destinationTile.isValid())
  451. stacksController->addNewAnim(new EffectAnimation(*this, animation.resourceName, flags, animation.transparency));
  452. else
  453. stacksController->addNewAnim(new EffectAnimation(*this, animation.resourceName, destinationTile, flags, animation.transparency));
  454. }
  455. }
  456. }
  457. void BattleInterface::displaySpellCast(const CSpell * spell, const BattleHex & destinationTile)
  458. {
  459. if(spell)
  460. displaySpellAnimationQueue(spell, spell->animationInfo.cast, destinationTile, false);
  461. }
  462. void BattleInterface::displaySpellEffect(const CSpell * spell, const BattleHex & destinationTile)
  463. {
  464. if(spell)
  465. displaySpellAnimationQueue(spell, spell->animationInfo.affect, destinationTile, false);
  466. }
  467. void BattleInterface::displaySpellHit(const CSpell * spell, const BattleHex & destinationTile)
  468. {
  469. if(spell)
  470. displaySpellAnimationQueue(spell, spell->animationInfo.hit, destinationTile, true);
  471. }
  472. CPlayerInterface *BattleInterface::getCurrentPlayerInterface() const
  473. {
  474. return curInt.get();
  475. }
  476. void BattleInterface::trySetActivePlayer( PlayerColor player )
  477. {
  478. if ( attackerInt && attackerInt->playerID == player )
  479. curInt = attackerInt;
  480. if ( defenderInt && defenderInt->playerID == player )
  481. curInt = defenderInt;
  482. }
  483. void BattleInterface::activateStack()
  484. {
  485. stacksController->activateStack();
  486. const CStack * s = stacksController->getActiveStack();
  487. if(!s)
  488. return;
  489. windowObject->updateQueue();
  490. windowObject->blockUI(false);
  491. fieldController->redrawBackgroundWithHexes();
  492. actionsController->activateStack();
  493. ENGINE->fakeMouseMove();
  494. }
  495. bool BattleInterface::makingTurn() const
  496. {
  497. return stacksController->getActiveStack() != nullptr;
  498. }
  499. BattleID BattleInterface::getBattleID() const
  500. {
  501. return battleID;
  502. }
  503. std::shared_ptr<CPlayerBattleCallback> BattleInterface::getBattle() const
  504. {
  505. return curInt->cb->getBattle(battleID);
  506. }
  507. void BattleInterface::endAction(const BattleAction &action)
  508. {
  509. // it is possible that tactics mode ended while opening music is still playing
  510. waitForAnimations();
  511. const CStack *stack = getBattle()->battleGetStackByID(action.stackNumber);
  512. // Activate stack from stackToActivate because this might have been temporary disabled, e.g., during spell cast
  513. activateStack();
  514. stacksController->endAction(action);
  515. windowObject->updateQueue();
  516. //stack ended movement in tactics phase -> select the next one
  517. if (tacticsMode)
  518. tacticNextStack(stack);
  519. //we have activated next stack after sending request that has been just realized -> blockmap due to movement has changed
  520. if(action.actionType == EActionType::HERO_SPELL)
  521. fieldController->redrawBackgroundWithHexes();
  522. }
  523. void BattleInterface::appendBattleLog(const std::string & newEntry)
  524. {
  525. console->addText(newEntry);
  526. }
  527. void BattleInterface::startAction(const BattleAction & action)
  528. {
  529. if(action.actionType == EActionType::END_TACTIC_PHASE)
  530. {
  531. windowObject->tacticPhaseEnded();
  532. return;
  533. }
  534. stacksController->startAction(action);
  535. if (!action.isUnitAction())
  536. return;
  537. assert(getBattle()->battleGetStackByID(action.stackNumber));
  538. windowObject->updateQueue();
  539. effectsController->startAction(action);
  540. }
  541. void BattleInterface::tacticPhaseEnd()
  542. {
  543. stacksController->setActiveStack(nullptr);
  544. tacticsMode = false;
  545. auto side = tacticianInterface->cb->getBattle(battleID)->playerToSide(tacticianInterface->playerID);
  546. auto action = BattleAction::makeEndOFTacticPhase(side);
  547. tacticianInterface->cb->battleMakeTacticAction(battleID, action);
  548. }
  549. static bool immobile(const CStack *s)
  550. {
  551. return s->getMovementRange() == 0; //should bound stacks be immobile?
  552. }
  553. void BattleInterface::tacticNextStack(const CStack * current)
  554. {
  555. if (!current)
  556. current = stacksController->getActiveStack();
  557. //no switching stacks when the current one is moving
  558. checkForAnimations();
  559. TStacks stacksOfMine = tacticianInterface->cb->getBattle(battleID)->battleGetStacks(CPlayerBattleCallback::ONLY_MINE);
  560. vstd::erase_if (stacksOfMine, &immobile);
  561. if (stacksOfMine.empty())
  562. {
  563. tacticPhaseEnd();
  564. return;
  565. }
  566. auto it = vstd::find(stacksOfMine, current);
  567. if (it != stacksOfMine.end() && ++it != stacksOfMine.end())
  568. stackActivated(*it);
  569. else
  570. stackActivated(stacksOfMine.front());
  571. }
  572. void BattleInterface::obstaclePlaced(const std::vector<std::shared_ptr<const CObstacleInstance>> oi)
  573. {
  574. obstacleController->obstaclePlaced(oi);
  575. }
  576. void BattleInterface::obstacleRemoved(const std::vector<ObstacleChanges> & obstacles)
  577. {
  578. obstacleController->obstacleRemoved(obstacles);
  579. }
  580. const CGHeroInstance *BattleInterface::currentHero() const
  581. {
  582. if (attackingHeroInstance && attackingHeroInstance->tempOwner == curInt->playerID)
  583. return attackingHeroInstance;
  584. if (defendingHeroInstance && defendingHeroInstance->tempOwner == curInt->playerID)
  585. return defendingHeroInstance;
  586. return nullptr;
  587. }
  588. InfoAboutHero BattleInterface::enemyHero() const
  589. {
  590. InfoAboutHero ret;
  591. if (attackingHeroInstance->tempOwner == curInt->playerID)
  592. curInt->cb->getHeroInfo(defendingHeroInstance, ret);
  593. else
  594. curInt->cb->getHeroInfo(attackingHeroInstance, ret);
  595. return ret;
  596. }
  597. void BattleInterface::requestAutofightingAIToTakeAction()
  598. {
  599. assert(curInt->isAutoFightOn);
  600. if(getBattle()->battleIsFinished())
  601. {
  602. return; // battle finished with spellcast
  603. }
  604. if (tacticsMode)
  605. {
  606. // Always end tactics mode. Player interface is blocked currently, so it's not possible that
  607. // the AI can take any action except end tactics phase (AI actions won't be triggered)
  608. //TODO implement the possibility that the AI will be triggered for further actions
  609. //TODO any solution to merge tactics phase & normal phase in the way it is handled by the player and battle interface?
  610. tacticPhaseEnd();
  611. stacksController->setActiveStack(nullptr);
  612. }
  613. else
  614. {
  615. const CStack* activeStack = stacksController->getActiveStack();
  616. // If enemy is moving, activeStack can be null
  617. if (activeStack)
  618. {
  619. stacksController->setActiveStack(nullptr);
  620. // FIXME: unsafe
  621. // Run task in separate thread to avoid UI lock while AI is making turn (which might take some time)
  622. // HOWEVER this thread won't atttempt to lock game state, potentially leading to races
  623. std::thread aiThread([localBattleID = battleID, localCurInt = curInt, activeStack]()
  624. {
  625. setThreadName("autofightingAI");
  626. localCurInt->autofightingAI->activeStack(localBattleID, activeStack);
  627. });
  628. aiThread.detach();
  629. }
  630. }
  631. }
  632. void BattleInterface::castThisSpell(SpellID spellID)
  633. {
  634. actionsController->castThisSpell(spellID);
  635. }
  636. void BattleInterface::endNetwork()
  637. {
  638. ongoingAnimationsState.requestTermination();
  639. }
  640. void BattleInterface::executeStagedAnimations()
  641. {
  642. EAnimationEvents earliestStage = EAnimationEvents::COUNT;
  643. for(const auto & event : awaitingEvents)
  644. earliestStage = std::min(earliestStage, event.event);
  645. if(earliestStage != EAnimationEvents::COUNT)
  646. executeAnimationStage(earliestStage);
  647. }
  648. void BattleInterface::executeAnimationStage(EAnimationEvents event)
  649. {
  650. decltype(awaitingEvents) executingEvents;
  651. for(auto it = awaitingEvents.begin(); it != awaitingEvents.end();)
  652. {
  653. if(it->event == event)
  654. {
  655. executingEvents.push_back(*it);
  656. it = awaitingEvents.erase(it);
  657. }
  658. else
  659. ++it;
  660. }
  661. for(const auto & event : executingEvents)
  662. event.action();
  663. }
  664. void BattleInterface::onAnimationsStarted()
  665. {
  666. ongoingAnimationsState.setBusy();
  667. }
  668. void BattleInterface::onAnimationsFinished()
  669. {
  670. ongoingAnimationsState.setFree();
  671. }
  672. void BattleInterface::waitForAnimations()
  673. {
  674. {
  675. auto unlockInterface = vstd::makeUnlockGuard(ENGINE->interfaceMutex);
  676. ongoingAnimationsState.waitWhileBusy();
  677. }
  678. assert(!hasAnimations());
  679. assert(awaitingEvents.empty());
  680. if (!awaitingEvents.empty())
  681. {
  682. logGlobal->error("Wait for animations finished but we still have awaiting events!");
  683. awaitingEvents.clear();
  684. }
  685. }
  686. bool BattleInterface::hasAnimations()
  687. {
  688. return ongoingAnimationsState.isBusy();
  689. }
  690. void BattleInterface::checkForAnimations()
  691. {
  692. assert(!hasAnimations());
  693. if(hasAnimations())
  694. logGlobal->error("Unexpected animations state: expected all animations to be over, but some are still ongoing!");
  695. waitForAnimations();
  696. }
  697. void BattleInterface::addToAnimationStage(EAnimationEvents event, const AwaitingAnimationAction & action)
  698. {
  699. awaitingEvents.push_back({action, event});
  700. }
  701. void BattleInterface::setBattleQueueVisibility(bool visible)
  702. {
  703. windowObject->hideQueue();
  704. if(visible)
  705. windowObject->showQueue();
  706. }
  707. void BattleInterface::setStickyHeroWindowsVisibility(bool visible)
  708. {
  709. windowObject->hideStickyHeroWindows();
  710. if(visible)
  711. windowObject->showStickyHeroWindows();
  712. }
  713. void BattleInterface::setStickyQuickSpellWindowVisibility(bool visible)
  714. {
  715. windowObject->hideStickyQuickSpellWindow();
  716. if(visible)
  717. windowObject->showStickyQuickSpellWindow();
  718. }