BattleInterface.cpp 26 KB

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