CBattleAnimations.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212
  1. /*
  2. * CBattleAnimations.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 "CBattleAnimations.h"
  12. #include <boost/math/constants/constants.hpp>
  13. #include "CBattleInterfaceClasses.h"
  14. #include "CBattleInterface.h"
  15. #include "CBattleProjectileController.h"
  16. #include "CBattleSiegeController.h"
  17. #include "CBattleFieldController.h"
  18. #include "CBattleEffectsController.h"
  19. #include "CBattleStacksController.h"
  20. #include "CCreatureAnimation.h"
  21. #include "../CGameInfo.h"
  22. #include "../CMusicHandler.h"
  23. #include "../CPlayerInterface.h"
  24. #include "../Graphics.h"
  25. #include "../gui/CAnimation.h"
  26. #include "../gui/CCursorHandler.h"
  27. #include "../gui/CGuiHandler.h"
  28. #include "../../CCallback.h"
  29. #include "../../lib/CStack.h"
  30. #include "../../lib/CTownHandler.h"
  31. #include "../../lib/mapObjects/CGTownInstance.h"
  32. CBattleAnimation::CBattleAnimation(CBattleInterface * _owner)
  33. : owner(_owner),
  34. ID(_owner->stacksController->animIDhelper++),
  35. initialized(false)
  36. {
  37. logAnim->trace("Animation #%d created", ID);
  38. }
  39. bool CBattleAnimation::tryInitialize()
  40. {
  41. assert(!initialized);
  42. if ( init() )
  43. {
  44. initialized = true;
  45. return true;
  46. }
  47. return false;
  48. }
  49. bool CBattleAnimation::isInitialized()
  50. {
  51. return initialized;
  52. }
  53. CBattleAnimation::~CBattleAnimation()
  54. {
  55. logAnim->trace("Animation #%d ended, type is %s", ID, typeid(this).name());
  56. for(auto & elem : pendingAnimations())
  57. {
  58. if(elem == this)
  59. elem = nullptr;
  60. }
  61. logAnim->trace("Animation #%d deleted", ID);
  62. }
  63. std::vector<CBattleAnimation *> & CBattleAnimation::pendingAnimations()
  64. {
  65. return owner->stacksController->currentAnimations;
  66. }
  67. std::shared_ptr<CCreatureAnimation> CBattleAnimation::stackAnimation(const CStack * stack)
  68. {
  69. return owner->stacksController->stackAnimation[stack->ID];
  70. }
  71. bool CBattleAnimation::stackFacingRight(const CStack * stack)
  72. {
  73. return owner->stacksController->stackFacingRight[stack->ID];
  74. }
  75. void CBattleAnimation::setStackFacingRight(const CStack * stack, bool facingRight)
  76. {
  77. owner->stacksController->stackFacingRight[stack->ID] = facingRight;
  78. }
  79. bool CBattleAnimation::checkInitialConditions()
  80. {
  81. int lowestMoveID = ID;
  82. auto * thAnim = dynamic_cast<CBattleStackAnimation *>(this);
  83. auto * thSen = dynamic_cast<CPointEffectAnimation *>(this);
  84. for(auto & elem : pendingAnimations())
  85. {
  86. auto * sen = dynamic_cast<CPointEffectAnimation *>(elem);
  87. // all effect animations can play concurrently with each other
  88. if(sen && thSen && sen != thSen)
  89. continue;
  90. auto * revAnim = dynamic_cast<CReverseAnimation *>(elem);
  91. // if there is high-priority reverse animation affecting our stack then this animation will wait
  92. if(revAnim && thAnim && revAnim && revAnim->stack->ID == thAnim->stack->ID && revAnim->priority)
  93. return false;
  94. if(elem)
  95. vstd::amin(lowestMoveID, elem->ID);
  96. }
  97. return ID == lowestMoveID;
  98. }
  99. CBattleStackAnimation::CBattleStackAnimation(CBattleInterface * owner, const CStack * stack)
  100. : CBattleAnimation(owner),
  101. myAnim(stackAnimation(stack)),
  102. stack(stack)
  103. {
  104. assert(myAnim);
  105. }
  106. void CBattleStackAnimation::shiftColor(const ColorShifter * shifter)
  107. {
  108. assert(myAnim);
  109. myAnim->shiftColor(shifter);
  110. }
  111. void CAttackAnimation::nextFrame()
  112. {
  113. if(myAnim->getType() != group)
  114. {
  115. myAnim->setType(group);
  116. myAnim->onAnimationReset += [&](){ delete this; };
  117. }
  118. if(!soundPlayed)
  119. {
  120. if(shooting)
  121. CCS->soundh->playSound(battle_sound(getCreature(), shoot));
  122. else
  123. CCS->soundh->playSound(battle_sound(getCreature(), attack));
  124. soundPlayed = true;
  125. }
  126. }
  127. CAttackAnimation::~CAttackAnimation()
  128. {
  129. myAnim->setType(CCreatureAnim::HOLDING);
  130. }
  131. bool CAttackAnimation::checkInitialConditions()
  132. {
  133. for(auto & elem : pendingAnimations())
  134. {
  135. CBattleStackAnimation * stAnim = dynamic_cast<CBattleStackAnimation *>(elem);
  136. CReverseAnimation * revAnim = dynamic_cast<CReverseAnimation *>(stAnim);
  137. if(revAnim && attackedStack) // enemy must be fully reversed
  138. {
  139. if (revAnim->stack->ID == attackedStack->ID)
  140. return false;
  141. }
  142. }
  143. return CBattleAnimation::checkInitialConditions();
  144. }
  145. const CCreature * CAttackAnimation::getCreature()
  146. {
  147. if (attackingStack->getCreature()->idNumber == CreatureID::ARROW_TOWERS)
  148. return owner->siegeController->getTurretCreature();
  149. else
  150. return attackingStack->getCreature();
  151. }
  152. CAttackAnimation::CAttackAnimation(CBattleInterface *_owner, const CStack *attacker, BattleHex _dest, const CStack *defender)
  153. : CBattleStackAnimation(_owner, attacker),
  154. shooting(false),
  155. group(CCreatureAnim::SHOOT_FRONT),
  156. soundPlayed(false),
  157. dest(_dest),
  158. attackedStack(defender),
  159. attackingStack(attacker)
  160. {
  161. assert(attackingStack && "attackingStack is nullptr in CBattleAttack::CBattleAttack !\n");
  162. attackingStackPosBeforeReturn = attackingStack->getPosition();
  163. }
  164. CDefenceAnimation::CDefenceAnimation(StackAttackedInfo _attackedInfo, CBattleInterface * _owner)
  165. : CBattleStackAnimation(_owner, _attackedInfo.defender),
  166. attacker(_attackedInfo.attacker),
  167. rangedAttack(_attackedInfo.indirectAttack),
  168. killed(_attackedInfo.killed),
  169. timeToWait(0)
  170. {
  171. logAnim->debug("Created defence anim for %s", _attackedInfo.defender->getName());
  172. }
  173. bool CDefenceAnimation::init()
  174. {
  175. ui32 lowestMoveID = ID;
  176. for(auto & elem : pendingAnimations())
  177. {
  178. auto * defAnim = dynamic_cast<CDefenceAnimation *>(elem);
  179. if(defAnim && defAnim->stack->ID != stack->ID)
  180. continue;
  181. auto * attAnim = dynamic_cast<CAttackAnimation *>(elem);
  182. if(attAnim && attAnim->stack->ID != stack->ID)
  183. continue;
  184. auto * sen = dynamic_cast<CPointEffectAnimation *>(elem);
  185. if (sen && attacker == nullptr)
  186. return false;
  187. if (sen)
  188. continue;
  189. CReverseAnimation * animAsRev = dynamic_cast<CReverseAnimation *>(elem);
  190. if(animAsRev)
  191. return false;
  192. if(elem)
  193. vstd::amin(lowestMoveID, elem->ID);
  194. }
  195. if(ID > lowestMoveID)
  196. return false;
  197. //reverse unit if necessary
  198. if(attacker && owner->getCurrentPlayerInterface()->cb->isToReverse(stack->getPosition(), attacker->getPosition(), stackFacingRight(stack), attacker->doubleWide(), stackFacingRight(attacker)))
  199. {
  200. owner->stacksController->addNewAnim(new CReverseAnimation(owner, stack, stack->getPosition(), true));
  201. return false;
  202. }
  203. //unit reversed
  204. if(rangedAttack && attacker != nullptr && owner->projectilesController->hasActiveProjectile(attacker)) //delay hit animation
  205. {
  206. return false;
  207. }
  208. // synchronize animation with attacker, unless defending or attacked by shooter:
  209. // wait for 1/2 of attack animation
  210. if (!rangedAttack && getMyAnimType() != CCreatureAnim::DEFENCE)
  211. {
  212. float frameLength = AnimationControls::getCreatureAnimationSpeed(
  213. stack->getCreature(), stackAnimation(stack).get(), getMyAnimType());
  214. timeToWait = myAnim->framesInGroup(getMyAnimType()) * frameLength / 2;
  215. myAnim->setType(CCreatureAnim::HOLDING);
  216. }
  217. else
  218. {
  219. timeToWait = 0;
  220. startAnimation();
  221. }
  222. return true; //initialized successfuly
  223. }
  224. std::string CDefenceAnimation::getMySound()
  225. {
  226. if(killed)
  227. return battle_sound(stack->getCreature(), killed);
  228. else if(stack->defendingAnim)
  229. return battle_sound(stack->getCreature(), defend);
  230. else
  231. return battle_sound(stack->getCreature(), wince);
  232. }
  233. CCreatureAnim::EAnimType CDefenceAnimation::getMyAnimType()
  234. {
  235. if(killed)
  236. {
  237. if(rangedAttack && myAnim->framesInGroup(CCreatureAnim::DEATH_RANGED) > 0)
  238. return CCreatureAnim::DEATH_RANGED;
  239. else
  240. return CCreatureAnim::DEATH;
  241. }
  242. if(stack->defendingAnim)
  243. return CCreatureAnim::DEFENCE;
  244. else
  245. return CCreatureAnim::HITTED;
  246. }
  247. void CDefenceAnimation::startAnimation()
  248. {
  249. CCS->soundh->playSound(getMySound());
  250. myAnim->setType(getMyAnimType());
  251. myAnim->onAnimationReset += [&](){ delete this; };
  252. }
  253. void CDefenceAnimation::nextFrame()
  254. {
  255. if (timeToWait > 0)
  256. {
  257. timeToWait -= float(GH.mainFPSmng->getElapsedMilliseconds()) / 1000;
  258. if (timeToWait <= 0)
  259. startAnimation();
  260. }
  261. CBattleAnimation::nextFrame();
  262. }
  263. CDefenceAnimation::~CDefenceAnimation()
  264. {
  265. if(killed)
  266. {
  267. if(rangedAttack && myAnim->framesInGroup(CCreatureAnim::DEAD_RANGED) > 0)
  268. myAnim->setType(CCreatureAnim::DEAD_RANGED);
  269. else
  270. myAnim->setType(CCreatureAnim::DEAD);
  271. }
  272. else
  273. {
  274. myAnim->setType(CCreatureAnim::HOLDING);
  275. }
  276. }
  277. CDummyAnimation::CDummyAnimation(CBattleInterface * _owner, int howManyFrames)
  278. : CBattleAnimation(_owner),
  279. counter(0),
  280. howMany(howManyFrames)
  281. {
  282. logAnim->debug("Created dummy animation for %d frames", howManyFrames);
  283. }
  284. bool CDummyAnimation::init()
  285. {
  286. return true;
  287. }
  288. void CDummyAnimation::nextFrame()
  289. {
  290. counter++;
  291. if(counter > howMany)
  292. delete this;
  293. }
  294. bool CMeleeAttackAnimation::init()
  295. {
  296. if(!CAttackAnimation::checkInitialConditions())
  297. return false;
  298. if(!attackingStack || myAnim->isDeadOrDying())
  299. {
  300. delete this;
  301. return false;
  302. }
  303. bool toReverse = owner->getCurrentPlayerInterface()->cb->isToReverse(attackingStackPosBeforeReturn, attackedStack->getPosition(), stackFacingRight(stack), attackedStack->doubleWide(), stackFacingRight(attackedStack));
  304. if(toReverse)
  305. {
  306. owner->stacksController->addNewAnim(new CReverseAnimation(owner, stack, attackingStackPosBeforeReturn, true));
  307. return false;
  308. }
  309. // opponent must face attacker ( = different directions) before he can be attacked
  310. if(attackingStack && attackedStack &&
  311. stackFacingRight(attackingStack) == stackFacingRight(attackedStack))
  312. return false;
  313. //reversed
  314. shooting = false;
  315. static const CCreatureAnim::EAnimType mutPosToGroup[] =
  316. {
  317. CCreatureAnim::ATTACK_UP,
  318. CCreatureAnim::ATTACK_UP,
  319. CCreatureAnim::ATTACK_FRONT,
  320. CCreatureAnim::ATTACK_DOWN,
  321. CCreatureAnim::ATTACK_DOWN,
  322. CCreatureAnim::ATTACK_FRONT
  323. };
  324. static const CCreatureAnim::EAnimType mutPosToGroup2H[] =
  325. {
  326. CCreatureAnim::VCMI_2HEX_UP,
  327. CCreatureAnim::VCMI_2HEX_UP,
  328. CCreatureAnim::VCMI_2HEX_FRONT,
  329. CCreatureAnim::VCMI_2HEX_DOWN,
  330. CCreatureAnim::VCMI_2HEX_DOWN,
  331. CCreatureAnim::VCMI_2HEX_FRONT
  332. };
  333. int revShiftattacker = (attackingStack->side == BattleSide::ATTACKER ? -1 : 1);
  334. int mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn, dest);
  335. if(mutPos == -1 && attackingStack->doubleWide())
  336. {
  337. mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn + revShiftattacker, attackedStack->getPosition());
  338. }
  339. if (mutPos == -1 && attackedStack->doubleWide())
  340. {
  341. mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn, attackedStack->occupiedHex());
  342. }
  343. if (mutPos == -1 && attackedStack->doubleWide() && attackingStack->doubleWide())
  344. {
  345. mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn + revShiftattacker, attackedStack->occupiedHex());
  346. }
  347. switch(mutPos) //attack direction
  348. {
  349. case 0:
  350. case 1:
  351. case 2:
  352. case 3:
  353. case 4:
  354. case 5:
  355. group = mutPosToGroup[mutPos];
  356. if(attackingStack->hasBonusOfType(Bonus::TWO_HEX_ATTACK_BREATH))
  357. {
  358. CCreatureAnim::EAnimType group2H = mutPosToGroup2H[mutPos];
  359. if(myAnim->framesInGroup(group2H)>0)
  360. group = group2H;
  361. }
  362. break;
  363. default:
  364. logGlobal->error("Critical Error! Wrong dest in stackAttacking! dest: %d; attacking stack pos: %d; mutual pos: %d", dest.hex, attackingStackPosBeforeReturn, mutPos);
  365. group = CCreatureAnim::ATTACK_FRONT;
  366. break;
  367. }
  368. return true;
  369. }
  370. CMeleeAttackAnimation::CMeleeAttackAnimation(CBattleInterface * _owner, const CStack * attacker, BattleHex _dest, const CStack * _attacked)
  371. : CAttackAnimation(_owner, attacker, _dest, _attacked)
  372. {
  373. logAnim->debug("Created melee attack anim for %s", attacker->getName());
  374. }
  375. CStackMoveAnimation::CStackMoveAnimation(CBattleInterface * _owner, const CStack * _stack, BattleHex _currentHex):
  376. CBattleStackAnimation(_owner, _stack),
  377. currentHex(_currentHex)
  378. {
  379. }
  380. bool CMovementAnimation::init()
  381. {
  382. if( !CBattleAnimation::checkInitialConditions() )
  383. return false;
  384. if(!stack || myAnim->isDeadOrDying())
  385. {
  386. delete this;
  387. return false;
  388. }
  389. if(stackAnimation(stack)->framesInGroup(CCreatureAnim::MOVING) == 0 ||
  390. stack->hasBonus(Selector::typeSubtype(Bonus::FLYING, 1)))
  391. {
  392. //no movement or teleport, end immediately
  393. delete this;
  394. return false;
  395. }
  396. //reverse unit if necessary
  397. if(owner->stacksController->shouldRotate(stack, oldPos, currentHex))
  398. {
  399. // it seems that H3 does NOT plays full rotation animation here in most situations
  400. // Logical since it takes quite a lot of time
  401. if (curentMoveIndex == 0) // full rotation only for moving towards first tile.
  402. {
  403. owner->stacksController->addNewAnim(new CReverseAnimation(owner, stack, oldPos, true));
  404. return false;
  405. }
  406. else
  407. {
  408. rotateStack(oldPos);
  409. }
  410. }
  411. if(myAnim->getType() != CCreatureAnim::MOVING)
  412. {
  413. myAnim->setType(CCreatureAnim::MOVING);
  414. }
  415. if (owner->moveSoundHander == -1)
  416. {
  417. owner->moveSoundHander = CCS->soundh->playSound(battle_sound(stack->getCreature(), move), -1);
  418. }
  419. Point begPosition = owner->stacksController->getStackPositionAtHex(oldPos, stack);
  420. Point endPosition = owner->stacksController->getStackPositionAtHex(currentHex, stack);
  421. timeToMove = AnimationControls::getMovementDuration(stack->getCreature());
  422. begX = begPosition.x;
  423. begY = begPosition.y;
  424. progress = 0;
  425. distanceX = endPosition.x - begPosition.x;
  426. distanceY = endPosition.y - begPosition.y;
  427. if (stack->hasBonus(Selector::type()(Bonus::FLYING)))
  428. {
  429. float distance = static_cast<float>(sqrt(distanceX * distanceX + distanceY * distanceY));
  430. timeToMove *= AnimationControls::getFlightDistance(stack->getCreature()) / distance;
  431. }
  432. return true;
  433. }
  434. void CMovementAnimation::nextFrame()
  435. {
  436. progress += float(GH.mainFPSmng->getElapsedMilliseconds()) / 1000 * timeToMove;
  437. //moving instructions
  438. myAnim->pos.x = static_cast<Sint16>(begX + distanceX * progress );
  439. myAnim->pos.y = static_cast<Sint16>(begY + distanceY * progress );
  440. CBattleAnimation::nextFrame();
  441. if(progress >= 1.0)
  442. {
  443. // Sets the position of the creature animation sprites
  444. Point coords = owner->stacksController->getStackPositionAtHex(currentHex, stack);
  445. myAnim->pos = coords;
  446. // true if creature haven't reached the final destination hex
  447. if ((curentMoveIndex + 1) < destTiles.size())
  448. {
  449. // update the next hex field which has to be reached by the stack
  450. curentMoveIndex++;
  451. oldPos = currentHex;
  452. currentHex = destTiles[curentMoveIndex];
  453. // request re-initialization
  454. initialized = false;
  455. }
  456. else
  457. delete this;
  458. }
  459. }
  460. CMovementAnimation::~CMovementAnimation()
  461. {
  462. assert(stack);
  463. myAnim->pos = owner->stacksController->getStackPositionAtHex(currentHex, stack);
  464. owner->stacksController->addNewAnim(new CMovementEndAnimation(owner, stack, currentHex));
  465. if(owner->moveSoundHander != -1)
  466. {
  467. CCS->soundh->stopSound(owner->moveSoundHander);
  468. owner->moveSoundHander = -1;
  469. }
  470. }
  471. CMovementAnimation::CMovementAnimation(CBattleInterface *_owner, const CStack *_stack, std::vector<BattleHex> _destTiles, int _distance)
  472. : CStackMoveAnimation(_owner, _stack, _destTiles.front()),
  473. destTiles(_destTiles),
  474. curentMoveIndex(0),
  475. oldPos(stack->getPosition()),
  476. begX(0), begY(0),
  477. distanceX(0), distanceY(0),
  478. timeToMove(0.0),
  479. progress(0.0)
  480. {
  481. logAnim->debug("Created movement anim for %s", stack->getName());
  482. }
  483. CMovementEndAnimation::CMovementEndAnimation(CBattleInterface * _owner, const CStack * _stack, BattleHex destTile)
  484. : CStackMoveAnimation(_owner, _stack, destTile)
  485. {
  486. logAnim->debug("Created movement end anim for %s", stack->getName());
  487. }
  488. bool CMovementEndAnimation::init()
  489. {
  490. //if( !isEarliest(true) )
  491. // return false;
  492. if(!stack || myAnim->framesInGroup(CCreatureAnim::MOVE_END) == 0 ||
  493. myAnim->isDeadOrDying())
  494. {
  495. delete this;
  496. return false;
  497. }
  498. CCS->soundh->playSound(battle_sound(stack->getCreature(), endMoving));
  499. myAnim->setType(CCreatureAnim::MOVE_END);
  500. myAnim->onAnimationReset += [&](){ delete this; };
  501. return true;
  502. }
  503. CMovementEndAnimation::~CMovementEndAnimation()
  504. {
  505. if(myAnim->getType() != CCreatureAnim::DEAD)
  506. myAnim->setType(CCreatureAnim::HOLDING); //resetting to default
  507. CCS->curh->show();
  508. }
  509. CMovementStartAnimation::CMovementStartAnimation(CBattleInterface * _owner, const CStack * _stack)
  510. : CStackMoveAnimation(_owner, _stack, _stack->getPosition())
  511. {
  512. logAnim->debug("Created movement start anim for %s", stack->getName());
  513. }
  514. bool CMovementStartAnimation::init()
  515. {
  516. if( !CBattleAnimation::checkInitialConditions() )
  517. return false;
  518. if(!stack || myAnim->isDeadOrDying())
  519. {
  520. delete this;
  521. return false;
  522. }
  523. CCS->soundh->playSound(battle_sound(stack->getCreature(), startMoving));
  524. myAnim->setType(CCreatureAnim::MOVE_START);
  525. myAnim->onAnimationReset += [&](){ delete this; };
  526. return true;
  527. }
  528. CReverseAnimation::CReverseAnimation(CBattleInterface * _owner, const CStack * stack, BattleHex dest, bool _priority)
  529. : CStackMoveAnimation(_owner, stack, dest),
  530. priority(_priority)
  531. {
  532. logAnim->debug("Created reverse anim for %s", stack->getName());
  533. }
  534. bool CReverseAnimation::init()
  535. {
  536. if(myAnim == nullptr || myAnim->isDeadOrDying())
  537. {
  538. delete this;
  539. return false; //there is no such creature
  540. }
  541. if(!priority && !CBattleAnimation::checkInitialConditions())
  542. return false;
  543. if(myAnim->framesInGroup(CCreatureAnim::TURN_L))
  544. {
  545. myAnim->setType(CCreatureAnim::TURN_L);
  546. myAnim->onAnimationReset += std::bind(&CReverseAnimation::setupSecondPart, this);
  547. }
  548. else
  549. {
  550. setupSecondPart();
  551. }
  552. return true;
  553. }
  554. CReverseAnimation::~CReverseAnimation()
  555. {
  556. if( stack && stack->alive() )//don't do that if stack is dead
  557. myAnim->setType(CCreatureAnim::HOLDING);
  558. }
  559. void CBattleStackAnimation::rotateStack(BattleHex hex)
  560. {
  561. setStackFacingRight(stack, !stackFacingRight(stack));
  562. stackAnimation(stack)->pos = owner->stacksController->getStackPositionAtHex(hex, stack);
  563. }
  564. void CReverseAnimation::setupSecondPart()
  565. {
  566. if(!stack)
  567. {
  568. delete this;
  569. return;
  570. }
  571. rotateStack(currentHex);
  572. if(myAnim->framesInGroup(CCreatureAnim::TURN_R))
  573. {
  574. myAnim->setType(CCreatureAnim::TURN_R);
  575. myAnim->onAnimationReset += [&](){ delete this; };
  576. }
  577. else
  578. delete this;
  579. }
  580. CRangedAttackAnimation::CRangedAttackAnimation(CBattleInterface * owner_, const CStack * attacker, BattleHex dest_, const CStack * defender)
  581. : CAttackAnimation(owner_, attacker, dest_, defender),
  582. projectileEmitted(false)
  583. {
  584. logAnim->info("Ranged attack animation created");
  585. }
  586. bool CRangedAttackAnimation::init()
  587. {
  588. if( !CAttackAnimation::checkInitialConditions() )
  589. return false;
  590. assert(attackingStack);
  591. assert(!myAnim->isDeadOrDying());
  592. if(!attackingStack || myAnim->isDeadOrDying())
  593. {
  594. //FIXME: how is this possible?
  595. logAnim->warn("Shooting animation has not started yet but attacker is dead! Aborting...");
  596. delete this;
  597. return false;
  598. }
  599. //reverse unit if necessary
  600. if (attackingStack && attackedStack && owner->getCurrentPlayerInterface()->cb->isToReverse(attackingStack->getPosition(), attackedStack->getPosition(), stackFacingRight(attackingStack), attackingStack->doubleWide(), stackFacingRight(attackedStack)))
  601. {
  602. owner->stacksController->addNewAnim(new CReverseAnimation(owner, attackingStack, attackingStack->getPosition(), true));
  603. return false;
  604. }
  605. logAnim->info("Ranged attack animation initialized");
  606. setAnimationGroup();
  607. initializeProjectile();
  608. shooting = true;
  609. return true;
  610. }
  611. void CRangedAttackAnimation::setAnimationGroup()
  612. {
  613. Point shooterPos = stackAnimation(attackingStack)->pos.topLeft();
  614. Point shotTarget = owner->stacksController->getStackPositionAtHex(dest, attackedStack);
  615. //maximal angle in radians between straight horizontal line and shooting line for which shot is considered to be straight (absoulte value)
  616. static const double straightAngle = 0.2;
  617. double projectileAngle = -atan2(shotTarget.y - shooterPos.y, std::abs(shotTarget.x - shooterPos.x));
  618. // Calculate projectile start position. Offsets are read out of the CRANIM.TXT.
  619. if (projectileAngle > straightAngle)
  620. group = getUpwardsGroup();
  621. else if (projectileAngle < -straightAngle)
  622. group = getDownwardsGroup();
  623. else
  624. group = getForwardGroup();
  625. }
  626. void CRangedAttackAnimation::initializeProjectile()
  627. {
  628. const CCreature *shooterInfo = getCreature();
  629. Point shotTarget = owner->stacksController->getStackPositionAtHex(dest, attackedStack) + Point(225, 225);
  630. Point shotOrigin = stackAnimation(attackingStack)->pos.topLeft() + Point(222, 265);
  631. int multiplier = stackFacingRight(attackingStack) ? 1 : -1;
  632. if (group == getUpwardsGroup())
  633. {
  634. shotOrigin.x += ( -25 + shooterInfo->animation.upperRightMissleOffsetX ) * multiplier;
  635. shotOrigin.y += shooterInfo->animation.upperRightMissleOffsetY;
  636. }
  637. else if (group == getDownwardsGroup())
  638. {
  639. shotOrigin.x += ( -25 + shooterInfo->animation.lowerRightMissleOffsetX ) * multiplier;
  640. shotOrigin.y += shooterInfo->animation.lowerRightMissleOffsetY;
  641. }
  642. else if (group == getForwardGroup())
  643. {
  644. shotOrigin.x += ( -25 + shooterInfo->animation.rightMissleOffsetX ) * multiplier;
  645. shotOrigin.y += shooterInfo->animation.rightMissleOffsetY;
  646. }
  647. else
  648. {
  649. assert(0);
  650. }
  651. createProjectile(shotOrigin, shotTarget);
  652. }
  653. void CRangedAttackAnimation::emitProjectile()
  654. {
  655. logAnim->info("Ranged attack projectile emitted");
  656. owner->projectilesController->emitStackProjectile(attackingStack);
  657. projectileEmitted = true;
  658. }
  659. void CRangedAttackAnimation::nextFrame()
  660. {
  661. for(auto & it : pendingAnimations())
  662. {
  663. CMovementStartAnimation * anim = dynamic_cast<CMovementStartAnimation *>(it);
  664. CReverseAnimation * anim2 = dynamic_cast<CReverseAnimation *>(it);
  665. if( (anim && anim->stack->ID == stack->ID) || (anim2 && anim2->stack->ID == stack->ID && anim2->priority ) )
  666. {
  667. assert(0); // FIXME: our stack started to move even though we are playing shooting animation? How?
  668. return;
  669. }
  670. }
  671. // animation should be paused if there is an active projectile
  672. if (projectileEmitted)
  673. {
  674. if (owner->projectilesController->hasActiveProjectile(attackingStack))
  675. stackAnimation(attackingStack)->pause();
  676. else
  677. stackAnimation(attackingStack)->play();
  678. }
  679. CAttackAnimation::nextFrame();
  680. if (!projectileEmitted)
  681. {
  682. const CCreature *shooterInfo = getCreature();
  683. logAnim->info("Ranged attack executing, %d / %d / %d",
  684. stackAnimation(attackingStack)->getCurrentFrame(),
  685. shooterInfo->animation.attackClimaxFrame,
  686. stackAnimation(attackingStack)->framesInGroup(group));
  687. // emit projectile once animation playback reached "climax" frame
  688. if ( stackAnimation(attackingStack)->getCurrentFrame() >= shooterInfo->animation.attackClimaxFrame )
  689. {
  690. emitProjectile();
  691. stackAnimation(attackingStack)->pause();
  692. return;
  693. }
  694. }
  695. }
  696. CRangedAttackAnimation::~CRangedAttackAnimation()
  697. {
  698. logAnim->info("Ranged attack animation is over");
  699. //FIXME: this assert triggers under some unclear, rare conditions. Possibly - if game window is inactive and/or in foreground/minimized?
  700. assert(!owner->projectilesController->hasActiveProjectile(attackingStack));
  701. assert(projectileEmitted);
  702. // FIXME: is this possible? Animation is over but we're yet to fire projectile?
  703. if (!projectileEmitted)
  704. {
  705. logAnim->warn("Shooting animation has finished but projectile was not emitted! Emitting it now...");
  706. emitProjectile();
  707. }
  708. }
  709. CShootingAnimation::CShootingAnimation(CBattleInterface * _owner, const CStack * attacker, BattleHex _dest, const CStack * _attacked)
  710. : CRangedAttackAnimation(_owner, attacker, _dest, _attacked)
  711. {
  712. logAnim->debug("Created shooting anim for %s", stack->getName());
  713. }
  714. void CShootingAnimation::createProjectile(const Point & from, const Point & dest) const
  715. {
  716. owner->projectilesController->createProjectile(attackingStack, attackedStack, from, dest);
  717. }
  718. CCreatureAnim::EAnimType CShootingAnimation::getUpwardsGroup() const
  719. {
  720. return CCreatureAnim::SHOOT_UP;
  721. }
  722. CCreatureAnim::EAnimType CShootingAnimation::getForwardGroup() const
  723. {
  724. return CCreatureAnim::SHOOT_FRONT;
  725. }
  726. CCreatureAnim::EAnimType CShootingAnimation::getDownwardsGroup() const
  727. {
  728. return CCreatureAnim::SHOOT_DOWN;
  729. }
  730. CCatapultAnimation::CCatapultAnimation(CBattleInterface * _owner, const CStack * attacker, BattleHex _dest, const CStack * _attacked, int _catapultDmg)
  731. : CShootingAnimation(_owner, attacker, _dest, _attacked),
  732. catapultDamage(_catapultDmg),
  733. explosionEmitted(false)
  734. {
  735. logAnim->debug("Created shooting anim for %s", stack->getName());
  736. }
  737. void CCatapultAnimation::nextFrame()
  738. {
  739. CShootingAnimation::nextFrame();
  740. if ( explosionEmitted)
  741. return;
  742. if ( !projectileEmitted)
  743. return;
  744. if (owner->projectilesController->hasActiveProjectile(attackingStack))
  745. return;
  746. explosionEmitted = true;
  747. Point shotTarget = owner->stacksController->getStackPositionAtHex(dest, attackedStack) + Point(225, 225) - Point(126, 105);
  748. if(catapultDamage > 0)
  749. owner->stacksController->addNewAnim( new CPointEffectAnimation(owner, soundBase::WALLHIT, "SGEXPL.DEF", shotTarget));
  750. else
  751. owner->stacksController->addNewAnim( new CPointEffectAnimation(owner, soundBase::WALLMISS, "CSGRCK.DEF", shotTarget));
  752. }
  753. void CCatapultAnimation::createProjectile(const Point & from, const Point & dest) const
  754. {
  755. owner->projectilesController->createCatapultProjectile(attackingStack, from, dest);
  756. }
  757. CCastAnimation::CCastAnimation(CBattleInterface * owner_, const CStack * attacker, BattleHex dest_, const CStack * defender, const CSpell * spell)
  758. : CRangedAttackAnimation(owner_, attacker, dest_, defender),
  759. spell(spell)
  760. {
  761. assert(dest.isValid());// FIXME: when?
  762. if(!dest_.isValid() && defender)
  763. dest = defender->getPosition();
  764. }
  765. CCreatureAnim::EAnimType CCastAnimation::findValidGroup( const std::vector<CCreatureAnim::EAnimType> candidates ) const
  766. {
  767. for ( auto group : candidates)
  768. {
  769. if(myAnim->framesInGroup(group) > 0)
  770. return group;
  771. }
  772. assert(0);
  773. return CCreatureAnim::HOLDING;
  774. }
  775. CCreatureAnim::EAnimType CCastAnimation::getUpwardsGroup() const
  776. {
  777. return findValidGroup({
  778. CCreatureAnim::VCMI_CAST_UP,
  779. CCreatureAnim::CAST_UP,
  780. CCreatureAnim::SHOOT_UP,
  781. CCreatureAnim::ATTACK_UP
  782. });
  783. }
  784. CCreatureAnim::EAnimType CCastAnimation::getForwardGroup() const
  785. {
  786. return findValidGroup({
  787. CCreatureAnim::VCMI_CAST_FRONT,
  788. CCreatureAnim::CAST_FRONT,
  789. CCreatureAnim::SHOOT_FRONT,
  790. CCreatureAnim::ATTACK_FRONT
  791. });
  792. }
  793. CCreatureAnim::EAnimType CCastAnimation::getDownwardsGroup() const
  794. {
  795. return findValidGroup({
  796. CCreatureAnim::VCMI_CAST_DOWN,
  797. CCreatureAnim::CAST_DOWN,
  798. CCreatureAnim::SHOOT_DOWN,
  799. CCreatureAnim::ATTACK_DOWN
  800. });
  801. }
  802. void CCastAnimation::createProjectile(const Point & from, const Point & dest) const
  803. {
  804. if (!spell->animationInfo.projectile.empty())
  805. owner->projectilesController->createSpellProjectile(attackingStack, attackedStack, from, dest, spell);
  806. }
  807. CPointEffectAnimation::CPointEffectAnimation(CBattleInterface * _owner, soundBase::soundID sound, std::string animationName, int effects):
  808. CBattleAnimation(_owner),
  809. animation(std::make_shared<CAnimation>(animationName)),
  810. sound(sound),
  811. effectFlags(effects),
  812. soundPlayed(false),
  813. soundFinished(false),
  814. effectFinished(false)
  815. {
  816. }
  817. CPointEffectAnimation::CPointEffectAnimation(CBattleInterface * _owner, soundBase::soundID sound, std::string animationName, std::vector<BattleHex> hex, int effects):
  818. CPointEffectAnimation(_owner, sound, animationName, effects)
  819. {
  820. battlehexes = hex;
  821. }
  822. CPointEffectAnimation::CPointEffectAnimation(CBattleInterface * _owner, soundBase::soundID sound, std::string animationName, BattleHex hex, int effects):
  823. CPointEffectAnimation(_owner, sound, animationName, effects)
  824. {
  825. assert(hex.isValid());
  826. battlehexes.push_back(hex);
  827. }
  828. CPointEffectAnimation::CPointEffectAnimation(CBattleInterface * _owner, soundBase::soundID sound, std::string animationName, std::vector<Point> pos, int effects):
  829. CPointEffectAnimation(_owner, sound, animationName, effects)
  830. {
  831. positions = pos;
  832. }
  833. CPointEffectAnimation::CPointEffectAnimation(CBattleInterface * _owner, soundBase::soundID sound, std::string animationName, Point pos, int effects):
  834. CPointEffectAnimation(_owner, sound, animationName, effects)
  835. {
  836. positions.push_back(pos);
  837. }
  838. CPointEffectAnimation::CPointEffectAnimation(CBattleInterface * _owner, soundBase::soundID sound, std::string animationName, Point pos, BattleHex hex, int effects):
  839. CPointEffectAnimation(_owner, sound, animationName, effects)
  840. {
  841. assert(hex.isValid());
  842. battlehexes.push_back(hex);
  843. positions.push_back(pos);
  844. }
  845. bool CPointEffectAnimation::init()
  846. {
  847. if(!CBattleAnimation::checkInitialConditions())
  848. return false;
  849. animation->preload();
  850. auto first = animation->getImage(0, 0, true);
  851. if(!first)
  852. {
  853. delete this;
  854. return false;
  855. }
  856. if (screenFill())
  857. {
  858. for(int i=0; i * first->width() < owner->pos.w ; ++i)
  859. for(int j=0; j * first->height() < owner->pos.h ; ++j)
  860. positions.push_back(Point(i * first->width(), j * first->height()));
  861. }
  862. BattleEffect be;
  863. be.effectID = ID;
  864. be.animation = animation;
  865. be.currentFrame = 0;
  866. for (size_t i = 0; i < std::max(battlehexes.size(), positions.size()); ++i)
  867. {
  868. bool hasTile = i < battlehexes.size();
  869. bool hasPosition = i < positions.size();
  870. if (hasTile && !forceOnTop())
  871. be.position = battlehexes[i];
  872. else
  873. be.position = BattleHex::INVALID;
  874. if (hasPosition)
  875. {
  876. be.x = positions[i].x;
  877. be.y = positions[i].y;
  878. }
  879. else
  880. {
  881. const CStack * destStack = owner->getCurrentPlayerInterface()->cb->battleGetStackByPos(battlehexes[i], false);
  882. Rect tilePos = owner->fieldController->hexPosition(battlehexes[i]);
  883. be.x = tilePos.x + tilePos.w/2 - first->width()/2;
  884. if(destStack && destStack->doubleWide()) // Correction for 2-hex creatures.
  885. be.x += (destStack->side == BattleSide::ATTACKER ? -1 : 1)*tilePos.w/2;
  886. if (alignToBottom())
  887. be.y = tilePos.y + tilePos.h - first->height();
  888. else
  889. be.y = tilePos.y - first->height()/2;
  890. }
  891. owner->effectsController->battleEffects.push_back(be);
  892. }
  893. return true;
  894. }
  895. void CPointEffectAnimation::nextFrame()
  896. {
  897. playSound();
  898. playEffect();
  899. if (soundFinished && effectFinished)
  900. {
  901. //remove visual effect itself only if sound has finished as well - necessary for obstacles like force field
  902. clearEffect();
  903. delete this;
  904. }
  905. }
  906. bool CPointEffectAnimation::alignToBottom() const
  907. {
  908. return effectFlags & ALIGN_TO_BOTTOM;
  909. }
  910. bool CPointEffectAnimation::waitForSound() const
  911. {
  912. return effectFlags & WAIT_FOR_SOUND;
  913. }
  914. bool CPointEffectAnimation::forceOnTop() const
  915. {
  916. return effectFlags & FORCE_ON_TOP;
  917. }
  918. bool CPointEffectAnimation::screenFill() const
  919. {
  920. return effectFlags & SCREEN_FILL;
  921. }
  922. void CPointEffectAnimation::onEffectFinished()
  923. {
  924. effectFinished = true;
  925. }
  926. void CPointEffectAnimation::onSoundFinished()
  927. {
  928. soundFinished = true;
  929. }
  930. void CPointEffectAnimation::playSound()
  931. {
  932. if (soundPlayed)
  933. return;
  934. soundPlayed = true;
  935. if (sound == soundBase::invalid)
  936. {
  937. onSoundFinished();
  938. return;
  939. }
  940. int channel = CCS->soundh->playSound(sound);
  941. if (!waitForSound() || channel == -1)
  942. onSoundFinished();
  943. else
  944. CCS->soundh->setCallback(channel, [&](){ onSoundFinished(); });
  945. }
  946. void CPointEffectAnimation::playEffect()
  947. {
  948. if ( effectFinished )
  949. return;
  950. for(auto & elem : owner->effectsController->battleEffects)
  951. {
  952. if(elem.effectID == ID)
  953. {
  954. elem.currentFrame += AnimationControls::getSpellEffectSpeed() * GH.mainFPSmng->getElapsedMilliseconds() / 1000;
  955. if(elem.currentFrame >= elem.animation->size())
  956. {
  957. elem.currentFrame = elem.animation->size() - 1;
  958. onEffectFinished();
  959. break;
  960. }
  961. }
  962. }
  963. }
  964. void CPointEffectAnimation::clearEffect()
  965. {
  966. auto & effects = owner->effectsController->battleEffects;
  967. for ( auto it = effects.begin(); it != effects.end(); )
  968. {
  969. if (it->effectID == ID)
  970. it = effects.erase(it);
  971. else
  972. it++;
  973. }
  974. }
  975. CPointEffectAnimation::~CPointEffectAnimation()
  976. {
  977. assert(effectFinished);
  978. assert(soundFinished);
  979. }
  980. CWaitingAnimation::CWaitingAnimation(CBattleInterface * owner_):
  981. CBattleAnimation(owner_)
  982. {}
  983. void CWaitingAnimation::nextFrame()
  984. {
  985. // initialization conditions fulfilled, delay is over
  986. delete this;
  987. }
  988. CWaitingProjectileAnimation::CWaitingProjectileAnimation(CBattleInterface * owner_, const CStack * shooter):
  989. CWaitingAnimation(owner_),
  990. shooter(shooter)
  991. {}
  992. bool CWaitingProjectileAnimation::init()
  993. {
  994. for(auto & elem : pendingAnimations())
  995. {
  996. auto * attackAnim = dynamic_cast<CRangedAttackAnimation *>(elem);
  997. if( attackAnim && shooter && attackAnim->stack->ID == shooter->ID && !attackAnim->isInitialized() )
  998. {
  999. // there is ongoing ranged attack that involves our stack, but projectile was not created yet
  1000. return false;
  1001. }
  1002. }
  1003. if(owner->projectilesController->hasActiveProjectile(shooter))
  1004. return false;
  1005. return true;
  1006. }