BattleStacksController.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873
  1. /*
  2. * BattleStacksController.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 "BattleStacksController.h"
  12. #include "BattleSiegeController.h"
  13. #include "BattleInterfaceClasses.h"
  14. #include "BattleInterface.h"
  15. #include "BattleActionsController.h"
  16. #include "BattleAnimationClasses.h"
  17. #include "BattleFieldController.h"
  18. #include "BattleEffectsController.h"
  19. #include "BattleProjectileController.h"
  20. #include "BattleControlPanel.h"
  21. #include "BattleRenderer.h"
  22. #include "CreatureAnimation.h"
  23. #include "../CPlayerInterface.h"
  24. #include "../CMusicHandler.h"
  25. #include "../CGameInfo.h"
  26. #include "../gui/CAnimation.h"
  27. #include "../gui/CGuiHandler.h"
  28. #include "../gui/Canvas.h"
  29. #include "../../lib/spells/ISpellMechanics.h"
  30. #include "../../CCallback.h"
  31. #include "../../lib/battle/BattleHex.h"
  32. #include "../../lib/CGameState.h"
  33. #include "../../lib/CStack.h"
  34. #include "../../lib/CondSh.h"
  35. static void onAnimationFinished(const CStack *stack, std::weak_ptr<CreatureAnimation> anim)
  36. {
  37. std::shared_ptr<CreatureAnimation> animation = anim.lock();
  38. if(!animation)
  39. return;
  40. if (!stack->isFrozen() && animation->getType() == ECreatureAnimType::FROZEN)
  41. animation->setType(ECreatureAnimType::HOLDING);
  42. if (animation->isIdle())
  43. {
  44. if (stack->isFrozen())
  45. animation->setType(ECreatureAnimType::FROZEN);
  46. const CCreature *creature = stack->getCreature();
  47. if (animation->framesInGroup(ECreatureAnimType::MOUSEON) > 0)
  48. {
  49. if (CRandomGenerator::getDefault().nextDouble(99.0) < creature->animation.timeBetweenFidgets *10)
  50. animation->playOnce(ECreatureAnimType::MOUSEON);
  51. else
  52. animation->setType(ECreatureAnimType::HOLDING);
  53. }
  54. else
  55. {
  56. animation->setType(ECreatureAnimType::HOLDING);
  57. }
  58. }
  59. // always reset callback
  60. animation->onAnimationReset += std::bind(&onAnimationFinished, stack, anim);
  61. }
  62. BattleStacksController::BattleStacksController(BattleInterface & owner):
  63. owner(owner),
  64. activeStack(nullptr),
  65. stackToActivate(nullptr),
  66. selectedStack(nullptr),
  67. stackCanCastSpell(false),
  68. creatureSpellToCast(uint32_t(-1)),
  69. animIDhelper(0)
  70. {
  71. //preparing graphics for displaying amounts of creatures
  72. amountNormal = IImage::createFromFile("CMNUMWIN.BMP");
  73. amountPositive = IImage::createFromFile("CMNUMWIN.BMP");
  74. amountNegative = IImage::createFromFile("CMNUMWIN.BMP");
  75. amountEffNeutral = IImage::createFromFile("CMNUMWIN.BMP");
  76. static const auto shifterNormal = ColorFilter::genRangeShifter( 0,0,0, 0.6, 0.2, 1.0 );
  77. static const auto shifterPositive = ColorFilter::genRangeShifter( 0,0,0, 0.2, 1.0, 0.2 );
  78. static const auto shifterNegative = ColorFilter::genRangeShifter( 0,0,0, 1.0, 0.2, 0.2 );
  79. static const auto shifterNeutral = ColorFilter::genRangeShifter( 0,0,0, 1.0, 1.0, 0.2 );
  80. amountNormal->adjustPalette(shifterNormal);
  81. amountPositive->adjustPalette(shifterPositive);
  82. amountNegative->adjustPalette(shifterNegative);
  83. amountEffNeutral->adjustPalette(shifterNeutral);
  84. //Restore border color {255, 231, 132, 255} to its original state
  85. amountNormal->resetPalette(26);
  86. amountPositive->resetPalette(26);
  87. amountNegative->resetPalette(26);
  88. amountEffNeutral->resetPalette(26);
  89. std::vector<const CStack*> stacks = owner.curInt->cb->battleGetAllStacks(true);
  90. for(const CStack * s : stacks)
  91. {
  92. stackAdded(s, true);
  93. }
  94. }
  95. BattleHex BattleStacksController::getStackCurrentPosition(const CStack * stack) const
  96. {
  97. if ( !stackAnimation.at(stack->ID)->isMoving())
  98. return stack->getPosition();
  99. if (stack->hasBonusOfType(Bonus::FLYING) && stackAnimation.at(stack->ID)->getType() == ECreatureAnimType::MOVING )
  100. return BattleHex::HEX_AFTER_ALL;
  101. for (auto & anim : currentAnimations)
  102. {
  103. // certainly ugly workaround but fixes quite annoying bug
  104. // stack position will be updated only *after* movement is finished
  105. // before this - stack is always at its initial position. Thus we need to find
  106. // its current position. Which can be found only in this class
  107. if (StackMoveAnimation *move = dynamic_cast<StackMoveAnimation*>(anim))
  108. {
  109. if (move->stack == stack)
  110. return std::max(move->prevHex, move->nextHex);
  111. }
  112. }
  113. return stack->getPosition();
  114. }
  115. void BattleStacksController::collectRenderableObjects(BattleRenderer & renderer)
  116. {
  117. auto stacks = owner.curInt->cb->battleGetAllStacks(false);
  118. for (auto stack : stacks)
  119. {
  120. if (stackAnimation.find(stack->ID) == stackAnimation.end()) //e.g. for summoned but not yet handled stacks
  121. continue;
  122. //FIXME: hack to ignore ghost stacks
  123. if ((stackAnimation[stack->ID]->getType() == ECreatureAnimType::DEAD || stackAnimation[stack->ID]->getType() == ECreatureAnimType::HOLDING) && stack->isGhost())
  124. continue;
  125. auto layer = stackAnimation[stack->ID]->isDead() ? EBattleFieldLayer::CORPSES : EBattleFieldLayer::STACKS;
  126. auto location = getStackCurrentPosition(stack);
  127. renderer.insert(layer, location, [this, stack]( BattleRenderer::RendererRef renderer ){
  128. showStack(renderer, stack);
  129. });
  130. if (stackNeedsAmountBox(stack))
  131. {
  132. renderer.insert(EBattleFieldLayer::STACK_AMOUNTS, location, [this, stack]( BattleRenderer::RendererRef renderer ){
  133. showStackAmountBox(renderer, stack);
  134. });
  135. }
  136. }
  137. }
  138. void BattleStacksController::stackReset(const CStack * stack)
  139. {
  140. assert(owner.getAnimationCondition(EAnimationEvents::ACTION) == false);
  141. //reset orientation?
  142. //stackFacingRight[stack->ID] = stack->side == BattleSide::ATTACKER;
  143. auto iter = stackAnimation.find(stack->ID);
  144. if(iter == stackAnimation.end())
  145. {
  146. logGlobal->error("Unit %d have no animation", stack->ID);
  147. return;
  148. }
  149. auto animation = iter->second;
  150. if(stack->alive() && animation->isDeadOrDying())
  151. {
  152. owner.executeOnAnimationCondition(EAnimationEvents::HIT, true, [=]()
  153. {
  154. addNewAnim(new ResurrectionAnimation(owner, stack));
  155. });
  156. }
  157. }
  158. void BattleStacksController::stackAdded(const CStack * stack, bool instant)
  159. {
  160. // Tower shooters have only their upper half visible
  161. static const int turretCreatureAnimationHeight = 225;
  162. stackFacingRight[stack->ID] = stack->side == BattleSide::ATTACKER; // must be set before getting stack position
  163. Point coords = getStackPositionAtHex(stack->getPosition(), stack);
  164. if(stack->initialPosition < 0) //turret
  165. {
  166. assert(owner.siegeController);
  167. const CCreature *turretCreature = owner.siegeController->getTurretCreature();
  168. stackAnimation[stack->ID] = AnimationControls::getAnimation(turretCreature);
  169. stackAnimation[stack->ID]->pos.h = turretCreatureAnimationHeight;
  170. coords = owner.siegeController->getTurretCreaturePosition(stack->initialPosition);
  171. }
  172. else
  173. {
  174. stackAnimation[stack->ID] = AnimationControls::getAnimation(stack->getCreature());
  175. stackAnimation[stack->ID]->onAnimationReset += std::bind(&onAnimationFinished, stack, stackAnimation[stack->ID]);
  176. stackAnimation[stack->ID]->pos.h = stackAnimation[stack->ID]->getHeight();
  177. }
  178. stackAnimation[stack->ID]->pos.x = coords.x;
  179. stackAnimation[stack->ID]->pos.y = coords.y;
  180. stackAnimation[stack->ID]->pos.w = stackAnimation[stack->ID]->getWidth();
  181. stackAnimation[stack->ID]->setType(ECreatureAnimType::HOLDING);
  182. if (!instant)
  183. {
  184. // immediately make stack transparent, giving correct shifter time to start
  185. auto shifterFade = ColorFilter::genAlphaShifter(0);
  186. setStackColorFilter(shifterFade, stack, nullptr, true);
  187. owner.executeOnAnimationCondition(EAnimationEvents::HIT, true, [=]()
  188. {
  189. addNewAnim(ColorTransformAnimation::fadeInAnimation(owner, stack));
  190. if (stack->isClone())
  191. addNewAnim(ColorTransformAnimation::cloneAnimation(owner, stack, SpellID(SpellID::CLONE).toSpell()));
  192. });
  193. }
  194. }
  195. void BattleStacksController::setActiveStack(const CStack *stack)
  196. {
  197. if (activeStack) // update UI
  198. stackAnimation[activeStack->ID]->setBorderColor(AnimationControls::getNoBorder());
  199. activeStack = stack;
  200. if (activeStack) // update UI
  201. stackAnimation[activeStack->ID]->setBorderColor(AnimationControls::getGoldBorder());
  202. owner.controlPanel->blockUI(activeStack == nullptr);
  203. }
  204. bool BattleStacksController::stackNeedsAmountBox(const CStack * stack) const
  205. {
  206. BattleHex currentActionTarget;
  207. if(owner.curInt->curAction)
  208. {
  209. auto target = owner.curInt->curAction->getTarget(owner.curInt->cb.get());
  210. if(!target.empty())
  211. currentActionTarget = target.at(0).hexValue;
  212. }
  213. if(stack->hasBonusOfType(Bonus::SIEGE_WEAPON) && stack->getCount() == 1) //do not show box for singular war machines, stacked war machines with box shown are supported as extension feature
  214. return false;
  215. if(!stack->alive())
  216. return false;
  217. if(stack->getCount() == 0) //hide box when target is going to die anyway - do not display "0 creatures"
  218. return false;
  219. for(auto anim : currentAnimations) //no matter what other conditions below are, hide box when creature is playing hit animation
  220. {
  221. auto hitAnimation = dynamic_cast<DefenceAnimation*>(anim);
  222. if(hitAnimation && (hitAnimation->stack->ID == stack->ID))
  223. return false;
  224. }
  225. if(owner.curInt->curAction)
  226. {
  227. if(owner.curInt->curAction->stackNumber == stack->ID) //stack is currently taking action (is not a target of another creature's action etc)
  228. {
  229. if(owner.curInt->curAction->actionType == EActionType::WALK || owner.curInt->curAction->actionType == EActionType::SHOOT) //hide when stack walks or shoots
  230. return false;
  231. else if(owner.curInt->curAction->actionType == EActionType::WALK_AND_ATTACK && currentActionTarget != stack->getPosition()) //when attacking, hide until walk phase finished
  232. return false;
  233. }
  234. if(owner.curInt->curAction->actionType == EActionType::SHOOT && currentActionTarget == stack->getPosition()) //hide if we are ranged attack target
  235. return false;
  236. }
  237. return true;
  238. }
  239. std::shared_ptr<IImage> BattleStacksController::getStackAmountBox(const CStack * stack)
  240. {
  241. std::vector<si32> activeSpells = stack->activeSpells();
  242. if ( activeSpells.empty())
  243. return amountNormal;
  244. int effectsPositivness = 0;
  245. for ( auto const & spellID : activeSpells)
  246. effectsPositivness += CGI->spellh->objects.at(spellID)->positiveness;
  247. if (effectsPositivness > 0)
  248. return amountPositive;
  249. if (effectsPositivness < 0)
  250. return amountNegative;
  251. return amountEffNeutral;
  252. }
  253. void BattleStacksController::showStackAmountBox(Canvas & canvas, const CStack * stack)
  254. {
  255. //blitting amount background box
  256. auto amountBG = getStackAmountBox(stack);
  257. const int sideShift = stack->side == BattleSide::ATTACKER ? 1 : -1;
  258. const int reverseSideShift = stack->side == BattleSide::ATTACKER ? -1 : 1;
  259. const BattleHex nextPos = stack->getPosition() + sideShift;
  260. const bool edge = stack->getPosition() % GameConstants::BFIELD_WIDTH == (stack->side == BattleSide::ATTACKER ? GameConstants::BFIELD_WIDTH - 2 : 1);
  261. const bool moveInside = !edge && !owner.fieldController->stackCountOutsideHex(nextPos);
  262. int xAdd = (stack->side == BattleSide::ATTACKER ? 220 : 202) +
  263. (stack->doubleWide() ? 44 : 0) * sideShift +
  264. (moveInside ? amountBG->width() + 10 : 0) * reverseSideShift;
  265. int yAdd = 260 + ((stack->side == BattleSide::ATTACKER || moveInside) ? 0 : -15);
  266. canvas.draw(amountBG, stackAnimation[stack->ID]->pos.topLeft() + Point(xAdd, yAdd));
  267. //blitting amount
  268. Point textPos = stackAnimation[stack->ID]->pos.topLeft() + amountBG->dimensions()/2 + Point(xAdd, yAdd);
  269. canvas.drawText(textPos, EFonts::FONT_TINY, Colors::WHITE, ETextAlignment::CENTER, makeNumberShort(stack->getCount()));
  270. }
  271. void BattleStacksController::showStack(Canvas & canvas, const CStack * stack)
  272. {
  273. ColorFilter fullFilter = ColorFilter::genEmptyShifter();
  274. for (auto const & filter : stackFilterEffects)
  275. {
  276. if (filter.target == stack)
  277. fullFilter = ColorFilter::genCombined(fullFilter, filter.effect);
  278. }
  279. bool stackHasProjectile = owner.projectilesController->hasActiveProjectile(stack, true);
  280. if (stackHasProjectile)
  281. stackAnimation[stack->ID]->pause();
  282. else
  283. stackAnimation[stack->ID]->play();
  284. stackAnimation[stack->ID]->nextFrame(canvas, fullFilter, facingRight(stack)); // do actual blit
  285. stackAnimation[stack->ID]->incrementFrame(float(GH.mainFPSmng->getElapsedMilliseconds()) / 1000);
  286. }
  287. void BattleStacksController::update()
  288. {
  289. updateHoveredStacks();
  290. updateBattleAnimations();
  291. }
  292. void BattleStacksController::updateBattleAnimations()
  293. {
  294. for (auto & elem : currentAnimations)
  295. {
  296. if (!elem)
  297. continue;
  298. if (elem->isInitialized())
  299. elem->nextFrame();
  300. else
  301. elem->tryInitialize();
  302. }
  303. bool hadAnimations = !currentAnimations.empty();
  304. vstd::erase(currentAnimations, nullptr);
  305. if (hadAnimations && currentAnimations.empty())
  306. {
  307. //anims ended
  308. owner.setAnimationCondition(EAnimationEvents::ACTION, false);
  309. }
  310. }
  311. void BattleStacksController::addNewAnim(BattleAnimation *anim)
  312. {
  313. currentAnimations.push_back(anim);
  314. owner.setAnimationCondition(EAnimationEvents::ACTION, true);
  315. }
  316. void BattleStacksController::stackRemoved(uint32_t stackID)
  317. {
  318. if (getActiveStack() && getActiveStack()->ID == stackID)
  319. {
  320. BattleAction *action = new BattleAction();
  321. action->side = owner.defendingHeroInstance ? (owner.curInt->playerID == owner.defendingHeroInstance->tempOwner) : false;
  322. action->actionType = EActionType::CANCEL;
  323. action->stackNumber = getActiveStack()->ID;
  324. owner.givenCommand.setn(action);
  325. setActiveStack(nullptr);
  326. }
  327. }
  328. void BattleStacksController::stacksAreAttacked(std::vector<StackAttackedInfo> attackedInfos)
  329. {
  330. owner.executeOnAnimationCondition(EAnimationEvents::HIT, true, [=](){
  331. // remove any potentially erased petrification effect
  332. removeExpiredColorFilters();
  333. });
  334. for(auto & attackedInfo : attackedInfos)
  335. {
  336. if (!attackedInfo.attacker)
  337. continue;
  338. bool needsReverse =
  339. owner.curInt->cb->isToReverse(
  340. attackedInfo.defender->getPosition(),
  341. attackedInfo.attacker->getPosition(),
  342. facingRight(attackedInfo.defender),
  343. attackedInfo.attacker->doubleWide(),
  344. facingRight(attackedInfo.attacker));
  345. if (needsReverse)
  346. {
  347. owner.executeOnAnimationCondition(EAnimationEvents::MOVEMENT, true, [=]()
  348. {
  349. addNewAnim(new ReverseAnimation(owner, attackedInfo.defender, attackedInfo.defender->getPosition()));
  350. });
  351. }
  352. }
  353. for(auto & attackedInfo : attackedInfos)
  354. {
  355. bool useDeathAnim = attackedInfo.killed;
  356. bool useDefenceAnim = attackedInfo.defender->defendingAnim && !attackedInfo.indirectAttack && !attackedInfo.killed;
  357. EAnimationEvents usedEvent = useDefenceAnim ? EAnimationEvents::ATTACK : EAnimationEvents::HIT;
  358. owner.executeOnAnimationCondition(usedEvent, true, [=]()
  359. {
  360. if (useDeathAnim)
  361. addNewAnim(new DeathAnimation(owner, attackedInfo.defender, attackedInfo.indirectAttack));
  362. else if(useDefenceAnim)
  363. addNewAnim(new DefenceAnimation(owner, attackedInfo.defender));
  364. else
  365. addNewAnim(new HittedAnimation(owner, attackedInfo.defender));
  366. if (attackedInfo.fireShield)
  367. owner.effectsController->displayEffect(EBattleEffect::FIRE_SHIELD, attackedInfo.attacker->getPosition());
  368. if (attackedInfo.spellEffect != SpellID::NONE)
  369. owner.displaySpellEffect(attackedInfo.spellEffect, attackedInfo.defender->getPosition());
  370. });
  371. }
  372. for (auto & attackedInfo : attackedInfos)
  373. {
  374. if (attackedInfo.rebirth)
  375. {
  376. owner.executeOnAnimationCondition(EAnimationEvents::AFTER_HIT, true, [=](){
  377. owner.effectsController->displayEffect(EBattleEffect::RESURRECT, soundBase::RESURECT, attackedInfo.defender->getPosition());
  378. addNewAnim(new ResurrectionAnimation(owner, attackedInfo.defender));
  379. });
  380. }
  381. if (attackedInfo.killed && attackedInfo.defender->summoned)
  382. {
  383. owner.executeOnAnimationCondition(EAnimationEvents::AFTER_HIT, true, [=](){
  384. addNewAnim(ColorTransformAnimation::fadeOutAnimation(owner, attackedInfo.defender));
  385. stackRemoved(attackedInfo.defender->ID);
  386. });
  387. }
  388. }
  389. executeAttackAnimations();
  390. }
  391. void BattleStacksController::stackMoved(const CStack *stack, std::vector<BattleHex> destHex, int distance)
  392. {
  393. assert(destHex.size() > 0);
  394. assert(owner.getAnimationCondition(EAnimationEvents::ACTION) == false);
  395. if(shouldRotate(stack, stack->getPosition(), destHex[0]))
  396. {
  397. addNewAnim(new ReverseAnimation(owner, stack, stack->getPosition()));
  398. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  399. }
  400. addNewAnim(new MovementStartAnimation(owner, stack));
  401. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  402. addNewAnim(new MovementAnimation(owner, stack, destHex, distance));
  403. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  404. addNewAnim(new MovementEndAnimation(owner, stack, destHex.back()));
  405. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  406. }
  407. void BattleStacksController::stackAttacking( const StackAttackInfo & info )
  408. {
  409. assert(owner.getAnimationCondition(EAnimationEvents::ACTION) == false);
  410. bool needsReverse =
  411. owner.curInt->cb->isToReverse(
  412. info.attacker->getPosition(),
  413. info.defender->getPosition(),
  414. facingRight(info.attacker),
  415. info.attacker->doubleWide(),
  416. facingRight(info.defender));
  417. auto attacker = info.attacker;
  418. auto defender = info.defender;
  419. auto tile = info.tile;
  420. auto spellEffect = info.spellEffect;
  421. auto multiAttack = !info.secondaryDefender.empty();
  422. if (needsReverse)
  423. {
  424. owner.executeOnAnimationCondition(EAnimationEvents::MOVEMENT, true, [=]()
  425. {
  426. addNewAnim(new ReverseAnimation(owner, attacker, attacker->getPosition()));
  427. });
  428. }
  429. if(info.lucky)
  430. {
  431. owner.executeOnAnimationCondition(EAnimationEvents::BEFORE_HIT, true, [=]() {
  432. owner.controlPanel->console->addText(info.attacker->formatGeneralMessage(-45));
  433. owner.effectsController->displayEffect(EBattleEffect::GOOD_LUCK, soundBase::GOODLUCK, attacker->getPosition());
  434. });
  435. }
  436. if(info.unlucky)
  437. {
  438. owner.executeOnAnimationCondition(EAnimationEvents::BEFORE_HIT, true, [=]() {
  439. owner.controlPanel->console->addText(info.attacker->formatGeneralMessage(-44));
  440. owner.effectsController->displayEffect(EBattleEffect::BAD_LUCK, soundBase::BADLUCK, attacker->getPosition());
  441. });
  442. }
  443. if(info.deathBlow)
  444. {
  445. owner.executeOnAnimationCondition(EAnimationEvents::BEFORE_HIT, true, [=]() {
  446. owner.controlPanel->console->addText(info.attacker->formatGeneralMessage(365));
  447. owner.effectsController->displayEffect(EBattleEffect::DEATH_BLOW, soundBase::deathBlow, defender->getPosition());
  448. });
  449. for(auto elem : info.secondaryDefender)
  450. {
  451. owner.executeOnAnimationCondition(EAnimationEvents::BEFORE_HIT, true, [=]() {
  452. owner.effectsController->displayEffect(EBattleEffect::DEATH_BLOW, elem->getPosition());
  453. });
  454. }
  455. }
  456. owner.executeOnAnimationCondition(EAnimationEvents::ATTACK, true, [=]()
  457. {
  458. if (info.indirectAttack)
  459. {
  460. addNewAnim(new ShootingAnimation(owner, attacker, tile, defender));
  461. }
  462. else
  463. {
  464. addNewAnim(new MeleeAttackAnimation(owner, attacker, tile, defender, multiAttack));
  465. }
  466. });
  467. if (info.spellEffect != SpellID::NONE)
  468. {
  469. owner.executeOnAnimationCondition(EAnimationEvents::HIT, true, [=]()
  470. {
  471. owner.displaySpellHit(spellEffect, tile);
  472. });
  473. }
  474. if (info.lifeDrain)
  475. {
  476. owner.executeOnAnimationCondition(EAnimationEvents::AFTER_HIT, true, [=]()
  477. {
  478. owner.effectsController->displayEffect(EBattleEffect::DRAIN_LIFE, soundBase::DRAINLIF, attacker->getPosition());
  479. });
  480. }
  481. //return, animation playback will be handled by stacksAreAttacked
  482. }
  483. void BattleStacksController::executeAttackAnimations()
  484. {
  485. owner.setAnimationCondition(EAnimationEvents::MOVEMENT, true);
  486. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  487. owner.setAnimationCondition(EAnimationEvents::MOVEMENT, false);
  488. owner.setAnimationCondition(EAnimationEvents::BEFORE_HIT, true);
  489. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  490. owner.setAnimationCondition(EAnimationEvents::BEFORE_HIT, false);
  491. owner.setAnimationCondition(EAnimationEvents::ATTACK, true);
  492. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  493. owner.setAnimationCondition(EAnimationEvents::ATTACK, false);
  494. // Note that HIT event can also be emitted by attack animation
  495. owner.setAnimationCondition(EAnimationEvents::HIT, true);
  496. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  497. owner.setAnimationCondition(EAnimationEvents::HIT, false);
  498. owner.setAnimationCondition(EAnimationEvents::AFTER_HIT, true);
  499. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  500. owner.setAnimationCondition(EAnimationEvents::AFTER_HIT, false);
  501. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  502. }
  503. bool BattleStacksController::shouldRotate(const CStack * stack, const BattleHex & oldPos, const BattleHex & nextHex) const
  504. {
  505. Point begPosition = getStackPositionAtHex(oldPos,stack);
  506. Point endPosition = getStackPositionAtHex(nextHex, stack);
  507. if((begPosition.x > endPosition.x) && facingRight(stack))
  508. return true;
  509. else if((begPosition.x < endPosition.x) && !facingRight(stack))
  510. return true;
  511. return false;
  512. }
  513. void BattleStacksController::endAction(const BattleAction* action)
  514. {
  515. assert(owner.getAnimationCondition(EAnimationEvents::ACTION) == false);
  516. //check if we should reverse stacks
  517. TStacks stacks = owner.curInt->cb->battleGetStacks(CBattleCallback::MINE_AND_ENEMY);
  518. for (const CStack *s : stacks)
  519. {
  520. bool shouldFaceRight = s && s->side == BattleSide::ATTACKER;
  521. if (s && facingRight(s) != shouldFaceRight && s->alive() && stackAnimation[s->ID]->isIdle())
  522. {
  523. addNewAnim(new ReverseAnimation(owner, s, s->getPosition()));
  524. }
  525. }
  526. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  527. //Ensure that all animation flags were reset
  528. assert(owner.getAnimationCondition(EAnimationEvents::OPENING) == false);
  529. assert(owner.getAnimationCondition(EAnimationEvents::ACTION) == false);
  530. assert(owner.getAnimationCondition(EAnimationEvents::MOVEMENT) == false);
  531. assert(owner.getAnimationCondition(EAnimationEvents::ATTACK) == false);
  532. assert(owner.getAnimationCondition(EAnimationEvents::HIT) == false);
  533. assert(owner.getAnimationCondition(EAnimationEvents::PROJECTILES) == false);
  534. owner.controlPanel->blockUI(activeStack == nullptr);
  535. removeExpiredColorFilters();
  536. }
  537. void BattleStacksController::startAction(const BattleAction* action)
  538. {
  539. removeExpiredColorFilters();
  540. }
  541. void BattleStacksController::stackActivated(const CStack *stack) //TODO: check it all before game state is changed due to abilities
  542. {
  543. stackToActivate = stack;
  544. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  545. owner.activateStack();
  546. }
  547. void BattleStacksController::activateStack() //TODO: check it all before game state is changed due to abilities
  548. {
  549. if ( !currentAnimations.empty())
  550. return;
  551. if ( !stackToActivate)
  552. return;
  553. owner.trySetActivePlayer(stackToActivate->owner);
  554. setActiveStack(stackToActivate);
  555. stackToActivate = nullptr;
  556. const CStack * s = getActiveStack();
  557. if(!s)
  558. return;
  559. //set casting flag to true if creature can use it to not check it every time
  560. const auto spellcaster = s->getBonusLocalFirst(Selector::type()(Bonus::SPELLCASTER));
  561. const auto randomSpellcaster = s->getBonusLocalFirst(Selector::type()(Bonus::RANDOM_SPELLCASTER));
  562. if(s->canCast() && (spellcaster || randomSpellcaster))
  563. {
  564. stackCanCastSpell = true;
  565. if(randomSpellcaster)
  566. creatureSpellToCast = -1; //spell will be set later on cast
  567. else
  568. creatureSpellToCast = owner.curInt->cb->battleGetRandomStackSpell(CRandomGenerator::getDefault(), s, CBattleInfoCallback::RANDOM_AIMED); //faerie dragon can cast only one spell until their next move
  569. //TODO: what if creature can cast BOTH random genie spell and aimed spell?
  570. //TODO: faerie dragon type spell should be selected by server
  571. }
  572. else
  573. {
  574. stackCanCastSpell = false;
  575. creatureSpellToCast = -1;
  576. }
  577. }
  578. void BattleStacksController::setSelectedStack(const CStack *stack)
  579. {
  580. selectedStack = stack;
  581. }
  582. const CStack* BattleStacksController::getSelectedStack() const
  583. {
  584. return selectedStack;
  585. }
  586. const CStack* BattleStacksController::getActiveStack() const
  587. {
  588. return activeStack;
  589. }
  590. bool BattleStacksController::facingRight(const CStack * stack) const
  591. {
  592. return stackFacingRight.at(stack->ID);
  593. }
  594. bool BattleStacksController::activeStackSpellcaster()
  595. {
  596. return stackCanCastSpell;
  597. }
  598. SpellID BattleStacksController::activeStackSpellToCast()
  599. {
  600. if (!stackCanCastSpell)
  601. return SpellID::NONE;
  602. return SpellID(creatureSpellToCast);
  603. }
  604. Point BattleStacksController::getStackPositionAtHex(BattleHex hexNum, const CStack * stack) const
  605. {
  606. Point ret(-500, -500); //returned value
  607. if(stack && stack->initialPosition < 0) //creatures in turrets
  608. return owner.siegeController->getTurretCreaturePosition(stack->initialPosition);
  609. static const Point basePos(-190, -139); // position of creature in topleft corner
  610. static const int imageShiftX = 30; // X offset to base pos for facing right stacks, negative for facing left
  611. ret.x = basePos.x + 22 * ( (hexNum.getY() + 1)%2 ) + 44 * hexNum.getX();
  612. ret.y = basePos.y + 42 * hexNum.getY();
  613. if (stack)
  614. {
  615. if(facingRight(stack))
  616. ret.x += imageShiftX;
  617. else
  618. ret.x -= imageShiftX;
  619. //shifting position for double - hex creatures
  620. if(stack->doubleWide())
  621. {
  622. if(stack->side == BattleSide::ATTACKER)
  623. {
  624. if(facingRight(stack))
  625. ret.x -= 44;
  626. }
  627. else
  628. {
  629. if(!facingRight(stack))
  630. ret.x += 44;
  631. }
  632. }
  633. }
  634. //returning
  635. return ret + owner.pos.topLeft();
  636. }
  637. void BattleStacksController::setStackColorFilter(const ColorFilter & effect, const CStack * target, const CSpell * source, bool persistent)
  638. {
  639. for (auto & filter : stackFilterEffects)
  640. {
  641. if (filter.target == target && filter.source == source)
  642. {
  643. filter.effect = effect;
  644. filter.persistent = persistent;
  645. return;
  646. }
  647. }
  648. stackFilterEffects.push_back({ effect, target, source, persistent });
  649. }
  650. void BattleStacksController::removeExpiredColorFilters()
  651. {
  652. vstd::erase_if(stackFilterEffects, [&](const BattleStackFilterEffect & filter)
  653. {
  654. if (filter.persistent)
  655. return false;
  656. if (filter.effect == ColorFilter::genEmptyShifter())
  657. return false;
  658. if (filter.target->hasBonus(Selector::source(Bonus::SPELL_EFFECT, filter.source->id)))
  659. return false;
  660. return true;
  661. });
  662. }
  663. void BattleStacksController::updateHoveredStacks()
  664. {
  665. auto newStacks = selectHoveredStacks();
  666. for (auto const * stack : mouseHoveredStacks)
  667. {
  668. if (vstd::contains(newStacks, stack))
  669. continue;
  670. if (stack == activeStack)
  671. stackAnimation[stack->ID]->setBorderColor(AnimationControls::getGoldBorder());
  672. else
  673. stackAnimation[stack->ID]->setBorderColor(AnimationControls::getNoBorder());
  674. }
  675. for (auto const * stack : newStacks)
  676. {
  677. if (vstd::contains(mouseHoveredStacks, stack))
  678. continue;
  679. stackAnimation[stack->ID]->setBorderColor(AnimationControls::getBlueBorder());
  680. if (stackAnimation[stack->ID]->framesInGroup(ECreatureAnimType::MOUSEON) > 0)
  681. stackAnimation[stack->ID]->playOnce(ECreatureAnimType::MOUSEON);
  682. }
  683. mouseHoveredStacks = newStacks;
  684. }
  685. std::vector<const CStack *> BattleStacksController::selectHoveredStacks()
  686. {
  687. auto hoveredHex = owner.fieldController->getHoveredHex();
  688. if (!hoveredHex.isValid())
  689. return {};
  690. const spells::Caster *caster = nullptr;
  691. const CSpell *spell = nullptr;
  692. spells::Mode mode = spells::Mode::HERO;
  693. if(owner.actionsController->spellcastingModeActive())//hero casts spell
  694. {
  695. spell = owner.actionsController->selectedSpell().toSpell();
  696. caster = owner.getActiveHero();
  697. }
  698. else if(owner.stacksController->activeStackSpellToCast() != SpellID::NONE)//stack casts spell
  699. {
  700. spell = SpellID(owner.stacksController->activeStackSpellToCast()).toSpell();
  701. caster = owner.stacksController->getActiveStack();
  702. mode = spells::Mode::CREATURE_ACTIVE;
  703. }
  704. if(caster && spell) //when casting spell
  705. {
  706. spells::Target target;
  707. target.emplace_back(hoveredHex);
  708. spells::BattleCast event(owner.curInt->cb.get(), caster, mode, spell);
  709. auto mechanics = spell->battleMechanics(&event);
  710. return mechanics->getAffectedStacks(target);
  711. }
  712. if(hoveredHex.isValid())
  713. {
  714. const CStack * const stack = owner.curInt->cb->battleGetStackByPos(hoveredHex, true);
  715. if (stack)
  716. return {stack};
  717. }
  718. return {};
  719. }