BattleInterface.cpp 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  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, bool teleport)
  279. {
  280. if (teleport)
  281. stacksController->stackTeleported(stack, destHex, distance);
  282. else
  283. stacksController->stackMoved(stack, destHex, distance);
  284. }
  285. void BattleInterface::stacksAreAttacked(std::vector<StackAttackedInfo> attackedInfos)
  286. {
  287. stacksController->stacksAreAttacked(attackedInfos);
  288. std::array<int, 2> killedBySide = {0, 0};
  289. int targets = 0;
  290. for(const StackAttackedInfo & attackedInfo : attackedInfos)
  291. {
  292. ++targets;
  293. ui8 side = attackedInfo.defender->side;
  294. killedBySide.at(side) += attackedInfo.amountKilled;
  295. }
  296. for(ui8 side = 0; side < 2; side++)
  297. {
  298. if(killedBySide.at(side) > killedBySide.at(1-side))
  299. setHeroAnimation(side, EHeroAnimType::DEFEAT);
  300. else if(killedBySide.at(side) < killedBySide.at(1-side))
  301. setHeroAnimation(side, EHeroAnimType::VICTORY);
  302. }
  303. }
  304. void BattleInterface::stackAttacking( const StackAttackInfo & attackInfo )
  305. {
  306. stacksController->stackAttacking(attackInfo);
  307. }
  308. void BattleInterface::newRoundFirst( int round )
  309. {
  310. waitForAnimationCondition(EAnimationEvents::OPENING, false);
  311. }
  312. void BattleInterface::newRound(int number)
  313. {
  314. controlPanel->console->addText(CGI->generaltexth->allTexts[412]);
  315. }
  316. void BattleInterface::giveCommand(EActionType action, BattleHex tile, si32 additional)
  317. {
  318. const CStack * actor = nullptr;
  319. if(action != EActionType::HERO_SPELL && action != EActionType::RETREAT && action != EActionType::SURRENDER)
  320. {
  321. actor = stacksController->getActiveStack();
  322. }
  323. auto side = curInt->cb->playerToSide(curInt->playerID);
  324. if(!side)
  325. {
  326. logGlobal->error("Player %s is not in battle", curInt->playerID.getStr());
  327. return;
  328. }
  329. auto ba = new BattleAction(); //is deleted in CPlayerInterface::stacksController->getActiveStack()()
  330. ba->side = side.get();
  331. ba->actionType = action;
  332. ba->aimToHex(tile);
  333. ba->actionSubtype = additional;
  334. sendCommand(ba, actor);
  335. }
  336. void BattleInterface::sendCommand(BattleAction *& command, const CStack * actor)
  337. {
  338. command->stackNumber = actor ? actor->unitId() : ((command->side == BattleSide::ATTACKER) ? -1 : -2);
  339. if(!tacticsMode)
  340. {
  341. logGlobal->trace("Setting command for %s", (actor ? actor->nodeName() : "hero"));
  342. myTurn = false;
  343. stacksController->setActiveStack(nullptr);
  344. givenCommand.setn(command);
  345. }
  346. else
  347. {
  348. curInt->cb->battleMakeTacticAction(command);
  349. vstd::clear_pointer(command);
  350. stacksController->setActiveStack(nullptr);
  351. //next stack will be activated when action ends
  352. }
  353. }
  354. const CGHeroInstance * BattleInterface::getActiveHero()
  355. {
  356. const CStack *attacker = stacksController->getActiveStack();
  357. if(!attacker)
  358. {
  359. return nullptr;
  360. }
  361. if(attacker->side == BattleSide::ATTACKER)
  362. {
  363. return attackingHeroInstance;
  364. }
  365. return defendingHeroInstance;
  366. }
  367. void BattleInterface::hexLclicked(int whichOne)
  368. {
  369. actionsController->handleHex(whichOne, LCLICK);
  370. }
  371. void BattleInterface::stackIsCatapulting(const CatapultAttack & ca)
  372. {
  373. if (siegeController)
  374. siegeController->stackIsCatapulting(ca);
  375. }
  376. void BattleInterface::gateStateChanged(const EGateState state)
  377. {
  378. if (siegeController)
  379. siegeController->gateStateChanged(state);
  380. }
  381. void BattleInterface::battleFinished(const BattleResult& br)
  382. {
  383. bresult = &br;
  384. assert(getAnimationCondition(EAnimationEvents::ACTION) == false);
  385. waitForAnimationCondition(EAnimationEvents::ACTION, false);
  386. stacksController->setActiveStack(nullptr);
  387. displayBattleFinished();
  388. }
  389. void BattleInterface::displayBattleFinished()
  390. {
  391. CCS->curh->changeGraphic(ECursor::ADVENTURE,0);
  392. if(settings["session"]["spectate"].Bool() && settings["session"]["spectate-skip-battle-result"].Bool())
  393. {
  394. close();
  395. return;
  396. }
  397. GH.pushInt(std::make_shared<BattleResultWindow>(*bresult, *(this->curInt)));
  398. curInt->waitWhileDialog(); // Avoid freeze when AI end turn after battle. Check bug #1897
  399. CPlayerInterface::battleInt = nullptr;
  400. }
  401. void BattleInterface::spellCast(const BattleSpellCast * sc)
  402. {
  403. controlPanel->blockUI(true);
  404. const SpellID spellID = sc->spellID;
  405. const CSpell * spell = spellID.toSpell();
  406. auto targetedTile = sc->tile;
  407. assert(spell);
  408. if(!spell)
  409. return;
  410. const std::string & castSoundPath = spell->getCastSound();
  411. if (!castSoundPath.empty())
  412. {
  413. auto group = spell->animationInfo.projectile.empty() ?
  414. EAnimationEvents::HIT:
  415. EAnimationEvents::BEFORE_HIT;//FIXME: should be on projectile spawning
  416. executeOnAnimationCondition(group, true, [=]() {
  417. CCS->soundh->playSound(castSoundPath);
  418. });
  419. }
  420. if ( sc->activeCast )
  421. {
  422. const CStack * casterStack = curInt->cb->battleGetStackByID(sc->casterStack);
  423. if(casterStack != nullptr )
  424. {
  425. executeOnAnimationCondition(EAnimationEvents::BEFORE_HIT, true, [=]()
  426. {
  427. stacksController->addNewAnim(new CastAnimation(*this, casterStack, targetedTile, curInt->cb->battleGetStackByPos(targetedTile), spell));
  428. displaySpellCast(spellID, casterStack->getPosition());
  429. });
  430. }
  431. else
  432. {
  433. auto hero = sc->side ? defendingHero : attackingHero;
  434. assert(hero);
  435. executeOnAnimationCondition(EAnimationEvents::BEFORE_HIT, true, [=]()
  436. {
  437. stacksController->addNewAnim(new HeroCastAnimation(*this, hero, targetedTile, curInt->cb->battleGetStackByPos(targetedTile), spell));
  438. });
  439. }
  440. }
  441. executeOnAnimationCondition(EAnimationEvents::HIT, true, [=](){
  442. displaySpellHit(spellID, targetedTile);
  443. });
  444. //queuing affect animation
  445. for(auto & elem : sc->affectedCres)
  446. {
  447. auto stack = curInt->cb->battleGetStackByID(elem, false);
  448. assert(stack);
  449. if(stack)
  450. {
  451. executeOnAnimationCondition(EAnimationEvents::HIT, true, [=](){
  452. if (spellID == SpellID::BLOODLUST)
  453. stacksController->addNewAnim( ColorTransformAnimation::bloodlustAnimation(*this, stack, spell));
  454. else if (spellID == SpellID::STONE_GAZE)
  455. stacksController->addNewAnim( ColorTransformAnimation::petrifyAnimation(*this, stack, spell));
  456. else
  457. displaySpellEffect(spellID, stack->getPosition());
  458. });
  459. }
  460. }
  461. for(auto & elem : sc->reflectedCres)
  462. {
  463. auto stack = curInt->cb->battleGetStackByID(elem, false);
  464. assert(stack);
  465. executeOnAnimationCondition(EAnimationEvents::HIT, true, [=](){
  466. effectsController->displayEffect(EBattleEffect::MAGIC_MIRROR, stack->getPosition());
  467. });
  468. }
  469. for(auto & elem : sc->resistedCres)
  470. {
  471. auto stack = curInt->cb->battleGetStackByID(elem, false);
  472. assert(stack);
  473. executeOnAnimationCondition(EAnimationEvents::HIT, true, [=](){
  474. effectsController->displayEffect(EBattleEffect::RESISTANCE, stack->getPosition());
  475. });
  476. }
  477. //mana absorption
  478. if (sc->manaGained > 0)
  479. {
  480. Point leftHero = Point(15, 30) + pos;
  481. Point rightHero = Point(755, 30) + pos;
  482. bool side = sc->side;
  483. executeOnAnimationCondition(EAnimationEvents::AFTER_HIT, true, [=](){
  484. stacksController->addNewAnim(new PointEffectAnimation(*this, "", side ? "SP07_A.DEF" : "SP07_B.DEF", leftHero));
  485. stacksController->addNewAnim(new PointEffectAnimation(*this, "", side ? "SP07_B.DEF" : "SP07_A.DEF", rightHero));
  486. });
  487. }
  488. }
  489. void BattleInterface::battleStacksEffectsSet(const SetStackEffect & sse)
  490. {
  491. if(stacksController->getActiveStack() != nullptr)
  492. fieldController->redrawBackgroundWithHexes();
  493. }
  494. void BattleInterface::setHeroAnimation(ui8 side, EHeroAnimType phase)
  495. {
  496. if(side == BattleSide::ATTACKER)
  497. {
  498. if(attackingHero)
  499. attackingHero->setPhase(phase);
  500. }
  501. else
  502. {
  503. if(defendingHero)
  504. defendingHero->setPhase(phase);
  505. }
  506. }
  507. void BattleInterface::displayBattleLog(const std::vector<MetaString> & battleLog)
  508. {
  509. for(const auto & line : battleLog)
  510. {
  511. std::string formatted = line.toString();
  512. boost::algorithm::trim(formatted);
  513. if(!controlPanel->console->addText(formatted))
  514. logGlobal->warn("Too long battle log line");
  515. }
  516. }
  517. void BattleInterface::displaySpellAnimationQueue(const CSpell::TAnimationQueue & q, BattleHex destinationTile, bool isHit)
  518. {
  519. for(const CSpell::TAnimation & animation : q)
  520. {
  521. if(animation.pause > 0)
  522. stacksController->addNewAnim(new DummyAnimation(*this, animation.pause));
  523. else
  524. {
  525. int flags = 0;
  526. if (isHit)
  527. flags |= PointEffectAnimation::FORCE_ON_TOP;
  528. if (animation.verticalPosition == VerticalPosition::BOTTOM)
  529. flags |= PointEffectAnimation::ALIGN_TO_BOTTOM;
  530. if (!destinationTile.isValid())
  531. flags |= PointEffectAnimation::SCREEN_FILL;
  532. if (!destinationTile.isValid())
  533. stacksController->addNewAnim(new PointEffectAnimation(*this, "", animation.resourceName, flags));
  534. else
  535. stacksController->addNewAnim(new PointEffectAnimation(*this, "", animation.resourceName, destinationTile, flags));
  536. }
  537. }
  538. }
  539. void BattleInterface::displaySpellCast(SpellID spellID, BattleHex destinationTile)
  540. {
  541. const CSpell * spell = spellID.toSpell();
  542. if(spell)
  543. displaySpellAnimationQueue(spell->animationInfo.cast, destinationTile, false);
  544. }
  545. void BattleInterface::displaySpellEffect(SpellID spellID, BattleHex destinationTile)
  546. {
  547. const CSpell *spell = spellID.toSpell();
  548. if(spell)
  549. displaySpellAnimationQueue(spell->animationInfo.affect, destinationTile, false);
  550. }
  551. void BattleInterface::displaySpellHit(SpellID spellID, BattleHex destinationTile)
  552. {
  553. const CSpell * spell = spellID.toSpell();
  554. if(spell)
  555. displaySpellAnimationQueue(spell->animationInfo.hit, destinationTile, true);
  556. }
  557. void BattleInterface::setAnimSpeed(int set)
  558. {
  559. Settings speed = settings.write["battle"]["animationSpeed"];
  560. speed->Float() = float(set) / 100;
  561. }
  562. int BattleInterface::getAnimSpeed() const
  563. {
  564. if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-battle-speed"].isNull())
  565. return static_cast<int>(vstd::round(settings["session"]["spectate-battle-speed"].Float() *100));
  566. return static_cast<int>(vstd::round(settings["battle"]["animationSpeed"].Float() *100));
  567. }
  568. CPlayerInterface *BattleInterface::getCurrentPlayerInterface() const
  569. {
  570. return curInt.get();
  571. }
  572. void BattleInterface::trySetActivePlayer( PlayerColor player )
  573. {
  574. if ( attackerInt && attackerInt->playerID == player )
  575. curInt = attackerInt;
  576. if ( defenderInt && defenderInt->playerID == player )
  577. curInt = defenderInt;
  578. }
  579. void BattleInterface::activateStack()
  580. {
  581. stacksController->activateStack();
  582. const CStack * s = stacksController->getActiveStack();
  583. if(!s)
  584. return;
  585. myTurn = true;
  586. queue->update();
  587. fieldController->redrawBackgroundWithHexes();
  588. actionsController->activateStack();
  589. GH.fakeMouseMove();
  590. }
  591. void BattleInterface::endAction(const BattleAction* action)
  592. {
  593. const CStack *stack = curInt->cb->battleGetStackByID(action->stackNumber);
  594. stacksController->endAction(action);
  595. queue->update();
  596. //stack ended movement in tactics phase -> select the next one
  597. if (tacticsMode)
  598. tacticNextStack(stack);
  599. //we have activated next stack after sending request that has been just realized -> blockmap due to movement has changed
  600. if(action->actionType == EActionType::HERO_SPELL)
  601. fieldController->redrawBackgroundWithHexes();
  602. }
  603. void BattleInterface::hideQueue()
  604. {
  605. Settings showQueue = settings.write["battle"]["showQueue"];
  606. showQueue->Bool() = false;
  607. queue->deactivate();
  608. if (!queue->embedded)
  609. {
  610. moveBy(Point(0, -queue->pos.h / 2));
  611. GH.totalRedraw();
  612. }
  613. }
  614. void BattleInterface::showQueue()
  615. {
  616. Settings showQueue = settings.write["battle"]["showQueue"];
  617. showQueue->Bool() = true;
  618. queue->activate();
  619. if (!queue->embedded)
  620. {
  621. moveBy(Point(0, +queue->pos.h / 2));
  622. GH.totalRedraw();
  623. }
  624. }
  625. void BattleInterface::startAction(const BattleAction* action)
  626. {
  627. if(action->actionType == EActionType::END_TACTIC_PHASE)
  628. {
  629. controlPanel->tacticPhaseEnded();
  630. return;
  631. }
  632. const CStack *stack = curInt->cb->battleGetStackByID(action->stackNumber);
  633. if (stack)
  634. {
  635. queue->update();
  636. }
  637. else
  638. {
  639. assert(action->actionType == EActionType::HERO_SPELL); //only cast spell is valid action without acting stack number
  640. }
  641. stacksController->startAction(action);
  642. redraw(); // redraw after deactivation, including proper handling of hovered hexes
  643. if(action->actionType == EActionType::HERO_SPELL) //when hero casts spell
  644. return;
  645. if (!stack)
  646. {
  647. logGlobal->error("Something wrong with stackNumber in actionStarted. Stack number: %d", action->stackNumber);
  648. return;
  649. }
  650. effectsController->startAction(action);
  651. }
  652. void BattleInterface::tacticPhaseEnd()
  653. {
  654. stacksController->setActiveStack(nullptr);
  655. tacticsMode = false;
  656. }
  657. static bool immobile(const CStack *s)
  658. {
  659. return !s->Speed(0, true); //should bound stacks be immobile?
  660. }
  661. void BattleInterface::tacticNextStack(const CStack * current)
  662. {
  663. if (!current)
  664. current = stacksController->getActiveStack();
  665. //no switching stacks when the current one is moving
  666. assert(getAnimationCondition(EAnimationEvents::ACTION) == false);
  667. waitForAnimationCondition(EAnimationEvents::ACTION, false);
  668. TStacks stacksOfMine = tacticianInterface->cb->battleGetStacks(CBattleCallback::ONLY_MINE);
  669. vstd::erase_if (stacksOfMine, &immobile);
  670. if (stacksOfMine.empty())
  671. {
  672. tacticPhaseEnd();
  673. return;
  674. }
  675. auto it = vstd::find(stacksOfMine, current);
  676. if (it != stacksOfMine.end() && ++it != stacksOfMine.end())
  677. stackActivated(*it);
  678. else
  679. stackActivated(stacksOfMine.front());
  680. }
  681. void BattleInterface::obstaclePlaced(const std::vector<std::shared_ptr<const CObstacleInstance>> oi)
  682. {
  683. obstacleController->obstaclePlaced(oi);
  684. }
  685. const CGHeroInstance *BattleInterface::currentHero() const
  686. {
  687. if (attackingHeroInstance && attackingHeroInstance->tempOwner == curInt->playerID)
  688. return attackingHeroInstance;
  689. if (defendingHeroInstance && defendingHeroInstance->tempOwner == curInt->playerID)
  690. return defendingHeroInstance;
  691. return nullptr;
  692. }
  693. InfoAboutHero BattleInterface::enemyHero() const
  694. {
  695. InfoAboutHero ret;
  696. if (attackingHeroInstance->tempOwner == curInt->playerID)
  697. curInt->cb->getHeroInfo(defendingHeroInstance, ret);
  698. else
  699. curInt->cb->getHeroInfo(attackingHeroInstance, ret);
  700. return ret;
  701. }
  702. void BattleInterface::requestAutofightingAIToTakeAction()
  703. {
  704. assert(curInt->isAutoFightOn);
  705. boost::thread aiThread([&]()
  706. {
  707. auto ba = make_unique<BattleAction>(curInt->autofightingAI->activeStack(stacksController->getActiveStack()));
  708. if(curInt->cb->battleIsFinished())
  709. {
  710. return; // battle finished with spellcast
  711. }
  712. if (curInt->isAutoFightOn)
  713. {
  714. if (tacticsMode)
  715. {
  716. // Always end tactics mode. Player interface is blocked currently, so it's not possible that
  717. // the AI can take any action except end tactics phase (AI actions won't be triggered)
  718. //TODO implement the possibility that the AI will be triggered for further actions
  719. //TODO any solution to merge tactics phase & normal phase in the way it is handled by the player and battle interface?
  720. stacksController->setActiveStack(nullptr);
  721. tacticsMode = false;
  722. }
  723. else
  724. {
  725. givenCommand.setn(ba.release());
  726. }
  727. }
  728. else
  729. {
  730. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  731. activateStack();
  732. }
  733. });
  734. aiThread.detach();
  735. }
  736. void BattleInterface::showAll(SDL_Surface *to)
  737. {
  738. show(to);
  739. }
  740. void BattleInterface::show(SDL_Surface *to)
  741. {
  742. Canvas canvas(to);
  743. assert(to);
  744. SDL_Rect buf;
  745. SDL_GetClipRect(to, &buf);
  746. SDL_SetClipRect(to, &pos);
  747. ++animCount;
  748. fieldController->renderBattlefield(canvas);
  749. stacksController->update();
  750. SDL_SetClipRect(to, &buf); //restoring previous clip_rect
  751. showInterface(to);
  752. }
  753. void BattleInterface::collectRenderableObjects(BattleRenderer & renderer)
  754. {
  755. if (attackingHero)
  756. {
  757. renderer.insert(EBattleFieldLayer::HEROES, BattleHex(0),[this](BattleRenderer::RendererRef canvas)
  758. {
  759. attackingHero->render(canvas);
  760. });
  761. }
  762. if (defendingHero)
  763. {
  764. renderer.insert(EBattleFieldLayer::HEROES, BattleHex(GameConstants::BFIELD_WIDTH-1),[this](BattleRenderer::RendererRef canvas)
  765. {
  766. defendingHero->render(canvas);
  767. });
  768. }
  769. }
  770. void BattleInterface::showInterface(SDL_Surface * to)
  771. {
  772. //showing in-game console
  773. LOCPLINT->cingconsole->show(to);
  774. controlPanel->showAll(to);
  775. Rect posWithQueue = Rect(pos.x, pos.y, 800, 600);
  776. if (settings["battle"]["showQueue"].Bool())
  777. {
  778. if (!queue->embedded)
  779. {
  780. posWithQueue.y -= queue->pos.h;
  781. posWithQueue.h += queue->pos.h;
  782. }
  783. queue->showAll(to);
  784. }
  785. //printing border around interface
  786. if (screen->w != 800 || screen->h !=600)
  787. {
  788. CMessage::drawBorder(curInt->playerID,to,posWithQueue.w + 28, posWithQueue.h + 28, posWithQueue.x-14, posWithQueue.y-15);
  789. }
  790. }
  791. void BattleInterface::castThisSpell(SpellID spellID)
  792. {
  793. actionsController->castThisSpell(spellID);
  794. }
  795. void BattleInterface::setAnimationCondition( EAnimationEvents event, bool state)
  796. {
  797. logAnim->debug("setAnimationCondition: %d -> %s", static_cast<int>(event), state ? "ON" : "OFF");
  798. size_t index = static_cast<size_t>(event);
  799. animationEvents[index].setn(state);
  800. for (auto it = awaitingEvents.begin(); it != awaitingEvents.end();)
  801. {
  802. if (it->event == event && it->eventState == state)
  803. {
  804. it->action();
  805. it = awaitingEvents.erase(it);
  806. }
  807. else
  808. ++it;
  809. }
  810. }
  811. bool BattleInterface::getAnimationCondition( EAnimationEvents event)
  812. {
  813. size_t index = static_cast<size_t>(event);
  814. return animationEvents[index].get();
  815. }
  816. void BattleInterface::waitForAnimationCondition( EAnimationEvents event, bool state)
  817. {
  818. auto unlockPim = vstd::makeUnlockGuard(*CPlayerInterface::pim);
  819. size_t index = static_cast<size_t>(event);
  820. animationEvents[index].waitUntil(state);
  821. }
  822. void BattleInterface::executeOnAnimationCondition( EAnimationEvents event, bool state, const AwaitingAnimationAction & action)
  823. {
  824. awaitingEvents.push_back({action, event, state});
  825. }