BattleStacksController.cpp 27 KB

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