BattleStacksController.cpp 27 KB

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