BattleInterface.cpp 22 KB

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