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->getCreature();
  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->ID)->isMoving())
  95. return stack->getPosition();
  96. if (stack->hasBonusOfType(Bonus::FLYING) && stackAnimation.at(stack->ID)->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->ID) == stackAnimation.end()) //e.g. for summoned but not yet handled stacks
  118. continue;
  119. //FIXME: hack to ignore ghost stacks
  120. if ((stackAnimation[stack->ID]->getType() == ECreatureAnimType::DEAD || stackAnimation[stack->ID]->getType() == ECreatureAnimType::HOLDING) && stack->isGhost())
  121. continue;
  122. auto layer = stackAnimation[stack->ID]->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->ID] = stack->side == BattleSide::ATTACKER;
  140. auto iter = stackAnimation.find(stack->ID);
  141. if(iter == stackAnimation.end())
  142. {
  143. logGlobal->error("Unit %d have no animation", stack->ID);
  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->ID] = stack->side == 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->ID] = AnimationControls::getAnimation(turretCreature);
  166. stackAnimation[stack->ID]->pos.h = turretCreatureAnimationHeight;
  167. stackAnimation[stack->ID]->pos.w = stackAnimation[stack->ID]->getWidth();
  168. // FIXME: workaround for visible animation of Medusa tails (animation disabled in H3)
  169. if (turretCreature->getId() == CreatureID::MEDUSA )
  170. stackAnimation[stack->ID]->pos.w = 250;
  171. coords = owner.siegeController->getTurretCreaturePosition(stack->initialPosition);
  172. }
  173. else
  174. {
  175. stackAnimation[stack->ID] = AnimationControls::getAnimation(stack->getCreature());
  176. stackAnimation[stack->ID]->onAnimationReset += std::bind(&onAnimationFinished, stack, stackAnimation[stack->ID]);
  177. stackAnimation[stack->ID]->pos.h = stackAnimation[stack->ID]->getHeight();
  178. stackAnimation[stack->ID]->pos.w = stackAnimation[stack->ID]->getWidth();
  179. }
  180. stackAnimation[stack->ID]->pos.x = coords.x;
  181. stackAnimation[stack->ID]->pos.y = coords.y;
  182. stackAnimation[stack->ID]->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->ID]->setBorderColor(AnimationControls::getNoBorder());
  200. activeStack = stack;
  201. if (activeStack) // update UI
  202. stackAnimation[activeStack->ID]->setBorderColor(AnimationControls::getGoldBorder());
  203. owner.windowObject->blockUI(activeStack == nullptr);
  204. }
  205. bool BattleStacksController::stackNeedsAmountBox(const CStack * stack) const
  206. {
  207. BattleHex currentActionTarget;
  208. if(owner.curInt->curAction)
  209. {
  210. auto target = owner.curInt->curAction->getTarget(owner.curInt->cb.get());
  211. if(!target.empty())
  212. currentActionTarget = target.at(0).hexValue;
  213. }
  214. //do not show box for singular war machines, stacked war machines with box shown are supported as extension feature
  215. if(stack->hasBonusOfType(Bonus::SIEGE_WEAPON) && stack->getCount() == 1)
  216. return false;
  217. if(!stack->alive())
  218. return false;
  219. //hide box when target is going to die anyway - do not display "0 creatures"
  220. if(stack->getCount() == 0)
  221. return false;
  222. // if stack has any ongoing animation - hide the box
  223. if (stackAmountBoxHidden.count(stack->ID))
  224. return false;
  225. return true;
  226. }
  227. std::shared_ptr<IImage> BattleStacksController::getStackAmountBox(const CStack * stack)
  228. {
  229. std::vector<si32> activeSpells = stack->activeSpells();
  230. if ( activeSpells.empty())
  231. return amountNormal;
  232. int effectsPositivness = 0;
  233. for ( auto const & spellID : activeSpells)
  234. effectsPositivness += CGI->spellh->objects.at(spellID)->positiveness;
  235. if (effectsPositivness > 0)
  236. return amountPositive;
  237. if (effectsPositivness < 0)
  238. return amountNegative;
  239. return amountEffNeutral;
  240. }
  241. void BattleStacksController::showStackAmountBox(Canvas & canvas, const CStack * stack)
  242. {
  243. auto amountBG = getStackAmountBox(stack);
  244. bool doubleWide = stack->doubleWide();
  245. bool turnedRight = facingRight(stack);
  246. bool attacker = stack->side == BattleSide::ATTACKER;
  247. BattleHex stackPos = stack->getPosition();
  248. // double-wide unit turned around - use opposite hex for stack label
  249. if (doubleWide && turnedRight != attacker)
  250. stackPos = stack->occupiedHex();
  251. BattleHex frontPos = turnedRight ?
  252. stackPos.cloneInDirection(BattleHex::RIGHT) :
  253. stackPos.cloneInDirection(BattleHex::LEFT);
  254. bool moveInside = !owner.fieldController->stackCountOutsideHex(frontPos);
  255. Point boxPosition;
  256. if (moveInside)
  257. {
  258. boxPosition = owner.fieldController->hexPositionLocal(stackPos).center() + Point(-15, 1);
  259. }
  260. else
  261. {
  262. if (turnedRight)
  263. boxPosition = owner.fieldController->hexPositionLocal(frontPos).center() + Point (-22, 1);
  264. else
  265. boxPosition = owner.fieldController->hexPositionLocal(frontPos).center() + Point(-8, -14);
  266. }
  267. Point textPosition = amountBG->dimensions()/2 + boxPosition;
  268. canvas.draw(amountBG, boxPosition);
  269. canvas.drawText(textPosition, EFonts::FONT_TINY, Colors::WHITE, ETextAlignment::CENTER, TextOperations::formatMetric(stack->getCount(), 4));
  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. stackAnimation[stack->ID]->nextFrame(canvas, fullFilter, facingRight(stack)); // do actual blit
  280. stackAnimation[stack->ID]->incrementFrame(float(GH.mainFPSmng->getElapsedMilliseconds()) / 1000);
  281. }
  282. void BattleStacksController::update()
  283. {
  284. updateHoveredStacks();
  285. updateBattleAnimations();
  286. }
  287. void BattleStacksController::initializeBattleAnimations()
  288. {
  289. auto copiedVector = currentAnimations;
  290. for (auto & elem : copiedVector)
  291. if (elem && !elem->isInitialized())
  292. elem->tryInitialize();
  293. }
  294. void BattleStacksController::stepFrameBattleAnimations()
  295. {
  296. // operate on copy - to prevent potential iterator invalidation due to push_back's
  297. // FIXME? : remove remaining calls to addNewAnim from BattleAnimation::nextFrame (only Catapult explosion at the time of writing)
  298. auto copiedVector = currentAnimations;
  299. for (auto & elem : copiedVector)
  300. if (elem && elem->isInitialized())
  301. elem->nextFrame();
  302. }
  303. void BattleStacksController::updateBattleAnimations()
  304. {
  305. bool hadAnimations = !currentAnimations.empty();
  306. initializeBattleAnimations();
  307. stepFrameBattleAnimations();
  308. vstd::erase(currentAnimations, nullptr);
  309. if (hadAnimations && currentAnimations.empty())
  310. {
  311. //stackAmountBoxHidden.clear();
  312. owner.executeStagedAnimations();
  313. if (currentAnimations.empty())
  314. owner.onAnimationsFinished();
  315. }
  316. initializeBattleAnimations();
  317. }
  318. void BattleStacksController::addNewAnim(BattleAnimation *anim)
  319. {
  320. if (currentAnimations.empty())
  321. stackAmountBoxHidden.clear();
  322. owner.onAnimationsStarted();
  323. currentAnimations.push_back(anim);
  324. auto stackAnimation = dynamic_cast<BattleStackAnimation*>(anim);
  325. if(stackAnimation)
  326. stackAmountBoxHidden.insert(stackAnimation->stack->ID);
  327. }
  328. void BattleStacksController::stackRemoved(uint32_t stackID)
  329. {
  330. if (getActiveStack() && getActiveStack()->ID == stackID)
  331. {
  332. BattleAction *action = new BattleAction();
  333. action->side = owner.defendingHeroInstance ? (owner.curInt->playerID == owner.defendingHeroInstance->tempOwner) : false;
  334. action->actionType = EActionType::CANCEL;
  335. action->stackNumber = getActiveStack()->ID;
  336. owner.givenCommand.setn(action);
  337. setActiveStack(nullptr);
  338. }
  339. }
  340. void BattleStacksController::stacksAreAttacked(std::vector<StackAttackedInfo> attackedInfos)
  341. {
  342. owner.addToAnimationStage(EAnimationEvents::HIT, [=](){
  343. // remove any potentially erased petrification effect
  344. removeExpiredColorFilters();
  345. });
  346. for(auto & attackedInfo : attackedInfos)
  347. {
  348. if (!attackedInfo.attacker)
  349. continue;
  350. // In H3, attacked stack will not reverse on ranged attack
  351. if (attackedInfo.indirectAttack)
  352. continue;
  353. // Another type of indirect attack - dragon breath
  354. if (!CStack::isMeleeAttackPossible(attackedInfo.attacker, attackedInfo.defender))
  355. continue;
  356. // defender need to face in direction opposited to out attacker
  357. bool needsReverse = shouldAttackFacingRight(attackedInfo.attacker, attackedInfo.defender) == facingRight(attackedInfo.defender);
  358. // FIXME: this check is better, however not usable since stacksAreAttacked is called after net pack is applyed - petrification is already removed
  359. // if (needsReverse && !attackedInfo.defender->isFrozen())
  360. if (needsReverse && stackAnimation[attackedInfo.defender->ID]->getType() != ECreatureAnimType::FROZEN)
  361. {
  362. owner.addToAnimationStage(EAnimationEvents::MOVEMENT, [=]()
  363. {
  364. addNewAnim(new ReverseAnimation(owner, attackedInfo.defender, attackedInfo.defender->getPosition()));
  365. });
  366. }
  367. }
  368. for(auto & attackedInfo : attackedInfos)
  369. {
  370. bool useDeathAnim = attackedInfo.killed;
  371. bool useDefenceAnim = attackedInfo.defender->defendingAnim && !attackedInfo.indirectAttack && !attackedInfo.killed;
  372. EAnimationEvents usedEvent = useDefenceAnim ? EAnimationEvents::ATTACK : EAnimationEvents::HIT;
  373. owner.addToAnimationStage(usedEvent, [=]()
  374. {
  375. if (useDeathAnim)
  376. addNewAnim(new DeathAnimation(owner, attackedInfo.defender, attackedInfo.indirectAttack));
  377. else if(useDefenceAnim)
  378. addNewAnim(new DefenceAnimation(owner, attackedInfo.defender));
  379. else
  380. addNewAnim(new HittedAnimation(owner, attackedInfo.defender));
  381. if (attackedInfo.fireShield)
  382. owner.effectsController->displayEffect(EBattleEffect::FIRE_SHIELD, "FIRESHIE", attackedInfo.attacker->getPosition());
  383. if (attackedInfo.spellEffect != SpellID::NONE)
  384. {
  385. auto spell = attackedInfo.spellEffect.toSpell();
  386. if (!spell->getCastSound().empty())
  387. CCS->soundh->playSound(spell->getCastSound());
  388. owner.displaySpellEffect(spell, attackedInfo.defender->getPosition());
  389. }
  390. });
  391. }
  392. for (auto & attackedInfo : attackedInfos)
  393. {
  394. if (attackedInfo.rebirth)
  395. {
  396. owner.addToAnimationStage(EAnimationEvents::AFTER_HIT, [=](){
  397. owner.effectsController->displayEffect(EBattleEffect::RESURRECT, "RESURECT", attackedInfo.defender->getPosition());
  398. addNewAnim(new ResurrectionAnimation(owner, attackedInfo.defender));
  399. });
  400. }
  401. if (attackedInfo.killed && attackedInfo.defender->summoned)
  402. {
  403. owner.addToAnimationStage(EAnimationEvents::AFTER_HIT, [=](){
  404. addNewAnim(new ColorTransformAnimation(owner, attackedInfo.defender, "summonFadeOut", nullptr));
  405. stackRemoved(attackedInfo.defender->ID);
  406. });
  407. }
  408. }
  409. owner.executeStagedAnimations();
  410. owner.waitForAnimations();
  411. }
  412. void BattleStacksController::stackTeleported(const CStack *stack, std::vector<BattleHex> destHex, int distance)
  413. {
  414. assert(destHex.size() > 0);
  415. owner.checkForAnimations();
  416. owner.addToAnimationStage(EAnimationEvents::HIT, [=](){
  417. addNewAnim( new ColorTransformAnimation(owner, stack, "teleportFadeOut", nullptr) );
  418. });
  419. owner.addToAnimationStage(EAnimationEvents::AFTER_HIT, [=](){
  420. stackAnimation[stack->ID]->pos.moveTo(getStackPositionAtHex(destHex.back(), stack));
  421. addNewAnim( new ColorTransformAnimation(owner, stack, "teleportFadeIn", nullptr) );
  422. });
  423. // animations will be executed by spell
  424. }
  425. void BattleStacksController::stackMoved(const CStack *stack, std::vector<BattleHex> destHex, int distance)
  426. {
  427. assert(destHex.size() > 0);
  428. owner.checkForAnimations();
  429. if(shouldRotate(stack, stack->getPosition(), destHex[0]))
  430. {
  431. owner.addToAnimationStage(EAnimationEvents::ROTATE, [&]()
  432. {
  433. addNewAnim(new ReverseAnimation(owner, stack, stack->getPosition()));
  434. });
  435. }
  436. owner.addToAnimationStage(EAnimationEvents::MOVE_START, [&]()
  437. {
  438. addNewAnim(new MovementStartAnimation(owner, stack));
  439. });
  440. if (!stack->hasBonus(Selector::typeSubtype(Bonus::FLYING, 1)))
  441. {
  442. owner.addToAnimationStage(EAnimationEvents::MOVEMENT, [&]()
  443. {
  444. addNewAnim(new MovementAnimation(owner, stack, destHex, distance));
  445. });
  446. }
  447. owner.addToAnimationStage(EAnimationEvents::MOVE_END, [&]()
  448. {
  449. addNewAnim(new MovementEndAnimation(owner, stack, destHex.back()));
  450. });
  451. owner.executeStagedAnimations();
  452. owner.waitForAnimations();
  453. }
  454. bool BattleStacksController::shouldAttackFacingRight(const CStack * attacker, const CStack * defender)
  455. {
  456. bool mustReverse = owner.curInt->cb->isToReverse(
  457. attacker,
  458. defender);
  459. if (attacker->side == BattleSide::ATTACKER)
  460. return !mustReverse;
  461. else
  462. return mustReverse;
  463. }
  464. void BattleStacksController::stackAttacking( const StackAttackInfo & info )
  465. {
  466. owner.checkForAnimations();
  467. auto attacker = info.attacker;
  468. auto defender = info.defender;
  469. auto tile = info.tile;
  470. auto spellEffect = info.spellEffect;
  471. auto multiAttack = !info.secondaryDefender.empty();
  472. bool needsReverse = false;
  473. if (info.indirectAttack)
  474. {
  475. needsReverse = shouldRotate(attacker, attacker->position, info.tile);
  476. }
  477. else
  478. {
  479. needsReverse = shouldAttackFacingRight(attacker, defender) != facingRight(attacker);
  480. }
  481. if (needsReverse)
  482. {
  483. owner.addToAnimationStage(EAnimationEvents::MOVEMENT, [=]()
  484. {
  485. addNewAnim(new ReverseAnimation(owner, attacker, attacker->getPosition()));
  486. });
  487. }
  488. if(info.lucky)
  489. {
  490. owner.addToAnimationStage(EAnimationEvents::BEFORE_HIT, [=]() {
  491. owner.appendBattleLog(info.attacker->formatGeneralMessage(-45));
  492. owner.effectsController->displayEffect(EBattleEffect::GOOD_LUCK, "GOODLUCK", attacker->getPosition());
  493. });
  494. }
  495. if(info.unlucky)
  496. {
  497. owner.addToAnimationStage(EAnimationEvents::BEFORE_HIT, [=]() {
  498. owner.appendBattleLog(info.attacker->formatGeneralMessage(-44));
  499. owner.effectsController->displayEffect(EBattleEffect::BAD_LUCK, "BADLUCK", attacker->getPosition());
  500. });
  501. }
  502. if(info.deathBlow)
  503. {
  504. owner.addToAnimationStage(EAnimationEvents::BEFORE_HIT, [=]() {
  505. owner.appendBattleLog(info.attacker->formatGeneralMessage(365));
  506. owner.effectsController->displayEffect(EBattleEffect::DEATH_BLOW, "DEATHBLO", defender->getPosition());
  507. });
  508. for(auto elem : info.secondaryDefender)
  509. {
  510. owner.addToAnimationStage(EAnimationEvents::BEFORE_HIT, [=]() {
  511. owner.effectsController->displayEffect(EBattleEffect::DEATH_BLOW, elem->getPosition());
  512. });
  513. }
  514. }
  515. owner.addToAnimationStage(EAnimationEvents::ATTACK, [=]()
  516. {
  517. if (info.indirectAttack)
  518. {
  519. addNewAnim(new ShootingAnimation(owner, attacker, tile, defender));
  520. }
  521. else
  522. {
  523. addNewAnim(new MeleeAttackAnimation(owner, attacker, tile, defender, multiAttack));
  524. }
  525. });
  526. if (info.spellEffect != SpellID::NONE)
  527. {
  528. owner.addToAnimationStage(EAnimationEvents::HIT, [=]()
  529. {
  530. owner.displaySpellHit(spellEffect.toSpell(), tile);
  531. });
  532. }
  533. if (info.lifeDrain)
  534. {
  535. owner.addToAnimationStage(EAnimationEvents::AFTER_HIT, [=]()
  536. {
  537. owner.effectsController->displayEffect(EBattleEffect::DRAIN_LIFE, "DRAINLIF", attacker->getPosition());
  538. });
  539. }
  540. //return, animation playback will be handled by stacksAreAttacked
  541. }
  542. bool BattleStacksController::shouldRotate(const CStack * stack, const BattleHex & oldPos, const BattleHex & nextHex) const
  543. {
  544. Point begPosition = getStackPositionAtHex(oldPos,stack);
  545. Point endPosition = getStackPositionAtHex(nextHex, stack);
  546. if((begPosition.x > endPosition.x) && facingRight(stack))
  547. return true;
  548. else if((begPosition.x < endPosition.x) && !facingRight(stack))
  549. return true;
  550. return false;
  551. }
  552. void BattleStacksController::endAction(const BattleAction* action)
  553. {
  554. owner.checkForAnimations();
  555. //check if we should reverse stacks
  556. TStacks stacks = owner.curInt->cb->battleGetStacks(CBattleCallback::MINE_AND_ENEMY);
  557. for (const CStack *s : stacks)
  558. {
  559. bool shouldFaceRight = s && s->side == BattleSide::ATTACKER;
  560. if (s && facingRight(s) != shouldFaceRight && s->alive() && stackAnimation[s->ID]->isIdle())
  561. {
  562. addNewAnim(new ReverseAnimation(owner, s, s->getPosition()));
  563. }
  564. }
  565. owner.executeStagedAnimations();
  566. owner.waitForAnimations();
  567. stackAmountBoxHidden.clear();
  568. owner.windowObject->blockUI(activeStack == nullptr);
  569. removeExpiredColorFilters();
  570. }
  571. void BattleStacksController::startAction(const BattleAction* action)
  572. {
  573. removeExpiredColorFilters();
  574. }
  575. void BattleStacksController::stackActivated(const CStack *stack)
  576. {
  577. stackToActivate = stack;
  578. owner.waitForAnimations();
  579. logAnim->debug("Activating next stack");
  580. owner.activateStack();
  581. }
  582. void BattleStacksController::deactivateStack()
  583. {
  584. if (!activeStack) {
  585. return;
  586. }
  587. stackToActivate = activeStack;
  588. setActiveStack(nullptr);
  589. }
  590. void BattleStacksController::activateStack()
  591. {
  592. if ( !currentAnimations.empty())
  593. return;
  594. if ( !stackToActivate)
  595. return;
  596. owner.trySetActivePlayer(stackToActivate->owner);
  597. setActiveStack(stackToActivate);
  598. stackToActivate = nullptr;
  599. const CStack * s = getActiveStack();
  600. if(!s)
  601. return;
  602. }
  603. const CStack* BattleStacksController::getActiveStack() const
  604. {
  605. return activeStack;
  606. }
  607. bool BattleStacksController::facingRight(const CStack * stack) const
  608. {
  609. return stackFacingRight.at(stack->ID);
  610. }
  611. Point BattleStacksController::getStackPositionAtHex(BattleHex hexNum, const CStack * stack) const
  612. {
  613. Point ret(-500, -500); //returned value
  614. if(stack && stack->initialPosition < 0) //creatures in turrets
  615. return owner.siegeController->getTurretCreaturePosition(stack->initialPosition);
  616. static const Point basePos(-189, -139); // position of creature in topleft corner
  617. static const int imageShiftX = 29; // X offset to base pos for facing right stacks, negative for facing left
  618. ret.x = basePos.x + 22 * ( (hexNum.getY() + 1)%2 ) + 44 * hexNum.getX();
  619. ret.y = basePos.y + 42 * hexNum.getY();
  620. if (stack)
  621. {
  622. if(facingRight(stack))
  623. ret.x += imageShiftX;
  624. else
  625. ret.x -= imageShiftX;
  626. //shifting position for double - hex creatures
  627. if(stack->doubleWide())
  628. {
  629. if(stack->side == BattleSide::ATTACKER)
  630. {
  631. if(facingRight(stack))
  632. ret.x -= 44;
  633. }
  634. else
  635. {
  636. if(!facingRight(stack))
  637. ret.x += 44;
  638. }
  639. }
  640. }
  641. //returning
  642. return ret;
  643. }
  644. void BattleStacksController::setStackColorFilter(const ColorFilter & effect, const CStack * target, const CSpell * source, bool persistent)
  645. {
  646. for (auto & filter : stackFilterEffects)
  647. {
  648. if (filter.target == target && filter.source == source)
  649. {
  650. filter.effect = effect;
  651. filter.persistent = persistent;
  652. return;
  653. }
  654. }
  655. stackFilterEffects.push_back({ effect, target, source, persistent });
  656. }
  657. void BattleStacksController::removeExpiredColorFilters()
  658. {
  659. vstd::erase_if(stackFilterEffects, [&](const BattleStackFilterEffect & filter)
  660. {
  661. if (!filter.persistent)
  662. {
  663. if (filter.source && !filter.target->hasBonus(Selector::source(Bonus::SPELL_EFFECT, filter.source->id), Selector::all))
  664. return true;
  665. if (filter.effect == ColorFilter::genEmptyShifter())
  666. return true;
  667. }
  668. return false;
  669. });
  670. }
  671. void BattleStacksController::updateHoveredStacks()
  672. {
  673. auto newStacks = selectHoveredStacks();
  674. for (auto const * stack : mouseHoveredStacks)
  675. {
  676. if (vstd::contains(newStacks, stack))
  677. continue;
  678. if (stack == activeStack)
  679. stackAnimation[stack->ID]->setBorderColor(AnimationControls::getGoldBorder());
  680. else
  681. stackAnimation[stack->ID]->setBorderColor(AnimationControls::getNoBorder());
  682. }
  683. for (auto const * stack : newStacks)
  684. {
  685. if (vstd::contains(mouseHoveredStacks, stack))
  686. continue;
  687. stackAnimation[stack->ID]->setBorderColor(AnimationControls::getBlueBorder());
  688. if (stackAnimation[stack->ID]->framesInGroup(ECreatureAnimType::MOUSEON) > 0 && stack->alive() && !stack->isFrozen())
  689. stackAnimation[stack->ID]->playOnce(ECreatureAnimType::MOUSEON);
  690. }
  691. mouseHoveredStacks = newStacks;
  692. }
  693. std::vector<const CStack *> BattleStacksController::selectHoveredStacks()
  694. {
  695. // only allow during our turn - do not try to highlight creatures while they are in the middle of actions
  696. if (!activeStack)
  697. return {};
  698. if(owner.hasAnimations())
  699. return {};
  700. auto hoveredQueueUnitId = owner.windowObject->getQueueHoveredUnitId();
  701. if(hoveredQueueUnitId.is_initialized())
  702. {
  703. return { owner.curInt->cb->battleGetStackByID(hoveredQueueUnitId.value(), true) };
  704. }
  705. auto hoveredHex = owner.fieldController->getHoveredHex();
  706. if (!hoveredHex.isValid())
  707. return {};
  708. const spells::Caster *caster = nullptr;
  709. const CSpell *spell = nullptr;
  710. spells::Mode mode = owner.actionsController->getCurrentCastMode();
  711. spell = owner.actionsController->getCurrentSpell(hoveredHex);
  712. caster = owner.actionsController->getCurrentSpellcaster();
  713. if(caster && spell && owner.actionsController->currentActionSpellcasting(hoveredHex) ) //when casting spell
  714. {
  715. spells::Target target;
  716. target.emplace_back(hoveredHex);
  717. spells::BattleCast event(owner.curInt->cb.get(), caster, mode, spell);
  718. auto mechanics = spell->battleMechanics(&event);
  719. return mechanics->getAffectedStacks(target);
  720. }
  721. if(hoveredHex.isValid())
  722. {
  723. const CStack * const stack = owner.curInt->cb->battleGetStackByPos(hoveredHex, true);
  724. if (stack)
  725. return {stack};
  726. }
  727. return {};
  728. }
  729. const std::vector<uint32_t> BattleStacksController::getHoveredStacksUnitIds() const
  730. {
  731. auto result = std::vector<uint32_t>();
  732. for (auto const * stack : mouseHoveredStacks)
  733. {
  734. result.push_back(stack->unitId());
  735. }
  736. return result;
  737. }