BattleStacksController.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908
  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::summonAnimation(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. // In H3, attacked stack will not reverse on ranged attack
  339. if (attackedInfo.indirectAttack)
  340. continue;
  341. // defender need to face in direction opposited to out attacker
  342. bool needsReverse = shouldAttackFacingRight(attackedInfo.attacker, attackedInfo.defender) == facingRight(attackedInfo.defender);
  343. if (needsReverse && !attackedInfo.defender->isFrozen())
  344. {
  345. owner.executeOnAnimationCondition(EAnimationEvents::MOVEMENT, true, [=]()
  346. {
  347. addNewAnim(new ReverseAnimation(owner, attackedInfo.defender, attackedInfo.defender->getPosition()));
  348. });
  349. }
  350. }
  351. for(auto & attackedInfo : attackedInfos)
  352. {
  353. bool useDeathAnim = attackedInfo.killed;
  354. bool useDefenceAnim = attackedInfo.defender->defendingAnim && !attackedInfo.indirectAttack && !attackedInfo.killed;
  355. EAnimationEvents usedEvent = useDefenceAnim ? EAnimationEvents::ATTACK : EAnimationEvents::HIT;
  356. owner.executeOnAnimationCondition(usedEvent, true, [=]()
  357. {
  358. if (useDeathAnim)
  359. addNewAnim(new DeathAnimation(owner, attackedInfo.defender, attackedInfo.indirectAttack));
  360. else if(useDefenceAnim)
  361. addNewAnim(new DefenceAnimation(owner, attackedInfo.defender));
  362. else
  363. addNewAnim(new HittedAnimation(owner, attackedInfo.defender));
  364. if (attackedInfo.fireShield)
  365. owner.effectsController->displayEffect(EBattleEffect::FIRE_SHIELD, attackedInfo.attacker->getPosition());
  366. if (attackedInfo.spellEffect != SpellID::NONE)
  367. owner.displaySpellEffect(attackedInfo.spellEffect, attackedInfo.defender->getPosition());
  368. });
  369. }
  370. for (auto & attackedInfo : attackedInfos)
  371. {
  372. if (attackedInfo.rebirth)
  373. {
  374. owner.executeOnAnimationCondition(EAnimationEvents::AFTER_HIT, true, [=](){
  375. owner.effectsController->displayEffect(EBattleEffect::RESURRECT, soundBase::RESURECT, attackedInfo.defender->getPosition());
  376. addNewAnim(new ResurrectionAnimation(owner, attackedInfo.defender));
  377. });
  378. }
  379. if (attackedInfo.killed && attackedInfo.defender->summoned)
  380. {
  381. owner.executeOnAnimationCondition(EAnimationEvents::AFTER_HIT, true, [=](){
  382. addNewAnim(ColorTransformAnimation::fadeOutAnimation(owner, attackedInfo.defender));
  383. stackRemoved(attackedInfo.defender->ID);
  384. });
  385. }
  386. }
  387. executeAttackAnimations();
  388. }
  389. void BattleStacksController::stackTeleported(const CStack *stack, std::vector<BattleHex> destHex, int distance)
  390. {
  391. assert(destHex.size() > 0);
  392. assert(owner.getAnimationCondition(EAnimationEvents::ACTION) == false);
  393. owner.executeOnAnimationCondition(EAnimationEvents::HIT, true, [=](){
  394. addNewAnim( ColorTransformAnimation::teleportOutAnimation(owner, stack) );
  395. });
  396. owner.executeOnAnimationCondition(EAnimationEvents::AFTER_HIT, true, [=](){
  397. stackAnimation[stack->ID]->pos.moveTo(getStackPositionAtHex(destHex.back(), stack));
  398. addNewAnim( ColorTransformAnimation::teleportInAnimation(owner, stack) );
  399. });
  400. // animations will be executed by spell
  401. }
  402. void BattleStacksController::stackMoved(const CStack *stack, std::vector<BattleHex> destHex, int distance)
  403. {
  404. assert(destHex.size() > 0);
  405. assert(owner.getAnimationCondition(EAnimationEvents::ACTION) == false);
  406. if(shouldRotate(stack, stack->getPosition(), destHex[0]))
  407. {
  408. addNewAnim(new ReverseAnimation(owner, stack, stack->getPosition()));
  409. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  410. }
  411. addNewAnim(new MovementStartAnimation(owner, stack));
  412. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  413. // if creature can teleport, e.g Devils - skip movement animation
  414. if ( !stack->hasBonus(Selector::typeSubtype(Bonus::FLYING, 1)) )
  415. {
  416. addNewAnim(new MovementAnimation(owner, stack, destHex, distance));
  417. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  418. }
  419. addNewAnim(new MovementEndAnimation(owner, stack, destHex.back()));
  420. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  421. }
  422. bool BattleStacksController::shouldAttackFacingRight(const CStack * attacker, const CStack * defender)
  423. {
  424. bool mustReverse = owner.curInt->cb->isToReverse(
  425. attacker->getPosition(),
  426. attacker,
  427. defender);
  428. if (attacker->side == BattleSide::ATTACKER)
  429. return !mustReverse;
  430. else
  431. return mustReverse;
  432. }
  433. void BattleStacksController::stackAttacking( const StackAttackInfo & info )
  434. {
  435. assert(owner.getAnimationCondition(EAnimationEvents::ACTION) == false);
  436. auto attacker = info.attacker;
  437. auto defender = info.defender;
  438. auto tile = info.tile;
  439. auto spellEffect = info.spellEffect;
  440. auto multiAttack = !info.secondaryDefender.empty();
  441. bool needsReverse = false;
  442. if (info.indirectAttack)
  443. {
  444. needsReverse = shouldRotate(attacker, attacker->position, info.tile);
  445. }
  446. else
  447. {
  448. needsReverse = shouldAttackFacingRight(attacker, defender) != facingRight(attacker);
  449. }
  450. if (needsReverse)
  451. {
  452. owner.executeOnAnimationCondition(EAnimationEvents::MOVEMENT, true, [=]()
  453. {
  454. addNewAnim(new ReverseAnimation(owner, attacker, attacker->getPosition()));
  455. });
  456. }
  457. if(info.lucky)
  458. {
  459. owner.executeOnAnimationCondition(EAnimationEvents::BEFORE_HIT, true, [=]() {
  460. owner.controlPanel->console->addText(info.attacker->formatGeneralMessage(-45));
  461. owner.effectsController->displayEffect(EBattleEffect::GOOD_LUCK, soundBase::GOODLUCK, attacker->getPosition());
  462. });
  463. }
  464. if(info.unlucky)
  465. {
  466. owner.executeOnAnimationCondition(EAnimationEvents::BEFORE_HIT, true, [=]() {
  467. owner.controlPanel->console->addText(info.attacker->formatGeneralMessage(-44));
  468. owner.effectsController->displayEffect(EBattleEffect::BAD_LUCK, soundBase::BADLUCK, attacker->getPosition());
  469. });
  470. }
  471. if(info.deathBlow)
  472. {
  473. owner.executeOnAnimationCondition(EAnimationEvents::BEFORE_HIT, true, [=]() {
  474. owner.controlPanel->console->addText(info.attacker->formatGeneralMessage(365));
  475. owner.effectsController->displayEffect(EBattleEffect::DEATH_BLOW, soundBase::deathBlow, defender->getPosition());
  476. });
  477. for(auto elem : info.secondaryDefender)
  478. {
  479. owner.executeOnAnimationCondition(EAnimationEvents::BEFORE_HIT, true, [=]() {
  480. owner.effectsController->displayEffect(EBattleEffect::DEATH_BLOW, elem->getPosition());
  481. });
  482. }
  483. }
  484. owner.executeOnAnimationCondition(EAnimationEvents::ATTACK, true, [=]()
  485. {
  486. if (info.indirectAttack)
  487. {
  488. addNewAnim(new ShootingAnimation(owner, attacker, tile, defender));
  489. }
  490. else
  491. {
  492. addNewAnim(new MeleeAttackAnimation(owner, attacker, tile, defender, multiAttack));
  493. }
  494. });
  495. if (info.spellEffect != SpellID::NONE)
  496. {
  497. owner.executeOnAnimationCondition(EAnimationEvents::HIT, true, [=]()
  498. {
  499. owner.displaySpellHit(spellEffect, tile);
  500. });
  501. }
  502. if (info.lifeDrain)
  503. {
  504. owner.executeOnAnimationCondition(EAnimationEvents::AFTER_HIT, true, [=]()
  505. {
  506. owner.effectsController->displayEffect(EBattleEffect::DRAIN_LIFE, soundBase::DRAINLIF, attacker->getPosition());
  507. });
  508. }
  509. //return, animation playback will be handled by stacksAreAttacked
  510. }
  511. void BattleStacksController::executeAttackAnimations()
  512. {
  513. owner.setAnimationCondition(EAnimationEvents::MOVEMENT, true);
  514. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  515. owner.setAnimationCondition(EAnimationEvents::MOVEMENT, false);
  516. owner.setAnimationCondition(EAnimationEvents::BEFORE_HIT, true);
  517. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  518. owner.setAnimationCondition(EAnimationEvents::BEFORE_HIT, false);
  519. owner.setAnimationCondition(EAnimationEvents::ATTACK, true);
  520. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  521. owner.setAnimationCondition(EAnimationEvents::ATTACK, false);
  522. // Note that HIT event can also be emitted by attack animation
  523. owner.setAnimationCondition(EAnimationEvents::HIT, true);
  524. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  525. owner.setAnimationCondition(EAnimationEvents::HIT, false);
  526. owner.setAnimationCondition(EAnimationEvents::AFTER_HIT, true);
  527. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  528. owner.setAnimationCondition(EAnimationEvents::AFTER_HIT, false);
  529. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  530. }
  531. bool BattleStacksController::shouldRotate(const CStack * stack, const BattleHex & oldPos, const BattleHex & nextHex) const
  532. {
  533. Point begPosition = getStackPositionAtHex(oldPos,stack);
  534. Point endPosition = getStackPositionAtHex(nextHex, stack);
  535. if((begPosition.x > endPosition.x) && facingRight(stack))
  536. return true;
  537. else if((begPosition.x < endPosition.x) && !facingRight(stack))
  538. return true;
  539. return false;
  540. }
  541. void BattleStacksController::endAction(const BattleAction* action)
  542. {
  543. assert(owner.getAnimationCondition(EAnimationEvents::ACTION) == false);
  544. //check if we should reverse stacks
  545. TStacks stacks = owner.curInt->cb->battleGetStacks(CBattleCallback::MINE_AND_ENEMY);
  546. for (const CStack *s : stacks)
  547. {
  548. bool shouldFaceRight = s && s->side == BattleSide::ATTACKER;
  549. if (s && facingRight(s) != shouldFaceRight && s->alive() && stackAnimation[s->ID]->isIdle())
  550. {
  551. addNewAnim(new ReverseAnimation(owner, s, s->getPosition()));
  552. }
  553. }
  554. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  555. //Ensure that all animation flags were reset
  556. assert(owner.getAnimationCondition(EAnimationEvents::OPENING) == false);
  557. assert(owner.getAnimationCondition(EAnimationEvents::ACTION) == false);
  558. assert(owner.getAnimationCondition(EAnimationEvents::MOVEMENT) == false);
  559. assert(owner.getAnimationCondition(EAnimationEvents::ATTACK) == false);
  560. assert(owner.getAnimationCondition(EAnimationEvents::HIT) == false);
  561. assert(owner.getAnimationCondition(EAnimationEvents::PROJECTILES) == false);
  562. owner.controlPanel->blockUI(activeStack == nullptr);
  563. removeExpiredColorFilters();
  564. }
  565. void BattleStacksController::startAction(const BattleAction* action)
  566. {
  567. removeExpiredColorFilters();
  568. }
  569. void BattleStacksController::stackActivated(const CStack *stack) //TODO: check it all before game state is changed due to abilities
  570. {
  571. stackToActivate = stack;
  572. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  573. owner.activateStack();
  574. }
  575. void BattleStacksController::activateStack() //TODO: check it all before game state is changed due to abilities
  576. {
  577. if ( !currentAnimations.empty())
  578. return;
  579. if ( !stackToActivate)
  580. return;
  581. owner.trySetActivePlayer(stackToActivate->owner);
  582. setActiveStack(stackToActivate);
  583. stackToActivate = nullptr;
  584. const CStack * s = getActiveStack();
  585. if(!s)
  586. return;
  587. //set casting flag to true if creature can use it to not check it every time
  588. const auto spellcaster = s->getBonusLocalFirst(Selector::type()(Bonus::SPELLCASTER));
  589. const auto randomSpellcaster = s->getBonusLocalFirst(Selector::type()(Bonus::RANDOM_SPELLCASTER));
  590. if(s->canCast() && (spellcaster || randomSpellcaster))
  591. {
  592. stackCanCastSpell = true;
  593. if(randomSpellcaster)
  594. creatureSpellToCast = -1; //spell will be set later on cast
  595. else
  596. creatureSpellToCast = owner.curInt->cb->battleGetRandomStackSpell(CRandomGenerator::getDefault(), s, CBattleInfoCallback::RANDOM_AIMED); //faerie dragon can cast only one spell until their next move
  597. //TODO: what if creature can cast BOTH random genie spell and aimed spell?
  598. //TODO: faerie dragon type spell should be selected by server
  599. }
  600. else
  601. {
  602. stackCanCastSpell = false;
  603. creatureSpellToCast = -1;
  604. }
  605. }
  606. void BattleStacksController::setSelectedStack(const CStack *stack)
  607. {
  608. selectedStack = stack;
  609. }
  610. const CStack* BattleStacksController::getSelectedStack() const
  611. {
  612. return selectedStack;
  613. }
  614. const CStack* BattleStacksController::getActiveStack() const
  615. {
  616. return activeStack;
  617. }
  618. bool BattleStacksController::facingRight(const CStack * stack) const
  619. {
  620. return stackFacingRight.at(stack->ID);
  621. }
  622. bool BattleStacksController::activeStackSpellcaster()
  623. {
  624. return stackCanCastSpell;
  625. }
  626. SpellID BattleStacksController::activeStackSpellToCast()
  627. {
  628. if (!stackCanCastSpell)
  629. return SpellID::NONE;
  630. return SpellID(creatureSpellToCast);
  631. }
  632. Point BattleStacksController::getStackPositionAtHex(BattleHex hexNum, const CStack * stack) const
  633. {
  634. Point ret(-500, -500); //returned value
  635. if(stack && stack->initialPosition < 0) //creatures in turrets
  636. return owner.siegeController->getTurretCreaturePosition(stack->initialPosition);
  637. static const Point basePos(-190, -139); // position of creature in topleft corner
  638. static const int imageShiftX = 30; // X offset to base pos for facing right stacks, negative for facing left
  639. ret.x = basePos.x + 22 * ( (hexNum.getY() + 1)%2 ) + 44 * hexNum.getX();
  640. ret.y = basePos.y + 42 * hexNum.getY();
  641. if (stack)
  642. {
  643. if(facingRight(stack))
  644. ret.x += imageShiftX;
  645. else
  646. ret.x -= imageShiftX;
  647. //shifting position for double - hex creatures
  648. if(stack->doubleWide())
  649. {
  650. if(stack->side == BattleSide::ATTACKER)
  651. {
  652. if(facingRight(stack))
  653. ret.x -= 44;
  654. }
  655. else
  656. {
  657. if(!facingRight(stack))
  658. ret.x += 44;
  659. }
  660. }
  661. }
  662. //returning
  663. return ret + owner.pos.topLeft();
  664. }
  665. void BattleStacksController::setStackColorFilter(const ColorFilter & effect, const CStack * target, const CSpell * source, bool persistent)
  666. {
  667. for (auto & filter : stackFilterEffects)
  668. {
  669. if (filter.target == target && filter.source == source)
  670. {
  671. filter.effect = effect;
  672. filter.persistent = persistent;
  673. return;
  674. }
  675. }
  676. stackFilterEffects.push_back({ effect, target, source, persistent });
  677. }
  678. void BattleStacksController::removeExpiredColorFilters()
  679. {
  680. vstd::erase_if(stackFilterEffects, [&](const BattleStackFilterEffect & filter)
  681. {
  682. if (filter.persistent)
  683. return false;
  684. if (filter.effect == ColorFilter::genEmptyShifter())
  685. return false;
  686. if (filter.source && filter.target->hasBonus(Selector::source(Bonus::SPELL_EFFECT, filter.source->id)))
  687. return false;
  688. return true;
  689. });
  690. }
  691. void BattleStacksController::updateHoveredStacks()
  692. {
  693. auto newStacks = selectHoveredStacks();
  694. for (auto const * stack : mouseHoveredStacks)
  695. {
  696. if (vstd::contains(newStacks, stack))
  697. continue;
  698. if (stack == activeStack)
  699. stackAnimation[stack->ID]->setBorderColor(AnimationControls::getGoldBorder());
  700. else
  701. stackAnimation[stack->ID]->setBorderColor(AnimationControls::getNoBorder());
  702. }
  703. for (auto const * stack : newStacks)
  704. {
  705. if (vstd::contains(mouseHoveredStacks, stack))
  706. continue;
  707. stackAnimation[stack->ID]->setBorderColor(AnimationControls::getBlueBorder());
  708. if (stackAnimation[stack->ID]->framesInGroup(ECreatureAnimType::MOUSEON) > 0)
  709. stackAnimation[stack->ID]->playOnce(ECreatureAnimType::MOUSEON);
  710. }
  711. mouseHoveredStacks = newStacks;
  712. }
  713. std::vector<const CStack *> BattleStacksController::selectHoveredStacks()
  714. {
  715. auto hoveredHex = owner.fieldController->getHoveredHex();
  716. if (!hoveredHex.isValid())
  717. return {};
  718. const spells::Caster *caster = nullptr;
  719. const CSpell *spell = nullptr;
  720. spells::Mode mode = spells::Mode::HERO;
  721. if(owner.actionsController->spellcastingModeActive())//hero casts spell
  722. {
  723. spell = owner.actionsController->selectedSpell().toSpell();
  724. caster = owner.getActiveHero();
  725. }
  726. else if(owner.stacksController->activeStackSpellToCast() != SpellID::NONE)//stack casts spell
  727. {
  728. spell = SpellID(owner.stacksController->activeStackSpellToCast()).toSpell();
  729. caster = owner.stacksController->getActiveStack();
  730. mode = spells::Mode::CREATURE_ACTIVE;
  731. }
  732. if(caster && spell) //when casting spell
  733. {
  734. spells::Target target;
  735. target.emplace_back(hoveredHex);
  736. spells::BattleCast event(owner.curInt->cb.get(), caster, mode, spell);
  737. auto mechanics = spell->battleMechanics(&event);
  738. return mechanics->getAffectedStacks(target);
  739. }
  740. if(hoveredHex.isValid())
  741. {
  742. const CStack * const stack = owner.curInt->cb->battleGetStackByPos(hoveredHex, true);
  743. if (stack)
  744. return {stack};
  745. }
  746. return {};
  747. }