BattleStacksController.cpp 27 KB

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