CBattleInterface.cpp 28 KB

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