BattleStacksController.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  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 "BattleAnimationClasses.h"
  16. #include "BattleFieldController.h"
  17. #include "BattleEffectsController.h"
  18. #include "BattleProjectileController.h"
  19. #include "BattleControlPanel.h"
  20. #include "BattleRenderer.h"
  21. #include "CreatureAnimation.h"
  22. #include "../CPlayerInterface.h"
  23. #include "../CMusicHandler.h"
  24. #include "../CGameInfo.h"
  25. #include "../gui/CAnimation.h"
  26. #include "../gui/CGuiHandler.h"
  27. #include "../gui/Canvas.h"
  28. #include "../../CCallback.h"
  29. #include "../../lib/battle/BattleHex.h"
  30. #include "../../lib/CGameState.h"
  31. #include "../../lib/CStack.h"
  32. #include "../../lib/CondSh.h"
  33. static void onAnimationFinished(const CStack *stack, std::weak_ptr<CreatureAnimation> anim)
  34. {
  35. std::shared_ptr<CreatureAnimation> animation = anim.lock();
  36. if(!animation)
  37. return;
  38. if (animation->isIdle())
  39. {
  40. const CCreature *creature = stack->getCreature();
  41. if (animation->framesInGroup(ECreatureAnimType::MOUSEON) > 0)
  42. {
  43. if (CRandomGenerator::getDefault().nextDouble(99.0) < creature->animation.timeBetweenFidgets *10)
  44. animation->playOnce(ECreatureAnimType::MOUSEON);
  45. else
  46. animation->setType(ECreatureAnimType::HOLDING);
  47. }
  48. else
  49. {
  50. animation->setType(ECreatureAnimType::HOLDING);
  51. }
  52. }
  53. // always reset callback
  54. animation->onAnimationReset += std::bind(&onAnimationFinished, stack, anim);
  55. }
  56. BattleStacksController::BattleStacksController(BattleInterface & owner):
  57. owner(owner),
  58. activeStack(nullptr),
  59. mouseHoveredStack(nullptr),
  60. stackToActivate(nullptr),
  61. selectedStack(nullptr),
  62. stackCanCastSpell(false),
  63. creatureSpellToCast(uint32_t(-1)),
  64. animIDhelper(0)
  65. {
  66. //preparing graphics for displaying amounts of creatures
  67. amountNormal = IImage::createFromFile("CMNUMWIN.BMP");
  68. amountPositive = IImage::createFromFile("CMNUMWIN.BMP");
  69. amountNegative = IImage::createFromFile("CMNUMWIN.BMP");
  70. amountEffNeutral = IImage::createFromFile("CMNUMWIN.BMP");
  71. static const auto shifterNormal = ColorFilter::genRangeShifter( 0,0,0, 0.6, 0.2, 1.0 );
  72. static const auto shifterPositive = ColorFilter::genRangeShifter( 0,0,0, 0.2, 1.0, 0.2 );
  73. static const auto shifterNegative = ColorFilter::genRangeShifter( 0,0,0, 1.0, 0.2, 0.2 );
  74. static const auto shifterNeutral = ColorFilter::genRangeShifter( 0,0,0, 1.0, 1.0, 0.2 );
  75. amountNormal->adjustPalette(shifterNormal);
  76. amountPositive->adjustPalette(shifterPositive);
  77. amountNegative->adjustPalette(shifterNegative);
  78. amountEffNeutral->adjustPalette(shifterNeutral);
  79. //Restore border color {255, 231, 132, 255} to its original state
  80. amountNormal->resetPalette(26);
  81. amountPositive->resetPalette(26);
  82. amountNegative->resetPalette(26);
  83. amountEffNeutral->resetPalette(26);
  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->ID)->isMoving())
  93. return stack->getPosition();
  94. if (stack->hasBonusOfType(Bonus::FLYING) && stackAnimation.at(stack->ID)->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 move->currentHex;
  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->ID) == stackAnimation.end()) //e.g. for summoned but not yet handled stacks
  116. continue;
  117. //FIXME: hack to ignore ghost stacks
  118. if ((stackAnimation[stack->ID]->getType() == ECreatureAnimType::DEAD || stackAnimation[stack->ID]->getType() == ECreatureAnimType::HOLDING) && stack->isGhost())
  119. continue;
  120. auto layer = stackAnimation[stack->ID]->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. assert(owner.getAnimationCondition(EAnimationEvents::ACTION) == false);
  136. //reset orientation?
  137. //stackFacingRight[stack->ID] = stack->side == BattleSide::ATTACKER;
  138. auto iter = stackAnimation.find(stack->ID);
  139. if(iter == stackAnimation.end())
  140. {
  141. logGlobal->error("Unit %d have no animation", stack->ID);
  142. return;
  143. }
  144. auto animation = iter->second;
  145. if(stack->alive() && animation->isDeadOrDying())
  146. {
  147. owner.executeOnAnimationCondition(EAnimationEvents::HIT, true, [=]()
  148. {
  149. addNewAnim(new ResurrectionAnimation(owner, stack));
  150. });
  151. }
  152. }
  153. void BattleStacksController::stackAdded(const CStack * stack, bool instant)
  154. {
  155. // Tower shooters have only their upper half visible
  156. static const int turretCreatureAnimationHeight = 235;
  157. stackFacingRight[stack->ID] = stack->side == BattleSide::ATTACKER; // must be set before getting stack position
  158. Point coords = getStackPositionAtHex(stack->getPosition(), stack);
  159. if(stack->initialPosition < 0) //turret
  160. {
  161. assert(owner.siegeController);
  162. const CCreature *turretCreature = owner.siegeController->getTurretCreature();
  163. stackAnimation[stack->ID] = AnimationControls::getAnimation(turretCreature);
  164. stackAnimation[stack->ID]->pos.h = turretCreatureAnimationHeight;
  165. coords = owner.siegeController->getTurretCreaturePosition(stack->initialPosition);
  166. }
  167. else
  168. {
  169. stackAnimation[stack->ID] = AnimationControls::getAnimation(stack->getCreature());
  170. stackAnimation[stack->ID]->onAnimationReset += std::bind(&onAnimationFinished, stack, stackAnimation[stack->ID]);
  171. stackAnimation[stack->ID]->pos.h = stackAnimation[stack->ID]->getHeight();
  172. }
  173. stackAnimation[stack->ID]->pos.x = coords.x;
  174. stackAnimation[stack->ID]->pos.y = coords.y;
  175. stackAnimation[stack->ID]->pos.w = stackAnimation[stack->ID]->getWidth();
  176. stackAnimation[stack->ID]->setType(ECreatureAnimType::HOLDING);
  177. if (!instant)
  178. {
  179. // immediately make stack transparent, giving correct shifter time to start
  180. auto shifterFade = ColorFilter::genAlphaShifter(0);
  181. setStackColorFilter(shifterFade, stack, nullptr, true);
  182. owner.executeOnAnimationCondition(EAnimationEvents::HIT, true, [=]()
  183. {
  184. addNewAnim(ColorTransformAnimation::fadeInAnimation(owner, stack));
  185. if (stack->isClone())
  186. addNewAnim(ColorTransformAnimation::cloneAnimation(owner, stack, SpellID(SpellID::CLONE).toSpell()));
  187. });
  188. }
  189. }
  190. void BattleStacksController::setActiveStack(const CStack *stack)
  191. {
  192. if (activeStack) // update UI
  193. stackAnimation[activeStack->ID]->setBorderColor(AnimationControls::getNoBorder());
  194. activeStack = stack;
  195. if (activeStack) // update UI
  196. stackAnimation[activeStack->ID]->setBorderColor(AnimationControls::getGoldBorder());
  197. owner.controlPanel->blockUI(activeStack == nullptr);
  198. }
  199. void BattleStacksController::setHoveredStack(const CStack *stack)
  200. {
  201. if ( stack == mouseHoveredStack )
  202. return;
  203. if (mouseHoveredStack)
  204. stackAnimation[mouseHoveredStack->ID]->setBorderColor(AnimationControls::getNoBorder());
  205. // stack must be alive and not active (which uses gold border instead)
  206. if (stack && stack->alive() && stack != activeStack)
  207. {
  208. mouseHoveredStack = stack;
  209. if (mouseHoveredStack)
  210. {
  211. stackAnimation[mouseHoveredStack->ID]->setBorderColor(AnimationControls::getBlueBorder());
  212. if (stackAnimation[mouseHoveredStack->ID]->framesInGroup(ECreatureAnimType::MOUSEON) > 0)
  213. stackAnimation[mouseHoveredStack->ID]->playOnce(ECreatureAnimType::MOUSEON);
  214. }
  215. }
  216. else
  217. mouseHoveredStack = nullptr;
  218. }
  219. bool BattleStacksController::stackNeedsAmountBox(const CStack * stack) const
  220. {
  221. BattleHex currentActionTarget;
  222. if(owner.curInt->curAction)
  223. {
  224. auto target = owner.curInt->curAction->getTarget(owner.curInt->cb.get());
  225. if(!target.empty())
  226. currentActionTarget = target.at(0).hexValue;
  227. }
  228. if(stack->hasBonusOfType(Bonus::SIEGE_WEAPON) && stack->getCount() == 1) //do not show box for singular war machines, stacked war machines with box shown are supported as extension feature
  229. return false;
  230. if (!owner.battleActionsStarted) // do not perform any further checks since they are related to actions that will only occur after intro music
  231. return true;
  232. if(!stack->alive())
  233. return false;
  234. if(stack->getCount() == 0) //hide box when target is going to die anyway - do not display "0 creatures"
  235. return false;
  236. for(auto anim : currentAnimations) //no matter what other conditions below are, hide box when creature is playing hit animation
  237. {
  238. auto hitAnimation = dynamic_cast<DefenceAnimation*>(anim);
  239. if(hitAnimation && (hitAnimation->stack->ID == stack->ID))
  240. return false;
  241. }
  242. if(owner.curInt->curAction)
  243. {
  244. if(owner.curInt->curAction->stackNumber == stack->ID) //stack is currently taking action (is not a target of another creature's action etc)
  245. {
  246. if(owner.curInt->curAction->actionType == EActionType::WALK || owner.curInt->curAction->actionType == EActionType::SHOOT) //hide when stack walks or shoots
  247. return false;
  248. else if(owner.curInt->curAction->actionType == EActionType::WALK_AND_ATTACK && currentActionTarget != stack->getPosition()) //when attacking, hide until walk phase finished
  249. return false;
  250. }
  251. if(owner.curInt->curAction->actionType == EActionType::SHOOT && currentActionTarget == stack->getPosition()) //hide if we are ranged attack target
  252. return false;
  253. }
  254. return true;
  255. }
  256. std::shared_ptr<IImage> BattleStacksController::getStackAmountBox(const CStack * stack)
  257. {
  258. std::vector<si32> activeSpells = stack->activeSpells();
  259. if ( activeSpells.empty())
  260. return amountNormal;
  261. int effectsPositivness = 0;
  262. for ( auto const & spellID : activeSpells)
  263. effectsPositivness += CGI->spellh->objects.at(spellID)->positiveness;
  264. if (effectsPositivness > 0)
  265. return amountPositive;
  266. if (effectsPositivness < 0)
  267. return amountNegative;
  268. return amountEffNeutral;
  269. }
  270. void BattleStacksController::showStackAmountBox(Canvas & canvas, const CStack * stack)
  271. {
  272. //blitting amount background box
  273. auto amountBG = getStackAmountBox(stack);
  274. const int sideShift = stack->side == BattleSide::ATTACKER ? 1 : -1;
  275. const int reverseSideShift = stack->side == BattleSide::ATTACKER ? -1 : 1;
  276. const BattleHex nextPos = stack->getPosition() + sideShift;
  277. const bool edge = stack->getPosition() % GameConstants::BFIELD_WIDTH == (stack->side == BattleSide::ATTACKER ? GameConstants::BFIELD_WIDTH - 2 : 1);
  278. const bool moveInside = !edge && !owner.fieldController->stackCountOutsideHex(nextPos);
  279. int xAdd = (stack->side == BattleSide::ATTACKER ? 220 : 202) +
  280. (stack->doubleWide() ? 44 : 0) * sideShift +
  281. (moveInside ? amountBG->width() + 10 : 0) * reverseSideShift;
  282. int yAdd = 260 + ((stack->side == BattleSide::ATTACKER || moveInside) ? 0 : -15);
  283. canvas.draw(amountBG, stackAnimation[stack->ID]->pos.topLeft() + Point(xAdd, yAdd));
  284. //blitting amount
  285. Point textPos = stackAnimation[stack->ID]->pos.topLeft() + amountBG->dimensions()/2 + Point(xAdd, yAdd);
  286. canvas.drawText(textPos, EFonts::FONT_TINY, Colors::WHITE, ETextAlignment::CENTER, makeNumberShort(stack->getCount()));
  287. }
  288. void BattleStacksController::showStack(Canvas & canvas, const CStack * stack)
  289. {
  290. ColorFilter fullFilter = ColorFilter::genEmptyShifter();
  291. for (auto const & filter : stackFilterEffects)
  292. {
  293. if (filter.target == stack)
  294. fullFilter = ColorFilter::genCombined(fullFilter, filter.effect);
  295. }
  296. bool stackHasProjectile = owner.projectilesController->hasActiveProjectile(stack, true);
  297. //bool stackPetrified = stack->hasBonus(Selector::source(Bonus::SPELL_EFFECT, SpellID::STONE_GAZE));
  298. //bool stackFrozen = stackHasProjectile || stackPetrified;
  299. if (stackHasProjectile)
  300. stackAnimation[stack->ID]->pause();
  301. else
  302. stackAnimation[stack->ID]->play();
  303. stackAnimation[stack->ID]->nextFrame(canvas, fullFilter, facingRight(stack)); // do actual blit
  304. stackAnimation[stack->ID]->incrementFrame(float(GH.mainFPSmng->getElapsedMilliseconds()) / 1000);
  305. }
  306. void BattleStacksController::updateBattleAnimations()
  307. {
  308. for (auto & elem : currentAnimations)
  309. {
  310. if (!elem)
  311. continue;
  312. if (elem->isInitialized())
  313. elem->nextFrame();
  314. else
  315. elem->tryInitialize();
  316. }
  317. bool hadAnimations = !currentAnimations.empty();
  318. vstd::erase(currentAnimations, nullptr);
  319. if (hadAnimations && currentAnimations.empty())
  320. {
  321. //anims ended
  322. owner.setAnimationCondition(EAnimationEvents::ACTION, false);
  323. }
  324. }
  325. void BattleStacksController::addNewAnim(BattleAnimation *anim)
  326. {
  327. currentAnimations.push_back(anim);
  328. owner.setAnimationCondition(EAnimationEvents::ACTION, true);
  329. }
  330. void BattleStacksController::stackRemoved(uint32_t stackID)
  331. {
  332. if (getActiveStack() && getActiveStack()->ID == stackID)
  333. {
  334. BattleAction *action = new BattleAction();
  335. action->side = owner.defendingHeroInstance ? (owner.curInt->playerID == owner.defendingHeroInstance->tempOwner) : false;
  336. action->actionType = EActionType::CANCEL;
  337. action->stackNumber = getActiveStack()->ID;
  338. owner.givenCommand.setn(action);
  339. setActiveStack(nullptr);
  340. }
  341. }
  342. void BattleStacksController::stacksAreAttacked(std::vector<StackAttackedInfo> attackedInfos)
  343. {
  344. owner.executeOnAnimationCondition(EAnimationEvents::HIT, true, [=](){
  345. // remove any potentially erased petrification effect
  346. removeExpiredColorFilters();
  347. });
  348. for(auto & attackedInfo : attackedInfos)
  349. {
  350. if (!attackedInfo.attacker)
  351. continue;
  352. bool needsReverse =
  353. owner.curInt->cb->isToReverse(
  354. attackedInfo.defender->getPosition(),
  355. attackedInfo.attacker->getPosition(),
  356. facingRight(attackedInfo.defender),
  357. attackedInfo.attacker->doubleWide(),
  358. facingRight(attackedInfo.attacker));
  359. if (needsReverse)
  360. {
  361. owner.executeOnAnimationCondition(EAnimationEvents::MOVEMENT, true, [=]()
  362. {
  363. addNewAnim(new ReverseAnimation(owner, attackedInfo.defender, attackedInfo.defender->getPosition()));
  364. });
  365. }
  366. }
  367. for(auto & attackedInfo : attackedInfos)
  368. {
  369. bool useDeathAnim = attackedInfo.killed;
  370. bool useDefenceAnim = attackedInfo.defender->defendingAnim && !attackedInfo.indirectAttack && !attackedInfo.killed;
  371. EAnimationEvents usedEvent = useDefenceAnim ? EAnimationEvents::ATTACK : EAnimationEvents::HIT;
  372. owner.executeOnAnimationCondition(usedEvent, true, [=]()
  373. {
  374. if (useDeathAnim)
  375. addNewAnim(new DeathAnimation(owner, attackedInfo.defender, attackedInfo.indirectAttack));
  376. else if(useDefenceAnim)
  377. addNewAnim(new DefenceAnimation(owner, attackedInfo.defender));
  378. else
  379. addNewAnim(new HittedAnimation(owner, attackedInfo.defender));
  380. if (attackedInfo.battleEffect != EBattleEffect::INVALID)
  381. owner.effectsController->displayEffect(EBattleEffect::EBattleEffect(attackedInfo.battleEffect), attackedInfo.defender->getPosition());
  382. if (attackedInfo.spellEffect != SpellID::NONE)
  383. owner.displaySpellEffect(attackedInfo.spellEffect, attackedInfo.defender->getPosition());
  384. });
  385. }
  386. for (auto & attackedInfo : attackedInfos)
  387. {
  388. if (attackedInfo.rebirth)
  389. {
  390. owner.executeOnAnimationCondition(EAnimationEvents::AFTER_HIT, true, [=](){
  391. owner.effectsController->displayEffect(EBattleEffect::RESURRECT, soundBase::RESURECT, attackedInfo.defender->getPosition());
  392. addNewAnim(new ResurrectionAnimation(owner, attackedInfo.defender));
  393. });
  394. }
  395. if (attackedInfo.killed && attackedInfo.defender->summoned)
  396. {
  397. owner.executeOnAnimationCondition(EAnimationEvents::AFTER_HIT, true, [=](){
  398. addNewAnim(ColorTransformAnimation::fadeOutAnimation(owner, attackedInfo.defender));
  399. stackRemoved(attackedInfo.defender->ID);
  400. });
  401. }
  402. }
  403. executeAttackAnimations();
  404. }
  405. void BattleStacksController::stackMoved(const CStack *stack, std::vector<BattleHex> destHex, int distance)
  406. {
  407. assert(destHex.size() > 0);
  408. assert(owner.getAnimationCondition(EAnimationEvents::ACTION) == false);
  409. if(shouldRotate(stack, stack->getPosition(), destHex[0]))
  410. addNewAnim(new ReverseAnimation(owner, stack, destHex[0]));
  411. addNewAnim(new MovementStartAnimation(owner, stack));
  412. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  413. addNewAnim(new MovementAnimation(owner, stack, destHex, distance));
  414. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  415. addNewAnim(new MovementEndAnimation(owner, stack, destHex.back()));
  416. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  417. }
  418. void BattleStacksController::stackAttacking( const StackAttackInfo & info )
  419. {
  420. assert(owner.getAnimationCondition(EAnimationEvents::ACTION) == false);
  421. bool needsReverse =
  422. owner.curInt->cb->isToReverse(
  423. info.attacker->getPosition(),
  424. info.defender->getPosition(),
  425. facingRight(info.attacker),
  426. info.attacker->doubleWide(),
  427. facingRight(info.defender));
  428. auto attacker = info.attacker;
  429. auto defender = info.defender;
  430. auto tile = info.tile;
  431. auto spellEffect = info.spellEffect;
  432. auto multiAttack = !info.secondaryDefender.empty();
  433. if (needsReverse)
  434. {
  435. owner.executeOnAnimationCondition(EAnimationEvents::MOVEMENT, true, [=]()
  436. {
  437. addNewAnim(new ReverseAnimation(owner, attacker, attacker->getPosition()));
  438. });
  439. }
  440. if(info.lucky)
  441. {
  442. owner.executeOnAnimationCondition(EAnimationEvents::BEFORE_HIT, true, [=]() {
  443. owner.controlPanel->console->addText(info.attacker->formatGeneralMessage(-45));
  444. owner.effectsController->displayEffect(EBattleEffect::GOOD_LUCK, soundBase::GOODLUCK, attacker->getPosition());
  445. });
  446. }
  447. if(info.unlucky)
  448. {
  449. owner.executeOnAnimationCondition(EAnimationEvents::BEFORE_HIT, true, [=]() {
  450. owner.controlPanel->console->addText(info.attacker->formatGeneralMessage(-44));
  451. owner.effectsController->displayEffect(EBattleEffect::BAD_LUCK, soundBase::BADLUCK, attacker->getPosition());
  452. });
  453. }
  454. if(info.deathBlow)
  455. {
  456. owner.executeOnAnimationCondition(EAnimationEvents::BEFORE_HIT, true, [=]() {
  457. owner.controlPanel->console->addText(info.attacker->formatGeneralMessage(365));
  458. owner.effectsController->displayEffect(EBattleEffect::DEATH_BLOW, soundBase::deathBlow, defender->getPosition());
  459. });
  460. for(auto elem : info.secondaryDefender)
  461. {
  462. owner.executeOnAnimationCondition(EAnimationEvents::BEFORE_HIT, true, [=]() {
  463. owner.effectsController->displayEffect(EBattleEffect::DEATH_BLOW, elem->getPosition());
  464. });
  465. }
  466. }
  467. owner.executeOnAnimationCondition(EAnimationEvents::ATTACK, true, [=]()
  468. {
  469. if (info.indirectAttack)
  470. {
  471. addNewAnim(new ShootingAnimation(owner, attacker, tile, defender));
  472. }
  473. else
  474. {
  475. addNewAnim(new MeleeAttackAnimation(owner, attacker, tile, defender, multiAttack));
  476. }
  477. });
  478. if (info.spellEffect != SpellID::NONE)
  479. {
  480. owner.executeOnAnimationCondition(EAnimationEvents::HIT, true, [=]()
  481. {
  482. owner.displaySpellHit(spellEffect, tile);
  483. });
  484. }
  485. if (info.lifeDrain)
  486. {
  487. owner.executeOnAnimationCondition(EAnimationEvents::AFTER_HIT, true, [=]()
  488. {
  489. owner.effectsController->displayEffect(EBattleEffect::DRAIN_LIFE, soundBase::DRAINLIF, attacker->getPosition());
  490. });
  491. }
  492. //return, animation playback will be handled by stacksAreAttacked
  493. }
  494. void BattleStacksController::executeAttackAnimations()
  495. {
  496. owner.setAnimationCondition(EAnimationEvents::MOVEMENT, true);
  497. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  498. owner.setAnimationCondition(EAnimationEvents::MOVEMENT, false);
  499. owner.setAnimationCondition(EAnimationEvents::BEFORE_HIT, true);
  500. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  501. owner.setAnimationCondition(EAnimationEvents::BEFORE_HIT, false);
  502. owner.setAnimationCondition(EAnimationEvents::ATTACK, true);
  503. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  504. owner.setAnimationCondition(EAnimationEvents::ATTACK, false);
  505. // Note that HIT event can also be emitted by attack animation
  506. owner.setAnimationCondition(EAnimationEvents::HIT, true);
  507. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  508. owner.setAnimationCondition(EAnimationEvents::HIT, false);
  509. owner.setAnimationCondition(EAnimationEvents::AFTER_HIT, true);
  510. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  511. owner.setAnimationCondition(EAnimationEvents::AFTER_HIT, false);
  512. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  513. }
  514. bool BattleStacksController::shouldRotate(const CStack * stack, const BattleHex & oldPos, const BattleHex & nextHex) const
  515. {
  516. Point begPosition = getStackPositionAtHex(oldPos,stack);
  517. Point endPosition = getStackPositionAtHex(nextHex, stack);
  518. if((begPosition.x > endPosition.x) && facingRight(stack))
  519. return true;
  520. else if((begPosition.x < endPosition.x) && !facingRight(stack))
  521. return true;
  522. return false;
  523. }
  524. void BattleStacksController::endAction(const BattleAction* action)
  525. {
  526. assert(owner.getAnimationCondition(EAnimationEvents::ACTION) == false);
  527. //check if we should reverse stacks
  528. TStacks stacks = owner.curInt->cb->battleGetStacks(CBattleCallback::MINE_AND_ENEMY);
  529. for (const CStack *s : stacks)
  530. {
  531. bool shouldFaceRight = s && s->side == BattleSide::ATTACKER;
  532. if (s && facingRight(s) != shouldFaceRight && s->alive() && stackAnimation[s->ID]->isIdle())
  533. {
  534. addNewAnim(new ReverseAnimation(owner, s, s->getPosition()));
  535. }
  536. }
  537. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  538. //Ensure that all animation flags were reset
  539. assert(owner.getAnimationCondition(EAnimationEvents::OPENING) == false);
  540. assert(owner.getAnimationCondition(EAnimationEvents::ACTION) == false);
  541. assert(owner.getAnimationCondition(EAnimationEvents::MOVEMENT) == false);
  542. assert(owner.getAnimationCondition(EAnimationEvents::ATTACK) == false);
  543. assert(owner.getAnimationCondition(EAnimationEvents::HIT) == false);
  544. assert(owner.getAnimationCondition(EAnimationEvents::PROJECTILES) == false);
  545. owner.controlPanel->blockUI(activeStack == nullptr);
  546. removeExpiredColorFilters();
  547. }
  548. void BattleStacksController::startAction(const BattleAction* action)
  549. {
  550. setHoveredStack(nullptr);
  551. removeExpiredColorFilters();
  552. }
  553. void BattleStacksController::stackActivated(const CStack *stack) //TODO: check it all before game state is changed due to abilities
  554. {
  555. stackToActivate = stack;
  556. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  557. owner.activateStack();
  558. }
  559. void BattleStacksController::activateStack() //TODO: check it all before game state is changed due to abilities
  560. {
  561. if ( !currentAnimations.empty())
  562. return;
  563. if ( !stackToActivate)
  564. return;
  565. owner.trySetActivePlayer(stackToActivate->owner);
  566. setActiveStack(stackToActivate);
  567. stackToActivate = nullptr;
  568. const CStack * s = getActiveStack();
  569. if(!s)
  570. return;
  571. //set casting flag to true if creature can use it to not check it every time
  572. const auto spellcaster = s->getBonusLocalFirst(Selector::type()(Bonus::SPELLCASTER));
  573. const auto randomSpellcaster = s->getBonusLocalFirst(Selector::type()(Bonus::RANDOM_SPELLCASTER));
  574. if(s->canCast() && (spellcaster || randomSpellcaster))
  575. {
  576. stackCanCastSpell = true;
  577. if(randomSpellcaster)
  578. creatureSpellToCast = -1; //spell will be set later on cast
  579. else
  580. creatureSpellToCast = owner.curInt->cb->battleGetRandomStackSpell(CRandomGenerator::getDefault(), s, CBattleInfoCallback::RANDOM_AIMED); //faerie dragon can cast only one spell until their next move
  581. //TODO: what if creature can cast BOTH random genie spell and aimed spell?
  582. //TODO: faerie dragon type spell should be selected by server
  583. }
  584. else
  585. {
  586. stackCanCastSpell = false;
  587. creatureSpellToCast = -1;
  588. }
  589. }
  590. void BattleStacksController::setSelectedStack(const CStack *stack)
  591. {
  592. selectedStack = stack;
  593. }
  594. const CStack* BattleStacksController::getSelectedStack() const
  595. {
  596. return selectedStack;
  597. }
  598. const CStack* BattleStacksController::getActiveStack() const
  599. {
  600. return activeStack;
  601. }
  602. bool BattleStacksController::facingRight(const CStack * stack) const
  603. {
  604. return stackFacingRight.at(stack->ID);
  605. }
  606. bool BattleStacksController::activeStackSpellcaster()
  607. {
  608. return stackCanCastSpell;
  609. }
  610. SpellID BattleStacksController::activeStackSpellToCast()
  611. {
  612. if (!stackCanCastSpell)
  613. return SpellID::NONE;
  614. return SpellID(creatureSpellToCast);
  615. }
  616. Point BattleStacksController::getStackPositionAtHex(BattleHex hexNum, const CStack * stack) const
  617. {
  618. Point ret(-500, -500); //returned value
  619. if(stack && stack->initialPosition < 0) //creatures in turrets
  620. return owner.siegeController->getTurretCreaturePosition(stack->initialPosition);
  621. static const Point basePos(-190, -139); // position of creature in topleft corner
  622. static const int imageShiftX = 30; // X offset to base pos for facing right stacks, negative for facing left
  623. ret.x = basePos.x + 22 * ( (hexNum.getY() + 1)%2 ) + 44 * hexNum.getX();
  624. ret.y = basePos.y + 42 * hexNum.getY();
  625. if (stack)
  626. {
  627. if(facingRight(stack))
  628. ret.x += imageShiftX;
  629. else
  630. ret.x -= imageShiftX;
  631. //shifting position for double - hex creatures
  632. if(stack->doubleWide())
  633. {
  634. if(stack->side == BattleSide::ATTACKER)
  635. {
  636. if(facingRight(stack))
  637. ret.x -= 44;
  638. }
  639. else
  640. {
  641. if(!facingRight(stack))
  642. ret.x += 44;
  643. }
  644. }
  645. }
  646. //returning
  647. return ret + owner.pos.topLeft();
  648. }
  649. void BattleStacksController::setStackColorFilter(const ColorFilter & effect, const CStack * target, const CSpell * source, bool persistent)
  650. {
  651. for (auto & filter : stackFilterEffects)
  652. {
  653. if (filter.target == target && filter.source == source)
  654. {
  655. filter.effect = effect;
  656. filter.persistent = persistent;
  657. return;
  658. }
  659. }
  660. stackFilterEffects.push_back({ effect, target, source, persistent });
  661. }
  662. void BattleStacksController::removeExpiredColorFilters()
  663. {
  664. vstd::erase_if(stackFilterEffects, [&](const BattleStackFilterEffect & filter)
  665. {
  666. if (filter.persistent)
  667. return false;
  668. if (filter.effect == ColorFilter::genEmptyShifter())
  669. return false;
  670. if (filter.target->hasBonus(Selector::source(Bonus::SPELL_EFFECT, filter.source->id)))
  671. return false;
  672. return true;
  673. });
  674. }