BattleInterface.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  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 "BattleControlPanel.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. const SDL_Rect & myRect,
  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. , animCount(0)
  51. , attackerInt(att)
  52. , defenderInt(defen)
  53. , curInt(att)
  54. , myTurn(false)
  55. , moveSoundHander(-1)
  56. , bresult(nullptr)
  57. {
  58. OBJ_CONSTRUCTION;
  59. for ( auto & event : animationEvents)
  60. event.setn(false);
  61. if(spectatorInt)
  62. {
  63. curInt = spectatorInt;
  64. }
  65. else if(!curInt)
  66. {
  67. //May happen when we are defending during network MP game -> attacker interface is just not present
  68. curInt = defenderInt;
  69. }
  70. pos = myRect;
  71. strongInterest = true;
  72. givenCommand.setn(nullptr);
  73. //hot-seat -> check tactics for both players (defender may be local human)
  74. if(attackerInt && attackerInt->cb->battleGetTacticDist())
  75. tacticianInterface = attackerInt;
  76. else if(defenderInt && defenderInt->cb->battleGetTacticDist())
  77. tacticianInterface = defenderInt;
  78. //if we found interface of player with tactics, then enter tactics mode
  79. tacticsMode = static_cast<bool>(tacticianInterface);
  80. //create stack queue
  81. bool embedQueue;
  82. std::string queueSize = settings["battle"]["queueSize"].String();
  83. if(queueSize == "auto")
  84. embedQueue = screen->h < 700;
  85. else
  86. embedQueue = screen->h < 700 || queueSize == "small";
  87. queue = std::make_shared<StackQueue>(embedQueue, *this);
  88. if(!embedQueue)
  89. {
  90. if (settings["battle"]["showQueue"].Bool())
  91. pos.y += queue->pos.h / 2; //center whole window
  92. queue->moveTo(Point(pos.x, pos.y - queue->pos.h));
  93. }
  94. CPlayerInterface::battleInt = this;
  95. //initializing armies
  96. this->army1 = army1;
  97. this->army2 = army2;
  98. const CGTownInstance *town = curInt->cb->battleGetDefendedTown();
  99. if(town && town->hasFort())
  100. siegeController.reset(new BattleSiegeController(*this, town));
  101. controlPanel = std::make_shared<BattleControlPanel>(*this, Point(0, 556));
  102. projectilesController.reset(new BattleProjectileController(*this));
  103. fieldController.reset( new BattleFieldController(*this));
  104. stacksController.reset( new BattleStacksController(*this));
  105. actionsController.reset( new BattleActionsController(*this));
  106. effectsController.reset(new BattleEffectsController(*this));
  107. //loading hero animations
  108. if(hero1) // attacking hero
  109. {
  110. std::string battleImage;
  111. if(!hero1->type->battleImage.empty())
  112. {
  113. battleImage = hero1->type->battleImage;
  114. }
  115. else
  116. {
  117. if(hero1->sex)
  118. battleImage = hero1->type->heroClass->imageBattleFemale;
  119. else
  120. battleImage = hero1->type->heroClass->imageBattleMale;
  121. }
  122. attackingHero = std::make_shared<BattleHero>(battleImage, false, hero1->tempOwner, hero1->tempOwner == curInt->playerID ? hero1 : nullptr, *this);
  123. }
  124. if(hero2) // defending hero
  125. {
  126. std::string battleImage;
  127. if(!hero2->type->battleImage.empty())
  128. {
  129. battleImage = hero2->type->battleImage;
  130. }
  131. else
  132. {
  133. if(hero2->sex)
  134. battleImage = hero2->type->heroClass->imageBattleFemale;
  135. else
  136. battleImage = hero2->type->heroClass->imageBattleMale;
  137. }
  138. defendingHero = std::make_shared<BattleHero>(battleImage, true, hero2->tempOwner, hero2->tempOwner == curInt->playerID ? hero2 : nullptr, *this);
  139. }
  140. obstacleController.reset(new BattleObstacleController(*this));
  141. if(tacticsMode)
  142. tacticNextStack(nullptr);
  143. CCS->musich->stopMusic();
  144. setAnimationCondition(EAnimationEvents::OPENING, true);
  145. battleIntroSoundChannel = CCS->soundh->playSoundFromSet(CCS->soundh->battleIntroSounds);
  146. auto onIntroPlayed = [&]()
  147. {
  148. if(LOCPLINT->battleInt)
  149. {
  150. CCS->musich->playMusicFromSet("battle", true, true);
  151. setAnimationCondition(EAnimationEvents::OPENING, false);
  152. activateStack();
  153. battleIntroSoundChannel = -1;
  154. }
  155. };
  156. CCS->soundh->setCallback(battleIntroSoundChannel, onIntroPlayed);
  157. addUsedEvents(RCLICK | MOVE | KEYBOARD);
  158. queue->update();
  159. controlPanel->blockUI(true);
  160. }
  161. BattleInterface::~BattleInterface()
  162. {
  163. CPlayerInterface::battleInt = nullptr;
  164. givenCommand.cond.notify_all(); //that two lines should make any stacksController->getActiveStack() waiting thread to finish
  165. assert(!active);
  166. if (active) //dirty fix for #485
  167. deactivate();
  168. if (adventureInt && adventureInt->selection)
  169. {
  170. //FIXME: this should be moved to adventureInt which should restore correct track based on selection/active player
  171. const auto & terrain = *(LOCPLINT->cb->getTile(adventureInt->selection->visitablePos())->terType);
  172. CCS->musich->playMusicFromSet("terrain", terrain.name, true, false);
  173. }
  174. // may happen if user decided to close game while in battle
  175. if (getAnimationCondition(EAnimationEvents::ACTION) == true)
  176. logGlobal->error("Shutting down BattleInterface during animation playback!");
  177. setAnimationCondition(EAnimationEvents::ACTION, false);
  178. }
  179. void BattleInterface::setPrintCellBorders(bool set)
  180. {
  181. Settings cellBorders = settings.write["battle"]["cellBorders"];
  182. cellBorders->Bool() = set;
  183. fieldController->redrawBackgroundWithHexes();
  184. GH.totalRedraw();
  185. }
  186. void BattleInterface::setPrintStackRange(bool set)
  187. {
  188. Settings stackRange = settings.write["battle"]["stackRange"];
  189. stackRange->Bool() = set;
  190. fieldController->redrawBackgroundWithHexes();
  191. GH.totalRedraw();
  192. }
  193. void BattleInterface::setPrintMouseShadow(bool set)
  194. {
  195. Settings shadow = settings.write["battle"]["mouseShadow"];
  196. shadow->Bool() = set;
  197. }
  198. void BattleInterface::activate()
  199. {
  200. controlPanel->activate();
  201. if (curInt->isAutoFightOn)
  202. return;
  203. CIntObject::activate();
  204. if (attackingHero)
  205. attackingHero->activate();
  206. if (defendingHero)
  207. defendingHero->activate();
  208. fieldController->activate();
  209. if (settings["battle"]["showQueue"].Bool())
  210. queue->activate();
  211. LOCPLINT->cingconsole->activate();
  212. }
  213. void BattleInterface::deactivate()
  214. {
  215. controlPanel->deactivate();
  216. CIntObject::deactivate();
  217. fieldController->deactivate();
  218. if (attackingHero)
  219. attackingHero->deactivate();
  220. if (defendingHero)
  221. defendingHero->deactivate();
  222. if (settings["battle"]["showQueue"].Bool())
  223. queue->deactivate();
  224. LOCPLINT->cingconsole->deactivate();
  225. }
  226. void BattleInterface::keyPressed(const SDL_KeyboardEvent & key)
  227. {
  228. if(key.keysym.sym == SDLK_q && key.state == SDL_PRESSED)
  229. {
  230. if(settings["battle"]["showQueue"].Bool()) //hide queue
  231. hideQueue();
  232. else
  233. showQueue();
  234. }
  235. else if(key.keysym.sym == SDLK_f && key.state == SDL_PRESSED)
  236. {
  237. actionsController->enterCreatureCastingMode();
  238. }
  239. else if(key.keysym.sym == SDLK_ESCAPE)
  240. {
  241. if(getAnimationCondition(EAnimationEvents::OPENING) == true)
  242. CCS->soundh->stopSound(battleIntroSoundChannel);
  243. else
  244. actionsController->endCastingSpell();
  245. }
  246. }
  247. void BattleInterface::mouseMoved(const SDL_MouseMotionEvent &event)
  248. {
  249. BattleHex selectedHex = fieldController->getHoveredHex();
  250. actionsController->handleHex(selectedHex, MOVE);
  251. controlPanel->mouseMoved(event);
  252. }
  253. void BattleInterface::clickRight(tribool down, bool previousState)
  254. {
  255. if (!down)
  256. {
  257. actionsController->endCastingSpell();
  258. }
  259. }
  260. void BattleInterface::stackReset(const CStack * stack)
  261. {
  262. stacksController->stackReset(stack);
  263. }
  264. void BattleInterface::stackAdded(const CStack * stack)
  265. {
  266. stacksController->stackAdded(stack, false);
  267. }
  268. void BattleInterface::stackRemoved(uint32_t stackID)
  269. {
  270. stacksController->stackRemoved(stackID);
  271. fieldController->redrawBackgroundWithHexes();
  272. queue->update();
  273. }
  274. void BattleInterface::stackActivated(const CStack *stack)
  275. {
  276. stacksController->stackActivated(stack);
  277. }
  278. void BattleInterface::stackMoved(const CStack *stack, std::vector<BattleHex> destHex, int distance)
  279. {
  280. stacksController->stackMoved(stack, destHex, distance);
  281. }
  282. void BattleInterface::stacksAreAttacked(std::vector<StackAttackedInfo> attackedInfos)
  283. {
  284. stacksController->stacksAreAttacked(attackedInfos);
  285. std::array<int, 2> killedBySide = {0, 0};
  286. int targets = 0;
  287. for(const StackAttackedInfo & attackedInfo : attackedInfos)
  288. {
  289. ++targets;
  290. ui8 side = attackedInfo.defender->side;
  291. killedBySide.at(side) += attackedInfo.amountKilled;
  292. }
  293. for(ui8 side = 0; side < 2; side++)
  294. {
  295. if(killedBySide.at(side) > killedBySide.at(1-side))
  296. setHeroAnimation(side, EHeroAnimType::DEFEAT);
  297. else if(killedBySide.at(side) < killedBySide.at(1-side))
  298. setHeroAnimation(side, EHeroAnimType::VICTORY);
  299. }
  300. }
  301. void BattleInterface::stackAttacking( const StackAttackInfo & attackInfo )
  302. {
  303. stacksController->stackAttacking(attackInfo);
  304. }
  305. void BattleInterface::newRoundFirst( int round )
  306. {
  307. waitForAnimationCondition(EAnimationEvents::OPENING, false);
  308. }
  309. void BattleInterface::newRound(int number)
  310. {
  311. controlPanel->console->addText(CGI->generaltexth->allTexts[412]);
  312. }
  313. void BattleInterface::giveCommand(EActionType action, BattleHex tile, si32 additional)
  314. {
  315. const CStack * actor = nullptr;
  316. if(action != EActionType::HERO_SPELL && action != EActionType::RETREAT && action != EActionType::SURRENDER)
  317. {
  318. actor = stacksController->getActiveStack();
  319. }
  320. auto side = curInt->cb->playerToSide(curInt->playerID);
  321. if(!side)
  322. {
  323. logGlobal->error("Player %s is not in battle", curInt->playerID.getStr());
  324. return;
  325. }
  326. auto ba = new BattleAction(); //is deleted in CPlayerInterface::stacksController->getActiveStack()()
  327. ba->side = side.get();
  328. ba->actionType = action;
  329. ba->aimToHex(tile);
  330. ba->actionSubtype = additional;
  331. sendCommand(ba, actor);
  332. }
  333. void BattleInterface::sendCommand(BattleAction *& command, const CStack * actor)
  334. {
  335. command->stackNumber = actor ? actor->unitId() : ((command->side == BattleSide::ATTACKER) ? -1 : -2);
  336. if(!tacticsMode)
  337. {
  338. logGlobal->trace("Setting command for %s", (actor ? actor->nodeName() : "hero"));
  339. myTurn = false;
  340. stacksController->setActiveStack(nullptr);
  341. givenCommand.setn(command);
  342. }
  343. else
  344. {
  345. curInt->cb->battleMakeTacticAction(command);
  346. vstd::clear_pointer(command);
  347. stacksController->setActiveStack(nullptr);
  348. //next stack will be activated when action ends
  349. }
  350. }
  351. const CGHeroInstance * BattleInterface::getActiveHero()
  352. {
  353. const CStack *attacker = stacksController->getActiveStack();
  354. if(!attacker)
  355. {
  356. return nullptr;
  357. }
  358. if(attacker->side == BattleSide::ATTACKER)
  359. {
  360. return attackingHeroInstance;
  361. }
  362. return defendingHeroInstance;
  363. }
  364. void BattleInterface::hexLclicked(int whichOne)
  365. {
  366. actionsController->handleHex(whichOne, LCLICK);
  367. }
  368. void BattleInterface::stackIsCatapulting(const CatapultAttack & ca)
  369. {
  370. if (siegeController)
  371. siegeController->stackIsCatapulting(ca);
  372. }
  373. void BattleInterface::gateStateChanged(const EGateState state)
  374. {
  375. if (siegeController)
  376. siegeController->gateStateChanged(state);
  377. }
  378. void BattleInterface::battleFinished(const BattleResult& br)
  379. {
  380. bresult = &br;
  381. assert(getAnimationCondition(EAnimationEvents::ACTION) == false);
  382. waitForAnimationCondition(EAnimationEvents::ACTION, false);
  383. stacksController->setActiveStack(nullptr);
  384. displayBattleFinished();
  385. }
  386. void BattleInterface::displayBattleFinished()
  387. {
  388. CCS->curh->changeGraphic(ECursor::ADVENTURE,0);
  389. if(settings["session"]["spectate"].Bool() && settings["session"]["spectate-skip-battle-result"].Bool())
  390. {
  391. close();
  392. return;
  393. }
  394. GH.pushInt(std::make_shared<BattleResultWindow>(*bresult, *(this->curInt)));
  395. curInt->waitWhileDialog(); // Avoid freeze when AI end turn after battle. Check bug #1897
  396. CPlayerInterface::battleInt = nullptr;
  397. }
  398. void BattleInterface::spellCast(const BattleSpellCast * sc)
  399. {
  400. controlPanel->blockUI(true);
  401. const SpellID spellID = sc->spellID;
  402. const CSpell * spell = spellID.toSpell();
  403. auto targetedTile = sc->tile;
  404. assert(spell);
  405. if(!spell)
  406. return;
  407. const std::string & castSoundPath = spell->getCastSound();
  408. if (!castSoundPath.empty())
  409. {
  410. auto group = spell->animationInfo.projectile.empty() ?
  411. EAnimationEvents::HIT:
  412. EAnimationEvents::BEFORE_HIT;//FIXME: should be on projectile spawning
  413. executeOnAnimationCondition(group, true, [=]() {
  414. CCS->soundh->playSound(castSoundPath);
  415. });
  416. }
  417. if ( sc->activeCast )
  418. {
  419. const CStack * casterStack = curInt->cb->battleGetStackByID(sc->casterStack);
  420. if(casterStack != nullptr )
  421. {
  422. executeOnAnimationCondition(EAnimationEvents::BEFORE_HIT, true, [=]()
  423. {
  424. stacksController->addNewAnim(new CastAnimation(*this, casterStack, targetedTile, curInt->cb->battleGetStackByPos(targetedTile), spell));
  425. displaySpellCast(spellID, casterStack->getPosition());
  426. });
  427. }
  428. else
  429. {
  430. auto hero = sc->side ? defendingHero : attackingHero;
  431. assert(hero);
  432. executeOnAnimationCondition(EAnimationEvents::BEFORE_HIT, true, [=]()
  433. {
  434. stacksController->addNewAnim(new HeroCastAnimation(*this, hero, targetedTile, curInt->cb->battleGetStackByPos(targetedTile), spell));
  435. });
  436. }
  437. }
  438. executeOnAnimationCondition(EAnimationEvents::HIT, true, [=](){
  439. displaySpellHit(spellID, targetedTile);
  440. });
  441. //queuing affect animation
  442. for(auto & elem : sc->affectedCres)
  443. {
  444. auto stack = curInt->cb->battleGetStackByID(elem, false);
  445. assert(stack);
  446. if(stack)
  447. {
  448. executeOnAnimationCondition(EAnimationEvents::HIT, true, [=](){
  449. if (spellID == SpellID::BLOODLUST)
  450. stacksController->addNewAnim( ColorTransformAnimation::bloodlustAnimation(*this, stack, spell));
  451. else if (spellID == SpellID::STONE_GAZE)
  452. stacksController->addNewAnim( ColorTransformAnimation::petrifyAnimation(*this, stack, spell));
  453. else
  454. displaySpellEffect(spellID, stack->getPosition());
  455. });
  456. }
  457. }
  458. //queuing additional animation (magic mirror / resistance)
  459. for(auto & elem : sc->customEffects)
  460. {
  461. auto stack = curInt->cb->battleGetStackByID(elem.stack, false);
  462. assert(stack);
  463. if(stack)
  464. {
  465. executeOnAnimationCondition(EAnimationEvents::HIT, true, [=](){
  466. effectsController->displayEffect(EBattleEffect::EBattleEffect(elem.effect), stack->getPosition());
  467. });
  468. }
  469. }
  470. //mana absorption
  471. if (sc->manaGained > 0)
  472. {
  473. Point leftHero = Point(15, 30) + pos;
  474. Point rightHero = Point(755, 30) + pos;
  475. bool side = sc->side;
  476. executeOnAnimationCondition(EAnimationEvents::AFTER_HIT, true, [=](){
  477. stacksController->addNewAnim(new PointEffectAnimation(*this, "", side ? "SP07_A.DEF" : "SP07_B.DEF", leftHero));
  478. stacksController->addNewAnim(new PointEffectAnimation(*this, "", side ? "SP07_B.DEF" : "SP07_A.DEF", rightHero));
  479. });
  480. }
  481. }
  482. void BattleInterface::battleStacksEffectsSet(const SetStackEffect & sse)
  483. {
  484. if(stacksController->getActiveStack() != nullptr)
  485. fieldController->redrawBackgroundWithHexes();
  486. }
  487. void BattleInterface::setHeroAnimation(ui8 side, EHeroAnimType phase)
  488. {
  489. if(side == BattleSide::ATTACKER)
  490. {
  491. if(attackingHero)
  492. attackingHero->setPhase(phase);
  493. }
  494. else
  495. {
  496. if(defendingHero)
  497. defendingHero->setPhase(phase);
  498. }
  499. }
  500. void BattleInterface::displayBattleLog(const std::vector<MetaString> & battleLog)
  501. {
  502. for(const auto & line : battleLog)
  503. {
  504. std::string formatted = line.toString();
  505. boost::algorithm::trim(formatted);
  506. if(!controlPanel->console->addText(formatted))
  507. logGlobal->warn("Too long battle log line");
  508. }
  509. }
  510. void BattleInterface::displaySpellAnimationQueue(const CSpell::TAnimationQueue & q, BattleHex destinationTile, bool isHit)
  511. {
  512. for(const CSpell::TAnimation & animation : q)
  513. {
  514. if(animation.pause > 0)
  515. stacksController->addNewAnim(new DummyAnimation(*this, animation.pause));
  516. else
  517. {
  518. int flags = 0;
  519. if (isHit)
  520. flags |= PointEffectAnimation::FORCE_ON_TOP;
  521. if (animation.verticalPosition == VerticalPosition::BOTTOM)
  522. flags |= PointEffectAnimation::ALIGN_TO_BOTTOM;
  523. if (!destinationTile.isValid())
  524. flags |= PointEffectAnimation::SCREEN_FILL;
  525. if (!destinationTile.isValid())
  526. stacksController->addNewAnim(new PointEffectAnimation(*this, "", animation.resourceName, flags));
  527. else
  528. stacksController->addNewAnim(new PointEffectAnimation(*this, "", animation.resourceName, destinationTile, flags));
  529. }
  530. }
  531. }
  532. void BattleInterface::displaySpellCast(SpellID spellID, BattleHex destinationTile)
  533. {
  534. const CSpell * spell = spellID.toSpell();
  535. if(spell)
  536. displaySpellAnimationQueue(spell->animationInfo.cast, destinationTile, false);
  537. }
  538. void BattleInterface::displaySpellEffect(SpellID spellID, BattleHex destinationTile)
  539. {
  540. const CSpell *spell = spellID.toSpell();
  541. if(spell)
  542. displaySpellAnimationQueue(spell->animationInfo.affect, destinationTile, false);
  543. }
  544. void BattleInterface::displaySpellHit(SpellID spellID, BattleHex destinationTile)
  545. {
  546. const CSpell * spell = spellID.toSpell();
  547. if(spell)
  548. displaySpellAnimationQueue(spell->animationInfo.hit, destinationTile, true);
  549. }
  550. void BattleInterface::setAnimSpeed(int set)
  551. {
  552. Settings speed = settings.write["battle"]["animationSpeed"];
  553. speed->Float() = float(set) / 100;
  554. }
  555. int BattleInterface::getAnimSpeed() const
  556. {
  557. if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-battle-speed"].isNull())
  558. return static_cast<int>(vstd::round(settings["session"]["spectate-battle-speed"].Float() *100));
  559. return static_cast<int>(vstd::round(settings["battle"]["animationSpeed"].Float() *100));
  560. }
  561. CPlayerInterface *BattleInterface::getCurrentPlayerInterface() const
  562. {
  563. return curInt.get();
  564. }
  565. void BattleInterface::trySetActivePlayer( PlayerColor player )
  566. {
  567. if ( attackerInt && attackerInt->playerID == player )
  568. curInt = attackerInt;
  569. if ( defenderInt && defenderInt->playerID == player )
  570. curInt = defenderInt;
  571. }
  572. void BattleInterface::activateStack()
  573. {
  574. stacksController->activateStack();
  575. const CStack * s = stacksController->getActiveStack();
  576. if(!s)
  577. return;
  578. myTurn = true;
  579. queue->update();
  580. fieldController->redrawBackgroundWithHexes();
  581. actionsController->activateStack();
  582. GH.fakeMouseMove();
  583. }
  584. void BattleInterface::endAction(const BattleAction* action)
  585. {
  586. const CStack *stack = curInt->cb->battleGetStackByID(action->stackNumber);
  587. stacksController->endAction(action);
  588. queue->update();
  589. //stack ended movement in tactics phase -> select the next one
  590. if (tacticsMode)
  591. tacticNextStack(stack);
  592. //we have activated next stack after sending request that has been just realized -> blockmap due to movement has changed
  593. if(action->actionType == EActionType::HERO_SPELL)
  594. fieldController->redrawBackgroundWithHexes();
  595. }
  596. void BattleInterface::hideQueue()
  597. {
  598. Settings showQueue = settings.write["battle"]["showQueue"];
  599. showQueue->Bool() = false;
  600. queue->deactivate();
  601. if (!queue->embedded)
  602. {
  603. moveBy(Point(0, -queue->pos.h / 2));
  604. GH.totalRedraw();
  605. }
  606. }
  607. void BattleInterface::showQueue()
  608. {
  609. Settings showQueue = settings.write["battle"]["showQueue"];
  610. showQueue->Bool() = true;
  611. queue->activate();
  612. if (!queue->embedded)
  613. {
  614. moveBy(Point(0, +queue->pos.h / 2));
  615. GH.totalRedraw();
  616. }
  617. }
  618. void BattleInterface::startAction(const BattleAction* action)
  619. {
  620. if(action->actionType == EActionType::END_TACTIC_PHASE)
  621. {
  622. controlPanel->tacticPhaseEnded();
  623. return;
  624. }
  625. const CStack *stack = curInt->cb->battleGetStackByID(action->stackNumber);
  626. if (stack)
  627. {
  628. queue->update();
  629. }
  630. else
  631. {
  632. assert(action->actionType == EActionType::HERO_SPELL); //only cast spell is valid action without acting stack number
  633. }
  634. stacksController->startAction(action);
  635. redraw(); // redraw after deactivation, including proper handling of hovered hexes
  636. if(action->actionType == EActionType::HERO_SPELL) //when hero casts spell
  637. return;
  638. if (!stack)
  639. {
  640. logGlobal->error("Something wrong with stackNumber in actionStarted. Stack number: %d", action->stackNumber);
  641. return;
  642. }
  643. effectsController->startAction(action);
  644. }
  645. void BattleInterface::tacticPhaseEnd()
  646. {
  647. stacksController->setActiveStack(nullptr);
  648. tacticsMode = false;
  649. }
  650. static bool immobile(const CStack *s)
  651. {
  652. return !s->Speed(0, true); //should bound stacks be immobile?
  653. }
  654. void BattleInterface::tacticNextStack(const CStack * current)
  655. {
  656. if (!current)
  657. current = stacksController->getActiveStack();
  658. //no switching stacks when the current one is moving
  659. assert(getAnimationCondition(EAnimationEvents::ACTION) == false);
  660. waitForAnimationCondition(EAnimationEvents::ACTION, false);
  661. TStacks stacksOfMine = tacticianInterface->cb->battleGetStacks(CBattleCallback::ONLY_MINE);
  662. vstd::erase_if (stacksOfMine, &immobile);
  663. if (stacksOfMine.empty())
  664. {
  665. tacticPhaseEnd();
  666. return;
  667. }
  668. auto it = vstd::find(stacksOfMine, current);
  669. if (it != stacksOfMine.end() && ++it != stacksOfMine.end())
  670. stackActivated(*it);
  671. else
  672. stackActivated(stacksOfMine.front());
  673. }
  674. void BattleInterface::obstaclePlaced(const std::vector<std::shared_ptr<const CObstacleInstance>> oi)
  675. {
  676. obstacleController->obstaclePlaced(oi);
  677. }
  678. const CGHeroInstance *BattleInterface::currentHero() const
  679. {
  680. if (attackingHeroInstance && attackingHeroInstance->tempOwner == curInt->playerID)
  681. return attackingHeroInstance;
  682. if (defendingHeroInstance && defendingHeroInstance->tempOwner == curInt->playerID)
  683. return defendingHeroInstance;
  684. return nullptr;
  685. }
  686. InfoAboutHero BattleInterface::enemyHero() const
  687. {
  688. InfoAboutHero ret;
  689. if (attackingHeroInstance->tempOwner == curInt->playerID)
  690. curInt->cb->getHeroInfo(defendingHeroInstance, ret);
  691. else
  692. curInt->cb->getHeroInfo(attackingHeroInstance, ret);
  693. return ret;
  694. }
  695. void BattleInterface::requestAutofightingAIToTakeAction()
  696. {
  697. assert(curInt->isAutoFightOn);
  698. boost::thread aiThread([&]()
  699. {
  700. auto ba = make_unique<BattleAction>(curInt->autofightingAI->activeStack(stacksController->getActiveStack()));
  701. if(curInt->cb->battleIsFinished())
  702. {
  703. return; // battle finished with spellcast
  704. }
  705. if (curInt->isAutoFightOn)
  706. {
  707. if (tacticsMode)
  708. {
  709. // Always end tactics mode. Player interface is blocked currently, so it's not possible that
  710. // the AI can take any action except end tactics phase (AI actions won't be triggered)
  711. //TODO implement the possibility that the AI will be triggered for further actions
  712. //TODO any solution to merge tactics phase & normal phase in the way it is handled by the player and battle interface?
  713. stacksController->setActiveStack(nullptr);
  714. tacticsMode = false;
  715. }
  716. else
  717. {
  718. givenCommand.setn(ba.release());
  719. }
  720. }
  721. else
  722. {
  723. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  724. activateStack();
  725. }
  726. });
  727. aiThread.detach();
  728. }
  729. void BattleInterface::showAll(SDL_Surface *to)
  730. {
  731. show(to);
  732. }
  733. void BattleInterface::show(SDL_Surface *to)
  734. {
  735. Canvas canvas(to);
  736. assert(to);
  737. SDL_Rect buf;
  738. SDL_GetClipRect(to, &buf);
  739. SDL_SetClipRect(to, &pos);
  740. ++animCount;
  741. fieldController->renderBattlefield(canvas);
  742. stacksController->update();
  743. SDL_SetClipRect(to, &buf); //restoring previous clip_rect
  744. showInterface(to);
  745. }
  746. void BattleInterface::collectRenderableObjects(BattleRenderer & renderer)
  747. {
  748. if (attackingHero)
  749. {
  750. renderer.insert(EBattleFieldLayer::HEROES, BattleHex(0),[this](BattleRenderer::RendererRef canvas)
  751. {
  752. attackingHero->render(canvas);
  753. });
  754. }
  755. if (defendingHero)
  756. {
  757. renderer.insert(EBattleFieldLayer::HEROES, BattleHex(GameConstants::BFIELD_WIDTH-1),[this](BattleRenderer::RendererRef canvas)
  758. {
  759. defendingHero->render(canvas);
  760. });
  761. }
  762. }
  763. void BattleInterface::showInterface(SDL_Surface * to)
  764. {
  765. //showing in-game console
  766. LOCPLINT->cingconsole->show(to);
  767. controlPanel->showAll(to);
  768. Rect posWithQueue = Rect(pos.x, pos.y, 800, 600);
  769. if (settings["battle"]["showQueue"].Bool())
  770. {
  771. if (!queue->embedded)
  772. {
  773. posWithQueue.y -= queue->pos.h;
  774. posWithQueue.h += queue->pos.h;
  775. }
  776. queue->showAll(to);
  777. }
  778. //printing border around interface
  779. if (screen->w != 800 || screen->h !=600)
  780. {
  781. CMessage::drawBorder(curInt->playerID,to,posWithQueue.w + 28, posWithQueue.h + 28, posWithQueue.x-14, posWithQueue.y-15);
  782. }
  783. }
  784. void BattleInterface::castThisSpell(SpellID spellID)
  785. {
  786. actionsController->castThisSpell(spellID);
  787. }
  788. void BattleInterface::setAnimationCondition( EAnimationEvents event, bool state)
  789. {
  790. logAnim->debug("setAnimationCondition: %d -> %s", static_cast<int>(event), state ? "ON" : "OFF");
  791. size_t index = static_cast<size_t>(event);
  792. animationEvents[index].setn(state);
  793. for (auto it = awaitingEvents.begin(); it != awaitingEvents.end();)
  794. {
  795. if (it->event == event && it->eventState == state)
  796. {
  797. it->action();
  798. it = awaitingEvents.erase(it);
  799. }
  800. else
  801. ++it;
  802. }
  803. }
  804. bool BattleInterface::getAnimationCondition( EAnimationEvents event)
  805. {
  806. size_t index = static_cast<size_t>(event);
  807. return animationEvents[index].get();
  808. }
  809. void BattleInterface::waitForAnimationCondition( EAnimationEvents event, bool state)
  810. {
  811. auto unlockPim = vstd::makeUnlockGuard(*CPlayerInterface::pim);
  812. size_t index = static_cast<size_t>(event);
  813. animationEvents[index].waitUntil(state);
  814. }
  815. void BattleInterface::executeOnAnimationCondition( EAnimationEvents event, bool state, const AwaitingAnimationAction & action)
  816. {
  817. awaitingEvents.push_back({action, event, state});
  818. }