BattleAnimationClasses.cpp 30 KB

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