BattleAnimationClasses.cpp 33 KB

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