BattleInterface.cpp 23 KB

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