BattleInterface.cpp 21 KB

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