2
0

BattleStacksController.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958
  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/CAnimation.h"
  27. #include "../gui/CGuiHandler.h"
  28. #include "../gui/Canvas.h"
  29. #include "../gui/SDL_Extensions.h"
  30. #include "../../lib/spells/ISpellMechanics.h"
  31. #include "../../CCallback.h"
  32. #include "../../lib/battle/BattleHex.h"
  33. #include "../../lib/CGameState.h"
  34. #include "../../lib/CStack.h"
  35. #include "../../lib/CondSh.h"
  36. static void onAnimationFinished(const CStack *stack, std::weak_ptr<CreatureAnimation> anim)
  37. {
  38. std::shared_ptr<CreatureAnimation> animation = anim.lock();
  39. if(!animation)
  40. return;
  41. if (!stack->isFrozen() && animation->getType() == ECreatureAnimType::FROZEN)
  42. animation->setType(ECreatureAnimType::HOLDING);
  43. if (animation->isIdle())
  44. {
  45. const CCreature *creature = stack->getCreature();
  46. if (stack->isFrozen())
  47. animation->setType(ECreatureAnimType::FROZEN);
  48. else
  49. if (animation->framesInGroup(ECreatureAnimType::MOUSEON) > 0)
  50. {
  51. if (CRandomGenerator::getDefault().nextDouble(99.0) < creature->animation.timeBetweenFidgets *10)
  52. animation->playOnce(ECreatureAnimType::MOUSEON);
  53. else
  54. animation->setType(ECreatureAnimType::HOLDING);
  55. }
  56. else
  57. {
  58. animation->setType(ECreatureAnimType::HOLDING);
  59. }
  60. }
  61. // always reset callback
  62. animation->onAnimationReset += std::bind(&onAnimationFinished, stack, anim);
  63. }
  64. BattleStacksController::BattleStacksController(BattleInterface & owner):
  65. owner(owner),
  66. activeStack(nullptr),
  67. stackToActivate(nullptr),
  68. selectedStack(nullptr),
  69. stackCanCastSpell(false),
  70. creatureSpellToCast(uint32_t(-1)),
  71. animIDhelper(0)
  72. {
  73. //preparing graphics for displaying amounts of creatures
  74. amountNormal = IImage::createFromFile("CMNUMWIN.BMP");
  75. amountPositive = IImage::createFromFile("CMNUMWIN.BMP");
  76. amountNegative = IImage::createFromFile("CMNUMWIN.BMP");
  77. amountEffNeutral = IImage::createFromFile("CMNUMWIN.BMP");
  78. static const auto shifterNormal = ColorFilter::genRangeShifter( 0.f, 0.f, 0.f, 0.6f, 0.2f, 1.0f );
  79. static const auto shifterPositive = ColorFilter::genRangeShifter( 0.f, 0.f, 0.f, 0.2f, 1.0f, 0.2f );
  80. static const auto shifterNegative = ColorFilter::genRangeShifter( 0.f, 0.f, 0.f, 1.0f, 0.2f, 0.2f );
  81. static const auto shifterNeutral = ColorFilter::genRangeShifter( 0.f, 0.f, 0.f, 1.0f, 1.0f, 0.2f );
  82. amountNormal->adjustPalette(shifterNormal);
  83. amountPositive->adjustPalette(shifterPositive);
  84. amountNegative->adjustPalette(shifterNegative);
  85. amountEffNeutral->adjustPalette(shifterNeutral);
  86. //Restore border color {255, 231, 132, 255} to its original state
  87. amountNormal->resetPalette(26);
  88. amountPositive->resetPalette(26);
  89. amountNegative->resetPalette(26);
  90. amountEffNeutral->resetPalette(26);
  91. std::vector<const CStack*> stacks = owner.curInt->cb->battleGetAllStacks(true);
  92. for(const CStack * s : stacks)
  93. {
  94. stackAdded(s, true);
  95. }
  96. }
  97. BattleHex BattleStacksController::getStackCurrentPosition(const CStack * stack) const
  98. {
  99. if ( !stackAnimation.at(stack->ID)->isMoving())
  100. return stack->getPosition();
  101. if (stack->hasBonusOfType(Bonus::FLYING) && stackAnimation.at(stack->ID)->getType() == ECreatureAnimType::MOVING )
  102. return BattleHex::HEX_AFTER_ALL;
  103. for (auto & anim : currentAnimations)
  104. {
  105. // certainly ugly workaround but fixes quite annoying bug
  106. // stack position will be updated only *after* movement is finished
  107. // before this - stack is always at its initial position. Thus we need to find
  108. // its current position. Which can be found only in this class
  109. if (StackMoveAnimation *move = dynamic_cast<StackMoveAnimation*>(anim))
  110. {
  111. if (move->stack == stack)
  112. return std::max(move->prevHex, move->nextHex);
  113. }
  114. }
  115. return stack->getPosition();
  116. }
  117. void BattleStacksController::collectRenderableObjects(BattleRenderer & renderer)
  118. {
  119. auto stacks = owner.curInt->cb->battleGetAllStacks(false);
  120. for (auto stack : stacks)
  121. {
  122. if (stackAnimation.find(stack->ID) == stackAnimation.end()) //e.g. for summoned but not yet handled stacks
  123. continue;
  124. //FIXME: hack to ignore ghost stacks
  125. if ((stackAnimation[stack->ID]->getType() == ECreatureAnimType::DEAD || stackAnimation[stack->ID]->getType() == ECreatureAnimType::HOLDING) && stack->isGhost())
  126. continue;
  127. auto layer = stackAnimation[stack->ID]->isDead() ? EBattleFieldLayer::CORPSES : EBattleFieldLayer::STACKS;
  128. auto location = getStackCurrentPosition(stack);
  129. renderer.insert(layer, location, [this, stack]( BattleRenderer::RendererRef renderer ){
  130. showStack(renderer, stack);
  131. });
  132. if (stackNeedsAmountBox(stack))
  133. {
  134. renderer.insert(EBattleFieldLayer::STACK_AMOUNTS, location, [this, stack]( BattleRenderer::RendererRef renderer ){
  135. showStackAmountBox(renderer, stack);
  136. });
  137. }
  138. }
  139. }
  140. void BattleStacksController::stackReset(const CStack * stack)
  141. {
  142. assert(owner.getAnimationCondition(EAnimationEvents::ACTION) == false);
  143. //reset orientation?
  144. //stackFacingRight[stack->ID] = stack->side == BattleSide::ATTACKER;
  145. auto iter = stackAnimation.find(stack->ID);
  146. if(iter == stackAnimation.end())
  147. {
  148. logGlobal->error("Unit %d have no animation", stack->ID);
  149. return;
  150. }
  151. auto animation = iter->second;
  152. if(stack->alive() && animation->isDeadOrDying())
  153. {
  154. owner.executeOnAnimationCondition(EAnimationEvents::HIT, true, [=]()
  155. {
  156. addNewAnim(new ResurrectionAnimation(owner, stack));
  157. });
  158. }
  159. }
  160. void BattleStacksController::stackAdded(const CStack * stack, bool instant)
  161. {
  162. // Tower shooters have only their upper half visible
  163. static const int turretCreatureAnimationHeight = 225;
  164. stackFacingRight[stack->ID] = stack->side == BattleSide::ATTACKER; // must be set before getting stack position
  165. Point coords = getStackPositionAtHex(stack->getPosition(), stack);
  166. if(stack->initialPosition < 0) //turret
  167. {
  168. assert(owner.siegeController);
  169. const CCreature *turretCreature = owner.siegeController->getTurretCreature();
  170. stackAnimation[stack->ID] = AnimationControls::getAnimation(turretCreature);
  171. stackAnimation[stack->ID]->pos.h = turretCreatureAnimationHeight;
  172. coords = owner.siegeController->getTurretCreaturePosition(stack->initialPosition);
  173. }
  174. else
  175. {
  176. stackAnimation[stack->ID] = AnimationControls::getAnimation(stack->getCreature());
  177. stackAnimation[stack->ID]->onAnimationReset += std::bind(&onAnimationFinished, stack, stackAnimation[stack->ID]);
  178. stackAnimation[stack->ID]->pos.h = stackAnimation[stack->ID]->getHeight();
  179. }
  180. stackAnimation[stack->ID]->pos.x = coords.x;
  181. stackAnimation[stack->ID]->pos.y = coords.y;
  182. stackAnimation[stack->ID]->pos.w = stackAnimation[stack->ID]->getWidth();
  183. stackAnimation[stack->ID]->setType(ECreatureAnimType::HOLDING);
  184. if (!instant)
  185. {
  186. // immediately make stack transparent, giving correct shifter time to start
  187. auto shifterFade = ColorFilter::genAlphaShifter(0);
  188. setStackColorFilter(shifterFade, stack, nullptr, true);
  189. owner.executeOnAnimationCondition(EAnimationEvents::HIT, true, [=]()
  190. {
  191. addNewAnim(new ColorTransformAnimation(owner, stack, "summonFadeIn", nullptr));
  192. if (stack->isClone())
  193. addNewAnim(new ColorTransformAnimation(owner, stack, "cloning", SpellID(SpellID::CLONE).toSpell() ));
  194. });
  195. }
  196. }
  197. void BattleStacksController::setActiveStack(const CStack *stack)
  198. {
  199. if (activeStack) // update UI
  200. stackAnimation[activeStack->ID]->setBorderColor(AnimationControls::getNoBorder());
  201. activeStack = stack;
  202. if (activeStack) // update UI
  203. stackAnimation[activeStack->ID]->setBorderColor(AnimationControls::getGoldBorder());
  204. owner.windowObject->blockUI(activeStack == nullptr);
  205. }
  206. bool BattleStacksController::stackNeedsAmountBox(const CStack * stack) const
  207. {
  208. BattleHex currentActionTarget;
  209. if(owner.curInt->curAction)
  210. {
  211. auto target = owner.curInt->curAction->getTarget(owner.curInt->cb.get());
  212. if(!target.empty())
  213. currentActionTarget = target.at(0).hexValue;
  214. }
  215. //do not show box for singular war machines, stacked war machines with box shown are supported as extension feature
  216. if(stack->hasBonusOfType(Bonus::SIEGE_WEAPON) && stack->getCount() == 1)
  217. return false;
  218. if(!stack->alive())
  219. return false;
  220. //hide box when target is going to die anyway - do not display "0 creatures"
  221. if(stack->getCount() == 0)
  222. return false;
  223. // if stack has any ongoing animation - hide the box
  224. for(auto anim : currentAnimations)
  225. {
  226. auto stackAnimation = dynamic_cast<BattleStackAnimation*>(anim);
  227. if(stackAnimation && (stackAnimation->stack->ID == stack->ID))
  228. return false;
  229. }
  230. return true;
  231. }
  232. std::shared_ptr<IImage> BattleStacksController::getStackAmountBox(const CStack * stack)
  233. {
  234. std::vector<si32> activeSpells = stack->activeSpells();
  235. if ( activeSpells.empty())
  236. return amountNormal;
  237. int effectsPositivness = 0;
  238. for ( auto const & spellID : activeSpells)
  239. effectsPositivness += CGI->spellh->objects.at(spellID)->positiveness;
  240. if (effectsPositivness > 0)
  241. return amountPositive;
  242. if (effectsPositivness < 0)
  243. return amountNegative;
  244. return amountEffNeutral;
  245. }
  246. void BattleStacksController::showStackAmountBox(Canvas & canvas, const CStack * stack)
  247. {
  248. //blitting amount background box
  249. auto amountBG = getStackAmountBox(stack);
  250. const int sideShift = stack->side == BattleSide::ATTACKER ? 1 : -1;
  251. const int reverseSideShift = stack->side == BattleSide::ATTACKER ? -1 : 1;
  252. const BattleHex nextPos = stack->getPosition() + sideShift;
  253. const bool edge = stack->getPosition() % GameConstants::BFIELD_WIDTH == (stack->side == BattleSide::ATTACKER ? GameConstants::BFIELD_WIDTH - 2 : 1);
  254. const bool moveInside = !edge && !owner.fieldController->stackCountOutsideHex(nextPos);
  255. int xAdd = (stack->side == BattleSide::ATTACKER ? 220 : 202) +
  256. (stack->doubleWide() ? 44 : 0) * sideShift +
  257. (moveInside ? amountBG->width() + 10 : 0) * reverseSideShift;
  258. int yAdd = 260 + ((stack->side == BattleSide::ATTACKER || moveInside) ? 0 : -15);
  259. canvas.draw(amountBG, stackAnimation[stack->ID]->pos.topLeft() + Point(xAdd, yAdd));
  260. //blitting amount
  261. Point textPos = stackAnimation[stack->ID]->pos.topLeft() + amountBG->dimensions()/2 + Point(xAdd, yAdd);
  262. canvas.drawText(textPos, EFonts::FONT_TINY, Colors::WHITE, ETextAlignment::CENTER, CSDL_Ext::makeNumberShort(stack->getCount()));
  263. }
  264. void BattleStacksController::showStack(Canvas & canvas, const CStack * stack)
  265. {
  266. ColorFilter fullFilter = ColorFilter::genEmptyShifter();
  267. for (auto const & filter : stackFilterEffects)
  268. {
  269. if (filter.target == stack)
  270. fullFilter = ColorFilter::genCombined(fullFilter, filter.effect);
  271. }
  272. bool stackHasProjectile = owner.projectilesController->hasActiveProjectile(stack, true);
  273. if (stackHasProjectile)
  274. stackAnimation[stack->ID]->pause();
  275. else
  276. stackAnimation[stack->ID]->play();
  277. stackAnimation[stack->ID]->nextFrame(canvas, fullFilter, facingRight(stack)); // do actual blit
  278. stackAnimation[stack->ID]->incrementFrame(float(GH.mainFPSmng->getElapsedMilliseconds()) / 1000);
  279. }
  280. void BattleStacksController::update()
  281. {
  282. updateHoveredStacks();
  283. updateBattleAnimations();
  284. }
  285. void BattleStacksController::initializeBattleAnimations()
  286. {
  287. auto copiedVector = currentAnimations;
  288. for (auto & elem : copiedVector)
  289. if (elem && !elem->isInitialized())
  290. elem->tryInitialize();
  291. }
  292. void BattleStacksController::stepFrameBattleAnimations()
  293. {
  294. // operate on copy - to prevent potential iterator invalidation due to push_back's
  295. // FIXME? : remove remaining calls to addNewAnim from BattleAnimation::nextFrame (only Catapult explosion at the time of writing)
  296. auto copiedVector = currentAnimations;
  297. for (auto & elem : copiedVector)
  298. if (elem && elem->isInitialized())
  299. elem->nextFrame();
  300. }
  301. void BattleStacksController::updateBattleAnimations()
  302. {
  303. bool hadAnimations = !currentAnimations.empty();
  304. initializeBattleAnimations();
  305. stepFrameBattleAnimations();
  306. vstd::erase(currentAnimations, nullptr);
  307. if (hadAnimations && currentAnimations.empty())
  308. owner.setAnimationCondition(EAnimationEvents::ACTION, false);
  309. initializeBattleAnimations();
  310. }
  311. void BattleStacksController::addNewAnim(BattleAnimation *anim)
  312. {
  313. currentAnimations.push_back(anim);
  314. owner.setAnimationCondition(EAnimationEvents::ACTION, true);
  315. }
  316. void BattleStacksController::stackRemoved(uint32_t stackID)
  317. {
  318. if (getActiveStack() && getActiveStack()->ID == stackID)
  319. {
  320. BattleAction *action = new BattleAction();
  321. action->side = owner.defendingHeroInstance ? (owner.curInt->playerID == owner.defendingHeroInstance->tempOwner) : false;
  322. action->actionType = EActionType::CANCEL;
  323. action->stackNumber = getActiveStack()->ID;
  324. owner.givenCommand.setn(action);
  325. setActiveStack(nullptr);
  326. }
  327. }
  328. void BattleStacksController::stacksAreAttacked(std::vector<StackAttackedInfo> attackedInfos)
  329. {
  330. owner.executeOnAnimationCondition(EAnimationEvents::HIT, true, [=](){
  331. // remove any potentially erased petrification effect
  332. removeExpiredColorFilters();
  333. });
  334. for(auto & attackedInfo : attackedInfos)
  335. {
  336. if (!attackedInfo.attacker)
  337. continue;
  338. // In H3, attacked stack will not reverse on ranged attack
  339. if (attackedInfo.indirectAttack)
  340. continue;
  341. // Another type of indirect attack - dragon breath
  342. if (!CStack::isMeleeAttackPossible(attackedInfo.attacker, attackedInfo.defender))
  343. continue;
  344. // defender need to face in direction opposited to out attacker
  345. bool needsReverse = shouldAttackFacingRight(attackedInfo.attacker, attackedInfo.defender) == facingRight(attackedInfo.defender);
  346. // FIXME: this check is better, however not usable since stacksAreAttacked is called after net pack is applyed - petrification is already removed
  347. // if (needsReverse && !attackedInfo.defender->isFrozen())
  348. if (needsReverse && stackAnimation[attackedInfo.defender->ID]->getType() != ECreatureAnimType::FROZEN)
  349. {
  350. owner.executeOnAnimationCondition(EAnimationEvents::MOVEMENT, true, [=]()
  351. {
  352. addNewAnim(new ReverseAnimation(owner, attackedInfo.defender, attackedInfo.defender->getPosition()));
  353. });
  354. }
  355. }
  356. for(auto & attackedInfo : attackedInfos)
  357. {
  358. bool useDeathAnim = attackedInfo.killed;
  359. bool useDefenceAnim = attackedInfo.defender->defendingAnim && !attackedInfo.indirectAttack && !attackedInfo.killed;
  360. EAnimationEvents usedEvent = useDefenceAnim ? EAnimationEvents::ATTACK : EAnimationEvents::HIT;
  361. owner.executeOnAnimationCondition(usedEvent, true, [=]()
  362. {
  363. if (useDeathAnim)
  364. addNewAnim(new DeathAnimation(owner, attackedInfo.defender, attackedInfo.indirectAttack));
  365. else if(useDefenceAnim)
  366. addNewAnim(new DefenceAnimation(owner, attackedInfo.defender));
  367. else
  368. addNewAnim(new HittedAnimation(owner, attackedInfo.defender));
  369. if (attackedInfo.fireShield)
  370. owner.effectsController->displayEffect(EBattleEffect::FIRE_SHIELD, "FIRESHIE", attackedInfo.attacker->getPosition());
  371. if (attackedInfo.spellEffect != SpellID::NONE)
  372. {
  373. auto spell = attackedInfo.spellEffect.toSpell();
  374. if (!spell->getCastSound().empty())
  375. CCS->soundh->playSound(spell->getCastSound());
  376. owner.displaySpellEffect(spell, attackedInfo.defender->getPosition());
  377. }
  378. });
  379. }
  380. for (auto & attackedInfo : attackedInfos)
  381. {
  382. if (attackedInfo.rebirth)
  383. {
  384. owner.executeOnAnimationCondition(EAnimationEvents::AFTER_HIT, true, [=](){
  385. owner.effectsController->displayEffect(EBattleEffect::RESURRECT, "RESURECT", attackedInfo.defender->getPosition());
  386. addNewAnim(new ResurrectionAnimation(owner, attackedInfo.defender));
  387. });
  388. }
  389. if (attackedInfo.killed && attackedInfo.defender->summoned)
  390. {
  391. owner.executeOnAnimationCondition(EAnimationEvents::AFTER_HIT, true, [=](){
  392. addNewAnim(new ColorTransformAnimation(owner, attackedInfo.defender, "summonFadeOut", nullptr));
  393. stackRemoved(attackedInfo.defender->ID);
  394. });
  395. }
  396. }
  397. executeAttackAnimations();
  398. }
  399. void BattleStacksController::stackTeleported(const CStack *stack, std::vector<BattleHex> destHex, int distance)
  400. {
  401. assert(destHex.size() > 0);
  402. assert(owner.getAnimationCondition(EAnimationEvents::ACTION) == false);
  403. owner.executeOnAnimationCondition(EAnimationEvents::HIT, true, [=](){
  404. addNewAnim( new ColorTransformAnimation(owner, stack, "teleportFadeOut", nullptr) );
  405. });
  406. owner.executeOnAnimationCondition(EAnimationEvents::AFTER_HIT, true, [=](){
  407. stackAnimation[stack->ID]->pos.moveTo(getStackPositionAtHex(destHex.back(), stack));
  408. addNewAnim( new ColorTransformAnimation(owner, stack, "teleportFadeIn", nullptr) );
  409. });
  410. // animations will be executed by spell
  411. }
  412. void BattleStacksController::stackMoved(const CStack *stack, std::vector<BattleHex> destHex, int distance)
  413. {
  414. assert(destHex.size() > 0);
  415. assert(owner.getAnimationCondition(EAnimationEvents::ACTION) == false);
  416. bool stackTeleports = stack->hasBonus(Selector::typeSubtype(Bonus::FLYING, 1));
  417. owner.setAnimationCondition(EAnimationEvents::MOVEMENT, true);
  418. auto enqueMoveEnd = [&](){
  419. addNewAnim(new MovementEndAnimation(owner, stack, destHex.back()));
  420. owner.executeOnAnimationCondition(EAnimationEvents::ACTION, false, [&](){
  421. owner.setAnimationCondition(EAnimationEvents::MOVEMENT, false);
  422. });
  423. };
  424. auto enqueMove = [&](){
  425. if (!stackTeleports)
  426. {
  427. addNewAnim(new MovementAnimation(owner, stack, destHex, distance));
  428. owner.executeOnAnimationCondition(EAnimationEvents::ACTION, false, enqueMoveEnd);
  429. }
  430. else
  431. enqueMoveEnd();
  432. };
  433. auto enqueMoveStart = [&](){
  434. addNewAnim(new MovementStartAnimation(owner, stack));
  435. owner.executeOnAnimationCondition(EAnimationEvents::ACTION, false, enqueMove);
  436. };
  437. if(shouldRotate(stack, stack->getPosition(), destHex[0]))
  438. {
  439. addNewAnim(new ReverseAnimation(owner, stack, stack->getPosition()));
  440. owner.executeOnAnimationCondition(EAnimationEvents::ACTION, false, enqueMoveStart);
  441. }
  442. else
  443. enqueMoveStart();
  444. owner.waitForAnimationCondition(EAnimationEvents::MOVEMENT, false);
  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->side == BattleSide::ATTACKER)
  452. return !mustReverse;
  453. else
  454. return mustReverse;
  455. }
  456. void BattleStacksController::stackAttacking( const StackAttackInfo & info )
  457. {
  458. assert(owner.getAnimationCondition(EAnimationEvents::ACTION) == false);
  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.executeOnAnimationCondition(EAnimationEvents::MOVEMENT, true, [=]()
  476. {
  477. addNewAnim(new ReverseAnimation(owner, attacker, attacker->getPosition()));
  478. });
  479. }
  480. if(info.lucky)
  481. {
  482. owner.executeOnAnimationCondition(EAnimationEvents::BEFORE_HIT, true, [=]() {
  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.executeOnAnimationCondition(EAnimationEvents::BEFORE_HIT, true, [=]() {
  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.executeOnAnimationCondition(EAnimationEvents::BEFORE_HIT, true, [=]() {
  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.executeOnAnimationCondition(EAnimationEvents::BEFORE_HIT, true, [=]() {
  503. owner.effectsController->displayEffect(EBattleEffect::DEATH_BLOW, elem->getPosition());
  504. });
  505. }
  506. }
  507. owner.executeOnAnimationCondition(EAnimationEvents::ATTACK, true, [=]()
  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.executeOnAnimationCondition(EAnimationEvents::HIT, true, [=]()
  521. {
  522. owner.displaySpellHit(spellEffect.toSpell(), tile);
  523. });
  524. }
  525. if (info.lifeDrain)
  526. {
  527. owner.executeOnAnimationCondition(EAnimationEvents::AFTER_HIT, true, [=]()
  528. {
  529. owner.effectsController->displayEffect(EBattleEffect::DRAIN_LIFE, "DRAINLIF", attacker->getPosition());
  530. });
  531. }
  532. //return, animation playback will be handled by stacksAreAttacked
  533. }
  534. void BattleStacksController::executeAttackAnimations()
  535. {
  536. owner.setAnimationCondition(EAnimationEvents::MOVEMENT, true);
  537. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  538. owner.setAnimationCondition(EAnimationEvents::MOVEMENT, false);
  539. owner.setAnimationCondition(EAnimationEvents::BEFORE_HIT, true);
  540. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  541. owner.setAnimationCondition(EAnimationEvents::BEFORE_HIT, false);
  542. owner.setAnimationCondition(EAnimationEvents::ATTACK, true);
  543. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  544. owner.setAnimationCondition(EAnimationEvents::ATTACK, false);
  545. // Note that HIT event can also be emitted by attack animation
  546. owner.setAnimationCondition(EAnimationEvents::HIT, true);
  547. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  548. owner.setAnimationCondition(EAnimationEvents::HIT, false);
  549. owner.setAnimationCondition(EAnimationEvents::AFTER_HIT, true);
  550. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  551. owner.setAnimationCondition(EAnimationEvents::AFTER_HIT, false);
  552. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  553. }
  554. bool BattleStacksController::shouldRotate(const CStack * stack, const BattleHex & oldPos, const BattleHex & nextHex) const
  555. {
  556. Point begPosition = getStackPositionAtHex(oldPos,stack);
  557. Point endPosition = getStackPositionAtHex(nextHex, stack);
  558. if((begPosition.x > endPosition.x) && facingRight(stack))
  559. return true;
  560. else if((begPosition.x < endPosition.x) && !facingRight(stack))
  561. return true;
  562. return false;
  563. }
  564. void BattleStacksController::endAction(const BattleAction* action)
  565. {
  566. assert(owner.getAnimationCondition(EAnimationEvents::ACTION) == false);
  567. //check if we should reverse stacks
  568. TStacks stacks = owner.curInt->cb->battleGetStacks(CBattleCallback::MINE_AND_ENEMY);
  569. for (const CStack *s : stacks)
  570. {
  571. bool shouldFaceRight = s && s->side == BattleSide::ATTACKER;
  572. if (s && facingRight(s) != shouldFaceRight && s->alive() && stackAnimation[s->ID]->isIdle())
  573. {
  574. addNewAnim(new ReverseAnimation(owner, s, s->getPosition()));
  575. }
  576. }
  577. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  578. //Ensure that all animation flags were reset
  579. assert(owner.getAnimationCondition(EAnimationEvents::OPENING) == false);
  580. assert(owner.getAnimationCondition(EAnimationEvents::ACTION) == false);
  581. assert(owner.getAnimationCondition(EAnimationEvents::MOVEMENT) == false);
  582. assert(owner.getAnimationCondition(EAnimationEvents::ATTACK) == false);
  583. assert(owner.getAnimationCondition(EAnimationEvents::HIT) == false);
  584. owner.windowObject->blockUI(activeStack == nullptr);
  585. removeExpiredColorFilters();
  586. }
  587. void BattleStacksController::startAction(const BattleAction* action)
  588. {
  589. removeExpiredColorFilters();
  590. }
  591. void BattleStacksController::stackActivated(const CStack *stack)
  592. {
  593. stackToActivate = stack;
  594. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  595. owner.activateStack();
  596. }
  597. void BattleStacksController::activateStack()
  598. {
  599. if ( !currentAnimations.empty())
  600. return;
  601. if ( !stackToActivate)
  602. return;
  603. owner.trySetActivePlayer(stackToActivate->owner);
  604. setActiveStack(stackToActivate);
  605. stackToActivate = nullptr;
  606. const CStack * s = getActiveStack();
  607. if(!s)
  608. return;
  609. //set casting flag to true if creature can use it to not check it every time
  610. const auto spellcaster = s->getBonusLocalFirst(Selector::type()(Bonus::SPELLCASTER));
  611. const auto randomSpellcaster = s->getBonusLocalFirst(Selector::type()(Bonus::RANDOM_SPELLCASTER));
  612. if(s->canCast() && (spellcaster || randomSpellcaster))
  613. {
  614. stackCanCastSpell = true;
  615. if(randomSpellcaster)
  616. creatureSpellToCast = -1; //spell will be set later on cast
  617. else
  618. creatureSpellToCast = owner.curInt->cb->battleGetRandomStackSpell(CRandomGenerator::getDefault(), s, CBattleInfoCallback::RANDOM_AIMED); //faerie dragon can cast only one spell until their next move
  619. //TODO: what if creature can cast BOTH random genie spell and aimed spell?
  620. //TODO: faerie dragon type spell should be selected by server
  621. }
  622. else
  623. {
  624. stackCanCastSpell = false;
  625. creatureSpellToCast = -1;
  626. }
  627. }
  628. void BattleStacksController::setSelectedStack(const CStack *stack)
  629. {
  630. selectedStack = stack;
  631. }
  632. const CStack* BattleStacksController::getSelectedStack() const
  633. {
  634. return selectedStack;
  635. }
  636. const CStack* BattleStacksController::getActiveStack() const
  637. {
  638. return activeStack;
  639. }
  640. bool BattleStacksController::facingRight(const CStack * stack) const
  641. {
  642. return stackFacingRight.at(stack->ID);
  643. }
  644. bool BattleStacksController::activeStackSpellcaster()
  645. {
  646. return stackCanCastSpell;
  647. }
  648. SpellID BattleStacksController::activeStackSpellToCast()
  649. {
  650. if (!stackCanCastSpell)
  651. return SpellID::NONE;
  652. return SpellID(creatureSpellToCast);
  653. }
  654. Point BattleStacksController::getStackPositionAtHex(BattleHex hexNum, const CStack * stack) const
  655. {
  656. Point ret(-500, -500); //returned value
  657. if(stack && stack->initialPosition < 0) //creatures in turrets
  658. return owner.siegeController->getTurretCreaturePosition(stack->initialPosition);
  659. static const Point basePos(-190, -139); // position of creature in topleft corner
  660. static const int imageShiftX = 30; // X offset to base pos for facing right stacks, negative for facing left
  661. ret.x = basePos.x + 22 * ( (hexNum.getY() + 1)%2 ) + 44 * hexNum.getX();
  662. ret.y = basePos.y + 42 * hexNum.getY();
  663. if (stack)
  664. {
  665. if(facingRight(stack))
  666. ret.x += imageShiftX;
  667. else
  668. ret.x -= imageShiftX;
  669. //shifting position for double - hex creatures
  670. if(stack->doubleWide())
  671. {
  672. if(stack->side == BattleSide::ATTACKER)
  673. {
  674. if(facingRight(stack))
  675. ret.x -= 44;
  676. }
  677. else
  678. {
  679. if(!facingRight(stack))
  680. ret.x += 44;
  681. }
  682. }
  683. }
  684. //returning
  685. return ret;
  686. }
  687. void BattleStacksController::setStackColorFilter(const ColorFilter & effect, const CStack * target, const CSpell * source, bool persistent)
  688. {
  689. for (auto & filter : stackFilterEffects)
  690. {
  691. if (filter.target == target && filter.source == source)
  692. {
  693. filter.effect = effect;
  694. filter.persistent = persistent;
  695. return;
  696. }
  697. }
  698. stackFilterEffects.push_back({ effect, target, source, persistent });
  699. }
  700. void BattleStacksController::removeExpiredColorFilters()
  701. {
  702. vstd::erase_if(stackFilterEffects, [&](const BattleStackFilterEffect & filter)
  703. {
  704. if (!filter.persistent)
  705. {
  706. if (filter.source && !filter.target->hasBonus(Selector::source(Bonus::SPELL_EFFECT, filter.source->id), Selector::all))
  707. return true;
  708. if (filter.effect == ColorFilter::genEmptyShifter())
  709. return true;
  710. }
  711. return false;
  712. });
  713. }
  714. void BattleStacksController::updateHoveredStacks()
  715. {
  716. auto newStacks = selectHoveredStacks();
  717. for (auto const * stack : mouseHoveredStacks)
  718. {
  719. if (vstd::contains(newStacks, stack))
  720. continue;
  721. if (stack == activeStack)
  722. stackAnimation[stack->ID]->setBorderColor(AnimationControls::getGoldBorder());
  723. else
  724. stackAnimation[stack->ID]->setBorderColor(AnimationControls::getNoBorder());
  725. }
  726. for (auto const * stack : newStacks)
  727. {
  728. if (vstd::contains(mouseHoveredStacks, stack))
  729. continue;
  730. stackAnimation[stack->ID]->setBorderColor(AnimationControls::getBlueBorder());
  731. if (stackAnimation[stack->ID]->framesInGroup(ECreatureAnimType::MOUSEON) > 0 && stack->alive() && !stack->isFrozen())
  732. stackAnimation[stack->ID]->playOnce(ECreatureAnimType::MOUSEON);
  733. }
  734. mouseHoveredStacks = newStacks;
  735. }
  736. std::vector<const CStack *> BattleStacksController::selectHoveredStacks()
  737. {
  738. // only allow during our turn - do not try to highlight creatures while they are in the middle of actions
  739. if (!activeStack)
  740. return {};
  741. if(owner.getAnimationCondition(EAnimationEvents::ACTION) == true)
  742. return {};
  743. auto hoveredQueueUnitId = owner.windowObject->getQueueHoveredUnitId();
  744. if(hoveredQueueUnitId.is_initialized())
  745. {
  746. return { owner.curInt->cb->battleGetStackByUnitId(hoveredQueueUnitId.value(), true) };
  747. }
  748. auto hoveredHex = owner.fieldController->getHoveredHex();
  749. if (!hoveredHex.isValid())
  750. return {};
  751. const spells::Caster *caster = nullptr;
  752. const CSpell *spell = nullptr;
  753. spells::Mode mode = spells::Mode::HERO;
  754. if(owner.actionsController->spellcastingModeActive())//hero casts spell
  755. {
  756. spell = owner.actionsController->selectedSpell().toSpell();
  757. caster = owner.getActiveHero();
  758. }
  759. else if(owner.stacksController->activeStackSpellToCast() != SpellID::NONE)//stack casts spell
  760. {
  761. spell = SpellID(owner.stacksController->activeStackSpellToCast()).toSpell();
  762. caster = owner.stacksController->getActiveStack();
  763. mode = spells::Mode::CREATURE_ACTIVE;
  764. }
  765. if(caster && spell) //when casting spell
  766. {
  767. spells::Target target;
  768. target.emplace_back(hoveredHex);
  769. spells::BattleCast event(owner.curInt->cb.get(), caster, mode, spell);
  770. auto mechanics = spell->battleMechanics(&event);
  771. return mechanics->getAffectedStacks(target);
  772. }
  773. if(hoveredHex.isValid())
  774. {
  775. const CStack * const stack = owner.curInt->cb->battleGetStackByPos(hoveredHex, true);
  776. if (stack)
  777. return {stack};
  778. }
  779. return {};
  780. }
  781. const std::vector<uint32_t> BattleStacksController::getHoveredStacksUnitIds() const
  782. {
  783. auto result = std::vector<uint32_t>();
  784. for (auto const * stack : mouseHoveredStacks)
  785. {
  786. result.push_back(stack->unitId());
  787. }
  788. return result;
  789. }