BattleInterface.cpp 26 KB

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