BattleInterface.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  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 "../CMessage.h"
  26. #include "../CMusicHandler.h"
  27. #include "../CPlayerInterface.h"
  28. #include "../gui/Canvas.h"
  29. #include "../gui/CCursorHandler.h"
  30. #include "../gui/CGuiHandler.h"
  31. #include "../windows/CAdvmapInterface.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/mapObjects/CGTownInstance.h"
  39. #include "../../lib/NetPacks.h"
  40. #include "../../lib/UnlockGuard.h"
  41. CondSh<BattleAction *> BattleInterface::givenCommand(nullptr);
  42. BattleInterface::BattleInterface(const CCreatureSet *army1, const CCreatureSet *army2,
  43. const CGHeroInstance *hero1, const CGHeroInstance *hero2,
  44. std::shared_ptr<CPlayerInterface> att,
  45. std::shared_ptr<CPlayerInterface> defen,
  46. std::shared_ptr<CPlayerInterface> spectatorInt)
  47. : attackingHeroInstance(hero1)
  48. , defendingHeroInstance(hero2)
  49. , attackerInt(att)
  50. , defenderInt(defen)
  51. , curInt(att)
  52. , myTurn(false)
  53. , moveSoundHander(-1)
  54. {
  55. for ( auto & event : animationEvents)
  56. event.setn(false);
  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. givenCommand.setn(nullptr);
  67. //hot-seat -> check tactics for both players (defender may be local human)
  68. if(attackerInt && attackerInt->cb->battleGetTacticDist())
  69. tacticianInterface = attackerInt;
  70. else if(defenderInt && defenderInt->cb->battleGetTacticDist())
  71. tacticianInterface = defenderInt;
  72. //if we found interface of player with tactics, then enter tactics mode
  73. tacticsMode = static_cast<bool>(tacticianInterface);
  74. //initializing armies
  75. this->army1 = army1;
  76. this->army2 = army2;
  77. const CGTownInstance *town = curInt->cb->battleGetDefendedTown();
  78. if(town && town->hasFort())
  79. siegeController.reset(new BattleSiegeController(*this, town));
  80. windowObject = std::make_shared<BattleWindow>(*this);
  81. projectilesController.reset(new BattleProjectileController(*this));
  82. stacksController.reset( new BattleStacksController(*this));
  83. actionsController.reset( new BattleActionsController(*this));
  84. effectsController.reset(new BattleEffectsController(*this));
  85. obstacleController.reset(new BattleObstacleController(*this));
  86. CCS->musich->stopMusic();
  87. setAnimationCondition(EAnimationEvents::OPENING, true);
  88. battleIntroSoundChannel = CCS->soundh->playSoundFromSet(CCS->soundh->battleIntroSounds);
  89. auto onIntroPlayed = [this]()
  90. {
  91. if(LOCPLINT->battleInt)
  92. {
  93. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  94. onIntroSoundPlayed();
  95. }
  96. };
  97. GH.pushInt(windowObject);
  98. windowObject->blockUI(true);
  99. windowObject->updateQueue();
  100. if (battleIntroSoundChannel != -1)
  101. CCS->soundh->setCallback(battleIntroSoundChannel, onIntroPlayed);
  102. else
  103. onIntroSoundPlayed();
  104. }
  105. void BattleInterface::onIntroSoundPlayed()
  106. {
  107. setAnimationCondition(EAnimationEvents::OPENING, false);
  108. CCS->musich->playMusicFromSet("battle", true, true);
  109. if(tacticsMode)
  110. tacticNextStack(nullptr);
  111. activateStack();
  112. battleIntroSoundChannel = -1;
  113. }
  114. BattleInterface::~BattleInterface()
  115. {
  116. CPlayerInterface::battleInt = nullptr;
  117. givenCommand.cond.notify_all(); //that two lines should make any stacksController->getActiveStack() waiting thread to finish
  118. if (adventureInt && adventureInt->selection)
  119. {
  120. //FIXME: this should be moved to adventureInt which should restore correct track based on selection/active player
  121. const auto * terrain = LOCPLINT->cb->getTile(adventureInt->selection->visitablePos())->terType;
  122. CCS->musich->playMusicFromSet("terrain", terrain->getName(), true, false);
  123. }
  124. // may happen if user decided to close game while in battle
  125. if (getAnimationCondition(EAnimationEvents::ACTION) == true)
  126. logGlobal->error("Shutting down BattleInterface during animation playback!");
  127. setAnimationCondition(EAnimationEvents::ACTION, false);
  128. }
  129. void BattleInterface::setPrintCellBorders(bool set)
  130. {
  131. Settings cellBorders = settings.write["battle"]["cellBorders"];
  132. cellBorders->Bool() = set;
  133. fieldController->redrawBackgroundWithHexes();
  134. GH.totalRedraw();
  135. }
  136. void BattleInterface::setPrintStackRange(bool set)
  137. {
  138. Settings stackRange = settings.write["battle"]["stackRange"];
  139. stackRange->Bool() = set;
  140. fieldController->redrawBackgroundWithHexes();
  141. GH.totalRedraw();
  142. }
  143. void BattleInterface::setPrintMouseShadow(bool set)
  144. {
  145. Settings shadow = settings.write["battle"]["mouseShadow"];
  146. shadow->Bool() = set;
  147. }
  148. void BattleInterface::stackReset(const CStack * stack)
  149. {
  150. stacksController->stackReset(stack);
  151. }
  152. void BattleInterface::stackAdded(const CStack * stack)
  153. {
  154. stacksController->stackAdded(stack, false);
  155. }
  156. void BattleInterface::stackRemoved(uint32_t stackID)
  157. {
  158. stacksController->stackRemoved(stackID);
  159. fieldController->redrawBackgroundWithHexes();
  160. windowObject->updateQueue();
  161. }
  162. void BattleInterface::stackActivated(const CStack *stack)
  163. {
  164. stacksController->stackActivated(stack);
  165. }
  166. void BattleInterface::stackMoved(const CStack *stack, std::vector<BattleHex> destHex, int distance, bool teleport)
  167. {
  168. if (teleport)
  169. stacksController->stackTeleported(stack, destHex, distance);
  170. else
  171. stacksController->stackMoved(stack, destHex, distance);
  172. }
  173. void BattleInterface::stacksAreAttacked(std::vector<StackAttackedInfo> attackedInfos)
  174. {
  175. stacksController->stacksAreAttacked(attackedInfos);
  176. std::array<int, 2> killedBySide = {0, 0};
  177. int targets = 0;
  178. for(const StackAttackedInfo & attackedInfo : attackedInfos)
  179. {
  180. ++targets;
  181. ui8 side = attackedInfo.defender->side;
  182. killedBySide.at(side) += attackedInfo.amountKilled;
  183. }
  184. for(ui8 side = 0; side < 2; side++)
  185. {
  186. if(killedBySide.at(side) > killedBySide.at(1-side))
  187. setHeroAnimation(side, EHeroAnimType::DEFEAT);
  188. else if(killedBySide.at(side) < killedBySide.at(1-side))
  189. setHeroAnimation(side, EHeroAnimType::VICTORY);
  190. }
  191. }
  192. void BattleInterface::stackAttacking( const StackAttackInfo & attackInfo )
  193. {
  194. stacksController->stackAttacking(attackInfo);
  195. }
  196. void BattleInterface::newRoundFirst( int round )
  197. {
  198. waitForAnimationCondition(EAnimationEvents::OPENING, false);
  199. }
  200. void BattleInterface::newRound(int number)
  201. {
  202. console->addText(CGI->generaltexth->allTexts[412]);
  203. }
  204. void BattleInterface::giveCommand(EActionType action, BattleHex tile, si32 additional)
  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 = curInt->cb->playerToSide(curInt->playerID);
  212. if(!side)
  213. {
  214. logGlobal->error("Player %s is not in battle", curInt->playerID.getStr());
  215. return;
  216. }
  217. auto ba = new BattleAction(); //is deleted in CPlayerInterface::stacksController->getActiveStack()()
  218. ba->side = side.get();
  219. ba->actionType = action;
  220. ba->aimToHex(tile);
  221. ba->actionSubtype = additional;
  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. myTurn = false;
  231. stacksController->setActiveStack(nullptr);
  232. givenCommand.setn(command);
  233. }
  234. else
  235. {
  236. curInt->cb->battleMakeTacticAction(command);
  237. vstd::clear_pointer(command);
  238. stacksController->setActiveStack(nullptr);
  239. //next stack will be activated when action ends
  240. }
  241. }
  242. const CGHeroInstance * BattleInterface::getActiveHero()
  243. {
  244. const CStack *attacker = stacksController->getActiveStack();
  245. if(!attacker)
  246. {
  247. return nullptr;
  248. }
  249. if(attacker->side == BattleSide::ATTACKER)
  250. {
  251. return attackingHeroInstance;
  252. }
  253. return defendingHeroInstance;
  254. }
  255. void BattleInterface::stackIsCatapulting(const CatapultAttack & ca)
  256. {
  257. if (siegeController)
  258. siegeController->stackIsCatapulting(ca);
  259. }
  260. void BattleInterface::gateStateChanged(const EGateState state)
  261. {
  262. if (siegeController)
  263. siegeController->gateStateChanged(state);
  264. }
  265. void BattleInterface::battleFinished(const BattleResult& br)
  266. {
  267. assert(getAnimationCondition(EAnimationEvents::ACTION) == false);
  268. waitForAnimationCondition(EAnimationEvents::ACTION, false);
  269. stacksController->setActiveStack(nullptr);
  270. CCS->curh->set(Cursor::Map::POINTER);
  271. curInt->waitWhileDialog();
  272. if(settings["session"]["spectate"].Bool() && settings["session"]["spectate-skip-battle-result"].Bool())
  273. {
  274. windowObject->close();
  275. return;
  276. }
  277. GH.pushInt(std::make_shared<BattleResultWindow>(br, *(this->curInt)));
  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. windowObject->blockUI(true);
  284. const SpellID spellID = sc->spellID;
  285. const CSpell * spell = spellID.toSpell();
  286. auto targetedTile = sc->tile;
  287. assert(spell);
  288. if(!spell)
  289. return;
  290. const std::string & castSoundPath = spell->getCastSound();
  291. if (!castSoundPath.empty())
  292. {
  293. auto group = spell->animationInfo.projectile.empty() ?
  294. EAnimationEvents::HIT:
  295. EAnimationEvents::BEFORE_HIT;//FIXME: recheck whether this should be on projectile spawning
  296. executeOnAnimationCondition(group, true, [=]() {
  297. CCS->soundh->playSound(castSoundPath);
  298. });
  299. }
  300. if ( sc->activeCast )
  301. {
  302. const CStack * casterStack = curInt->cb->battleGetStackByID(sc->casterStack);
  303. if(casterStack != nullptr )
  304. {
  305. executeOnAnimationCondition(EAnimationEvents::BEFORE_HIT, true, [=]()
  306. {
  307. stacksController->addNewAnim(new CastAnimation(*this, casterStack, targetedTile, curInt->cb->battleGetStackByPos(targetedTile), spell));
  308. displaySpellCast(spell, casterStack->getPosition());
  309. });
  310. }
  311. else
  312. {
  313. auto hero = sc->side ? defendingHero : attackingHero;
  314. assert(hero);
  315. executeOnAnimationCondition(EAnimationEvents::BEFORE_HIT, true, [=]()
  316. {
  317. stacksController->addNewAnim(new HeroCastAnimation(*this, hero, targetedTile, curInt->cb->battleGetStackByPos(targetedTile), spell));
  318. });
  319. }
  320. }
  321. executeOnAnimationCondition(EAnimationEvents::HIT, true, [=](){
  322. displaySpellHit(spell, targetedTile);
  323. });
  324. //queuing affect animation
  325. for(auto & elem : sc->affectedCres)
  326. {
  327. auto stack = curInt->cb->battleGetStackByID(elem, false);
  328. assert(stack);
  329. if(stack)
  330. {
  331. executeOnAnimationCondition(EAnimationEvents::HIT, true, [=](){
  332. displaySpellEffect(spell, stack->getPosition());
  333. });
  334. }
  335. }
  336. for(auto & elem : sc->reflectedCres)
  337. {
  338. auto stack = curInt->cb->battleGetStackByID(elem, false);
  339. assert(stack);
  340. executeOnAnimationCondition(EAnimationEvents::HIT, true, [=](){
  341. effectsController->displayEffect(EBattleEffect::MAGIC_MIRROR, stack->getPosition());
  342. });
  343. }
  344. if (!sc->resistedCres.empty())
  345. {
  346. executeOnAnimationCondition(EAnimationEvents::HIT, true, [=](){
  347. CCS->soundh->playSound("MAGICRES");
  348. });
  349. }
  350. for(auto & elem : sc->resistedCres)
  351. {
  352. auto stack = curInt->cb->battleGetStackByID(elem, false);
  353. assert(stack);
  354. executeOnAnimationCondition(EAnimationEvents::HIT, true, [=](){
  355. effectsController->displayEffect(EBattleEffect::RESISTANCE, stack->getPosition());
  356. });
  357. }
  358. //mana absorption
  359. if (sc->manaGained > 0)
  360. {
  361. Point leftHero = Point(15, 30);
  362. Point rightHero = Point(755, 30);
  363. bool side = sc->side;
  364. executeOnAnimationCondition(EAnimationEvents::AFTER_HIT, true, [=](){
  365. stacksController->addNewAnim(new EffectAnimation(*this, side ? "SP07_A.DEF" : "SP07_B.DEF", leftHero));
  366. stacksController->addNewAnim(new EffectAnimation(*this, side ? "SP07_B.DEF" : "SP07_A.DEF", rightHero));
  367. });
  368. }
  369. }
  370. void BattleInterface::battleStacksEffectsSet(const SetStackEffect & sse)
  371. {
  372. if(stacksController->getActiveStack() != nullptr)
  373. fieldController->redrawBackgroundWithHexes();
  374. }
  375. void BattleInterface::setHeroAnimation(ui8 side, EHeroAnimType phase)
  376. {
  377. if(side == BattleSide::ATTACKER)
  378. {
  379. if(attackingHero)
  380. attackingHero->setPhase(phase);
  381. }
  382. else
  383. {
  384. if(defendingHero)
  385. defendingHero->setPhase(phase);
  386. }
  387. }
  388. void BattleInterface::displayBattleLog(const std::vector<MetaString> & battleLog)
  389. {
  390. for(const auto & line : battleLog)
  391. {
  392. std::string formatted = line.toString();
  393. boost::algorithm::trim(formatted);
  394. appendBattleLog(formatted);
  395. }
  396. }
  397. void BattleInterface::displaySpellAnimationQueue(const CSpell * spell, const CSpell::TAnimationQueue & q, BattleHex destinationTile, bool isHit)
  398. {
  399. for(const CSpell::TAnimation & animation : q)
  400. {
  401. if(animation.pause > 0)
  402. stacksController->addNewAnim(new DummyAnimation(*this, animation.pause));
  403. if (!animation.effectName.empty())
  404. {
  405. const CStack * destStack = getCurrentPlayerInterface()->cb->battleGetStackByPos(destinationTile, false);
  406. if (destStack)
  407. stacksController->addNewAnim(new ColorTransformAnimation(*this, destStack, animation.effectName, spell ));
  408. }
  409. if(!animation.resourceName.empty())
  410. {
  411. int flags = 0;
  412. if (isHit)
  413. flags |= EffectAnimation::FORCE_ON_TOP;
  414. if (animation.verticalPosition == VerticalPosition::BOTTOM)
  415. flags |= EffectAnimation::ALIGN_TO_BOTTOM;
  416. if (!destinationTile.isValid())
  417. flags |= EffectAnimation::SCREEN_FILL;
  418. if (!destinationTile.isValid())
  419. stacksController->addNewAnim(new EffectAnimation(*this, animation.resourceName, flags));
  420. else
  421. stacksController->addNewAnim(new EffectAnimation(*this, animation.resourceName, destinationTile, flags));
  422. }
  423. }
  424. }
  425. void BattleInterface::displaySpellCast(const CSpell * spell, BattleHex destinationTile)
  426. {
  427. if(spell)
  428. displaySpellAnimationQueue(spell, spell->animationInfo.cast, destinationTile, false);
  429. }
  430. void BattleInterface::displaySpellEffect(const CSpell * spell, BattleHex destinationTile)
  431. {
  432. if(spell)
  433. displaySpellAnimationQueue(spell, spell->animationInfo.affect, destinationTile, false);
  434. }
  435. void BattleInterface::displaySpellHit(const CSpell * spell, BattleHex destinationTile)
  436. {
  437. if(spell)
  438. displaySpellAnimationQueue(spell, spell->animationInfo.hit, destinationTile, true);
  439. }
  440. void BattleInterface::setAnimSpeed(int set)
  441. {
  442. Settings speed = settings.write["battle"]["animationSpeed"];
  443. speed->Float() = float(set) / 100;
  444. }
  445. int BattleInterface::getAnimSpeed() const
  446. {
  447. if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-battle-speed"].isNull())
  448. return static_cast<int>(vstd::round(settings["session"]["spectate-battle-speed"].Float() *100));
  449. return static_cast<int>(vstd::round(settings["battle"]["animationSpeed"].Float() *100));
  450. }
  451. CPlayerInterface *BattleInterface::getCurrentPlayerInterface() const
  452. {
  453. return curInt.get();
  454. }
  455. void BattleInterface::trySetActivePlayer( PlayerColor player )
  456. {
  457. if ( attackerInt && attackerInt->playerID == player )
  458. curInt = attackerInt;
  459. if ( defenderInt && defenderInt->playerID == player )
  460. curInt = defenderInt;
  461. }
  462. void BattleInterface::activateStack()
  463. {
  464. stacksController->activateStack();
  465. const CStack * s = stacksController->getActiveStack();
  466. if(!s)
  467. return;
  468. myTurn = true;
  469. windowObject->updateQueue();
  470. windowObject->blockUI(false);
  471. fieldController->redrawBackgroundWithHexes();
  472. actionsController->activateStack();
  473. GH.fakeMouseMove();
  474. }
  475. void BattleInterface::endAction(const BattleAction* action)
  476. {
  477. const CStack *stack = curInt->cb->battleGetStackByID(action->stackNumber);
  478. stacksController->endAction(action);
  479. windowObject->updateQueue();
  480. //stack ended movement in tactics phase -> select the next one
  481. if (tacticsMode)
  482. tacticNextStack(stack);
  483. //we have activated next stack after sending request that has been just realized -> blockmap due to movement has changed
  484. if(action->actionType == EActionType::HERO_SPELL)
  485. fieldController->redrawBackgroundWithHexes();
  486. }
  487. void BattleInterface::appendBattleLog(const std::string & newEntry)
  488. {
  489. console->addText(newEntry);
  490. }
  491. void BattleInterface::startAction(const BattleAction* action)
  492. {
  493. if(action->actionType == EActionType::END_TACTIC_PHASE)
  494. {
  495. windowObject->tacticPhaseEnded();
  496. return;
  497. }
  498. const CStack *stack = curInt->cb->battleGetStackByID(action->stackNumber);
  499. if (stack)
  500. {
  501. windowObject->updateQueue();
  502. }
  503. else
  504. {
  505. assert(action->actionType == EActionType::HERO_SPELL); //only cast spell is valid action without acting stack number
  506. }
  507. stacksController->startAction(action);
  508. if(action->actionType == EActionType::HERO_SPELL) //when hero casts spell
  509. return;
  510. if (!stack)
  511. {
  512. logGlobal->error("Something wrong with stackNumber in actionStarted. Stack number: %d", action->stackNumber);
  513. return;
  514. }
  515. effectsController->startAction(action);
  516. }
  517. void BattleInterface::tacticPhaseEnd()
  518. {
  519. stacksController->setActiveStack(nullptr);
  520. tacticsMode = false;
  521. }
  522. static bool immobile(const CStack *s)
  523. {
  524. return !s->Speed(0, true); //should bound stacks be immobile?
  525. }
  526. void BattleInterface::tacticNextStack(const CStack * current)
  527. {
  528. if (!current)
  529. current = stacksController->getActiveStack();
  530. //no switching stacks when the current one is moving
  531. assert(getAnimationCondition(EAnimationEvents::ACTION) == false);
  532. waitForAnimationCondition(EAnimationEvents::ACTION, false);
  533. TStacks stacksOfMine = tacticianInterface->cb->battleGetStacks(CBattleCallback::ONLY_MINE);
  534. vstd::erase_if (stacksOfMine, &immobile);
  535. if (stacksOfMine.empty())
  536. {
  537. tacticPhaseEnd();
  538. return;
  539. }
  540. auto it = vstd::find(stacksOfMine, current);
  541. if (it != stacksOfMine.end() && ++it != stacksOfMine.end())
  542. stackActivated(*it);
  543. else
  544. stackActivated(stacksOfMine.front());
  545. }
  546. void BattleInterface::obstaclePlaced(const std::vector<std::shared_ptr<const CObstacleInstance>> oi)
  547. {
  548. obstacleController->obstaclePlaced(oi);
  549. }
  550. const CGHeroInstance *BattleInterface::currentHero() const
  551. {
  552. if (attackingHeroInstance && attackingHeroInstance->tempOwner == curInt->playerID)
  553. return attackingHeroInstance;
  554. if (defendingHeroInstance && defendingHeroInstance->tempOwner == curInt->playerID)
  555. return defendingHeroInstance;
  556. return nullptr;
  557. }
  558. InfoAboutHero BattleInterface::enemyHero() const
  559. {
  560. InfoAboutHero ret;
  561. if (attackingHeroInstance->tempOwner == curInt->playerID)
  562. curInt->cb->getHeroInfo(defendingHeroInstance, ret);
  563. else
  564. curInt->cb->getHeroInfo(attackingHeroInstance, ret);
  565. return ret;
  566. }
  567. void BattleInterface::requestAutofightingAIToTakeAction()
  568. {
  569. assert(curInt->isAutoFightOn);
  570. boost::thread aiThread([&]()
  571. {
  572. auto ba = std::make_unique<BattleAction>(curInt->autofightingAI->activeStack(stacksController->getActiveStack()));
  573. if(curInt->cb->battleIsFinished())
  574. {
  575. return; // battle finished with spellcast
  576. }
  577. if (curInt->isAutoFightOn)
  578. {
  579. if (tacticsMode)
  580. {
  581. // Always end tactics mode. Player interface is blocked currently, so it's not possible that
  582. // the AI can take any action except end tactics phase (AI actions won't be triggered)
  583. //TODO implement the possibility that the AI will be triggered for further actions
  584. //TODO any solution to merge tactics phase & normal phase in the way it is handled by the player and battle interface?
  585. stacksController->setActiveStack(nullptr);
  586. tacticsMode = false;
  587. }
  588. else
  589. {
  590. givenCommand.setn(ba.release());
  591. }
  592. }
  593. else
  594. {
  595. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  596. activateStack();
  597. }
  598. });
  599. aiThread.detach();
  600. }
  601. void BattleInterface::castThisSpell(SpellID spellID)
  602. {
  603. actionsController->castThisSpell(spellID);
  604. }
  605. void BattleInterface::setAnimationCondition( EAnimationEvents event, bool state)
  606. {
  607. logAnim->debug("setAnimationCondition: %d -> %s", static_cast<int>(event), state ? "ON" : "OFF");
  608. size_t index = static_cast<size_t>(event);
  609. animationEvents[index].setn(state);
  610. decltype(awaitingEvents) executingEvents;
  611. for (auto it = awaitingEvents.begin(); it != awaitingEvents.end();)
  612. {
  613. if (it->event == event && it->eventState == state)
  614. {
  615. executingEvents.push_back(*it);
  616. it = awaitingEvents.erase(it);
  617. }
  618. else
  619. ++it;
  620. }
  621. for (auto const & event : executingEvents)
  622. event.action();
  623. }
  624. bool BattleInterface::getAnimationCondition( EAnimationEvents event)
  625. {
  626. size_t index = static_cast<size_t>(event);
  627. return animationEvents[index].get();
  628. }
  629. void BattleInterface::waitForAnimationCondition( EAnimationEvents event, bool state)
  630. {
  631. auto unlockPim = vstd::makeUnlockGuard(*CPlayerInterface::pim);
  632. size_t index = static_cast<size_t>(event);
  633. animationEvents[index].waitUntil(state);
  634. }
  635. void BattleInterface::executeOnAnimationCondition( EAnimationEvents event, bool state, const AwaitingAnimationAction & action)
  636. {
  637. awaitingEvents.push_back({action, event, state});
  638. }