BattleStacksController.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941
  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 "../../lib/spells/ISpellMechanics.h"
  30. #include "../../CCallback.h"
  31. #include "../../lib/battle/BattleHex.h"
  32. #include "../../lib/CGameState.h"
  33. #include "../../lib/CStack.h"
  34. #include "../../lib/CondSh.h"
  35. static void onAnimationFinished(const CStack *stack, std::weak_ptr<CreatureAnimation> anim)
  36. {
  37. std::shared_ptr<CreatureAnimation> animation = anim.lock();
  38. if(!animation)
  39. return;
  40. if (!stack->isFrozen() && animation->getType() == ECreatureAnimType::FROZEN)
  41. animation->setType(ECreatureAnimType::HOLDING);
  42. if (animation->isIdle())
  43. {
  44. const CCreature *creature = stack->getCreature();
  45. if (stack->isFrozen())
  46. animation->setType(ECreatureAnimType::FROZEN);
  47. else
  48. if (animation->framesInGroup(ECreatureAnimType::MOUSEON) > 0)
  49. {
  50. if (CRandomGenerator::getDefault().nextDouble(99.0) < creature->animation.timeBetweenFidgets *10)
  51. animation->playOnce(ECreatureAnimType::MOUSEON);
  52. else
  53. animation->setType(ECreatureAnimType::HOLDING);
  54. }
  55. else
  56. {
  57. animation->setType(ECreatureAnimType::HOLDING);
  58. }
  59. }
  60. // always reset callback
  61. animation->onAnimationReset += std::bind(&onAnimationFinished, stack, anim);
  62. }
  63. BattleStacksController::BattleStacksController(BattleInterface & owner):
  64. owner(owner),
  65. activeStack(nullptr),
  66. stackToActivate(nullptr),
  67. selectedStack(nullptr),
  68. stackCanCastSpell(false),
  69. creatureSpellToCast(uint32_t(-1)),
  70. animIDhelper(0)
  71. {
  72. //preparing graphics for displaying amounts of creatures
  73. amountNormal = IImage::createFromFile("CMNUMWIN.BMP");
  74. amountPositive = IImage::createFromFile("CMNUMWIN.BMP");
  75. amountNegative = IImage::createFromFile("CMNUMWIN.BMP");
  76. amountEffNeutral = IImage::createFromFile("CMNUMWIN.BMP");
  77. static const auto shifterNormal = ColorFilter::genRangeShifter( 0.f, 0.f, 0.f, 0.6f, 0.2f, 1.0f );
  78. static const auto shifterPositive = ColorFilter::genRangeShifter( 0.f, 0.f, 0.f, 0.2f, 1.0f, 0.2f );
  79. static const auto shifterNegative = ColorFilter::genRangeShifter( 0.f, 0.f, 0.f, 1.0f, 0.2f, 0.2f );
  80. static const auto shifterNeutral = ColorFilter::genRangeShifter( 0.f, 0.f, 0.f, 1.0f, 1.0f, 0.2f );
  81. amountNormal->adjustPalette(shifterNormal);
  82. amountPositive->adjustPalette(shifterPositive);
  83. amountNegative->adjustPalette(shifterNegative);
  84. amountEffNeutral->adjustPalette(shifterNeutral);
  85. //Restore border color {255, 231, 132, 255} to its original state
  86. amountNormal->resetPalette(26);
  87. amountPositive->resetPalette(26);
  88. amountNegative->resetPalette(26);
  89. amountEffNeutral->resetPalette(26);
  90. std::vector<const CStack*> stacks = owner.curInt->cb->battleGetAllStacks(true);
  91. for(const CStack * s : stacks)
  92. {
  93. stackAdded(s, true);
  94. }
  95. }
  96. BattleHex BattleStacksController::getStackCurrentPosition(const CStack * stack) const
  97. {
  98. if ( !stackAnimation.at(stack->ID)->isMoving())
  99. return stack->getPosition();
  100. if (stack->hasBonusOfType(Bonus::FLYING) && stackAnimation.at(stack->ID)->getType() == ECreatureAnimType::MOVING )
  101. return BattleHex::HEX_AFTER_ALL;
  102. for (auto & anim : currentAnimations)
  103. {
  104. // certainly ugly workaround but fixes quite annoying bug
  105. // stack position will be updated only *after* movement is finished
  106. // before this - stack is always at its initial position. Thus we need to find
  107. // its current position. Which can be found only in this class
  108. if (StackMoveAnimation *move = dynamic_cast<StackMoveAnimation*>(anim))
  109. {
  110. if (move->stack == stack)
  111. return std::max(move->prevHex, move->nextHex);
  112. }
  113. }
  114. return stack->getPosition();
  115. }
  116. void BattleStacksController::collectRenderableObjects(BattleRenderer & renderer)
  117. {
  118. auto stacks = owner.curInt->cb->battleGetAllStacks(false);
  119. for (auto stack : stacks)
  120. {
  121. if (stackAnimation.find(stack->ID) == stackAnimation.end()) //e.g. for summoned but not yet handled stacks
  122. continue;
  123. //FIXME: hack to ignore ghost stacks
  124. if ((stackAnimation[stack->ID]->getType() == ECreatureAnimType::DEAD || stackAnimation[stack->ID]->getType() == ECreatureAnimType::HOLDING) && stack->isGhost())
  125. continue;
  126. auto layer = stackAnimation[stack->ID]->isDead() ? EBattleFieldLayer::CORPSES : EBattleFieldLayer::STACKS;
  127. auto location = getStackCurrentPosition(stack);
  128. renderer.insert(layer, location, [this, stack]( BattleRenderer::RendererRef renderer ){
  129. showStack(renderer, stack);
  130. });
  131. if (stackNeedsAmountBox(stack))
  132. {
  133. renderer.insert(EBattleFieldLayer::STACK_AMOUNTS, location, [this, stack]( BattleRenderer::RendererRef renderer ){
  134. showStackAmountBox(renderer, stack);
  135. });
  136. }
  137. }
  138. }
  139. void BattleStacksController::stackReset(const CStack * stack)
  140. {
  141. assert(owner.getAnimationCondition(EAnimationEvents::ACTION) == false);
  142. //reset orientation?
  143. //stackFacingRight[stack->ID] = stack->side == BattleSide::ATTACKER;
  144. auto iter = stackAnimation.find(stack->ID);
  145. if(iter == stackAnimation.end())
  146. {
  147. logGlobal->error("Unit %d have no animation", stack->ID);
  148. return;
  149. }
  150. auto animation = iter->second;
  151. if(stack->alive() && animation->isDeadOrDying())
  152. {
  153. owner.executeOnAnimationCondition(EAnimationEvents::HIT, true, [=]()
  154. {
  155. addNewAnim(new ResurrectionAnimation(owner, stack));
  156. });
  157. }
  158. }
  159. void BattleStacksController::stackAdded(const CStack * stack, bool instant)
  160. {
  161. // Tower shooters have only their upper half visible
  162. static const int turretCreatureAnimationHeight = 225;
  163. stackFacingRight[stack->ID] = stack->side == BattleSide::ATTACKER; // must be set before getting stack position
  164. Point coords = getStackPositionAtHex(stack->getPosition(), stack);
  165. if(stack->initialPosition < 0) //turret
  166. {
  167. assert(owner.siegeController);
  168. const CCreature *turretCreature = owner.siegeController->getTurretCreature();
  169. stackAnimation[stack->ID] = AnimationControls::getAnimation(turretCreature);
  170. stackAnimation[stack->ID]->pos.h = turretCreatureAnimationHeight;
  171. coords = owner.siegeController->getTurretCreaturePosition(stack->initialPosition);
  172. }
  173. else
  174. {
  175. stackAnimation[stack->ID] = AnimationControls::getAnimation(stack->getCreature());
  176. stackAnimation[stack->ID]->onAnimationReset += std::bind(&onAnimationFinished, stack, stackAnimation[stack->ID]);
  177. stackAnimation[stack->ID]->pos.h = stackAnimation[stack->ID]->getHeight();
  178. }
  179. stackAnimation[stack->ID]->pos.x = coords.x;
  180. stackAnimation[stack->ID]->pos.y = coords.y;
  181. stackAnimation[stack->ID]->pos.w = stackAnimation[stack->ID]->getWidth();
  182. stackAnimation[stack->ID]->setType(ECreatureAnimType::HOLDING);
  183. if (!instant)
  184. {
  185. // immediately make stack transparent, giving correct shifter time to start
  186. auto shifterFade = ColorFilter::genAlphaShifter(0);
  187. setStackColorFilter(shifterFade, stack, nullptr, true);
  188. owner.executeOnAnimationCondition(EAnimationEvents::HIT, true, [=]()
  189. {
  190. addNewAnim(new ColorTransformAnimation(owner, stack, "summonFadeIn", nullptr));
  191. if (stack->isClone())
  192. addNewAnim(new ColorTransformAnimation(owner, stack, "cloning", SpellID(SpellID::CLONE).toSpell() ));
  193. });
  194. }
  195. }
  196. void BattleStacksController::setActiveStack(const CStack *stack)
  197. {
  198. if (activeStack) // update UI
  199. stackAnimation[activeStack->ID]->setBorderColor(AnimationControls::getNoBorder());
  200. activeStack = stack;
  201. if (activeStack) // update UI
  202. stackAnimation[activeStack->ID]->setBorderColor(AnimationControls::getGoldBorder());
  203. owner.windowObject->blockUI(activeStack == nullptr);
  204. }
  205. bool BattleStacksController::stackNeedsAmountBox(const CStack * stack) const
  206. {
  207. BattleHex currentActionTarget;
  208. if(owner.curInt->curAction)
  209. {
  210. auto target = owner.curInt->curAction->getTarget(owner.curInt->cb.get());
  211. if(!target.empty())
  212. currentActionTarget = target.at(0).hexValue;
  213. }
  214. //do not show box for singular war machines, stacked war machines with box shown are supported as extension feature
  215. if(stack->hasBonusOfType(Bonus::SIEGE_WEAPON) && stack->getCount() == 1)
  216. return false;
  217. if(!stack->alive())
  218. return false;
  219. //hide box when target is going to die anyway - do not display "0 creatures"
  220. if(stack->getCount() == 0)
  221. return false;
  222. // if stack has any ongoing animation - hide the box
  223. for(auto anim : currentAnimations)
  224. {
  225. auto stackAnimation = dynamic_cast<BattleStackAnimation*>(anim);
  226. if(stackAnimation && (stackAnimation->stack->ID == stack->ID))
  227. return false;
  228. }
  229. return true;
  230. }
  231. std::shared_ptr<IImage> BattleStacksController::getStackAmountBox(const CStack * stack)
  232. {
  233. std::vector<si32> activeSpells = stack->activeSpells();
  234. if ( activeSpells.empty())
  235. return amountNormal;
  236. int effectsPositivness = 0;
  237. for ( auto const & spellID : activeSpells)
  238. effectsPositivness += CGI->spellh->objects.at(spellID)->positiveness;
  239. if (effectsPositivness > 0)
  240. return amountPositive;
  241. if (effectsPositivness < 0)
  242. return amountNegative;
  243. return amountEffNeutral;
  244. }
  245. void BattleStacksController::showStackAmountBox(Canvas & canvas, const CStack * stack)
  246. {
  247. //blitting amount background box
  248. auto amountBG = getStackAmountBox(stack);
  249. const int sideShift = stack->side == BattleSide::ATTACKER ? 1 : -1;
  250. const int reverseSideShift = stack->side == BattleSide::ATTACKER ? -1 : 1;
  251. const BattleHex nextPos = stack->getPosition() + sideShift;
  252. const bool edge = stack->getPosition() % GameConstants::BFIELD_WIDTH == (stack->side == BattleSide::ATTACKER ? GameConstants::BFIELD_WIDTH - 2 : 1);
  253. const bool moveInside = !edge && !owner.fieldController->stackCountOutsideHex(nextPos);
  254. int xAdd = (stack->side == BattleSide::ATTACKER ? 220 : 202) +
  255. (stack->doubleWide() ? 44 : 0) * sideShift +
  256. (moveInside ? amountBG->width() + 10 : 0) * reverseSideShift;
  257. int yAdd = 260 + ((stack->side == BattleSide::ATTACKER || moveInside) ? 0 : -15);
  258. canvas.draw(amountBG, stackAnimation[stack->ID]->pos.topLeft() + Point(xAdd, yAdd));
  259. //blitting amount
  260. Point textPos = stackAnimation[stack->ID]->pos.topLeft() + amountBG->dimensions()/2 + Point(xAdd, yAdd);
  261. canvas.drawText(textPos, EFonts::FONT_TINY, Colors::WHITE, ETextAlignment::CENTER, makeNumberShort(stack->getCount()));
  262. }
  263. void BattleStacksController::showStack(Canvas & canvas, const CStack * stack)
  264. {
  265. ColorFilter fullFilter = ColorFilter::genEmptyShifter();
  266. for (auto const & filter : stackFilterEffects)
  267. {
  268. if (filter.target == stack)
  269. fullFilter = ColorFilter::genCombined(fullFilter, filter.effect);
  270. }
  271. bool stackHasProjectile = owner.projectilesController->hasActiveProjectile(stack, true);
  272. if (stackHasProjectile)
  273. stackAnimation[stack->ID]->pause();
  274. else
  275. stackAnimation[stack->ID]->play();
  276. stackAnimation[stack->ID]->nextFrame(canvas, fullFilter, facingRight(stack)); // do actual blit
  277. stackAnimation[stack->ID]->incrementFrame(float(GH.mainFPSmng->getElapsedMilliseconds()) / 1000);
  278. }
  279. void BattleStacksController::update()
  280. {
  281. updateHoveredStacks();
  282. updateBattleAnimations();
  283. }
  284. void BattleStacksController::initializeBattleAnimations()
  285. {
  286. auto copiedVector = currentAnimations;
  287. for (auto & elem : copiedVector)
  288. if (elem && !elem->isInitialized())
  289. elem->tryInitialize();
  290. }
  291. void BattleStacksController::stepFrameBattleAnimations()
  292. {
  293. // operate on copy - to prevent potential iterator invalidation due to push_back's
  294. // FIXME? : remove remaining calls to addNewAnim from BattleAnimation::nextFrame (only Catapult explosion at the time of writing)
  295. auto copiedVector = currentAnimations;
  296. for (auto & elem : copiedVector)
  297. if (elem && elem->isInitialized())
  298. elem->nextFrame();
  299. }
  300. void BattleStacksController::updateBattleAnimations()
  301. {
  302. bool hadAnimations = !currentAnimations.empty();
  303. initializeBattleAnimations();
  304. stepFrameBattleAnimations();
  305. vstd::erase(currentAnimations, nullptr);
  306. if (hadAnimations && currentAnimations.empty())
  307. owner.setAnimationCondition(EAnimationEvents::ACTION, false);
  308. initializeBattleAnimations();
  309. }
  310. void BattleStacksController::addNewAnim(BattleAnimation *anim)
  311. {
  312. currentAnimations.push_back(anim);
  313. owner.setAnimationCondition(EAnimationEvents::ACTION, true);
  314. }
  315. void BattleStacksController::stackRemoved(uint32_t stackID)
  316. {
  317. if (getActiveStack() && getActiveStack()->ID == stackID)
  318. {
  319. BattleAction *action = new BattleAction();
  320. action->side = owner.defendingHeroInstance ? (owner.curInt->playerID == owner.defendingHeroInstance->tempOwner) : false;
  321. action->actionType = EActionType::CANCEL;
  322. action->stackNumber = getActiveStack()->ID;
  323. owner.givenCommand.setn(action);
  324. setActiveStack(nullptr);
  325. }
  326. }
  327. void BattleStacksController::stacksAreAttacked(std::vector<StackAttackedInfo> attackedInfos)
  328. {
  329. owner.executeOnAnimationCondition(EAnimationEvents::HIT, true, [=](){
  330. // remove any potentially erased petrification effect
  331. removeExpiredColorFilters();
  332. });
  333. for(auto & attackedInfo : attackedInfos)
  334. {
  335. if (!attackedInfo.attacker)
  336. continue;
  337. // In H3, attacked stack will not reverse on ranged attack
  338. if (attackedInfo.indirectAttack)
  339. continue;
  340. // Another type of indirect attack - dragon breath
  341. if (!CStack::isMeleeAttackPossible(attackedInfo.attacker, attackedInfo.defender))
  342. continue;
  343. // defender need to face in direction opposited to out attacker
  344. bool needsReverse = shouldAttackFacingRight(attackedInfo.attacker, attackedInfo.defender) == facingRight(attackedInfo.defender);
  345. // FIXME: this check is better, however not usable since stacksAreAttacked is called after net pack is applyed - petrification is already removed
  346. // if (needsReverse && !attackedInfo.defender->isFrozen())
  347. if (needsReverse && stackAnimation[attackedInfo.defender->ID]->getType() != ECreatureAnimType::FROZEN)
  348. {
  349. owner.executeOnAnimationCondition(EAnimationEvents::MOVEMENT, true, [=]()
  350. {
  351. addNewAnim(new ReverseAnimation(owner, attackedInfo.defender, attackedInfo.defender->getPosition()));
  352. });
  353. }
  354. }
  355. for(auto & attackedInfo : attackedInfos)
  356. {
  357. bool useDeathAnim = attackedInfo.killed;
  358. bool useDefenceAnim = attackedInfo.defender->defendingAnim && !attackedInfo.indirectAttack && !attackedInfo.killed;
  359. EAnimationEvents usedEvent = useDefenceAnim ? EAnimationEvents::ATTACK : EAnimationEvents::HIT;
  360. owner.executeOnAnimationCondition(usedEvent, true, [=]()
  361. {
  362. if (useDeathAnim)
  363. addNewAnim(new DeathAnimation(owner, attackedInfo.defender, attackedInfo.indirectAttack));
  364. else if(useDefenceAnim)
  365. addNewAnim(new DefenceAnimation(owner, attackedInfo.defender));
  366. else
  367. addNewAnim(new HittedAnimation(owner, attackedInfo.defender));
  368. if (attackedInfo.fireShield)
  369. owner.effectsController->displayEffect(EBattleEffect::FIRE_SHIELD, "FIRESHIE", attackedInfo.attacker->getPosition());
  370. if (attackedInfo.spellEffect != SpellID::NONE)
  371. {
  372. auto spell = attackedInfo.spellEffect.toSpell();
  373. if (!spell->getCastSound().empty())
  374. CCS->soundh->playSound(spell->getCastSound());
  375. owner.displaySpellEffect(spell, attackedInfo.defender->getPosition());
  376. }
  377. });
  378. }
  379. for (auto & attackedInfo : attackedInfos)
  380. {
  381. if (attackedInfo.rebirth)
  382. {
  383. owner.executeOnAnimationCondition(EAnimationEvents::AFTER_HIT, true, [=](){
  384. owner.effectsController->displayEffect(EBattleEffect::RESURRECT, "RESURECT", attackedInfo.defender->getPosition());
  385. addNewAnim(new ResurrectionAnimation(owner, attackedInfo.defender));
  386. });
  387. }
  388. if (attackedInfo.killed && attackedInfo.defender->summoned)
  389. {
  390. owner.executeOnAnimationCondition(EAnimationEvents::AFTER_HIT, true, [=](){
  391. addNewAnim(new ColorTransformAnimation(owner, attackedInfo.defender, "summonFadeOut", nullptr));
  392. stackRemoved(attackedInfo.defender->ID);
  393. });
  394. }
  395. }
  396. executeAttackAnimations();
  397. }
  398. void BattleStacksController::stackTeleported(const CStack *stack, std::vector<BattleHex> destHex, int distance)
  399. {
  400. assert(destHex.size() > 0);
  401. assert(owner.getAnimationCondition(EAnimationEvents::ACTION) == false);
  402. owner.executeOnAnimationCondition(EAnimationEvents::HIT, true, [=](){
  403. addNewAnim( new ColorTransformAnimation(owner, stack, "teleportFadeOut", nullptr) );
  404. });
  405. owner.executeOnAnimationCondition(EAnimationEvents::AFTER_HIT, true, [=](){
  406. stackAnimation[stack->ID]->pos.moveTo(getStackPositionAtHex(destHex.back(), stack));
  407. addNewAnim( new ColorTransformAnimation(owner, stack, "teleportFadeIn", nullptr) );
  408. });
  409. // animations will be executed by spell
  410. }
  411. void BattleStacksController::stackMoved(const CStack *stack, std::vector<BattleHex> destHex, int distance)
  412. {
  413. assert(destHex.size() > 0);
  414. assert(owner.getAnimationCondition(EAnimationEvents::ACTION) == false);
  415. bool stackTeleports = stack->hasBonus(Selector::typeSubtype(Bonus::FLYING, 1));
  416. owner.setAnimationCondition(EAnimationEvents::MOVEMENT, true);
  417. auto enqueMoveEnd = [&](){
  418. addNewAnim(new MovementEndAnimation(owner, stack, destHex.back()));
  419. owner.executeOnAnimationCondition(EAnimationEvents::ACTION, false, [&](){
  420. owner.setAnimationCondition(EAnimationEvents::MOVEMENT, false);
  421. });
  422. };
  423. auto enqueMove = [&](){
  424. if (!stackTeleports)
  425. {
  426. addNewAnim(new MovementAnimation(owner, stack, destHex, distance));
  427. owner.executeOnAnimationCondition(EAnimationEvents::ACTION, false, enqueMoveEnd);
  428. }
  429. else
  430. enqueMoveEnd();
  431. };
  432. auto enqueMoveStart = [&](){
  433. addNewAnim(new MovementStartAnimation(owner, stack));
  434. owner.executeOnAnimationCondition(EAnimationEvents::ACTION, false, enqueMove);
  435. };
  436. if(shouldRotate(stack, stack->getPosition(), destHex[0]))
  437. {
  438. addNewAnim(new ReverseAnimation(owner, stack, stack->getPosition()));
  439. owner.executeOnAnimationCondition(EAnimationEvents::ACTION, false, enqueMoveStart);
  440. }
  441. else
  442. enqueMoveStart();
  443. owner.waitForAnimationCondition(EAnimationEvents::MOVEMENT, false);
  444. }
  445. bool BattleStacksController::shouldAttackFacingRight(const CStack * attacker, const CStack * defender)
  446. {
  447. bool mustReverse = owner.curInt->cb->isToReverse(
  448. attacker->getPosition(),
  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 hoveredHex = owner.fieldController->getHoveredHex();
  744. if (!hoveredHex.isValid())
  745. return {};
  746. const spells::Caster *caster = nullptr;
  747. const CSpell *spell = nullptr;
  748. spells::Mode mode = spells::Mode::HERO;
  749. if(owner.actionsController->spellcastingModeActive())//hero casts spell
  750. {
  751. spell = owner.actionsController->selectedSpell().toSpell();
  752. caster = owner.getActiveHero();
  753. }
  754. else if(owner.stacksController->activeStackSpellToCast() != SpellID::NONE)//stack casts spell
  755. {
  756. spell = SpellID(owner.stacksController->activeStackSpellToCast()).toSpell();
  757. caster = owner.stacksController->getActiveStack();
  758. mode = spells::Mode::CREATURE_ACTIVE;
  759. }
  760. if(caster && spell) //when casting spell
  761. {
  762. spells::Target target;
  763. target.emplace_back(hoveredHex);
  764. spells::BattleCast event(owner.curInt->cb.get(), caster, mode, spell);
  765. auto mechanics = spell->battleMechanics(&event);
  766. return mechanics->getAffectedStacks(target);
  767. }
  768. if(hoveredHex.isValid())
  769. {
  770. const CStack * const stack = owner.curInt->cb->battleGetStackByPos(hoveredHex, true);
  771. if (stack)
  772. return {stack};
  773. }
  774. return {};
  775. }