BattleStacksController.cpp 27 KB

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