BattleAnimationClasses.cpp 31 KB

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