BattleInterface.cpp 27 KB

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