BattleInterface.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824
  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 "../render/Canvas.h"
  31. #include "../adventureMap/AdventureMapInterface.h"
  32. #include "../../CCallback.h"
  33. #include "../../lib/CStack.h"
  34. #include "../../lib/CConfigHandler.h"
  35. #include "../../lib/CGeneralTextHandler.h"
  36. #include "../../lib/CHeroHandler.h"
  37. #include "../../lib/CondSh.h"
  38. #include "../../lib/gameState/InfoAboutArmy.h"
  39. #include "../../lib/mapObjects/CGTownInstance.h"
  40. #include "../../lib/NetPacks.h"
  41. #include "../../lib/UnlockGuard.h"
  42. #include "../../lib/TerrainHandler.h"
  43. CondSh<BattleAction *> BattleInterface::givenCommand(nullptr);
  44. BattleInterface::BattleInterface(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. , battleOpeningDelayActive(true)
  55. {
  56. if(spectatorInt)
  57. {
  58. curInt = spectatorInt;
  59. }
  60. else if(!curInt)
  61. {
  62. //May happen when we are defending during network MP game -> attacker interface is just not present
  63. curInt = defenderInt;
  64. }
  65. givenCommand.setn(nullptr);
  66. //hot-seat -> check tactics for both players (defender may be local human)
  67. if(attackerInt && attackerInt->cb->battleGetTacticDist())
  68. tacticianInterface = attackerInt;
  69. else if(defenderInt && defenderInt->cb->battleGetTacticDist())
  70. tacticianInterface = defenderInt;
  71. //if we found interface of player with tactics, then enter tactics mode
  72. tacticsMode = static_cast<bool>(tacticianInterface);
  73. //initializing armies
  74. this->army1 = army1;
  75. this->army2 = army2;
  76. const CGTownInstance *town = curInt->cb->battleGetDefendedTown();
  77. if(town && town->hasFort())
  78. siegeController.reset(new BattleSiegeController(*this, town));
  79. windowObject = std::make_shared<BattleWindow>(*this);
  80. projectilesController.reset(new BattleProjectileController(*this));
  81. stacksController.reset( new BattleStacksController(*this));
  82. actionsController.reset( new BattleActionsController(*this));
  83. effectsController.reset(new BattleEffectsController(*this));
  84. obstacleController.reset(new BattleObstacleController(*this));
  85. adventureInt->onAudioPaused();
  86. ongoingAnimationsState.set(true);
  87. GH.windows().pushWindow(windowObject);
  88. windowObject->blockUI(true);
  89. windowObject->updateQueue();
  90. playIntroSoundAndUnlockInterface();
  91. }
  92. void BattleInterface::playIntroSoundAndUnlockInterface()
  93. {
  94. auto onIntroPlayed = [this]()
  95. {
  96. if(LOCPLINT->battleInt)
  97. {
  98. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  99. onIntroSoundPlayed();
  100. }
  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. }
  135. BattleInterface::~BattleInterface()
  136. {
  137. CPlayerInterface::battleInt = nullptr;
  138. givenCommand.cond.notify_all(); //that two lines should make any stacksController->getActiveStack() waiting thread to finish
  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( int round )
  196. {
  197. waitForAnimations();
  198. }
  199. void BattleInterface::newRound(int number)
  200. {
  201. console->addText(CGI->generaltexth->allTexts[412]);
  202. }
  203. void BattleInterface::giveCommand(EActionType action, BattleHex tile, si32 additional)
  204. {
  205. const CStack * actor = nullptr;
  206. if(action != EActionType::HERO_SPELL && action != EActionType::RETREAT && action != EActionType::SURRENDER)
  207. {
  208. actor = stacksController->getActiveStack();
  209. }
  210. auto side = curInt->cb->playerToSide(curInt->playerID);
  211. if(!side)
  212. {
  213. logGlobal->error("Player %s is not in battle", curInt->playerID.getStr());
  214. return;
  215. }
  216. auto ba = new BattleAction(); //is deleted in CPlayerInterface::stacksController->getActiveStack()()
  217. ba->side = side.value();
  218. ba->actionType = action;
  219. ba->aimToHex(tile);
  220. ba->actionSubtype = additional;
  221. sendCommand(ba, actor);
  222. }
  223. void BattleInterface::sendCommand(BattleAction *& command, const CStack * actor)
  224. {
  225. command->stackNumber = actor ? actor->unitId() : ((command->side == BattleSide::ATTACKER) ? -1 : -2);
  226. if(!tacticsMode)
  227. {
  228. logGlobal->trace("Setting command for %s", (actor ? actor->nodeName() : "hero"));
  229. stacksController->setActiveStack(nullptr);
  230. givenCommand.setn(command);
  231. }
  232. else
  233. {
  234. curInt->cb->battleMakeTacticAction(command);
  235. vstd::clear_pointer(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. const CSpell * spell = spellID.toSpell();
  299. auto targetedTile = sc->tile;
  300. assert(spell);
  301. if(!spell)
  302. return;
  303. const std::string & castSoundPath = spell->getCastSound();
  304. if (!castSoundPath.empty())
  305. {
  306. auto group = spell->animationInfo.projectile.empty() ?
  307. EAnimationEvents::HIT:
  308. EAnimationEvents::BEFORE_HIT;//FIXME: recheck whether this should be on projectile spawning
  309. addToAnimationStage(group, [=]() {
  310. CCS->soundh->playSound(castSoundPath);
  311. });
  312. }
  313. if ( sc->activeCast )
  314. {
  315. const CStack * casterStack = curInt->cb->battleGetStackByID(sc->casterStack);
  316. if(casterStack != nullptr )
  317. {
  318. addToAnimationStage(EAnimationEvents::BEFORE_HIT, [=]()
  319. {
  320. stacksController->addNewAnim(new CastAnimation(*this, casterStack, targetedTile, curInt->cb->battleGetStackByPos(targetedTile), spell));
  321. displaySpellCast(spell, casterStack->getPosition());
  322. });
  323. }
  324. else
  325. {
  326. auto hero = sc->side ? defendingHero : attackingHero;
  327. assert(hero);
  328. addToAnimationStage(EAnimationEvents::BEFORE_HIT, [=]()
  329. {
  330. stacksController->addNewAnim(new HeroCastAnimation(*this, hero, targetedTile, curInt->cb->battleGetStackByPos(targetedTile), spell));
  331. });
  332. }
  333. }
  334. addToAnimationStage(EAnimationEvents::HIT, [=](){
  335. displaySpellHit(spell, targetedTile);
  336. });
  337. //queuing affect animation
  338. for(auto & elem : sc->affectedCres)
  339. {
  340. auto stack = curInt->cb->battleGetStackByID(elem, false);
  341. assert(stack);
  342. if(stack)
  343. {
  344. addToAnimationStage(EAnimationEvents::HIT, [=](){
  345. displaySpellEffect(spell, stack->getPosition());
  346. });
  347. }
  348. }
  349. for(auto & elem : sc->reflectedCres)
  350. {
  351. auto stack = curInt->cb->battleGetStackByID(elem, false);
  352. assert(stack);
  353. addToAnimationStage(EAnimationEvents::HIT, [=](){
  354. effectsController->displayEffect(EBattleEffect::MAGIC_MIRROR, stack->getPosition());
  355. });
  356. }
  357. if (!sc->resistedCres.empty())
  358. {
  359. addToAnimationStage(EAnimationEvents::HIT, [=](){
  360. CCS->soundh->playSound("MAGICRES");
  361. });
  362. }
  363. for(auto & elem : sc->resistedCres)
  364. {
  365. auto stack = curInt->cb->battleGetStackByID(elem, false);
  366. assert(stack);
  367. addToAnimationStage(EAnimationEvents::HIT, [=](){
  368. effectsController->displayEffect(EBattleEffect::RESISTANCE, stack->getPosition());
  369. });
  370. }
  371. //mana absorption
  372. if (sc->manaGained > 0)
  373. {
  374. Point leftHero = Point(15, 30);
  375. Point rightHero = Point(755, 30);
  376. bool side = sc->side;
  377. addToAnimationStage(EAnimationEvents::AFTER_HIT, [=](){
  378. stacksController->addNewAnim(new EffectAnimation(*this, side ? "SP07_A.DEF" : "SP07_B.DEF", leftHero));
  379. stacksController->addNewAnim(new EffectAnimation(*this, side ? "SP07_B.DEF" : "SP07_A.DEF", rightHero));
  380. });
  381. }
  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 = getCurrentPlayerInterface()->cb->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. void BattleInterface::endAction(const BattleAction* action)
  481. {
  482. // it is possible that tactics mode ended while opening music is still playing
  483. waitForAnimations();
  484. const CStack *stack = curInt->cb->battleGetStackByID(action->stackNumber);
  485. // Activate stack from stackToActivate because this might have been temporary disabled, e.g., during spell cast
  486. activateStack();
  487. stacksController->endAction(action);
  488. windowObject->updateQueue();
  489. //stack ended movement in tactics phase -> select the next one
  490. if (tacticsMode)
  491. tacticNextStack(stack);
  492. //we have activated next stack after sending request that has been just realized -> blockmap due to movement has changed
  493. if(action->actionType == EActionType::HERO_SPELL)
  494. fieldController->redrawBackgroundWithHexes();
  495. }
  496. void BattleInterface::appendBattleLog(const std::string & newEntry)
  497. {
  498. console->addText(newEntry);
  499. }
  500. void BattleInterface::startAction(const BattleAction* action)
  501. {
  502. if(action->actionType == EActionType::END_TACTIC_PHASE)
  503. {
  504. windowObject->tacticPhaseEnded();
  505. return;
  506. }
  507. const CStack *stack = curInt->cb->battleGetStackByID(action->stackNumber);
  508. if (stack)
  509. {
  510. windowObject->updateQueue();
  511. }
  512. else
  513. {
  514. assert(action->actionType == EActionType::HERO_SPELL); //only cast spell is valid action without acting stack number
  515. }
  516. stacksController->startAction(action);
  517. if(action->actionType == EActionType::HERO_SPELL) //when hero casts spell
  518. return;
  519. if (!stack)
  520. {
  521. logGlobal->error("Something wrong with stackNumber in actionStarted. Stack number: %d", action->stackNumber);
  522. return;
  523. }
  524. effectsController->startAction(action);
  525. }
  526. void BattleInterface::tacticPhaseEnd()
  527. {
  528. stacksController->setActiveStack(nullptr);
  529. tacticsMode = false;
  530. }
  531. static bool immobile(const CStack *s)
  532. {
  533. return !s->speed(0, true); //should bound stacks be immobile?
  534. }
  535. void BattleInterface::tacticNextStack(const CStack * current)
  536. {
  537. if (!current)
  538. current = stacksController->getActiveStack();
  539. //no switching stacks when the current one is moving
  540. checkForAnimations();
  541. TStacks stacksOfMine = tacticianInterface->cb->battleGetStacks(CBattleCallback::ONLY_MINE);
  542. vstd::erase_if (stacksOfMine, &immobile);
  543. if (stacksOfMine.empty())
  544. {
  545. tacticPhaseEnd();
  546. return;
  547. }
  548. auto it = vstd::find(stacksOfMine, current);
  549. if (it != stacksOfMine.end() && ++it != stacksOfMine.end())
  550. stackActivated(*it);
  551. else
  552. stackActivated(stacksOfMine.front());
  553. }
  554. void BattleInterface::obstaclePlaced(const std::vector<std::shared_ptr<const CObstacleInstance>> oi)
  555. {
  556. obstacleController->obstaclePlaced(oi);
  557. }
  558. void BattleInterface::obstacleRemoved(const std::vector<ObstacleChanges> & obstacles)
  559. {
  560. obstacleController->obstacleRemoved(obstacles);
  561. }
  562. const CGHeroInstance *BattleInterface::currentHero() const
  563. {
  564. if (attackingHeroInstance && attackingHeroInstance->tempOwner == curInt->playerID)
  565. return attackingHeroInstance;
  566. if (defendingHeroInstance && defendingHeroInstance->tempOwner == curInt->playerID)
  567. return defendingHeroInstance;
  568. return nullptr;
  569. }
  570. InfoAboutHero BattleInterface::enemyHero() const
  571. {
  572. InfoAboutHero ret;
  573. if (attackingHeroInstance->tempOwner == curInt->playerID)
  574. curInt->cb->getHeroInfo(defendingHeroInstance, ret);
  575. else
  576. curInt->cb->getHeroInfo(attackingHeroInstance, ret);
  577. return ret;
  578. }
  579. void BattleInterface::requestAutofightingAIToTakeAction()
  580. {
  581. assert(curInt->isAutoFightOn);
  582. boost::thread aiThread([&]()
  583. {
  584. if(curInt->cb->battleIsFinished())
  585. {
  586. return; // battle finished with spellcast
  587. }
  588. if (tacticsMode)
  589. {
  590. // Always end tactics mode. Player interface is blocked currently, so it's not possible that
  591. // the AI can take any action except end tactics phase (AI actions won't be triggered)
  592. //TODO implement the possibility that the AI will be triggered for further actions
  593. //TODO any solution to merge tactics phase & normal phase in the way it is handled by the player and battle interface?
  594. stacksController->setActiveStack(nullptr);
  595. tacticsMode = false;
  596. }
  597. else
  598. {
  599. const CStack* activeStack = stacksController->getActiveStack();
  600. // If enemy is moving, activeStack can be null
  601. if (activeStack)
  602. {
  603. auto ba = std::make_unique<BattleAction>(curInt->autofightingAI->activeStack(activeStack));
  604. givenCommand.setn(ba.release());
  605. }
  606. stacksController->setActiveStack(nullptr);
  607. }
  608. });
  609. aiThread.detach();
  610. }
  611. void BattleInterface::castThisSpell(SpellID spellID)
  612. {
  613. actionsController->castThisSpell(spellID);
  614. }
  615. void BattleInterface::executeStagedAnimations()
  616. {
  617. EAnimationEvents earliestStage = EAnimationEvents::COUNT;
  618. for(const auto & event : awaitingEvents)
  619. earliestStage = std::min(earliestStage, event.event);
  620. if(earliestStage != EAnimationEvents::COUNT)
  621. executeAnimationStage(earliestStage);
  622. }
  623. void BattleInterface::executeAnimationStage(EAnimationEvents event)
  624. {
  625. decltype(awaitingEvents) executingEvents;
  626. for(auto it = awaitingEvents.begin(); it != awaitingEvents.end();)
  627. {
  628. if(it->event == event)
  629. {
  630. executingEvents.push_back(*it);
  631. it = awaitingEvents.erase(it);
  632. }
  633. else
  634. ++it;
  635. }
  636. for(const auto & event : executingEvents)
  637. event.action();
  638. }
  639. void BattleInterface::onAnimationsStarted()
  640. {
  641. ongoingAnimationsState.setn(true);
  642. }
  643. void BattleInterface::onAnimationsFinished()
  644. {
  645. ongoingAnimationsState.setn(false);
  646. }
  647. void BattleInterface::waitForAnimations()
  648. {
  649. {
  650. auto unlockPim = vstd::makeUnlockGuard(*CPlayerInterface::pim);
  651. ongoingAnimationsState.waitUntil(false);
  652. }
  653. assert(!hasAnimations());
  654. assert(awaitingEvents.empty());
  655. if (!awaitingEvents.empty())
  656. {
  657. logGlobal->error("Wait for animations finished but we still have awaiting events!");
  658. awaitingEvents.clear();
  659. }
  660. }
  661. bool BattleInterface::hasAnimations()
  662. {
  663. return ongoingAnimationsState.get();
  664. }
  665. void BattleInterface::checkForAnimations()
  666. {
  667. assert(!hasAnimations());
  668. if(hasAnimations())
  669. logGlobal->error("Unexpected animations state: expected all animations to be over, but some are still ongoing!");
  670. waitForAnimations();
  671. }
  672. void BattleInterface::addToAnimationStage(EAnimationEvents event, const AwaitingAnimationAction & action)
  673. {
  674. awaitingEvents.push_back({action, event});
  675. }
  676. void BattleInterface::setBattleQueueVisibility(bool visible)
  677. {
  678. windowObject->hideQueue();
  679. if(visible)
  680. windowObject->showQueue();
  681. }