BattleStacksController.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  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/CGuiHandler.h"
  27. #include "../render/Colors.h"
  28. #include "../render/Canvas.h"
  29. #include "../render/IRenderHandler.h"
  30. #include "../../CCallback.h"
  31. #include "../../lib/spells/ISpellMechanics.h"
  32. #include "../../lib/battle/BattleAction.h"
  33. #include "../../lib/battle/BattleHex.h"
  34. #include "../../lib/bonuses/BonusSubtypes.h"
  35. #include "../../lib/CStack.h"
  36. #include "../../lib/CondSh.h"
  37. #include "../../lib/TextOperations.h"
  38. static void onAnimationFinished(const CStack *stack, std::weak_ptr<CreatureAnimation> anim)
  39. {
  40. std::shared_ptr<CreatureAnimation> animation = anim.lock();
  41. if(!animation)
  42. return;
  43. if (!stack->isFrozen() && animation->getType() == ECreatureAnimType::FROZEN)
  44. animation->setType(ECreatureAnimType::HOLDING);
  45. if (animation->isIdle())
  46. {
  47. const CCreature *creature = stack->unitType();
  48. if (stack->isFrozen())
  49. animation->setType(ECreatureAnimType::FROZEN);
  50. else
  51. if (animation->framesInGroup(ECreatureAnimType::MOUSEON) > 0)
  52. {
  53. if (CRandomGenerator::getDefault().nextDouble(99.0) < creature->animation.timeBetweenFidgets *10)
  54. animation->playOnce(ECreatureAnimType::MOUSEON);
  55. else
  56. animation->setType(ECreatureAnimType::HOLDING);
  57. }
  58. else
  59. {
  60. animation->setType(ECreatureAnimType::HOLDING);
  61. }
  62. }
  63. // always reset callback
  64. animation->onAnimationReset += std::bind(&onAnimationFinished, stack, anim);
  65. }
  66. BattleStacksController::BattleStacksController(BattleInterface & owner):
  67. owner(owner),
  68. activeStack(nullptr),
  69. stackToActivate(nullptr),
  70. animIDhelper(0)
  71. {
  72. //preparing graphics for displaying amounts of creatures
  73. amountNormal = GH.renderHandler().loadImage(ImagePath::builtin("CMNUMWIN.BMP"), EImageBlitMode::COLORKEY);
  74. amountPositive = GH.renderHandler().loadImage(ImagePath::builtin("CMNUMWIN.BMP"), EImageBlitMode::COLORKEY);
  75. amountNegative = GH.renderHandler().loadImage(ImagePath::builtin("CMNUMWIN.BMP"), EImageBlitMode::COLORKEY);
  76. amountEffNeutral = GH.renderHandler().loadImage(ImagePath::builtin("CMNUMWIN.BMP"), EImageBlitMode::COLORKEY);
  77. static const auto shifterNormal = ColorFilter::genRangeShifter( 0.f, 0.f, 0.f, 0.6f, 0.2f, 1.0f );
  78. static const auto shifterPositive = ColorFilter::genRangeShifter( 0.f, 0.f, 0.f, 0.2f, 1.0f, 0.2f );
  79. static const auto shifterNegative = ColorFilter::genRangeShifter( 0.f, 0.f, 0.f, 1.0f, 0.2f, 0.2f );
  80. static const auto shifterNeutral = ColorFilter::genRangeShifter( 0.f, 0.f, 0.f, 1.0f, 1.0f, 0.2f );
  81. // do not change border color
  82. static const int32_t ignoredMask = 1 << 26;
  83. amountNormal->adjustPalette(shifterNormal, ignoredMask);
  84. amountPositive->adjustPalette(shifterPositive, ignoredMask);
  85. amountNegative->adjustPalette(shifterNegative, ignoredMask);
  86. amountEffNeutral->adjustPalette(shifterNeutral, ignoredMask);
  87. std::vector<const CStack*> stacks = owner.getBattle()->battleGetAllStacks(true);
  88. for(const CStack * s : stacks)
  89. {
  90. stackAdded(s, true);
  91. }
  92. }
  93. BattleHex BattleStacksController::getStackCurrentPosition(const CStack * stack) const
  94. {
  95. if ( !stackAnimation.at(stack->unitId())->isMoving())
  96. return stack->getPosition();
  97. if (stack->hasBonusOfType(BonusType::FLYING) && stackAnimation.at(stack->unitId())->getType() == ECreatureAnimType::MOVING )
  98. return BattleHex::HEX_AFTER_ALL;
  99. for (auto & anim : currentAnimations)
  100. {
  101. // certainly ugly workaround but fixes quite annoying bug
  102. // stack position will be updated only *after* movement is finished
  103. // before this - stack is always at its initial position. Thus we need to find
  104. // its current position. Which can be found only in this class
  105. if (StackMoveAnimation *move = dynamic_cast<StackMoveAnimation*>(anim))
  106. {
  107. if (move->stack == stack)
  108. return std::max(move->prevHex, move->nextHex);
  109. }
  110. }
  111. return stack->getPosition();
  112. }
  113. void BattleStacksController::collectRenderableObjects(BattleRenderer & renderer)
  114. {
  115. auto stacks = owner.getBattle()->battleGetAllStacks(false);
  116. for (auto stack : stacks)
  117. {
  118. if (stackAnimation.find(stack->unitId()) == stackAnimation.end()) //e.g. for summoned but not yet handled stacks
  119. continue;
  120. //FIXME: hack to ignore ghost stacks
  121. if ((stackAnimation[stack->unitId()]->getType() == ECreatureAnimType::DEAD || stackAnimation[stack->unitId()]->getType() == ECreatureAnimType::HOLDING) && stack->isGhost())
  122. continue;
  123. auto layer = stackAnimation[stack->unitId()]->isDead() ? EBattleFieldLayer::CORPSES : EBattleFieldLayer::STACKS;
  124. auto location = getStackCurrentPosition(stack);
  125. renderer.insert(layer, location, [this, stack]( BattleRenderer::RendererRef renderer ){
  126. showStack(renderer, stack);
  127. });
  128. if (stackNeedsAmountBox(stack))
  129. {
  130. renderer.insert(EBattleFieldLayer::STACK_AMOUNTS, location, [this, stack]( BattleRenderer::RendererRef renderer ){
  131. showStackAmountBox(renderer, stack);
  132. });
  133. }
  134. }
  135. }
  136. void BattleStacksController::stackReset(const CStack * stack)
  137. {
  138. auto iter = stackAnimation.find(stack->unitId());
  139. if(iter == stackAnimation.end())
  140. {
  141. logGlobal->error("Unit %d have no animation", stack->unitId());
  142. return;
  143. }
  144. auto animation = iter->second;
  145. if(stack->alive() && animation->isDeadOrDying())
  146. {
  147. owner.addToAnimationStage(EAnimationEvents::HIT, [=]()
  148. {
  149. addNewAnim(new ResurrectionAnimation(owner, stack));
  150. });
  151. }
  152. }
  153. void BattleStacksController::stackAdded(const CStack * stack, bool instant)
  154. {
  155. // Tower shooters have only their upper half visible
  156. static const int turretCreatureAnimationHeight = 232;
  157. stackFacingRight[stack->unitId()] = stack->unitSide() == BattleSide::ATTACKER; // must be set before getting stack position
  158. Point coords = getStackPositionAtHex(stack->getPosition(), stack);
  159. if(stack->initialPosition < 0) //turret
  160. {
  161. assert(owner.siegeController);
  162. const CCreature *turretCreature = owner.siegeController->getTurretCreature();
  163. stackAnimation[stack->unitId()] = AnimationControls::getAnimation(turretCreature);
  164. stackAnimation[stack->unitId()]->pos.h = turretCreatureAnimationHeight;
  165. stackAnimation[stack->unitId()]->pos.w = stackAnimation[stack->unitId()]->getWidth();
  166. // FIXME: workaround for visible animation of Medusa tails (animation disabled in H3)
  167. if (turretCreature->getId() == CreatureID::MEDUSA )
  168. stackAnimation[stack->unitId()]->pos.w = 250;
  169. coords = owner.siegeController->getTurretCreaturePosition(stack->initialPosition);
  170. }
  171. else
  172. {
  173. stackAnimation[stack->unitId()] = AnimationControls::getAnimation(stack->unitType());
  174. stackAnimation[stack->unitId()]->onAnimationReset += std::bind(&onAnimationFinished, stack, stackAnimation[stack->unitId()]);
  175. stackAnimation[stack->unitId()]->pos.h = stackAnimation[stack->unitId()]->getHeight();
  176. stackAnimation[stack->unitId()]->pos.w = stackAnimation[stack->unitId()]->getWidth();
  177. }
  178. stackAnimation[stack->unitId()]->pos.x = coords.x;
  179. stackAnimation[stack->unitId()]->pos.y = coords.y;
  180. stackAnimation[stack->unitId()]->setType(ECreatureAnimType::HOLDING);
  181. if (!instant)
  182. {
  183. // immediately make stack transparent, giving correct shifter time to start
  184. auto shifterFade = ColorFilter::genAlphaShifter(0);
  185. setStackColorFilter(shifterFade, stack, nullptr, true);
  186. owner.addToAnimationStage(EAnimationEvents::HIT, [=]()
  187. {
  188. addNewAnim(new ColorTransformAnimation(owner, stack, "summonFadeIn", nullptr));
  189. if (stack->isClone())
  190. addNewAnim(new ColorTransformAnimation(owner, stack, "cloning", SpellID(SpellID::CLONE).toSpell() ));
  191. });
  192. }
  193. }
  194. void BattleStacksController::setActiveStack(const CStack *stack)
  195. {
  196. if (activeStack) // update UI
  197. stackAnimation[activeStack->unitId()]->setBorderColor(AnimationControls::getNoBorder());
  198. activeStack = stack;
  199. if (activeStack) // update UI
  200. stackAnimation[activeStack->unitId()]->setBorderColor(AnimationControls::getGoldBorder());
  201. owner.windowObject->blockUI(activeStack == nullptr);
  202. if (activeStack)
  203. stackAmountBoxHidden.clear();
  204. }
  205. bool BattleStacksController::stackNeedsAmountBox(const CStack * stack) const
  206. {
  207. //do not show box for singular war machines, stacked war machines with box shown are supported as extension feature
  208. if(stack->hasBonusOfType(BonusType::SIEGE_WEAPON) && stack->getCount() == 1)
  209. return false;
  210. if(!stack->alive())
  211. return false;
  212. //hide box when target is going to die anyway - do not display "0 creatures"
  213. if(stack->getCount() == 0)
  214. return false;
  215. // if stack has any ongoing animation - hide the box
  216. if (stackAmountBoxHidden.count(stack->unitId()))
  217. return false;
  218. return true;
  219. }
  220. std::shared_ptr<IImage> BattleStacksController::getStackAmountBox(const CStack * stack)
  221. {
  222. std::vector<si32> activeSpells = stack->activeSpells();
  223. if ( activeSpells.empty())
  224. return amountNormal;
  225. int effectsPositivness = 0;
  226. for(const auto & spellID : activeSpells)
  227. {
  228. auto positiveness = CGI->spells()->getByIndex(spellID)->getPositiveness();
  229. if(!boost::logic::indeterminate(positiveness))
  230. {
  231. if(positiveness)
  232. effectsPositivness++;
  233. else
  234. effectsPositivness--;
  235. }
  236. }
  237. if (effectsPositivness > 0)
  238. return amountPositive;
  239. if (effectsPositivness < 0)
  240. return amountNegative;
  241. return amountEffNeutral;
  242. }
  243. void BattleStacksController::showStackAmountBox(Canvas & canvas, const CStack * stack)
  244. {
  245. auto amountBG = getStackAmountBox(stack);
  246. bool doubleWide = stack->doubleWide();
  247. bool turnedRight = facingRight(stack);
  248. bool attacker = stack->unitSide() == BattleSide::ATTACKER;
  249. BattleHex stackPos = stack->getPosition();
  250. // double-wide unit turned around - use opposite hex for stack label
  251. if (doubleWide && turnedRight != attacker)
  252. stackPos = stack->occupiedHex();
  253. BattleHex frontPos = turnedRight ?
  254. stackPos.cloneInDirection(BattleHex::RIGHT) :
  255. stackPos.cloneInDirection(BattleHex::LEFT);
  256. bool moveInside = !owner.fieldController->stackCountOutsideHex(frontPos);
  257. Point boxPosition;
  258. if (moveInside)
  259. {
  260. boxPosition = owner.fieldController->hexPositionLocal(stackPos).center() + Point(-15, 1);
  261. }
  262. else
  263. {
  264. if (turnedRight)
  265. boxPosition = owner.fieldController->hexPositionLocal(frontPos).center() + Point (-22, 1);
  266. else
  267. boxPosition = owner.fieldController->hexPositionLocal(frontPos).center() + Point(-8, -14);
  268. }
  269. Point textPosition = amountBG->dimensions()/2 + boxPosition;
  270. canvas.draw(amountBG, boxPosition);
  271. canvas.drawText(textPosition, EFonts::FONT_TINY, Colors::WHITE, ETextAlignment::CENTER, TextOperations::formatMetric(stack->getCount(), 4));
  272. }
  273. void BattleStacksController::showStack(Canvas & canvas, const CStack * stack)
  274. {
  275. ColorFilter fullFilter = ColorFilter::genEmptyShifter();
  276. for(const auto & filter : stackFilterEffects)
  277. {
  278. if (filter.target == stack)
  279. fullFilter = ColorFilter::genCombined(fullFilter, filter.effect);
  280. }
  281. stackAnimation[stack->unitId()]->nextFrame(canvas, fullFilter, facingRight(stack)); // do actual blit
  282. }
  283. void BattleStacksController::tick(uint32_t msPassed)
  284. {
  285. updateHoveredStacks();
  286. updateBattleAnimations(msPassed);
  287. }
  288. void BattleStacksController::initializeBattleAnimations()
  289. {
  290. auto copiedVector = currentAnimations;
  291. for (auto & elem : copiedVector)
  292. if (elem && !elem->isInitialized())
  293. elem->tryInitialize();
  294. }
  295. void BattleStacksController::tickFrameBattleAnimations(uint32_t msPassed)
  296. {
  297. for (auto stack : owner.getBattle()->battleGetAllStacks(true))
  298. {
  299. if (stackAnimation.find(stack->unitId()) == stackAnimation.end()) //e.g. for summoned but not yet handled stacks
  300. continue;
  301. stackAnimation[stack->unitId()]->incrementFrame(msPassed / 1000.f);
  302. }
  303. // operate on copy - to prevent potential iterator invalidation due to push_back's
  304. // FIXME? : remove remaining calls to addNewAnim from BattleAnimation::nextFrame (only Catapult explosion at the time of writing)
  305. auto copiedVector = currentAnimations;
  306. for (auto & elem : copiedVector)
  307. if (elem && elem->isInitialized())
  308. elem->tick(msPassed);
  309. }
  310. void BattleStacksController::updateBattleAnimations(uint32_t msPassed)
  311. {
  312. bool hadAnimations = !currentAnimations.empty();
  313. initializeBattleAnimations();
  314. tickFrameBattleAnimations(msPassed);
  315. vstd::erase(currentAnimations, nullptr);
  316. if (currentAnimations.empty())
  317. owner.executeStagedAnimations();
  318. if (hadAnimations && currentAnimations.empty())
  319. owner.onAnimationsFinished();
  320. initializeBattleAnimations();
  321. }
  322. void BattleStacksController::addNewAnim(BattleAnimation *anim)
  323. {
  324. if (currentAnimations.empty())
  325. stackAmountBoxHidden.clear();
  326. owner.onAnimationsStarted();
  327. currentAnimations.push_back(anim);
  328. auto stackAnimation = dynamic_cast<BattleStackAnimation*>(anim);
  329. if(stackAnimation)
  330. stackAmountBoxHidden.insert(stackAnimation->stack->unitId());
  331. }
  332. void BattleStacksController::stackRemoved(uint32_t stackID)
  333. {
  334. if (getActiveStack() && getActiveStack()->unitId() == stackID)
  335. setActiveStack(nullptr);
  336. }
  337. void BattleStacksController::stacksAreAttacked(std::vector<StackAttackedInfo> attackedInfos)
  338. {
  339. owner.addToAnimationStage(EAnimationEvents::HIT, [=](){
  340. // remove any potentially erased petrification effect
  341. removeExpiredColorFilters();
  342. });
  343. for(auto & attackedInfo : attackedInfos)
  344. {
  345. if (!attackedInfo.attacker)
  346. continue;
  347. // In H3, attacked stack will not reverse on ranged attack
  348. if (attackedInfo.indirectAttack)
  349. continue;
  350. // Another type of indirect attack - dragon breath
  351. if (!CStack::isMeleeAttackPossible(attackedInfo.attacker, attackedInfo.defender))
  352. continue;
  353. // defender need to face in direction opposited to out attacker
  354. bool needsReverse = shouldAttackFacingRight(attackedInfo.attacker, attackedInfo.defender) == facingRight(attackedInfo.defender);
  355. // FIXME: this check is better, however not usable since stacksAreAttacked is called after net pack is applyed - petrification is already removed
  356. // if (needsReverse && !attackedInfo.defender->isFrozen())
  357. if (needsReverse && stackAnimation[attackedInfo.defender->unitId()]->getType() != ECreatureAnimType::FROZEN)
  358. {
  359. owner.addToAnimationStage(EAnimationEvents::MOVEMENT, [=]()
  360. {
  361. addNewAnim(new ReverseAnimation(owner, attackedInfo.defender, attackedInfo.defender->getPosition()));
  362. });
  363. }
  364. }
  365. for(auto & attackedInfo : attackedInfos)
  366. {
  367. bool useDeathAnim = attackedInfo.killed;
  368. bool useDefenceAnim = attackedInfo.defender->defendingAnim && !attackedInfo.indirectAttack && !attackedInfo.killed;
  369. EAnimationEvents usedEvent = useDefenceAnim ? EAnimationEvents::ATTACK : EAnimationEvents::HIT;
  370. owner.addToAnimationStage(usedEvent, [=]()
  371. {
  372. if (useDeathAnim)
  373. addNewAnim(new DeathAnimation(owner, attackedInfo.defender, attackedInfo.indirectAttack));
  374. else if(useDefenceAnim)
  375. addNewAnim(new DefenceAnimation(owner, attackedInfo.defender));
  376. else
  377. addNewAnim(new HittedAnimation(owner, attackedInfo.defender));
  378. if (attackedInfo.fireShield)
  379. owner.effectsController->displayEffect(EBattleEffect::FIRE_SHIELD, AudioPath::builtin("FIRESHIE"), attackedInfo.attacker->getPosition());
  380. if (attackedInfo.spellEffect != SpellID::NONE)
  381. {
  382. auto spell = attackedInfo.spellEffect.toSpell();
  383. if (!spell->getCastSound().empty())
  384. CCS->soundh->playSound(spell->getCastSound());
  385. owner.displaySpellEffect(spell, attackedInfo.defender->getPosition());
  386. }
  387. });
  388. }
  389. for (auto & attackedInfo : attackedInfos)
  390. {
  391. if (attackedInfo.rebirth)
  392. {
  393. owner.addToAnimationStage(EAnimationEvents::AFTER_HIT, [=](){
  394. owner.effectsController->displayEffect(EBattleEffect::RESURRECT, AudioPath::builtin("RESURECT"), attackedInfo.defender->getPosition());
  395. addNewAnim(new ResurrectionAnimation(owner, attackedInfo.defender));
  396. });
  397. }
  398. if (attackedInfo.killed && attackedInfo.defender->summoned)
  399. {
  400. owner.addToAnimationStage(EAnimationEvents::AFTER_HIT, [=](){
  401. addNewAnim(new ColorTransformAnimation(owner, attackedInfo.defender, "summonFadeOut", nullptr));
  402. stackRemoved(attackedInfo.defender->unitId());
  403. });
  404. }
  405. }
  406. owner.executeStagedAnimations();
  407. owner.waitForAnimations();
  408. }
  409. void BattleStacksController::stackTeleported(const CStack *stack, std::vector<BattleHex> destHex, int distance)
  410. {
  411. assert(destHex.size() > 0);
  412. //owner.checkForAnimations(); // NOTE: at this point spellcast animations were added, but not executed
  413. owner.addToAnimationStage(EAnimationEvents::HIT, [=](){
  414. addNewAnim( new ColorTransformAnimation(owner, stack, "teleportFadeOut", nullptr) );
  415. });
  416. owner.addToAnimationStage(EAnimationEvents::AFTER_HIT, [=](){
  417. stackAnimation[stack->unitId()]->pos.moveTo(getStackPositionAtHex(destHex.back(), stack));
  418. addNewAnim( new ColorTransformAnimation(owner, stack, "teleportFadeIn", nullptr) );
  419. });
  420. // animations will be executed by spell
  421. }
  422. void BattleStacksController::stackMoved(const CStack *stack, std::vector<BattleHex> destHex, int distance)
  423. {
  424. assert(destHex.size() > 0);
  425. owner.checkForAnimations();
  426. if(shouldRotate(stack, stack->getPosition(), destHex[0]))
  427. {
  428. owner.addToAnimationStage(EAnimationEvents::ROTATE, [&]()
  429. {
  430. addNewAnim(new ReverseAnimation(owner, stack, stack->getPosition()));
  431. });
  432. }
  433. owner.addToAnimationStage(EAnimationEvents::MOVE_START, [&]()
  434. {
  435. addNewAnim(new MovementStartAnimation(owner, stack));
  436. });
  437. if (!stack->hasBonus(Selector::typeSubtype(BonusType::FLYING, BonusSubtypes::movementFlying)))
  438. {
  439. owner.addToAnimationStage(EAnimationEvents::MOVEMENT, [&]()
  440. {
  441. addNewAnim(new MovementAnimation(owner, stack, destHex, distance));
  442. });
  443. }
  444. owner.addToAnimationStage(EAnimationEvents::MOVE_END, [&]()
  445. {
  446. addNewAnim(new MovementEndAnimation(owner, stack, destHex.back()));
  447. });
  448. owner.executeStagedAnimations();
  449. owner.waitForAnimations();
  450. }
  451. bool BattleStacksController::shouldAttackFacingRight(const CStack * attacker, const CStack * defender)
  452. {
  453. bool mustReverse = owner.getBattle()->isToReverse(attacker, defender);
  454. if (attacker->unitSide() == BattleSide::ATTACKER)
  455. return !mustReverse;
  456. else
  457. return mustReverse;
  458. }
  459. void BattleStacksController::stackAttacking( const StackAttackInfo & info )
  460. {
  461. owner.checkForAnimations();
  462. auto attacker = info.attacker;
  463. auto defender = info.defender;
  464. auto tile = info.tile;
  465. auto spellEffect = info.spellEffect;
  466. auto multiAttack = !info.secondaryDefender.empty();
  467. bool needsReverse = false;
  468. if (info.indirectAttack)
  469. {
  470. needsReverse = shouldRotate(attacker, attacker->position, info.tile);
  471. }
  472. else
  473. {
  474. needsReverse = shouldAttackFacingRight(attacker, defender) != facingRight(attacker);
  475. }
  476. if (needsReverse)
  477. {
  478. owner.addToAnimationStage(EAnimationEvents::MOVEMENT, [=]()
  479. {
  480. addNewAnim(new ReverseAnimation(owner, attacker, attacker->getPosition()));
  481. });
  482. }
  483. if(info.lucky)
  484. {
  485. owner.addToAnimationStage(EAnimationEvents::BEFORE_HIT, [=]() {
  486. owner.appendBattleLog(info.attacker->formatGeneralMessage(-45));
  487. owner.effectsController->displayEffect(EBattleEffect::GOOD_LUCK, AudioPath::builtin("GOODLUCK"), attacker->getPosition());
  488. });
  489. }
  490. if(info.unlucky)
  491. {
  492. owner.addToAnimationStage(EAnimationEvents::BEFORE_HIT, [=]() {
  493. owner.appendBattleLog(info.attacker->formatGeneralMessage(-44));
  494. owner.effectsController->displayEffect(EBattleEffect::BAD_LUCK, AudioPath::builtin("BADLUCK"), attacker->getPosition());
  495. });
  496. }
  497. if(info.deathBlow)
  498. {
  499. owner.addToAnimationStage(EAnimationEvents::BEFORE_HIT, [=]() {
  500. owner.appendBattleLog(info.attacker->formatGeneralMessage(365));
  501. owner.effectsController->displayEffect(EBattleEffect::DEATH_BLOW, AudioPath::builtin("DEATHBLO"), defender->getPosition());
  502. });
  503. for(auto elem : info.secondaryDefender)
  504. {
  505. owner.addToAnimationStage(EAnimationEvents::BEFORE_HIT, [=]() {
  506. owner.effectsController->displayEffect(EBattleEffect::DEATH_BLOW, elem->getPosition());
  507. });
  508. }
  509. }
  510. owner.addToAnimationStage(EAnimationEvents::ATTACK, [=]()
  511. {
  512. if (info.indirectAttack)
  513. {
  514. addNewAnim(new ShootingAnimation(owner, attacker, tile, defender));
  515. }
  516. else
  517. {
  518. addNewAnim(new MeleeAttackAnimation(owner, attacker, tile, defender, multiAttack));
  519. }
  520. });
  521. if (info.spellEffect != SpellID::NONE)
  522. {
  523. owner.addToAnimationStage(EAnimationEvents::HIT, [=]()
  524. {
  525. owner.displaySpellHit(spellEffect.toSpell(), tile);
  526. });
  527. }
  528. if (info.lifeDrain)
  529. {
  530. owner.addToAnimationStage(EAnimationEvents::AFTER_HIT, [=]()
  531. {
  532. owner.effectsController->displayEffect(EBattleEffect::DRAIN_LIFE, AudioPath::builtin("DRAINLIF"), attacker->getPosition());
  533. });
  534. }
  535. //return, animation playback will be handled by stacksAreAttacked
  536. }
  537. bool BattleStacksController::shouldRotate(const CStack * stack, const BattleHex & oldPos, const BattleHex & nextHex) const
  538. {
  539. Point begPosition = getStackPositionAtHex(oldPos,stack);
  540. Point endPosition = getStackPositionAtHex(nextHex, stack);
  541. if((begPosition.x > endPosition.x) && facingRight(stack))
  542. return true;
  543. else if((begPosition.x < endPosition.x) && !facingRight(stack))
  544. return true;
  545. return false;
  546. }
  547. void BattleStacksController::endAction(const BattleAction & action)
  548. {
  549. owner.checkForAnimations();
  550. //check if we should reverse stacks
  551. TStacks stacks = owner.getBattle()->battleGetStacks(CPlayerBattleCallback::MINE_AND_ENEMY);
  552. for (const CStack *s : stacks)
  553. {
  554. bool shouldFaceRight = s && s->unitSide() == BattleSide::ATTACKER;
  555. if (s && facingRight(s) != shouldFaceRight && s->alive() && stackAnimation[s->unitId()]->isIdle())
  556. {
  557. addNewAnim(new ReverseAnimation(owner, s, s->getPosition()));
  558. }
  559. }
  560. owner.executeStagedAnimations();
  561. owner.waitForAnimations();
  562. stackAmountBoxHidden.clear();
  563. owner.windowObject->blockUI(activeStack == nullptr);
  564. removeExpiredColorFilters();
  565. }
  566. void BattleStacksController::startAction(const BattleAction & action)
  567. {
  568. removeExpiredColorFilters();
  569. }
  570. void BattleStacksController::stackActivated(const CStack *stack)
  571. {
  572. stackToActivate = stack;
  573. owner.waitForAnimations();
  574. logAnim->debug("Activating next stack");
  575. owner.activateStack();
  576. }
  577. void BattleStacksController::deactivateStack()
  578. {
  579. if (!activeStack) {
  580. return;
  581. }
  582. stackToActivate = activeStack;
  583. setActiveStack(nullptr);
  584. }
  585. void BattleStacksController::activateStack()
  586. {
  587. if ( !currentAnimations.empty())
  588. return;
  589. if ( !stackToActivate)
  590. return;
  591. owner.trySetActivePlayer(stackToActivate->unitOwner());
  592. setActiveStack(stackToActivate);
  593. stackToActivate = nullptr;
  594. const CStack * s = getActiveStack();
  595. if(!s)
  596. return;
  597. }
  598. const CStack* BattleStacksController::getActiveStack() const
  599. {
  600. return activeStack;
  601. }
  602. bool BattleStacksController::facingRight(const CStack * stack) const
  603. {
  604. return stackFacingRight.at(stack->unitId());
  605. }
  606. Point BattleStacksController::getStackPositionAtHex(BattleHex hexNum, const CStack * stack) const
  607. {
  608. Point ret(-500, -500); //returned value
  609. if(stack && stack->initialPosition < 0) //creatures in turrets
  610. return owner.siegeController->getTurretCreaturePosition(stack->initialPosition);
  611. static const Point basePos(-189, -139); // position of creature in topleft corner
  612. static const int imageShiftX = 29; // X offset to base pos for facing right stacks, negative for facing left
  613. ret.x = basePos.x + 22 * ( (hexNum.getY() + 1)%2 ) + 44 * hexNum.getX();
  614. ret.y = basePos.y + 42 * hexNum.getY();
  615. if (stack)
  616. {
  617. if(facingRight(stack))
  618. ret.x += imageShiftX;
  619. else
  620. ret.x -= imageShiftX;
  621. //shifting position for double - hex creatures
  622. if(stack->doubleWide())
  623. {
  624. if(stack->unitSide() == BattleSide::ATTACKER)
  625. {
  626. if(facingRight(stack))
  627. ret.x -= 44;
  628. }
  629. else
  630. {
  631. if(!facingRight(stack))
  632. ret.x += 44;
  633. }
  634. }
  635. }
  636. //returning
  637. return ret;
  638. }
  639. void BattleStacksController::setStackColorFilter(const ColorFilter & effect, const CStack * target, const CSpell * source, bool persistent)
  640. {
  641. for (auto & filter : stackFilterEffects)
  642. {
  643. if (filter.target == target && filter.source == source)
  644. {
  645. filter.effect = effect;
  646. filter.persistent = persistent;
  647. return;
  648. }
  649. }
  650. stackFilterEffects.push_back({ effect, target, source, persistent });
  651. }
  652. void BattleStacksController::removeExpiredColorFilters()
  653. {
  654. vstd::erase_if(stackFilterEffects, [&](const BattleStackFilterEffect & filter)
  655. {
  656. if (!filter.persistent)
  657. {
  658. if (filter.source && !filter.target->hasBonus(Selector::source(BonusSource::SPELL_EFFECT, filter.source->id), Selector::all))
  659. return true;
  660. if (filter.effect == ColorFilter::genEmptyShifter())
  661. return true;
  662. }
  663. return false;
  664. });
  665. }
  666. void BattleStacksController::updateHoveredStacks()
  667. {
  668. auto newStacks = selectHoveredStacks();
  669. for(const auto * stack : mouseHoveredStacks)
  670. {
  671. if (vstd::contains(newStacks, stack))
  672. continue;
  673. if (stack == activeStack)
  674. stackAnimation[stack->unitId()]->setBorderColor(AnimationControls::getGoldBorder());
  675. else
  676. stackAnimation[stack->unitId()]->setBorderColor(AnimationControls::getNoBorder());
  677. }
  678. for(const auto * stack : newStacks)
  679. {
  680. if (vstd::contains(mouseHoveredStacks, stack))
  681. continue;
  682. stackAnimation[stack->unitId()]->setBorderColor(AnimationControls::getBlueBorder());
  683. if (stackAnimation[stack->unitId()]->framesInGroup(ECreatureAnimType::MOUSEON) > 0 && stack->alive() && !stack->isFrozen())
  684. stackAnimation[stack->unitId()]->playOnce(ECreatureAnimType::MOUSEON);
  685. }
  686. mouseHoveredStacks = newStacks;
  687. }
  688. std::vector<const CStack *> BattleStacksController::selectHoveredStacks()
  689. {
  690. // only allow during our turn - do not try to highlight creatures while they are in the middle of actions
  691. if (!activeStack)
  692. return {};
  693. if(owner.hasAnimations())
  694. return {};
  695. auto hoveredQueueUnitId = owner.windowObject->getQueueHoveredUnitId();
  696. if(hoveredQueueUnitId.has_value())
  697. {
  698. return { owner.getBattle()->battleGetStackByID(hoveredQueueUnitId.value(), true) };
  699. }
  700. auto hoveredHex = owner.fieldController->getHoveredHex();
  701. if (!hoveredHex.isValid())
  702. return {};
  703. const spells::Caster *caster = nullptr;
  704. const CSpell *spell = nullptr;
  705. spells::Mode mode = owner.actionsController->getCurrentCastMode();
  706. spell = owner.actionsController->getCurrentSpell(hoveredHex);
  707. caster = owner.actionsController->getCurrentSpellcaster();
  708. if(caster && spell && owner.actionsController->currentActionSpellcasting(hoveredHex) ) //when casting spell
  709. {
  710. spells::Target target;
  711. target.emplace_back(hoveredHex);
  712. spells::BattleCast event(owner.getBattle().get(), caster, mode, spell);
  713. auto mechanics = spell->battleMechanics(&event);
  714. return mechanics->getAffectedStacks(target);
  715. }
  716. if(hoveredHex.isValid())
  717. {
  718. const CStack * const stack = owner.getBattle()->battleGetStackByPos(hoveredHex, true);
  719. if (stack)
  720. return {stack};
  721. }
  722. return {};
  723. }
  724. const std::vector<uint32_t> BattleStacksController::getHoveredStacksUnitIds() const
  725. {
  726. auto result = std::vector<uint32_t>();
  727. for(const auto * stack : mouseHoveredStacks)
  728. {
  729. result.push_back(stack->unitId());
  730. }
  731. return result;
  732. }