BattleStacksController.cpp 30 KB

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