BattleInterface.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  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 "../render/Canvas.h"
  30. #include "../adventureMap/CAdvMapInt.h"
  31. #include "../../CCallback.h"
  32. #include "../../lib/CStack.h"
  33. #include "../../lib/CConfigHandler.h"
  34. #include "../../lib/CGeneralTextHandler.h"
  35. #include "../../lib/CHeroHandler.h"
  36. #include "../../lib/CondSh.h"
  37. #include "../../lib/mapObjects/CGTownInstance.h"
  38. #include "../../lib/NetPacks.h"
  39. #include "../../lib/UnlockGuard.h"
  40. #include "../../lib/TerrainHandler.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->getJsonKey(), 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. for(const StackAttackedInfo & attackedInfo : attackedInfos)
  178. {
  179. ui8 side = attackedInfo.defender->side;
  180. killedBySide.at(side) += attackedInfo.amountKilled;
  181. }
  182. for(ui8 side = 0; side < 2; side++)
  183. {
  184. if(killedBySide.at(side) > killedBySide.at(1-side))
  185. setHeroAnimation(side, EHeroAnimType::DEFEAT);
  186. else if(killedBySide.at(side) < killedBySide.at(1-side))
  187. setHeroAnimation(side, EHeroAnimType::VICTORY);
  188. }
  189. }
  190. void BattleInterface::stackAttacking( const StackAttackInfo & attackInfo )
  191. {
  192. stacksController->stackAttacking(attackInfo);
  193. }
  194. void BattleInterface::newRoundFirst( int round )
  195. {
  196. waitForAnimationCondition(EAnimationEvents::OPENING, false);
  197. }
  198. void BattleInterface::newRound(int number)
  199. {
  200. console->addText(CGI->generaltexth->allTexts[412]);
  201. }
  202. void BattleInterface::giveCommand(EActionType action, BattleHex tile, si32 additional)
  203. {
  204. const CStack * actor = nullptr;
  205. if(action != EActionType::HERO_SPELL && action != EActionType::RETREAT && action != EActionType::SURRENDER)
  206. {
  207. actor = stacksController->getActiveStack();
  208. }
  209. auto side = curInt->cb->playerToSide(curInt->playerID);
  210. if(!side)
  211. {
  212. logGlobal->error("Player %s is not in battle", curInt->playerID.getStr());
  213. return;
  214. }
  215. auto ba = new BattleAction(); //is deleted in CPlayerInterface::stacksController->getActiveStack()()
  216. ba->side = side.get();
  217. ba->actionType = action;
  218. ba->aimToHex(tile);
  219. ba->actionSubtype = additional;
  220. sendCommand(ba, actor);
  221. }
  222. void BattleInterface::sendCommand(BattleAction *& command, const CStack * actor)
  223. {
  224. command->stackNumber = actor ? actor->unitId() : ((command->side == BattleSide::ATTACKER) ? -1 : -2);
  225. if(!tacticsMode)
  226. {
  227. logGlobal->trace("Setting command for %s", (actor ? actor->nodeName() : "hero"));
  228. myTurn = false;
  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. }
  240. const CGHeroInstance * BattleInterface::getActiveHero()
  241. {
  242. const CStack *attacker = stacksController->getActiveStack();
  243. if(!attacker)
  244. {
  245. return nullptr;
  246. }
  247. if(attacker->side == BattleSide::ATTACKER)
  248. {
  249. return attackingHeroInstance;
  250. }
  251. return defendingHeroInstance;
  252. }
  253. void BattleInterface::stackIsCatapulting(const CatapultAttack & ca)
  254. {
  255. if (siegeController)
  256. siegeController->stackIsCatapulting(ca);
  257. }
  258. void BattleInterface::gateStateChanged(const EGateState state)
  259. {
  260. if (siegeController)
  261. siegeController->gateStateChanged(state);
  262. }
  263. void BattleInterface::battleFinished(const BattleResult& br)
  264. {
  265. assert(getAnimationCondition(EAnimationEvents::ACTION) == false);
  266. waitForAnimationCondition(EAnimationEvents::ACTION, false);
  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. windowObject->close();
  273. return;
  274. }
  275. GH.pushInt(std::make_shared<BattleResultWindow>(br, *(this->curInt)));
  276. curInt->waitWhileDialog(); // Avoid freeze when AI end turn after battle. Check bug #1897
  277. CPlayerInterface::battleInt = nullptr;
  278. }
  279. void BattleInterface::spellCast(const BattleSpellCast * sc)
  280. {
  281. windowObject->blockUI(true);
  282. const SpellID spellID = sc->spellID;
  283. const CSpell * spell = spellID.toSpell();
  284. auto targetedTile = sc->tile;
  285. assert(spell);
  286. if(!spell)
  287. return;
  288. const std::string & castSoundPath = spell->getCastSound();
  289. if (!castSoundPath.empty())
  290. {
  291. auto group = spell->animationInfo.projectile.empty() ?
  292. EAnimationEvents::HIT:
  293. EAnimationEvents::BEFORE_HIT;//FIXME: recheck whether this should be on projectile spawning
  294. executeOnAnimationCondition(group, true, [=]() {
  295. CCS->soundh->playSound(castSoundPath);
  296. });
  297. }
  298. if ( sc->activeCast )
  299. {
  300. const CStack * casterStack = curInt->cb->battleGetStackByID(sc->casterStack);
  301. if(casterStack != nullptr )
  302. {
  303. executeOnAnimationCondition(EAnimationEvents::BEFORE_HIT, true, [=]()
  304. {
  305. stacksController->addNewAnim(new CastAnimation(*this, casterStack, targetedTile, curInt->cb->battleGetStackByPos(targetedTile), spell));
  306. displaySpellCast(spell, casterStack->getPosition());
  307. });
  308. }
  309. else
  310. {
  311. auto hero = sc->side ? defendingHero : attackingHero;
  312. assert(hero);
  313. executeOnAnimationCondition(EAnimationEvents::BEFORE_HIT, true, [=]()
  314. {
  315. stacksController->addNewAnim(new HeroCastAnimation(*this, hero, targetedTile, curInt->cb->battleGetStackByPos(targetedTile), spell));
  316. });
  317. }
  318. }
  319. executeOnAnimationCondition(EAnimationEvents::HIT, true, [=](){
  320. displaySpellHit(spell, targetedTile);
  321. });
  322. //queuing affect animation
  323. for(auto & elem : sc->affectedCres)
  324. {
  325. auto stack = curInt->cb->battleGetStackByID(elem, false);
  326. assert(stack);
  327. if(stack)
  328. {
  329. executeOnAnimationCondition(EAnimationEvents::HIT, true, [=](){
  330. displaySpellEffect(spell, stack->getPosition());
  331. });
  332. }
  333. }
  334. for(auto & elem : sc->reflectedCres)
  335. {
  336. auto stack = curInt->cb->battleGetStackByID(elem, false);
  337. assert(stack);
  338. executeOnAnimationCondition(EAnimationEvents::HIT, true, [=](){
  339. effectsController->displayEffect(EBattleEffect::MAGIC_MIRROR, stack->getPosition());
  340. });
  341. }
  342. if (!sc->resistedCres.empty())
  343. {
  344. executeOnAnimationCondition(EAnimationEvents::HIT, true, [=](){
  345. CCS->soundh->playSound("MAGICRES");
  346. });
  347. }
  348. for(auto & elem : sc->resistedCres)
  349. {
  350. auto stack = curInt->cb->battleGetStackByID(elem, false);
  351. assert(stack);
  352. executeOnAnimationCondition(EAnimationEvents::HIT, true, [=](){
  353. effectsController->displayEffect(EBattleEffect::RESISTANCE, stack->getPosition());
  354. });
  355. }
  356. //mana absorption
  357. if (sc->manaGained > 0)
  358. {
  359. Point leftHero = Point(15, 30);
  360. Point rightHero = Point(755, 30);
  361. bool side = sc->side;
  362. executeOnAnimationCondition(EAnimationEvents::AFTER_HIT, true, [=](){
  363. stacksController->addNewAnim(new EffectAnimation(*this, side ? "SP07_A.DEF" : "SP07_B.DEF", leftHero));
  364. stacksController->addNewAnim(new EffectAnimation(*this, side ? "SP07_B.DEF" : "SP07_A.DEF", rightHero));
  365. });
  366. }
  367. }
  368. void BattleInterface::battleStacksEffectsSet(const SetStackEffect & sse)
  369. {
  370. if(stacksController->getActiveStack() != nullptr)
  371. fieldController->redrawBackgroundWithHexes();
  372. }
  373. void BattleInterface::setHeroAnimation(ui8 side, EHeroAnimType phase)
  374. {
  375. if(side == BattleSide::ATTACKER)
  376. {
  377. if(attackingHero)
  378. attackingHero->setPhase(phase);
  379. }
  380. else
  381. {
  382. if(defendingHero)
  383. defendingHero->setPhase(phase);
  384. }
  385. }
  386. void BattleInterface::displayBattleLog(const std::vector<MetaString> & battleLog)
  387. {
  388. for(const auto & line : battleLog)
  389. {
  390. std::string formatted = line.toString();
  391. boost::algorithm::trim(formatted);
  392. appendBattleLog(formatted);
  393. }
  394. }
  395. void BattleInterface::displaySpellAnimationQueue(const CSpell * spell, const CSpell::TAnimationQueue & q, BattleHex destinationTile, bool isHit)
  396. {
  397. for(const CSpell::TAnimation & animation : q)
  398. {
  399. if(animation.pause > 0)
  400. stacksController->addNewAnim(new DummyAnimation(*this, animation.pause));
  401. if (!animation.effectName.empty())
  402. {
  403. const CStack * destStack = getCurrentPlayerInterface()->cb->battleGetStackByPos(destinationTile, false);
  404. if (destStack)
  405. stacksController->addNewAnim(new ColorTransformAnimation(*this, destStack, animation.effectName, spell ));
  406. }
  407. if(!animation.resourceName.empty())
  408. {
  409. int flags = 0;
  410. if (isHit)
  411. flags |= EffectAnimation::FORCE_ON_TOP;
  412. if (animation.verticalPosition == VerticalPosition::BOTTOM)
  413. flags |= EffectAnimation::ALIGN_TO_BOTTOM;
  414. if (!destinationTile.isValid())
  415. flags |= EffectAnimation::SCREEN_FILL;
  416. if (!destinationTile.isValid())
  417. stacksController->addNewAnim(new EffectAnimation(*this, animation.resourceName, flags));
  418. else
  419. stacksController->addNewAnim(new EffectAnimation(*this, animation.resourceName, destinationTile, flags));
  420. }
  421. }
  422. }
  423. void BattleInterface::displaySpellCast(const CSpell * spell, BattleHex destinationTile)
  424. {
  425. if(spell)
  426. displaySpellAnimationQueue(spell, spell->animationInfo.cast, destinationTile, false);
  427. }
  428. void BattleInterface::displaySpellEffect(const CSpell * spell, BattleHex destinationTile)
  429. {
  430. if(spell)
  431. displaySpellAnimationQueue(spell, spell->animationInfo.affect, destinationTile, false);
  432. }
  433. void BattleInterface::displaySpellHit(const CSpell * spell, BattleHex destinationTile)
  434. {
  435. if(spell)
  436. displaySpellAnimationQueue(spell, spell->animationInfo.hit, destinationTile, true);
  437. }
  438. void BattleInterface::setAnimSpeed(int set)
  439. {
  440. Settings speed = settings.write["battle"]["speedFactor"];
  441. speed->Float() = float(set);
  442. }
  443. int BattleInterface::getAnimSpeed() const
  444. {
  445. if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-battle-speed"].isNull())
  446. return static_cast<int>(vstd::round(settings["session"]["spectate-battle-speed"].Float()));
  447. return static_cast<int>(vstd::round(settings["battle"]["speedFactor"].Float()));
  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. myTurn = true;
  467. windowObject->updateQueue();
  468. windowObject->blockUI(false);
  469. fieldController->redrawBackgroundWithHexes();
  470. actionsController->activateStack();
  471. GH.fakeMouseMove();
  472. }
  473. void BattleInterface::endAction(const BattleAction* action)
  474. {
  475. const CStack *stack = curInt->cb->battleGetStackByID(action->stackNumber);
  476. stacksController->endAction(action);
  477. windowObject->updateQueue();
  478. //stack ended movement in tactics phase -> select the next one
  479. if (tacticsMode)
  480. tacticNextStack(stack);
  481. //we have activated next stack after sending request that has been just realized -> blockmap due to movement has changed
  482. if(action->actionType == EActionType::HERO_SPELL)
  483. fieldController->redrawBackgroundWithHexes();
  484. }
  485. void BattleInterface::appendBattleLog(const std::string & newEntry)
  486. {
  487. console->addText(newEntry);
  488. }
  489. void BattleInterface::startAction(const BattleAction* action)
  490. {
  491. if(action->actionType == EActionType::END_TACTIC_PHASE)
  492. {
  493. windowObject->tacticPhaseEnded();
  494. return;
  495. }
  496. const CStack *stack = curInt->cb->battleGetStackByID(action->stackNumber);
  497. if (stack)
  498. {
  499. windowObject->updateQueue();
  500. }
  501. else
  502. {
  503. assert(action->actionType == EActionType::HERO_SPELL); //only cast spell is valid action without acting stack number
  504. }
  505. stacksController->startAction(action);
  506. if(action->actionType == EActionType::HERO_SPELL) //when hero casts spell
  507. return;
  508. if (!stack)
  509. {
  510. logGlobal->error("Something wrong with stackNumber in actionStarted. Stack number: %d", action->stackNumber);
  511. return;
  512. }
  513. effectsController->startAction(action);
  514. }
  515. void BattleInterface::tacticPhaseEnd()
  516. {
  517. stacksController->setActiveStack(nullptr);
  518. tacticsMode = false;
  519. }
  520. static bool immobile(const CStack *s)
  521. {
  522. return !s->Speed(0, true); //should bound stacks be immobile?
  523. }
  524. void BattleInterface::tacticNextStack(const CStack * current)
  525. {
  526. if (!current)
  527. current = stacksController->getActiveStack();
  528. //no switching stacks when the current one is moving
  529. assert(getAnimationCondition(EAnimationEvents::ACTION) == false);
  530. waitForAnimationCondition(EAnimationEvents::ACTION, false);
  531. TStacks stacksOfMine = tacticianInterface->cb->battleGetStacks(CBattleCallback::ONLY_MINE);
  532. vstd::erase_if (stacksOfMine, &immobile);
  533. if (stacksOfMine.empty())
  534. {
  535. tacticPhaseEnd();
  536. return;
  537. }
  538. auto it = vstd::find(stacksOfMine, current);
  539. if (it != stacksOfMine.end() && ++it != stacksOfMine.end())
  540. stackActivated(*it);
  541. else
  542. stackActivated(stacksOfMine.front());
  543. }
  544. void BattleInterface::obstaclePlaced(const std::vector<std::shared_ptr<const CObstacleInstance>> oi)
  545. {
  546. obstacleController->obstaclePlaced(oi);
  547. }
  548. const CGHeroInstance *BattleInterface::currentHero() const
  549. {
  550. if (attackingHeroInstance && attackingHeroInstance->tempOwner == curInt->playerID)
  551. return attackingHeroInstance;
  552. if (defendingHeroInstance && defendingHeroInstance->tempOwner == curInt->playerID)
  553. return defendingHeroInstance;
  554. return nullptr;
  555. }
  556. InfoAboutHero BattleInterface::enemyHero() const
  557. {
  558. InfoAboutHero ret;
  559. if (attackingHeroInstance->tempOwner == curInt->playerID)
  560. curInt->cb->getHeroInfo(defendingHeroInstance, ret);
  561. else
  562. curInt->cb->getHeroInfo(attackingHeroInstance, ret);
  563. return ret;
  564. }
  565. void BattleInterface::requestAutofightingAIToTakeAction()
  566. {
  567. assert(curInt->isAutoFightOn);
  568. boost::thread aiThread([&]()
  569. {
  570. auto ba = std::make_unique<BattleAction>(curInt->autofightingAI->activeStack(stacksController->getActiveStack()));
  571. if(curInt->cb->battleIsFinished())
  572. {
  573. return; // battle finished with spellcast
  574. }
  575. if (curInt->isAutoFightOn)
  576. {
  577. if (tacticsMode)
  578. {
  579. // Always end tactics mode. Player interface is blocked currently, so it's not possible that
  580. // the AI can take any action except end tactics phase (AI actions won't be triggered)
  581. //TODO implement the possibility that the AI will be triggered for further actions
  582. //TODO any solution to merge tactics phase & normal phase in the way it is handled by the player and battle interface?
  583. stacksController->setActiveStack(nullptr);
  584. tacticsMode = false;
  585. }
  586. else
  587. {
  588. givenCommand.setn(ba.release());
  589. }
  590. }
  591. else
  592. {
  593. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  594. activateStack();
  595. }
  596. });
  597. aiThread.detach();
  598. }
  599. void BattleInterface::castThisSpell(SpellID spellID)
  600. {
  601. actionsController->castThisSpell(spellID);
  602. }
  603. void BattleInterface::setAnimationCondition( EAnimationEvents event, bool state)
  604. {
  605. logAnim->debug("setAnimationCondition: %d -> %s", static_cast<int>(event), state ? "ON" : "OFF");
  606. size_t index = static_cast<size_t>(event);
  607. animationEvents[index].setn(state);
  608. decltype(awaitingEvents) executingEvents;
  609. for (auto it = awaitingEvents.begin(); it != awaitingEvents.end();)
  610. {
  611. if (it->event == event && it->eventState == state)
  612. {
  613. executingEvents.push_back(*it);
  614. it = awaitingEvents.erase(it);
  615. }
  616. else
  617. ++it;
  618. }
  619. for (auto const & event : executingEvents)
  620. event.action();
  621. }
  622. bool BattleInterface::getAnimationCondition( EAnimationEvents event)
  623. {
  624. size_t index = static_cast<size_t>(event);
  625. return animationEvents[index].get();
  626. }
  627. void BattleInterface::waitForAnimationCondition( EAnimationEvents event, bool state)
  628. {
  629. auto unlockPim = vstd::makeUnlockGuard(*CPlayerInterface::pim);
  630. size_t index = static_cast<size_t>(event);
  631. animationEvents[index].waitUntil(state);
  632. }
  633. void BattleInterface::executeOnAnimationCondition( EAnimationEvents event, bool state, const AwaitingAnimationAction & action)
  634. {
  635. awaitingEvents.push_back({action, event, state});
  636. }