BattleInterface.cpp 22 KB

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