BattleAnimationClasses.cpp 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142
  1. /*
  2. * BattleAnimationClasses.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 "BattleAnimationClasses.h"
  12. #include "BattleInterface.h"
  13. #include "BattleInterfaceClasses.h"
  14. #include "BattleProjectileController.h"
  15. #include "BattleSiegeController.h"
  16. #include "BattleFieldController.h"
  17. #include "BattleEffectsController.h"
  18. #include "BattleStacksController.h"
  19. #include "CreatureAnimation.h"
  20. #include "../CPlayerInterface.h"
  21. #include "../gui/CursorHandler.h"
  22. #include "../GameEngine.h"
  23. #include "../media/ISoundPlayer.h"
  24. #include "../render/CAnimation.h"
  25. #include "../render/IRenderHandler.h"
  26. #include "../../lib/battle/CPlayerBattleCallback.h"
  27. #include "../../lib/CStack.h"
  28. BattleAnimation::BattleAnimation(BattleInterface & owner)
  29. : owner(owner),
  30. ID(owner.stacksController->animIDhelper++),
  31. initialized(false)
  32. {
  33. logAnim->trace("Animation #%d created", ID);
  34. }
  35. bool BattleAnimation::tryInitialize()
  36. {
  37. assert(!initialized);
  38. if ( init() )
  39. {
  40. initialized = true;
  41. return true;
  42. }
  43. return false;
  44. }
  45. bool BattleAnimation::isInitialized()
  46. {
  47. return initialized;
  48. }
  49. BattleAnimation::~BattleAnimation()
  50. {
  51. logAnim->trace("Animation #%d ended, type is %s", ID, typeid(this).name());
  52. for(auto & elem : pendingAnimations())
  53. {
  54. if(elem == this)
  55. elem = nullptr;
  56. }
  57. logAnim->trace("Animation #%d deleted", ID);
  58. }
  59. std::vector<BattleAnimation *> & BattleAnimation::pendingAnimations()
  60. {
  61. return owner.stacksController->currentAnimations;
  62. }
  63. std::shared_ptr<CreatureAnimation> BattleAnimation::stackAnimation(const CStack * stack) const
  64. {
  65. return owner.stacksController->stackAnimation[stack->unitId()];
  66. }
  67. bool BattleAnimation::stackFacingRight(const CStack * stack)
  68. {
  69. return owner.stacksController->stackFacingRight[stack->unitId()];
  70. }
  71. void BattleAnimation::setStackFacingRight(const CStack * stack, bool facingRight)
  72. {
  73. owner.stacksController->stackFacingRight[stack->unitId()] = facingRight;
  74. }
  75. BattleStackAnimation::BattleStackAnimation(BattleInterface & owner, const CStack * stack)
  76. : BattleAnimation(owner),
  77. myAnim(stackAnimation(stack)),
  78. stack(stack)
  79. {
  80. assert(myAnim);
  81. }
  82. StackActionAnimation::StackActionAnimation(BattleInterface & owner, const CStack * stack)
  83. : BattleStackAnimation(owner, stack)
  84. , nextGroup(ECreatureAnimType::HOLDING)
  85. , currGroup(ECreatureAnimType::HOLDING)
  86. {
  87. }
  88. ECreatureAnimType StackActionAnimation::getGroup() const
  89. {
  90. return currGroup;
  91. }
  92. void StackActionAnimation::setNextGroup( ECreatureAnimType group )
  93. {
  94. nextGroup = group;
  95. }
  96. void StackActionAnimation::setGroup( ECreatureAnimType group )
  97. {
  98. currGroup = group;
  99. }
  100. void StackActionAnimation::setSound( const AudioPath & sound )
  101. {
  102. this->sound = sound;
  103. }
  104. bool StackActionAnimation::init()
  105. {
  106. if (!sound.empty())
  107. ENGINE->sound().playSound(sound);
  108. if (myAnim->framesInGroup(currGroup) > 0)
  109. {
  110. myAnim->playOnce(currGroup);
  111. myAnim->onAnimationReset += [&](){ delete this; };
  112. }
  113. else
  114. delete this;
  115. return true;
  116. }
  117. StackActionAnimation::~StackActionAnimation()
  118. {
  119. if (stack->isFrozen() && currGroup != ECreatureAnimType::DEATH && currGroup != ECreatureAnimType::DEATH_RANGED)
  120. myAnim->setType(ECreatureAnimType::HOLDING);
  121. else
  122. myAnim->setType(nextGroup);
  123. }
  124. ECreatureAnimType AttackAnimation::findValidGroup( const std::vector<ECreatureAnimType> candidates ) const
  125. {
  126. for ( auto group : candidates)
  127. {
  128. if(myAnim->framesInGroup(group) > 0)
  129. return group;
  130. }
  131. assert(0);
  132. return ECreatureAnimType::HOLDING;
  133. }
  134. const CCreature * AttackAnimation::getCreature() const
  135. {
  136. if (attackingStack->unitType()->getId() == CreatureID::ARROW_TOWERS)
  137. return owner.siegeController->getTurretCreature(attackingStack->initialPosition);
  138. else
  139. return attackingStack->unitType();
  140. }
  141. AttackAnimation::AttackAnimation(BattleInterface & owner, const CStack *attacker, BattleHex _dest, const CStack *defender)
  142. : StackActionAnimation(owner, attacker),
  143. dest(_dest),
  144. defendingStack(defender),
  145. attackingStack(attacker)
  146. {
  147. assert(attackingStack && "attackingStack is nullptr in CBattleAttack::CBattleAttack !\n");
  148. attackingStackPosBeforeReturn = attackingStack->getPosition().toInt();
  149. }
  150. HittedAnimation::HittedAnimation(BattleInterface & owner, const CStack * stack)
  151. : StackActionAnimation(owner, stack)
  152. {
  153. setGroup(ECreatureAnimType::HITTED);
  154. setSound(stack->unitType()->sounds.wince);
  155. logAnim->debug("Created HittedAnimation for %s", stack->getName());
  156. }
  157. DefenceAnimation::DefenceAnimation(BattleInterface & owner, const CStack * stack)
  158. : StackActionAnimation(owner, stack)
  159. {
  160. setGroup(ECreatureAnimType::DEFENCE);
  161. setSound(stack->unitType()->sounds.defend);
  162. logAnim->debug("Created DefenceAnimation for %s", stack->getName());
  163. }
  164. DeathAnimation::DeathAnimation(BattleInterface & owner, const CStack * stack, bool ranged):
  165. StackActionAnimation(owner, stack)
  166. {
  167. setSound(stack->unitType()->sounds.killed);
  168. if(ranged && myAnim->framesInGroup(ECreatureAnimType::DEATH_RANGED) > 0)
  169. setGroup(ECreatureAnimType::DEATH_RANGED);
  170. else
  171. setGroup(ECreatureAnimType::DEATH);
  172. if(ranged && myAnim->framesInGroup(ECreatureAnimType::DEAD_RANGED) > 0)
  173. setNextGroup(ECreatureAnimType::DEAD_RANGED);
  174. else
  175. setNextGroup(ECreatureAnimType::DEAD);
  176. logAnim->debug("Created DeathAnimation for %s", stack->getName());
  177. }
  178. DummyAnimation::DummyAnimation(BattleInterface & owner, int howManyFrames)
  179. : BattleAnimation(owner),
  180. counter(0),
  181. howMany(howManyFrames)
  182. {
  183. logAnim->debug("Created dummy animation for %d frames", howManyFrames);
  184. }
  185. bool DummyAnimation::init()
  186. {
  187. return true;
  188. }
  189. void DummyAnimation::tick(uint32_t msPassed)
  190. {
  191. counter++;
  192. if(counter > howMany)
  193. delete this;
  194. }
  195. ECreatureAnimType MeleeAttackAnimation::getUpwardsGroup(bool multiAttack) const
  196. {
  197. if (!multiAttack)
  198. return ECreatureAnimType::ATTACK_UP;
  199. return findValidGroup({
  200. ECreatureAnimType::GROUP_ATTACK_UP,
  201. ECreatureAnimType::SPECIAL_UP,
  202. ECreatureAnimType::SPECIAL_FRONT, // weird, but required for H3
  203. ECreatureAnimType::ATTACK_UP
  204. });
  205. }
  206. ECreatureAnimType MeleeAttackAnimation::getForwardGroup(bool multiAttack) const
  207. {
  208. if (!multiAttack)
  209. return ECreatureAnimType::ATTACK_FRONT;
  210. return findValidGroup({
  211. ECreatureAnimType::GROUP_ATTACK_FRONT,
  212. ECreatureAnimType::SPECIAL_FRONT,
  213. ECreatureAnimType::ATTACK_FRONT
  214. });
  215. }
  216. ECreatureAnimType MeleeAttackAnimation::getDownwardsGroup(bool multiAttack) const
  217. {
  218. if (!multiAttack)
  219. return ECreatureAnimType::ATTACK_DOWN;
  220. return findValidGroup({
  221. ECreatureAnimType::GROUP_ATTACK_DOWN,
  222. ECreatureAnimType::SPECIAL_DOWN,
  223. ECreatureAnimType::SPECIAL_FRONT, // weird, but required for H3
  224. ECreatureAnimType::ATTACK_DOWN
  225. });
  226. }
  227. ECreatureAnimType MeleeAttackAnimation::selectGroup(bool multiAttack)
  228. {
  229. const ECreatureAnimType mutPosToGroup[] =
  230. {
  231. getUpwardsGroup (multiAttack),
  232. getUpwardsGroup (multiAttack),
  233. getForwardGroup (multiAttack),
  234. getDownwardsGroup(multiAttack),
  235. getDownwardsGroup(multiAttack),
  236. getForwardGroup (multiAttack)
  237. };
  238. int revShiftattacker = (attackingStack->unitSide() == BattleSide::ATTACKER ? -1 : 1);
  239. int mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn, dest);
  240. if(mutPos == -1 && attackingStack->doubleWide())
  241. {
  242. mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn + revShiftattacker, defendingStack->getPosition());
  243. }
  244. if (mutPos == -1 && defendingStack->doubleWide())
  245. {
  246. mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn, defendingStack->occupiedHex());
  247. }
  248. if (mutPos == -1 && defendingStack->doubleWide() && attackingStack->doubleWide())
  249. {
  250. mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn + revShiftattacker, defendingStack->occupiedHex());
  251. }
  252. assert(mutPos >= 0 && mutPos <=5);
  253. return mutPosToGroup[mutPos];
  254. }
  255. void MeleeAttackAnimation::tick(uint32_t msPassed)
  256. {
  257. size_t currentFrame = stackAnimation(attackingStack)->getCurrentFrame();
  258. size_t totalFrames = stackAnimation(attackingStack)->framesInGroup(getGroup());
  259. if ( currentFrame * 2 >= totalFrames )
  260. owner.executeAnimationStage(EAnimationEvents::HIT);
  261. AttackAnimation::tick(msPassed);
  262. }
  263. MeleeAttackAnimation::MeleeAttackAnimation(BattleInterface & owner, const CStack * attacker, BattleHex _dest, const CStack * _attacked, bool multiAttack)
  264. : AttackAnimation(owner, attacker, _dest, _attacked)
  265. {
  266. logAnim->debug("Created MeleeAttackAnimation for %s", attacker->getName());
  267. setSound(getCreature()->sounds.attack);
  268. setGroup(selectGroup(multiAttack));
  269. }
  270. StackMoveAnimation::StackMoveAnimation(BattleInterface & owner, const CStack * _stack, BattleHex prevHex, BattleHex nextHex):
  271. BattleStackAnimation(owner, _stack),
  272. prevHex(prevHex),
  273. nextHex(nextHex)
  274. {
  275. }
  276. bool MovementAnimation::init()
  277. {
  278. assert(stack);
  279. assert(!myAnim->isDeadOrDying());
  280. assert(stackAnimation(stack)->framesInGroup(ECreatureAnimType::MOVING) > 0);
  281. if(stackAnimation(stack)->framesInGroup(ECreatureAnimType::MOVING) == 0)
  282. {
  283. //no movement, end immediately
  284. delete this;
  285. return false;
  286. }
  287. logAnim->debug("CMovementAnimation::init: stack %s moves %d -> %d", stack->getName(), prevHex, nextHex);
  288. //reverse unit if necessary
  289. if(owner.stacksController->shouldRotate(stack, prevHex, nextHex))
  290. {
  291. // it seems that H3 does NOT plays full rotation animation during movement
  292. // Logical since it takes quite a lot of time
  293. rotateStack(prevHex);
  294. }
  295. if(myAnim->getType() != ECreatureAnimType::MOVING)
  296. {
  297. myAnim->setType(ECreatureAnimType::MOVING);
  298. }
  299. if (moveSoundHandler == -1)
  300. {
  301. moveSoundHandler = ENGINE->sound().playSoundLooped(stack->unitType()->sounds.move);
  302. }
  303. Point begPosition = owner.stacksController->getStackPositionAtHex(prevHex, stack);
  304. Point endPosition = owner.stacksController->getStackPositionAtHex(nextHex, stack);
  305. progressPerSecond = AnimationControls::getMovementRange(stack->unitType());
  306. begX = begPosition.x;
  307. begY = begPosition.y;
  308. //progress = 0;
  309. distanceX = endPosition.x - begPosition.x;
  310. distanceY = endPosition.y - begPosition.y;
  311. if (stack->hasBonus(Selector::type()(BonusType::FLYING)))
  312. {
  313. float distance = static_cast<float>(sqrt(distanceX * distanceX + distanceY * distanceY));
  314. progressPerSecond = AnimationControls::getFlightDistance(stack->unitType()) / distance;
  315. }
  316. return true;
  317. }
  318. void MovementAnimation::tick(uint32_t msPassed)
  319. {
  320. progress += float(msPassed) / 1000 * progressPerSecond;
  321. //moving instructions
  322. myAnim->pos.x = begX + distanceX * progress;
  323. myAnim->pos.y = begY + distanceY * progress;
  324. BattleAnimation::tick(msPassed);
  325. if(progress >= 1.0)
  326. {
  327. progress -= 1.0;
  328. // Sets the position of the creature animation sprites
  329. Point coords = owner.stacksController->getStackPositionAtHex(nextHex, stack);
  330. myAnim->pos.moveTo(coords);
  331. // true if creature haven't reached the final destination hex
  332. if ((currentMoveIndex + 1) < destTiles.size())
  333. {
  334. // update the next hex field which has to be reached by the stack
  335. currentMoveIndex++;
  336. prevHex = nextHex;
  337. nextHex = destTiles[currentMoveIndex];
  338. // request re-initialization
  339. initialized = false;
  340. }
  341. else
  342. delete this;
  343. }
  344. }
  345. MovementAnimation::~MovementAnimation()
  346. {
  347. assert(stack);
  348. if(moveSoundHandler != -1)
  349. ENGINE->sound().stopSound(moveSoundHandler);
  350. }
  351. MovementAnimation::MovementAnimation(BattleInterface & owner, const CStack *stack, const BattleHexArray & _destTiles, int _distance)
  352. : StackMoveAnimation(owner, stack, stack->getPosition(), _destTiles.front()),
  353. destTiles(_destTiles),
  354. currentMoveIndex(0),
  355. begX(0), begY(0),
  356. distanceX(0), distanceY(0),
  357. progressPerSecond(0.0),
  358. moveSoundHandler(-1),
  359. progress(0.0)
  360. {
  361. logAnim->debug("Created MovementAnimation for %s", stack->getName());
  362. }
  363. MovementEndAnimation::MovementEndAnimation(BattleInterface & owner, const CStack * _stack, BattleHex destTile)
  364. : StackMoveAnimation(owner, _stack, destTile, destTile)
  365. {
  366. logAnim->debug("Created MovementEndAnimation for %s", stack->getName());
  367. }
  368. bool MovementEndAnimation::init()
  369. {
  370. assert(stack);
  371. assert(!myAnim->isDeadOrDying());
  372. if(!stack || myAnim->isDeadOrDying())
  373. {
  374. delete this;
  375. return false;
  376. }
  377. logAnim->debug("CMovementEndAnimation::init: stack %s", stack->getName());
  378. myAnim->pos.moveTo(owner.stacksController->getStackPositionAtHex(nextHex, stack));
  379. ENGINE->sound().playSound(stack->unitType()->sounds.endMoving);
  380. if(!myAnim->framesInGroup(ECreatureAnimType::MOVE_END))
  381. {
  382. delete this;
  383. return false;
  384. }
  385. myAnim->setType(ECreatureAnimType::MOVE_END);
  386. myAnim->onAnimationReset += [&](){ delete this; };
  387. return true;
  388. }
  389. MovementEndAnimation::~MovementEndAnimation()
  390. {
  391. if(myAnim->getType() != ECreatureAnimType::DEAD)
  392. myAnim->setType(ECreatureAnimType::HOLDING); //resetting to default
  393. ENGINE->cursor().show();
  394. }
  395. MovementStartAnimation::MovementStartAnimation(BattleInterface & owner, const CStack * _stack)
  396. : StackMoveAnimation(owner, _stack, _stack->getPosition(), _stack->getPosition())
  397. {
  398. logAnim->debug("Created MovementStartAnimation for %s", stack->getName());
  399. }
  400. bool MovementStartAnimation::init()
  401. {
  402. assert(stack);
  403. assert(!myAnim->isDeadOrDying());
  404. if(!stack || myAnim->isDeadOrDying())
  405. {
  406. delete this;
  407. return false;
  408. }
  409. logAnim->debug("CMovementStartAnimation::init: stack %s", stack->getName());
  410. ENGINE->sound().playSound(stack->unitType()->sounds.startMoving);
  411. if(!myAnim->framesInGroup(ECreatureAnimType::MOVE_START))
  412. {
  413. delete this;
  414. return false;
  415. }
  416. myAnim->setType(ECreatureAnimType::MOVE_START);
  417. myAnim->onAnimationReset += [&](){ delete this; };
  418. return true;
  419. }
  420. ReverseAnimation::ReverseAnimation(BattleInterface & owner, const CStack * stack, BattleHex dest)
  421. : StackMoveAnimation(owner, stack, dest, dest)
  422. {
  423. logAnim->debug("Created ReverseAnimation for %s", stack->getName());
  424. }
  425. bool ReverseAnimation::init()
  426. {
  427. assert(myAnim);
  428. assert(!myAnim->isDeadOrDying());
  429. if(myAnim == nullptr || myAnim->isDeadOrDying())
  430. {
  431. delete this;
  432. return false; //there is no such creature
  433. }
  434. logAnim->debug("CReverseAnimation::init: stack %s", stack->getName());
  435. if(myAnim->framesInGroup(ECreatureAnimType::TURN_L))
  436. {
  437. myAnim->playOnce(ECreatureAnimType::TURN_L);
  438. myAnim->onAnimationReset += std::bind(&ReverseAnimation::setupSecondPart, this);
  439. }
  440. else
  441. {
  442. setupSecondPart();
  443. }
  444. return true;
  445. }
  446. void BattleStackAnimation::rotateStack(BattleHex hex)
  447. {
  448. setStackFacingRight(stack, !stackFacingRight(stack));
  449. stackAnimation(stack)->pos.moveTo(owner.stacksController->getStackPositionAtHex(hex, stack));
  450. }
  451. void ReverseAnimation::setupSecondPart()
  452. {
  453. assert(stack);
  454. if(!stack)
  455. {
  456. delete this;
  457. return;
  458. }
  459. rotateStack(nextHex);
  460. if(myAnim->framesInGroup(ECreatureAnimType::TURN_R))
  461. {
  462. myAnim->playOnce(ECreatureAnimType::TURN_R);
  463. myAnim->onAnimationReset += [&](){ delete this; };
  464. }
  465. else
  466. delete this;
  467. }
  468. ResurrectionAnimation::ResurrectionAnimation(BattleInterface & owner, const CStack * _stack):
  469. StackActionAnimation(owner, _stack)
  470. {
  471. setGroup(ECreatureAnimType::RESURRECTION);
  472. logAnim->debug("Created ResurrectionAnimation for %s", stack->getName());
  473. }
  474. bool ColorTransformAnimation::init()
  475. {
  476. return true;
  477. }
  478. void ColorTransformAnimation::tick(uint32_t msPassed)
  479. {
  480. float elapsed = msPassed / 1000.f;
  481. float fullTime = AnimationControls::getFadeInDuration();
  482. float delta = elapsed / fullTime;
  483. totalProgress += delta;
  484. size_t index = 0;
  485. while (index < timePoints.size() && timePoints[index] < totalProgress )
  486. ++index;
  487. if (index == timePoints.size())
  488. {
  489. //end of animation. Apply ColorShifter using final values and die
  490. const auto & lastColor = effectColors[index - 1];
  491. const auto & lastAlpha = transparency[index - 1];
  492. owner.stacksController->setStackColorFilter(lastColor, lastAlpha, stack, spell, false);
  493. delete this;
  494. return;
  495. }
  496. assert(index != 0);
  497. const auto & prevColor = effectColors[index - 1];
  498. const auto & nextColor = effectColors[index];
  499. const auto & prevAlpha = transparency[index - 1];
  500. const auto & nextAlpha = transparency[index];
  501. float prevPoint = timePoints[index-1];
  502. float nextPoint = timePoints[index];
  503. float localProgress = totalProgress - prevPoint;
  504. float stepDuration = (nextPoint - prevPoint);
  505. float factor = localProgress / stepDuration;
  506. const auto & currColor = vstd::lerp(prevColor, nextColor, factor);
  507. const auto & currAlpha = vstd::lerp(prevAlpha, nextAlpha, factor);
  508. owner.stacksController->setStackColorFilter(currColor, currAlpha, stack, spell, true);
  509. }
  510. ColorTransformAnimation::ColorTransformAnimation(BattleInterface & owner, const CStack * _stack, const std::string & colorFilterName, const CSpell * spell):
  511. BattleStackAnimation(owner, _stack),
  512. spell(spell),
  513. totalProgress(0.f)
  514. {
  515. auto effect = owner.effectsController->getMuxerEffect(colorFilterName);
  516. effectColors = effect.effectColors;
  517. transparency = effect.transparency;
  518. timePoints = effect.timePoints;
  519. assert(!effectColors.empty() && effectColors.size() == timePoints.size());
  520. logAnim->debug("Created ColorTransformAnimation for %s", stack->getName());
  521. }
  522. RangedAttackAnimation::RangedAttackAnimation(BattleInterface & owner_, const CStack * attacker, BattleHex dest_, const CStack * defender)
  523. : AttackAnimation(owner_, attacker, dest_, defender),
  524. projectileEmitted(false)
  525. {
  526. setSound(getCreature()->sounds.shoot);
  527. }
  528. bool RangedAttackAnimation::init()
  529. {
  530. setAnimationGroup();
  531. initializeProjectile();
  532. return AttackAnimation::init();
  533. }
  534. void RangedAttackAnimation::setAnimationGroup()
  535. {
  536. Point shooterPos = stackAnimation(attackingStack)->pos.topLeft();
  537. Point shotTarget = owner.stacksController->getStackPositionAtHex(dest, defendingStack);
  538. //maximal angle in radians between straight horizontal line and shooting line for which shot is considered to be straight (absolute value)
  539. static const double straightAngle = 0.2;
  540. double projectileAngle = -atan2(shotTarget.y - shooterPos.y, std::abs(shotTarget.x - shooterPos.x));
  541. // Calculate projectile start position. Offsets are read out of the CRANIM.TXT.
  542. if (projectileAngle > straightAngle)
  543. setGroup(getUpwardsGroup());
  544. else if (projectileAngle < -straightAngle)
  545. setGroup(getDownwardsGroup());
  546. else
  547. setGroup(getForwardGroup());
  548. }
  549. void RangedAttackAnimation::initializeProjectile()
  550. {
  551. const CCreature *shooterInfo = getCreature();
  552. Point shotTarget = owner.stacksController->getStackPositionAtHex(dest, defendingStack) + Point(225, 225);
  553. Point shotOrigin = stackAnimation(attackingStack)->pos.topLeft() + Point(222, 265);
  554. int multiplier = stackFacingRight(attackingStack) ? 1 : -1;
  555. if (getGroup() == getUpwardsGroup())
  556. {
  557. shotOrigin.x += ( -25 + shooterInfo->animation.upperRightMissileOffsetX ) * multiplier;
  558. shotOrigin.y += shooterInfo->animation.upperRightMissileOffsetY;
  559. }
  560. else if (getGroup() == getDownwardsGroup())
  561. {
  562. shotOrigin.x += ( -25 + shooterInfo->animation.lowerRightMissileOffsetX ) * multiplier;
  563. shotOrigin.y += shooterInfo->animation.lowerRightMissileOffsetY;
  564. }
  565. else if (getGroup() == getForwardGroup())
  566. {
  567. shotOrigin.x += ( -25 + shooterInfo->animation.rightMissileOffsetX ) * multiplier;
  568. shotOrigin.y += shooterInfo->animation.rightMissileOffsetY;
  569. }
  570. else
  571. {
  572. assert(0);
  573. }
  574. createProjectile(shotOrigin, shotTarget);
  575. }
  576. void RangedAttackAnimation::emitProjectile()
  577. {
  578. logAnim->debug("Ranged attack projectile emitted");
  579. owner.projectilesController->emitStackProjectile(attackingStack);
  580. projectileEmitted = true;
  581. }
  582. void RangedAttackAnimation::tick(uint32_t msPassed)
  583. {
  584. // animation should be paused if there is an active projectile
  585. if (projectileEmitted)
  586. {
  587. if (!owner.projectilesController->hasActiveProjectile(attackingStack, false))
  588. owner.executeAnimationStage(EAnimationEvents::HIT);
  589. }
  590. bool stackHasProjectile = owner.projectilesController->hasActiveProjectile(stack, true);
  591. if (!projectileEmitted || stackHasProjectile)
  592. stackAnimation(attackingStack)->playUntil(getAttackClimaxFrame());
  593. else
  594. stackAnimation(attackingStack)->playUntil(static_cast<size_t>(-1));
  595. AttackAnimation::tick(msPassed);
  596. if (!projectileEmitted)
  597. {
  598. // emit projectile once animation playback reached "climax" frame
  599. if ( stackAnimation(attackingStack)->getCurrentFrame() >= getAttackClimaxFrame() )
  600. {
  601. emitProjectile();
  602. return;
  603. }
  604. }
  605. }
  606. RangedAttackAnimation::~RangedAttackAnimation()
  607. {
  608. assert(!owner.projectilesController->hasActiveProjectile(attackingStack, false));
  609. assert(projectileEmitted);
  610. // FIXME: is this possible? Animation is over but we're yet to fire projectile?
  611. if (!projectileEmitted)
  612. {
  613. logAnim->warn("Shooting animation has finished but projectile was not emitted! Emitting it now...");
  614. emitProjectile();
  615. }
  616. }
  617. ShootingAnimation::ShootingAnimation(BattleInterface & owner, const CStack * attacker, BattleHex _dest, const CStack * _attacked)
  618. : RangedAttackAnimation(owner, attacker, _dest, _attacked)
  619. {
  620. logAnim->debug("Created ShootingAnimation for %s", stack->getName());
  621. }
  622. void ShootingAnimation::createProjectile(const Point & from, const Point & dest) const
  623. {
  624. owner.projectilesController->createProjectile(attackingStack, from, dest);
  625. }
  626. uint32_t ShootingAnimation::getAttackClimaxFrame() const
  627. {
  628. const CCreature *shooterInfo = getCreature();
  629. uint32_t maxFrames = stackAnimation(attackingStack)->framesInGroup(getGroup());
  630. uint32_t climaxFrame = shooterInfo->animation.attackClimaxFrame;
  631. uint32_t selectedFrame = std::clamp<int>(shooterInfo->animation.attackClimaxFrame, 1, maxFrames);
  632. if (climaxFrame != selectedFrame)
  633. logGlobal->warn("Shooter %s has ranged attack climax frame set to %d, but only %d available!", shooterInfo->getNamePluralTranslated(), climaxFrame, maxFrames);
  634. return selectedFrame - 1; // H3 counts frames from 1
  635. }
  636. ECreatureAnimType ShootingAnimation::getUpwardsGroup() const
  637. {
  638. return ECreatureAnimType::SHOOT_UP;
  639. }
  640. ECreatureAnimType ShootingAnimation::getForwardGroup() const
  641. {
  642. return ECreatureAnimType::SHOOT_FRONT;
  643. }
  644. ECreatureAnimType ShootingAnimation::getDownwardsGroup() const
  645. {
  646. return ECreatureAnimType::SHOOT_DOWN;
  647. }
  648. CatapultAnimation::CatapultAnimation(BattleInterface & owner, const CStack * attacker, BattleHex _dest, const CStack * _attacked, int _catapultDmg)
  649. : ShootingAnimation(owner, attacker, _dest, _attacked),
  650. catapultDamage(_catapultDmg),
  651. explosionEmitted(false)
  652. {
  653. logAnim->debug("Created shooting anim for %s", stack->getName());
  654. }
  655. void CatapultAnimation::tick(uint32_t msPassed)
  656. {
  657. ShootingAnimation::tick(msPassed);
  658. if ( explosionEmitted)
  659. return;
  660. if ( !projectileEmitted)
  661. return;
  662. if (owner.projectilesController->hasActiveProjectile(attackingStack, false))
  663. return;
  664. explosionEmitted = true;
  665. Point shotTarget = owner.stacksController->getStackPositionAtHex(dest, defendingStack) + Point(225, 225) - Point(126, 105);
  666. auto soundFilename = AudioPath::builtin((catapultDamage > 0) ? "WALLHIT" : "WALLMISS");
  667. AnimationPath effectFilename = AnimationPath::builtin((catapultDamage > 0) ? "SGEXPL" : "CSGRCK");
  668. ENGINE->sound().playSound( soundFilename );
  669. owner.stacksController->addNewAnim( new EffectAnimation(owner, effectFilename, shotTarget));
  670. }
  671. void CatapultAnimation::createProjectile(const Point & from, const Point & dest) const
  672. {
  673. owner.projectilesController->createCatapultProjectile(attackingStack, from, dest);
  674. }
  675. CastAnimation::CastAnimation(BattleInterface & owner_, const CStack * attacker, BattleHex dest, const CStack * defender, const CSpell * spell)
  676. : RangedAttackAnimation(owner_, attacker, dest, defender),
  677. spell(spell)
  678. {
  679. if(!dest.isValid())
  680. {
  681. assert(spell->animationInfo.projectile.empty());
  682. if (defender)
  683. dest = defender->getPosition();
  684. else
  685. dest = attacker->getPosition();
  686. }
  687. }
  688. ECreatureAnimType CastAnimation::getUpwardsGroup() const
  689. {
  690. return findValidGroup({
  691. ECreatureAnimType::CAST_UP,
  692. ECreatureAnimType::SPECIAL_UP,
  693. ECreatureAnimType::SPECIAL_FRONT, // weird, but required for H3
  694. ECreatureAnimType::SHOOT_UP,
  695. ECreatureAnimType::ATTACK_UP
  696. });
  697. }
  698. ECreatureAnimType CastAnimation::getForwardGroup() const
  699. {
  700. return findValidGroup({
  701. ECreatureAnimType::CAST_FRONT,
  702. ECreatureAnimType::SPECIAL_FRONT,
  703. ECreatureAnimType::SHOOT_FRONT,
  704. ECreatureAnimType::ATTACK_FRONT
  705. });
  706. }
  707. ECreatureAnimType CastAnimation::getDownwardsGroup() const
  708. {
  709. return findValidGroup({
  710. ECreatureAnimType::CAST_DOWN,
  711. ECreatureAnimType::SPECIAL_DOWN,
  712. ECreatureAnimType::SPECIAL_FRONT, // weird, but required for H3
  713. ECreatureAnimType::SHOOT_DOWN,
  714. ECreatureAnimType::ATTACK_DOWN
  715. });
  716. }
  717. void CastAnimation::createProjectile(const Point & from, const Point & dest) const
  718. {
  719. if (!spell->animationInfo.projectile.empty())
  720. owner.projectilesController->createSpellProjectile(attackingStack, from, dest, spell);
  721. }
  722. uint32_t CastAnimation::getAttackClimaxFrame() const
  723. {
  724. //TODO: allow defining this parameter in config file, separately from attackClimaxFrame of missile attacks
  725. uint32_t maxFrames = stackAnimation(attackingStack)->framesInGroup(getGroup());
  726. return maxFrames / 2;
  727. }
  728. EffectAnimation::EffectAnimation(BattleInterface & owner, const AnimationPath & animationName, int effects, float transparencyFactor, bool reversed):
  729. BattleAnimation(owner),
  730. animation(ENGINE->renderHandler().loadAnimation(animationName, EImageBlitMode::SIMPLE)),
  731. transparencyFactor(transparencyFactor),
  732. effectFlags(effects),
  733. effectFinished(false),
  734. reversed(reversed)
  735. {
  736. logAnim->debug("CPointEffectAnimation::init: effect %s", animationName.getName());
  737. }
  738. EffectAnimation::EffectAnimation(BattleInterface & owner, const AnimationPath & animationName, const BattleHexArray & hexes, int effects, bool reversed):
  739. EffectAnimation(owner, animationName, effects, 1.0f, reversed)
  740. {
  741. battlehexes = hexes;
  742. }
  743. EffectAnimation::EffectAnimation(BattleInterface & owner, const AnimationPath & animationName, BattleHex hex, int effects, float transparencyFactor, bool reversed):
  744. EffectAnimation(owner, animationName, effects, transparencyFactor, reversed)
  745. {
  746. assert(hex.isValid());
  747. battlehexes.insert(hex);
  748. }
  749. EffectAnimation::EffectAnimation(BattleInterface & owner, const AnimationPath & animationName, std::vector<Point> pos, int effects, bool reversed):
  750. EffectAnimation(owner, animationName, effects, 1.0f, reversed)
  751. {
  752. positions = pos;
  753. }
  754. EffectAnimation::EffectAnimation(BattleInterface & owner, const AnimationPath & animationName, Point pos, int effects, bool reversed):
  755. EffectAnimation(owner, animationName, effects, 1.0f, reversed)
  756. {
  757. positions.push_back(pos);
  758. }
  759. EffectAnimation::EffectAnimation(BattleInterface & owner, const AnimationPath & animationName, Point pos, BattleHex hex, int effects, bool reversed):
  760. EffectAnimation(owner, animationName, effects, 1.0f, reversed)
  761. {
  762. assert(hex.isValid());
  763. battlehexes.insert(hex);
  764. positions.push_back(pos);
  765. }
  766. bool EffectAnimation::init()
  767. {
  768. auto first = animation->getImage(0, 0, true);
  769. if(!first)
  770. {
  771. delete this;
  772. return false;
  773. }
  774. for (size_t i = 0; i < animation->size(size_t(BattleEffect::AnimType::DEFAULT)); ++i)
  775. {
  776. size_t current = animation->size(size_t(BattleEffect::AnimType::DEFAULT)) - 1 - i;
  777. animation->duplicateImage(size_t(BattleEffect::AnimType::DEFAULT), current, size_t(BattleEffect::AnimType::REVERSE));
  778. }
  779. if (screenFill())
  780. {
  781. for(int i=0; i * first->width() < owner.fieldController->pos.w ; ++i)
  782. for(int j=0; j * first->height() < owner.fieldController->pos.h ; ++j)
  783. positions.push_back(Point( i * first->width(), j * first->height()));
  784. }
  785. BattleEffect be;
  786. be.effectID = ID;
  787. be.animation = animation;
  788. be.currentFrame = 0;
  789. be.transparencyFactor = transparencyFactor;
  790. be.type = reversed ? BattleEffect::AnimType::REVERSE : BattleEffect::AnimType::DEFAULT;
  791. for (size_t i = 0; i < std::max(battlehexes.size(), positions.size()); ++i)
  792. {
  793. bool hasTile = i < battlehexes.size();
  794. bool hasPosition = i < positions.size();
  795. if (hasTile && !forceOnTop())
  796. be.tile = battlehexes[i];
  797. else
  798. be.tile = BattleHex::INVALID;
  799. if (hasPosition)
  800. {
  801. be.pos.x = positions[i].x;
  802. be.pos.y = positions[i].y;
  803. }
  804. else
  805. {
  806. const auto * destStack = owner.getBattle()->battleGetUnitByPos(battlehexes[i], false);
  807. Rect tilePos = owner.fieldController->hexPositionLocal(battlehexes[i]);
  808. be.pos.x = tilePos.x + tilePos.w/2 - first->width()/2;
  809. if(destStack && destStack->doubleWide()) // Correction for 2-hex creatures.
  810. be.pos.x += (destStack->unitSide() == BattleSide::ATTACKER ? -1 : 1)*tilePos.w/2;
  811. if (alignToBottom())
  812. be.pos.y = tilePos.y + tilePos.h - first->height();
  813. else
  814. be.pos.y = tilePos.y - first->height()/2;
  815. }
  816. owner.effectsController->battleEffects.push_back(be);
  817. }
  818. return true;
  819. }
  820. void EffectAnimation::tick(uint32_t msPassed)
  821. {
  822. playEffect(msPassed);
  823. if (effectFinished)
  824. {
  825. //remove visual effect itself only if sound has finished as well - necessary for obstacles like force field
  826. clearEffect();
  827. delete this;
  828. }
  829. }
  830. bool EffectAnimation::alignToBottom() const
  831. {
  832. return effectFlags & ALIGN_TO_BOTTOM;
  833. }
  834. bool EffectAnimation::forceOnTop() const
  835. {
  836. return effectFlags & FORCE_ON_TOP;
  837. }
  838. bool EffectAnimation::screenFill() const
  839. {
  840. return effectFlags & SCREEN_FILL;
  841. }
  842. void EffectAnimation::onEffectFinished()
  843. {
  844. effectFinished = true;
  845. }
  846. void EffectAnimation::playEffect(uint32_t msPassed)
  847. {
  848. if ( effectFinished )
  849. return;
  850. for(auto & elem : owner.effectsController->battleEffects)
  851. {
  852. if(elem.effectID == ID)
  853. {
  854. elem.currentFrame += AnimationControls::getSpellEffectSpeed() * msPassed / 1000;
  855. if(elem.currentFrame >= elem.animation->size())
  856. {
  857. elem.currentFrame = elem.animation->size() - 1;
  858. onEffectFinished();
  859. break;
  860. }
  861. }
  862. }
  863. }
  864. void EffectAnimation::clearEffect()
  865. {
  866. auto & effects = owner.effectsController->battleEffects;
  867. vstd::erase_if(effects, [&](const BattleEffect & effect){
  868. return effect.effectID == ID;
  869. });
  870. }
  871. EffectAnimation::~EffectAnimation()
  872. {
  873. assert(effectFinished);
  874. }
  875. HeroCastAnimation::HeroCastAnimation(BattleInterface & owner, std::shared_ptr<BattleHero> hero, BattleHex dest, const CStack * defender, const CSpell * spell):
  876. BattleAnimation(owner),
  877. projectileEmitted(false),
  878. hero(hero),
  879. target(defender),
  880. tile(dest),
  881. spell(spell)
  882. {
  883. }
  884. bool HeroCastAnimation::init()
  885. {
  886. hero->setPhase(EHeroAnimType::CAST_SPELL);
  887. hero->onPhaseFinished([&](){
  888. delete this;
  889. });
  890. initializeProjectile();
  891. return true;
  892. }
  893. void HeroCastAnimation::initializeProjectile()
  894. {
  895. // spell has no projectile to play, ignore this step
  896. if (spell->animationInfo.projectile.empty())
  897. return;
  898. // targeted spells should have well, target
  899. assert(tile.isValid());
  900. Point srccoord = hero->pos.center() - hero->parent->pos.topLeft();
  901. Point destcoord = owner.stacksController->getStackPositionAtHex(tile, target); //position attacked by projectile
  902. destcoord += Point(222, 265); // FIXME: what are these constants?
  903. owner.projectilesController->createSpellProjectile( nullptr, srccoord, destcoord, spell);
  904. }
  905. void HeroCastAnimation::emitProjectile()
  906. {
  907. if (projectileEmitted)
  908. return;
  909. //spell has no projectile to play, skip this step and immediately play hit animations
  910. if (spell->animationInfo.projectile.empty())
  911. emitAnimationEvent();
  912. else
  913. owner.projectilesController->emitStackProjectile( nullptr );
  914. projectileEmitted = true;
  915. }
  916. void HeroCastAnimation::emitAnimationEvent()
  917. {
  918. owner.executeAnimationStage(EAnimationEvents::HIT);
  919. }
  920. void HeroCastAnimation::tick(uint32_t msPassed)
  921. {
  922. float frame = hero->getFrame();
  923. if (frame < 4.0f) // middle point of animation //TODO: un-hardcode
  924. return;
  925. if (!projectileEmitted)
  926. {
  927. emitProjectile();
  928. hero->pause();
  929. return;
  930. }
  931. if (!owner.projectilesController->hasActiveProjectile(nullptr, false))
  932. {
  933. emitAnimationEvent();
  934. //TODO: check H3 - it is possible that hero animation should be paused until hit effect is over, not just projectile
  935. hero->play();
  936. }
  937. }