BattleInterface.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831
  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. BattleInterface::BattleInterface(const CCreatureSet *army1, const CCreatureSet *army2,
  44. const CGHeroInstance *hero1, const CGHeroInstance *hero2,
  45. std::shared_ptr<CPlayerInterface> att,
  46. std::shared_ptr<CPlayerInterface> defen,
  47. std::shared_ptr<CPlayerInterface> spectatorInt)
  48. : attackingHeroInstance(hero1)
  49. , defendingHeroInstance(hero2)
  50. , attackerInt(att)
  51. , defenderInt(defen)
  52. , curInt(att)
  53. , battleOpeningDelayActive(true)
  54. {
  55. if(spectatorInt)
  56. {
  57. curInt = spectatorInt;
  58. }
  59. else if(!curInt)
  60. {
  61. //May happen when we are defending during network MP game -> attacker interface is just not present
  62. curInt = defenderInt;
  63. }
  64. //hot-seat -> check tactics for both players (defender may be local human)
  65. if(attackerInt && attackerInt->cb->battleGetTacticDist())
  66. tacticianInterface = attackerInt;
  67. else if(defenderInt && defenderInt->cb->battleGetTacticDist())
  68. tacticianInterface = defenderInt;
  69. //if we found interface of player with tactics, then enter tactics mode
  70. tacticsMode = static_cast<bool>(tacticianInterface);
  71. //initializing armies
  72. this->army1 = army1;
  73. this->army2 = army2;
  74. const CGTownInstance *town = curInt->cb->battleGetDefendedTown();
  75. if(town && town->hasFort())
  76. siegeController.reset(new BattleSiegeController(*this, town));
  77. windowObject = std::make_shared<BattleWindow>(*this);
  78. projectilesController.reset(new BattleProjectileController(*this));
  79. stacksController.reset( new BattleStacksController(*this));
  80. actionsController.reset( new BattleActionsController(*this));
  81. effectsController.reset(new BattleEffectsController(*this));
  82. obstacleController.reset(new BattleObstacleController(*this));
  83. adventureInt->onAudioPaused();
  84. ongoingAnimationsState.set(true);
  85. GH.windows().pushWindow(windowObject);
  86. windowObject->blockUI(true);
  87. windowObject->updateQueue();
  88. playIntroSoundAndUnlockInterface();
  89. }
  90. void BattleInterface::playIntroSoundAndUnlockInterface()
  91. {
  92. auto onIntroPlayed = [this]()
  93. {
  94. if(LOCPLINT->battleInt)
  95. {
  96. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  97. onIntroSoundPlayed();
  98. }
  99. };
  100. int battleIntroSoundChannel = CCS->soundh->playSoundFromSet(CCS->soundh->battleIntroSounds);
  101. if (battleIntroSoundChannel != -1)
  102. {
  103. CCS->soundh->setCallback(battleIntroSoundChannel, onIntroPlayed);
  104. if (settings["gameTweaks"]["skipBattleIntroMusic"].Bool())
  105. openingEnd();
  106. }
  107. else // failed to play sound
  108. {
  109. onIntroSoundPlayed();
  110. }
  111. }
  112. bool BattleInterface::openingPlaying()
  113. {
  114. return battleOpeningDelayActive;
  115. }
  116. void BattleInterface::onIntroSoundPlayed()
  117. {
  118. if (openingPlaying())
  119. openingEnd();
  120. CCS->musich->playMusicFromSet("battle", true, true);
  121. }
  122. void BattleInterface::openingEnd()
  123. {
  124. assert(openingPlaying());
  125. if (!openingPlaying())
  126. return;
  127. onAnimationsFinished();
  128. if(tacticsMode)
  129. tacticNextStack(nullptr);
  130. activateStack();
  131. battleOpeningDelayActive = false;
  132. }
  133. BattleInterface::~BattleInterface()
  134. {
  135. CPlayerInterface::battleInt = nullptr;
  136. if (adventureInt)
  137. adventureInt->onAudioResumed();
  138. awaitingEvents.clear();
  139. onAnimationsFinished();
  140. }
  141. void BattleInterface::redrawBattlefield()
  142. {
  143. fieldController->redrawBackgroundWithHexes();
  144. GH.windows().totalRedraw();
  145. }
  146. void BattleInterface::stackReset(const CStack * stack)
  147. {
  148. stacksController->stackReset(stack);
  149. }
  150. void BattleInterface::stackAdded(const CStack * stack)
  151. {
  152. stacksController->stackAdded(stack, false);
  153. }
  154. void BattleInterface::stackRemoved(uint32_t stackID)
  155. {
  156. stacksController->stackRemoved(stackID);
  157. fieldController->redrawBackgroundWithHexes();
  158. windowObject->updateQueue();
  159. }
  160. void BattleInterface::stackActivated(const CStack *stack)
  161. {
  162. stacksController->stackActivated(stack);
  163. }
  164. void BattleInterface::stackMoved(const CStack *stack, std::vector<BattleHex> destHex, int distance, bool teleport)
  165. {
  166. if (teleport)
  167. stacksController->stackTeleported(stack, destHex, distance);
  168. else
  169. stacksController->stackMoved(stack, destHex, distance);
  170. }
  171. void BattleInterface::stacksAreAttacked(std::vector<StackAttackedInfo> attackedInfos)
  172. {
  173. stacksController->stacksAreAttacked(attackedInfos);
  174. std::array<int, 2> killedBySide = {0, 0};
  175. for(const StackAttackedInfo & attackedInfo : attackedInfos)
  176. {
  177. ui8 side = attackedInfo.defender->unitSide();
  178. killedBySide.at(side) += attackedInfo.amountKilled;
  179. }
  180. for(ui8 side = 0; side < 2; side++)
  181. {
  182. if(killedBySide.at(side) > killedBySide.at(1-side))
  183. setHeroAnimation(side, EHeroAnimType::DEFEAT);
  184. else if(killedBySide.at(side) < killedBySide.at(1-side))
  185. setHeroAnimation(side, EHeroAnimType::VICTORY);
  186. }
  187. }
  188. void BattleInterface::stackAttacking( const StackAttackInfo & attackInfo )
  189. {
  190. stacksController->stackAttacking(attackInfo);
  191. }
  192. void BattleInterface::newRoundFirst( int round )
  193. {
  194. waitForAnimations();
  195. }
  196. void BattleInterface::newRound(int number)
  197. {
  198. console->addText(CGI->generaltexth->allTexts[412]);
  199. }
  200. void BattleInterface::giveCommand(EActionType action, BattleHex tile, si32 additional)
  201. {
  202. const CStack * actor = nullptr;
  203. if(action != EActionType::HERO_SPELL && action != EActionType::RETREAT && action != EActionType::SURRENDER)
  204. {
  205. actor = stacksController->getActiveStack();
  206. }
  207. auto side = curInt->cb->playerToSide(curInt->playerID);
  208. if(!side)
  209. {
  210. logGlobal->error("Player %s is not in battle", curInt->playerID.getStr());
  211. return;
  212. }
  213. BattleAction ba;
  214. ba.side = side.value();
  215. ba.actionType = action;
  216. ba.aimToHex(tile);
  217. ba.actionSubtype = additional;
  218. sendCommand(ba, actor);
  219. }
  220. void BattleInterface::sendCommand(BattleAction command, const CStack * actor)
  221. {
  222. command.stackNumber = actor ? actor->unitId() : ((command.side == BattleSide::ATTACKER) ? -1 : -2);
  223. if(!tacticsMode)
  224. {
  225. logGlobal->trace("Setting command for %s", (actor ? actor->nodeName() : "hero"));
  226. stacksController->setActiveStack(nullptr);
  227. LOCPLINT->cb->battleMakeUnitAction(command);
  228. }
  229. else
  230. {
  231. curInt->cb->battleMakeTacticAction(command);
  232. stacksController->setActiveStack(nullptr);
  233. //next stack will be activated when action ends
  234. }
  235. CCS->curh->set(Cursor::Combat::POINTER);
  236. }
  237. const CGHeroInstance * BattleInterface::getActiveHero()
  238. {
  239. const CStack *attacker = stacksController->getActiveStack();
  240. if(!attacker)
  241. {
  242. return nullptr;
  243. }
  244. if(attacker->unitSide() == BattleSide::ATTACKER)
  245. {
  246. return attackingHeroInstance;
  247. }
  248. return defendingHeroInstance;
  249. }
  250. void BattleInterface::stackIsCatapulting(const CatapultAttack & ca)
  251. {
  252. if (siegeController)
  253. siegeController->stackIsCatapulting(ca);
  254. }
  255. void BattleInterface::gateStateChanged(const EGateState state)
  256. {
  257. if (siegeController)
  258. siegeController->gateStateChanged(state);
  259. }
  260. void BattleInterface::battleFinished(const BattleResult& br, QueryID queryID)
  261. {
  262. checkForAnimations();
  263. stacksController->setActiveStack(nullptr);
  264. CCS->curh->set(Cursor::Map::POINTER);
  265. curInt->waitWhileDialog();
  266. if(settings["session"]["spectate"].Bool() && settings["session"]["spectate-skip-battle-result"].Bool())
  267. {
  268. curInt->cb->selectionMade(0, queryID);
  269. windowObject->close();
  270. return;
  271. }
  272. auto wnd = std::make_shared<BattleResultWindow>(br, *(this->curInt));
  273. wnd->resultCallback = [=](ui32 selection)
  274. {
  275. curInt->cb->selectionMade(selection, queryID);
  276. };
  277. GH.windows().pushWindow(wnd);
  278. curInt->waitWhileDialog(); // Avoid freeze when AI end turn after battle. Check bug #1897
  279. CPlayerInterface::battleInt = nullptr;
  280. }
  281. void BattleInterface::spellCast(const BattleSpellCast * sc)
  282. {
  283. // Do not deactivate anything in tactics mode
  284. // This is battlefield setup spells
  285. if(!tacticsMode)
  286. {
  287. windowObject->blockUI(true);
  288. // Disable current active stack duing the cast
  289. // Store the current activeStack to stackToActivate
  290. stacksController->deactivateStack();
  291. }
  292. CCS->curh->set(Cursor::Combat::BLOCKED);
  293. const SpellID spellID = sc->spellID;
  294. const CSpell * spell = spellID.toSpell();
  295. auto targetedTile = sc->tile;
  296. assert(spell);
  297. if(!spell)
  298. return;
  299. const std::string & castSoundPath = spell->getCastSound();
  300. if (!castSoundPath.empty())
  301. {
  302. auto group = spell->animationInfo.projectile.empty() ?
  303. EAnimationEvents::HIT:
  304. EAnimationEvents::BEFORE_HIT;//FIXME: recheck whether this should be on projectile spawning
  305. addToAnimationStage(group, [=]() {
  306. CCS->soundh->playSound(castSoundPath);
  307. });
  308. }
  309. if ( sc->activeCast )
  310. {
  311. const CStack * casterStack = curInt->cb->battleGetStackByID(sc->casterStack);
  312. if(casterStack != nullptr )
  313. {
  314. addToAnimationStage(EAnimationEvents::BEFORE_HIT, [=]()
  315. {
  316. stacksController->addNewAnim(new CastAnimation(*this, casterStack, targetedTile, curInt->cb->battleGetStackByPos(targetedTile), spell));
  317. displaySpellCast(spell, casterStack->getPosition());
  318. });
  319. }
  320. else
  321. {
  322. auto hero = sc->side ? defendingHero : attackingHero;
  323. assert(hero);
  324. addToAnimationStage(EAnimationEvents::BEFORE_HIT, [=]()
  325. {
  326. stacksController->addNewAnim(new HeroCastAnimation(*this, hero, targetedTile, curInt->cb->battleGetStackByPos(targetedTile), spell));
  327. });
  328. }
  329. }
  330. addToAnimationStage(EAnimationEvents::HIT, [=](){
  331. displaySpellHit(spell, targetedTile);
  332. });
  333. //queuing affect animation
  334. for(auto & elem : sc->affectedCres)
  335. {
  336. auto stack = curInt->cb->battleGetStackByID(elem, false);
  337. assert(stack);
  338. if(stack)
  339. {
  340. addToAnimationStage(EAnimationEvents::HIT, [=](){
  341. displaySpellEffect(spell, stack->getPosition());
  342. });
  343. }
  344. }
  345. for(auto & elem : sc->reflectedCres)
  346. {
  347. auto stack = curInt->cb->battleGetStackByID(elem, false);
  348. assert(stack);
  349. addToAnimationStage(EAnimationEvents::HIT, [=](){
  350. effectsController->displayEffect(EBattleEffect::MAGIC_MIRROR, stack->getPosition());
  351. });
  352. }
  353. if (!sc->resistedCres.empty())
  354. {
  355. addToAnimationStage(EAnimationEvents::HIT, [=](){
  356. CCS->soundh->playSound("MAGICRES");
  357. });
  358. }
  359. for(auto & elem : sc->resistedCres)
  360. {
  361. auto stack = curInt->cb->battleGetStackByID(elem, false);
  362. assert(stack);
  363. addToAnimationStage(EAnimationEvents::HIT, [=](){
  364. effectsController->displayEffect(EBattleEffect::RESISTANCE, stack->getPosition());
  365. });
  366. }
  367. //mana absorption
  368. if (sc->manaGained > 0)
  369. {
  370. Point leftHero = Point(15, 30);
  371. Point rightHero = Point(755, 30);
  372. bool side = sc->side;
  373. addToAnimationStage(EAnimationEvents::AFTER_HIT, [=](){
  374. stacksController->addNewAnim(new EffectAnimation(*this, side ? "SP07_A.DEF" : "SP07_B.DEF", leftHero));
  375. stacksController->addNewAnim(new EffectAnimation(*this, side ? "SP07_B.DEF" : "SP07_A.DEF", rightHero));
  376. });
  377. }
  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 = getCurrentPlayerInterface()->cb->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. void BattleInterface::endAction(const BattleAction* action)
  477. {
  478. // it is possible that tactics mode ended while opening music is still playing
  479. waitForAnimations();
  480. const CStack *stack = curInt->cb->battleGetStackByID(action->stackNumber);
  481. // Activate stack from stackToActivate because this might have been temporary disabled, e.g., during spell cast
  482. activateStack();
  483. stacksController->endAction(action);
  484. windowObject->updateQueue();
  485. //stack ended movement in tactics phase -> select the next one
  486. if (tacticsMode)
  487. tacticNextStack(stack);
  488. //we have activated next stack after sending request that has been just realized -> blockmap due to movement has changed
  489. if(action->actionType == EActionType::HERO_SPELL)
  490. fieldController->redrawBackgroundWithHexes();
  491. }
  492. void BattleInterface::appendBattleLog(const std::string & newEntry)
  493. {
  494. console->addText(newEntry);
  495. }
  496. void BattleInterface::startAction(const BattleAction* action)
  497. {
  498. if(action->actionType == EActionType::END_TACTIC_PHASE)
  499. {
  500. windowObject->tacticPhaseEnded();
  501. return;
  502. }
  503. const CStack *stack = curInt->cb->battleGetStackByID(action->stackNumber);
  504. if (stack)
  505. {
  506. windowObject->updateQueue();
  507. }
  508. else
  509. {
  510. assert(action->actionType == EActionType::HERO_SPELL); //only cast spell is valid action without acting stack number
  511. }
  512. stacksController->startAction(action);
  513. if(action->actionType == EActionType::HERO_SPELL) //when hero casts spell
  514. return;
  515. if (!stack)
  516. {
  517. logGlobal->error("Something wrong with stackNumber in actionStarted. Stack number: %d", action->stackNumber);
  518. return;
  519. }
  520. effectsController->startAction(action);
  521. }
  522. void BattleInterface::tacticPhaseEnd()
  523. {
  524. stacksController->setActiveStack(nullptr);
  525. tacticsMode = false;
  526. auto side = tacticianInterface->cb->playerToSide(tacticianInterface->playerID);
  527. auto action = BattleAction::makeEndOFTacticPhase(*side);
  528. tacticianInterface->cb->battleMakeTacticAction(action);
  529. }
  530. static bool immobile(const CStack *s)
  531. {
  532. return !s->speed(0, true); //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->battleGetStacks(CBattleCallback::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(curInt->cb->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([&]()
  605. {
  606. curInt->autofightingAI->activeStack(activeStack);
  607. });
  608. aiThread.detach();
  609. }
  610. }
  611. }
  612. void BattleInterface::castThisSpell(SpellID spellID)
  613. {
  614. actionsController->castThisSpell(spellID);
  615. }
  616. void BattleInterface::executeStagedAnimations()
  617. {
  618. EAnimationEvents earliestStage = EAnimationEvents::COUNT;
  619. for(const auto & event : awaitingEvents)
  620. earliestStage = std::min(earliestStage, event.event);
  621. if(earliestStage != EAnimationEvents::COUNT)
  622. executeAnimationStage(earliestStage);
  623. }
  624. void BattleInterface::executeAnimationStage(EAnimationEvents event)
  625. {
  626. decltype(awaitingEvents) executingEvents;
  627. for(auto it = awaitingEvents.begin(); it != awaitingEvents.end();)
  628. {
  629. if(it->event == event)
  630. {
  631. executingEvents.push_back(*it);
  632. it = awaitingEvents.erase(it);
  633. }
  634. else
  635. ++it;
  636. }
  637. for(const auto & event : executingEvents)
  638. event.action();
  639. }
  640. void BattleInterface::onAnimationsStarted()
  641. {
  642. ongoingAnimationsState.setn(true);
  643. }
  644. void BattleInterface::onAnimationsFinished()
  645. {
  646. ongoingAnimationsState.setn(false);
  647. }
  648. void BattleInterface::waitForAnimations()
  649. {
  650. {
  651. auto unlockPim = vstd::makeUnlockGuard(*CPlayerInterface::pim);
  652. ongoingAnimationsState.waitUntil(false);
  653. }
  654. assert(!hasAnimations());
  655. assert(awaitingEvents.empty());
  656. if (!awaitingEvents.empty())
  657. {
  658. logGlobal->error("Wait for animations finished but we still have awaiting events!");
  659. awaitingEvents.clear();
  660. }
  661. }
  662. bool BattleInterface::hasAnimations()
  663. {
  664. return ongoingAnimationsState.get();
  665. }
  666. void BattleInterface::checkForAnimations()
  667. {
  668. assert(!hasAnimations());
  669. if(hasAnimations())
  670. logGlobal->error("Unexpected animations state: expected all animations to be over, but some are still ongoing!");
  671. waitForAnimations();
  672. }
  673. void BattleInterface::addToAnimationStage(EAnimationEvents event, const AwaitingAnimationAction & action)
  674. {
  675. awaitingEvents.push_back({action, event});
  676. }
  677. void BattleInterface::setBattleQueueVisibility(bool visible)
  678. {
  679. windowObject->hideQueue();
  680. if(visible)
  681. windowObject->showQueue();
  682. }
  683. void BattleInterface::setStickyHeroWindowsVisibility(bool visible)
  684. {
  685. windowObject->hideStickyHeroWindows();
  686. if(visible)
  687. windowObject->showStickyHeroWindows();
  688. }