CBattleAnimations.cpp 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  1. #include "StdInc.h"
  2. #include "CBattleAnimations.h"
  3. #include <boost/math/constants/constants.hpp>
  4. #include "CBattleInterfaceClasses.h"
  5. #include "CBattleInterface.h"
  6. #include "CCreatureAnimation.h"
  7. #include "../CDefHandler.h"
  8. #include "../CGameInfo.h"
  9. #include "../CMusicHandler.h"
  10. #include "../CPlayerInterface.h"
  11. #include "../Graphics.h"
  12. #include "../gui/CCursorHandler.h"
  13. #include "../gui/CGuiHandler.h"
  14. #include "../gui/SDL_Extensions.h"
  15. #include "../../CCallback.h"
  16. #include "../../lib/BattleState.h"
  17. #include "../../lib/CTownHandler.h"
  18. /*
  19. * CBattleAnimations.cpp, part of VCMI engine
  20. *
  21. * Authors: listed in file AUTHORS in main folder
  22. *
  23. * License: GNU General Public License v2.0 or later
  24. * Full text of license available in license.txt file, in main folder
  25. *
  26. */
  27. CBattleAnimation::CBattleAnimation(CBattleInterface * _owner)
  28. : owner(_owner), ID(_owner->animIDhelper++)
  29. {
  30. logAnim->traceStream() << "Animation #" << ID << " created";
  31. }
  32. CBattleAnimation::~CBattleAnimation()
  33. {
  34. logAnim->traceStream() << "Animation #" << ID << " deleted";
  35. }
  36. void CBattleAnimation::endAnim()
  37. {
  38. logAnim->traceStream() << "Animation #" << ID << " ended, type is " << typeid(this).name();
  39. for(auto & elem : owner->pendingAnims)
  40. {
  41. if(elem.first == this)
  42. {
  43. elem.first = nullptr;
  44. }
  45. }
  46. }
  47. bool CBattleAnimation::isEarliest(bool perStackConcurrency)
  48. {
  49. int lowestMoveID = owner->animIDhelper + 5;
  50. CBattleStackAnimation * thAnim = dynamic_cast<CBattleStackAnimation *>(this);
  51. CSpellEffectAnimation * thSen = dynamic_cast<CSpellEffectAnimation *>(this);
  52. for(auto & elem : owner->pendingAnims)
  53. {
  54. if (elem.first == this)
  55. continue;
  56. CBattleStackAnimation * stAnim = dynamic_cast<CBattleStackAnimation *>(elem.first);
  57. CSpellEffectAnimation * sen = dynamic_cast<CSpellEffectAnimation *>(elem.first);
  58. if(perStackConcurrency && stAnim && thAnim && stAnim->stack->ID != thAnim->stack->ID)
  59. continue;
  60. if(perStackConcurrency && sen && thSen && sen != thSen)
  61. continue;
  62. CReverseAnimation * revAnim = dynamic_cast<CReverseAnimation *>(stAnim);
  63. if(revAnim && thAnim && stAnim && stAnim->stack->ID == thAnim->stack->ID && revAnim->priority)
  64. return false;
  65. if(elem.first)
  66. vstd::amin(lowestMoveID, elem.first->ID);
  67. }
  68. return (ID == lowestMoveID) || (lowestMoveID == (owner->animIDhelper + 5));
  69. }
  70. CBattleStackAnimation::CBattleStackAnimation(CBattleInterface * owner, const CStack * stack)
  71. : CBattleAnimation(owner),
  72. myAnim(owner->creAnims[stack->ID]),
  73. stack(stack)
  74. {}
  75. void CAttackAnimation::nextFrame()
  76. {
  77. if(myAnim->getType() != group)
  78. {
  79. myAnim->setType(group);
  80. myAnim->onAnimationReset += std::bind(&CAttackAnimation::endAnim, this);
  81. }
  82. if(!soundPlayed)
  83. {
  84. if(shooting)
  85. CCS->soundh->playSound(battle_sound(attackingStack->getCreature(), shoot));
  86. else
  87. CCS->soundh->playSound(battle_sound(attackingStack->getCreature(), attack));
  88. soundPlayed = true;
  89. }
  90. CBattleAnimation::nextFrame();
  91. }
  92. void CAttackAnimation::endAnim()
  93. {
  94. myAnim->setType(CCreatureAnim::HOLDING);
  95. CBattleStackAnimation::endAnim();
  96. }
  97. bool CAttackAnimation::checkInitialConditions()
  98. {
  99. for(auto & elem : owner->pendingAnims)
  100. {
  101. CBattleStackAnimation * stAnim = dynamic_cast<CBattleStackAnimation *>(elem.first);
  102. CReverseAnimation * revAnim = dynamic_cast<CReverseAnimation *>(stAnim);
  103. if(revAnim) // enemy must be fully reversed
  104. {
  105. if (revAnim->stack->ID == attackedStack->ID)
  106. return false;
  107. }
  108. }
  109. return isEarliest(false);
  110. }
  111. CAttackAnimation::CAttackAnimation(CBattleInterface *_owner, const CStack *attacker, BattleHex _dest, const CStack *defender)
  112. : CBattleStackAnimation(_owner, attacker),
  113. soundPlayed(false),
  114. dest(_dest), attackedStack(defender), attackingStack(attacker)
  115. {
  116. assert(attackingStack && "attackingStack is nullptr in CBattleAttack::CBattleAttack !\n");
  117. bool isCatapultAttack = attackingStack->hasBonusOfType(Bonus::CATAPULT)
  118. && owner->curInt->cb->battleHexToWallPart(_dest) >= 0;
  119. assert(attackedStack || isCatapultAttack);
  120. attackingStackPosBeforeReturn = attackingStack->position;
  121. }
  122. CDefenceAnimation::CDefenceAnimation(StackAttackedInfo _attackedInfo, CBattleInterface * _owner)
  123. : CBattleStackAnimation(_owner, _attackedInfo.defender),
  124. attacker(_attackedInfo.attacker), rangedAttack(_attackedInfo.rangedAttack),
  125. killed(_attackedInfo.killed)
  126. {}
  127. bool CDefenceAnimation::init()
  128. {
  129. if(attacker == nullptr && owner->battleEffects.size() > 0)
  130. return false;
  131. ui32 lowestMoveID = owner->animIDhelper + 5;
  132. for(auto & elem : owner->pendingAnims)
  133. {
  134. if (elem.first == this)
  135. continue;
  136. CDefenceAnimation * defAnim = dynamic_cast<CDefenceAnimation *>(elem.first);
  137. if(defAnim && defAnim->stack->ID != stack->ID)
  138. continue;
  139. CAttackAnimation * attAnim = dynamic_cast<CAttackAnimation *>(elem.first);
  140. if(attAnim && attAnim->stack->ID != stack->ID)
  141. continue;
  142. CReverseAnimation * animAsRev = dynamic_cast<CReverseAnimation *>(elem.first);
  143. if(animAsRev)
  144. return false;
  145. if(elem.first)
  146. vstd::amin(lowestMoveID, elem.first->ID);
  147. }
  148. if(ID > lowestMoveID)
  149. return false;
  150. //reverse unit if necessary
  151. if (attacker && owner->curInt->cb->isToReverse(stack->position, attacker->position, owner->creDir[stack->ID], attacker->doubleWide(), owner->creDir[attacker->ID]))
  152. {
  153. owner->addNewAnim(new CReverseAnimation(owner, stack, stack->position, true));
  154. return false;
  155. }
  156. //unit reversed
  157. if(rangedAttack) //delay hit animation
  158. {
  159. for(std::list<ProjectileInfo>::const_iterator it = owner->projectiles.begin(); it != owner->projectiles.end(); ++it)
  160. {
  161. if(it->creID == attacker->getCreature()->idNumber)
  162. {
  163. return false;
  164. }
  165. }
  166. }
  167. // synchronize animation with attacker, unless defending or attacked by shooter:
  168. // wait for 1/2 of attack animation
  169. if (!rangedAttack && getMyAnimType() != CCreatureAnim::DEFENCE)
  170. {
  171. float frameLength = AnimationControls::getCreatureAnimationSpeed(
  172. stack->getCreature(), owner->creAnims[stack->ID], getMyAnimType());
  173. timeToWait = myAnim->framesInGroup(getMyAnimType()) * frameLength / 2;
  174. myAnim->setType(CCreatureAnim::HOLDING);
  175. }
  176. else
  177. {
  178. timeToWait = 0;
  179. startAnimation();
  180. }
  181. return true; //initialized successfuly
  182. }
  183. std::string CDefenceAnimation::getMySound()
  184. {
  185. if(killed)
  186. return battle_sound(stack->getCreature(), killed);
  187. if (stack->valOfBonuses(Selector::durationType(Bonus::STACK_GETS_TURN)))
  188. return battle_sound(stack->getCreature(), defend);
  189. return battle_sound(stack->getCreature(), wince);
  190. }
  191. CCreatureAnim::EAnimType CDefenceAnimation::getMyAnimType()
  192. {
  193. if(killed)
  194. return CCreatureAnim::DEATH;
  195. if (stack->valOfBonuses(Selector::durationType(Bonus::STACK_GETS_TURN).And(Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE))))
  196. return CCreatureAnim::DEFENCE;
  197. return CCreatureAnim::HITTED;
  198. }
  199. void CDefenceAnimation::startAnimation()
  200. {
  201. CCS->soundh->playSound(getMySound());
  202. myAnim->setType(getMyAnimType());
  203. myAnim->onAnimationReset += std::bind(&CDefenceAnimation::endAnim, this);
  204. }
  205. void CDefenceAnimation::nextFrame()
  206. {
  207. if (timeToWait > 0)
  208. {
  209. timeToWait -= float(GH.mainFPSmng->getElapsedMilliseconds()) / 1000;
  210. if (timeToWait <= 0)
  211. startAnimation();
  212. }
  213. CBattleAnimation::nextFrame();
  214. }
  215. void CDefenceAnimation::endAnim()
  216. {
  217. if (killed)
  218. myAnim->setType(CCreatureAnim::DEAD);
  219. else
  220. myAnim->setType(CCreatureAnim::HOLDING);
  221. CBattleAnimation::endAnim();
  222. delete this;
  223. }
  224. CDummyAnimation::CDummyAnimation(CBattleInterface * _owner, int howManyFrames)
  225. : CBattleAnimation(_owner), counter(0), howMany(howManyFrames)
  226. {}
  227. bool CDummyAnimation::init()
  228. {
  229. return true;
  230. }
  231. void CDummyAnimation::nextFrame()
  232. {
  233. counter++;
  234. if(counter > howMany)
  235. endAnim();
  236. }
  237. void CDummyAnimation::endAnim()
  238. {
  239. CBattleAnimation::endAnim();
  240. delete this;
  241. }
  242. bool CMeleeAttackAnimation::init()
  243. {
  244. if( !CAttackAnimation::checkInitialConditions() )
  245. return false;
  246. if(!attackingStack || myAnim->isDead())
  247. {
  248. endAnim();
  249. return false;
  250. }
  251. bool toReverse = owner->curInt->cb->isToReverse(attackingStackPosBeforeReturn, dest, owner->creDir[stack->ID], attackedStack->doubleWide(), owner->creDir[attackedStack->ID]);
  252. if (toReverse)
  253. {
  254. owner->addNewAnim(new CReverseAnimation(owner, stack, attackingStackPosBeforeReturn, true));
  255. return false;
  256. }
  257. // opponent must face attacker ( = different directions) before he can be attacked
  258. if (attackingStack && attackedStack &&
  259. owner->creDir[attackingStack->ID] == owner->creDir[attackedStack->ID])
  260. return false;
  261. //reversed
  262. shooting = false;
  263. static const CCreatureAnim::EAnimType mutPosToGroup[] = {CCreatureAnim::ATTACK_UP, CCreatureAnim::ATTACK_UP,
  264. CCreatureAnim::ATTACK_FRONT, CCreatureAnim::ATTACK_DOWN, CCreatureAnim::ATTACK_DOWN, CCreatureAnim::ATTACK_FRONT};
  265. int revShiftattacker = (attackingStack->attackerOwned ? -1 : 1);
  266. int mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn, dest);
  267. if(mutPos == -1 && attackingStack->doubleWide())
  268. {
  269. mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn + revShiftattacker, attackedStack->position);
  270. }
  271. if (mutPos == -1 && attackedStack->doubleWide())
  272. {
  273. mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn, attackedStack->occupiedHex());
  274. }
  275. if (mutPos == -1 && attackedStack->doubleWide() && attackingStack->doubleWide())
  276. {
  277. mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn + revShiftattacker, attackedStack->occupiedHex());
  278. }
  279. switch(mutPos) //attack direction
  280. {
  281. case 0: case 1: case 2: case 3: case 4: case 5:
  282. group = mutPosToGroup[mutPos];
  283. break;
  284. default:
  285. logGlobal->errorStream()<<"Critical Error! Wrong dest in stackAttacking! dest: "<<dest<<" attacking stack pos: "<<attackingStackPosBeforeReturn<<" mutual pos: "<<mutPos;
  286. group = CCreatureAnim::ATTACK_FRONT;
  287. break;
  288. }
  289. return true;
  290. }
  291. CMeleeAttackAnimation::CMeleeAttackAnimation(CBattleInterface * _owner, const CStack * attacker, BattleHex _dest, const CStack * _attacked)
  292. : CAttackAnimation(_owner, attacker, _dest, _attacked)
  293. {}
  294. void CMeleeAttackAnimation::endAnim()
  295. {
  296. CAttackAnimation::endAnim();
  297. delete this;
  298. }
  299. bool CMovementAnimation::shouldRotate()
  300. {
  301. Point begPosition = CClickableHex::getXYUnitAnim(oldPos, stack, owner);
  302. Point endPosition = CClickableHex::getXYUnitAnim(nextHex, stack, owner);
  303. if((begPosition.x > endPosition.x) && owner->creDir[stack->ID] == true)
  304. {
  305. return true;
  306. }
  307. else if ((begPosition.x < endPosition.x) && owner->creDir[stack->ID] == false)
  308. {
  309. return true;
  310. }
  311. return false;
  312. }
  313. bool CMovementAnimation::init()
  314. {
  315. if( !isEarliest(false) )
  316. return false;
  317. if(!stack || myAnim->isDead())
  318. {
  319. endAnim();
  320. return false;
  321. }
  322. if(owner->creAnims[stack->ID]->framesInGroup(CCreatureAnim::MOVING) == 0 ||
  323. stack->hasBonus(Selector::typeSubtype(Bonus::FLYING, 1)))
  324. {
  325. //no movement or teleport, end immediately
  326. endAnim();
  327. return false;
  328. }
  329. //reverse unit if necessary
  330. if(shouldRotate())
  331. {
  332. // it seems that H3 does NOT plays full rotation animation here in most situations
  333. // Logical since it takes quite a lot of time
  334. if (curentMoveIndex == 0) // full rotation only for moving towards first tile.
  335. {
  336. owner->addNewAnim(new CReverseAnimation(owner, stack, oldPos, true));
  337. return false;
  338. }
  339. else
  340. {
  341. CReverseAnimation::rotateStack(owner, stack, oldPos);
  342. }
  343. }
  344. if(myAnim->getType() != CCreatureAnim::MOVING)
  345. {
  346. myAnim->setType(CCreatureAnim::MOVING);
  347. }
  348. if (owner->moveSoundHander == -1)
  349. {
  350. owner->moveSoundHander = CCS->soundh->playSound(battle_sound(stack->getCreature(), move), -1);
  351. }
  352. Point begPosition = CClickableHex::getXYUnitAnim(oldPos, stack, owner);
  353. Point endPosition = CClickableHex::getXYUnitAnim(nextHex, stack, owner);
  354. timeToMove = AnimationControls::getMovementDuration(stack->getCreature());
  355. begX = begPosition.x;
  356. begY = begPosition.y;
  357. progress = 0;
  358. distanceX = endPosition.x - begPosition.x;
  359. distanceY = endPosition.y - begPosition.y;
  360. if (stack->hasBonus(Selector::type(Bonus::FLYING)))
  361. {
  362. float distance = sqrt(distanceX * distanceX + distanceY * distanceY);
  363. timeToMove *= AnimationControls::getFlightDistance(stack->getCreature()) / distance;
  364. }
  365. return true;
  366. }
  367. void CMovementAnimation::nextFrame()
  368. {
  369. progress += float(GH.mainFPSmng->getElapsedMilliseconds()) / 1000 * timeToMove;
  370. //moving instructions
  371. myAnim->pos.x = static_cast<Sint16>(begX + distanceX * progress );
  372. myAnim->pos.y = static_cast<Sint16>(begY + distanceY * progress );
  373. CBattleAnimation::nextFrame();
  374. if(progress >= 1.0)
  375. {
  376. // Sets the position of the creature animation sprites
  377. Point coords = CClickableHex::getXYUnitAnim(nextHex, stack, owner);
  378. myAnim->pos = coords;
  379. // true if creature haven't reached the final destination hex
  380. if ((curentMoveIndex + 1) < destTiles.size())
  381. {
  382. // update the next hex field which has to be reached by the stack
  383. curentMoveIndex++;
  384. oldPos = nextHex;
  385. nextHex = destTiles[curentMoveIndex];
  386. // re-init animation
  387. for(auto & elem : owner->pendingAnims)
  388. {
  389. if (elem.first == this)
  390. {
  391. elem.second = false;
  392. break;
  393. }
  394. }
  395. }
  396. else
  397. endAnim();
  398. }
  399. }
  400. void CMovementAnimation::endAnim()
  401. {
  402. assert(stack);
  403. myAnim->pos = CClickableHex::getXYUnitAnim(nextHex, stack, owner);
  404. CBattleAnimation::endAnim();
  405. owner->addNewAnim(new CMovementEndAnimation(owner, stack, nextHex));
  406. if(owner->moveSoundHander != -1)
  407. {
  408. CCS->soundh->stopSound(owner->moveSoundHander);
  409. owner->moveSoundHander = -1;
  410. }
  411. delete this;
  412. }
  413. CMovementAnimation::CMovementAnimation(CBattleInterface *_owner, const CStack *_stack, std::vector<BattleHex> _destTiles, int _distance)
  414. : CBattleStackAnimation(_owner, _stack),
  415. destTiles(_destTiles),
  416. curentMoveIndex(0),
  417. oldPos(stack->position),
  418. begX(0), begY(0),
  419. distanceX(0), distanceY(0),
  420. timeToMove(0.0),
  421. progress(0.0),
  422. nextHex(destTiles.front())
  423. {
  424. }
  425. CMovementEndAnimation::CMovementEndAnimation(CBattleInterface * _owner, const CStack * _stack, BattleHex destTile)
  426. : CBattleStackAnimation(_owner, _stack), destinationTile(destTile)
  427. {}
  428. bool CMovementEndAnimation::init()
  429. {
  430. if( !isEarliest(true) )
  431. return false;
  432. if(!stack || myAnim->framesInGroup(CCreatureAnim::MOVE_END) == 0 ||
  433. myAnim->isDead())
  434. {
  435. endAnim();
  436. return false;
  437. }
  438. CCS->soundh->playSound(battle_sound(stack->getCreature(), endMoving));
  439. myAnim->setType(CCreatureAnim::MOVE_END);
  440. myAnim->onAnimationReset += std::bind(&CMovementEndAnimation::endAnim, this);
  441. return true;
  442. }
  443. void CMovementEndAnimation::endAnim()
  444. {
  445. CBattleAnimation::endAnim();
  446. if(myAnim->getType() != CCreatureAnim::DEAD)
  447. myAnim->setType(CCreatureAnim::HOLDING); //resetting to default
  448. CCS->curh->show();
  449. delete this;
  450. }
  451. CMovementStartAnimation::CMovementStartAnimation(CBattleInterface * _owner, const CStack * _stack)
  452. : CBattleStackAnimation(_owner, _stack)
  453. {}
  454. bool CMovementStartAnimation::init()
  455. {
  456. if( !isEarliest(false) )
  457. return false;
  458. if(!stack || myAnim->isDead())
  459. {
  460. CMovementStartAnimation::endAnim();
  461. return false;
  462. }
  463. CCS->soundh->playSound(battle_sound(stack->getCreature(), startMoving));
  464. myAnim->setType(CCreatureAnim::MOVE_START);
  465. myAnim->onAnimationReset += std::bind(&CMovementStartAnimation::endAnim, this);
  466. return true;
  467. }
  468. void CMovementStartAnimation::endAnim()
  469. {
  470. CBattleAnimation::endAnim();
  471. delete this;
  472. }
  473. CReverseAnimation::CReverseAnimation(CBattleInterface * _owner, const CStack * stack, BattleHex dest, bool _priority)
  474. : CBattleStackAnimation(_owner, stack), hex(dest), priority(_priority)
  475. {}
  476. bool CReverseAnimation::init()
  477. {
  478. if(myAnim == nullptr || myAnim->isDead())
  479. {
  480. endAnim();
  481. return false; //there is no such creature
  482. }
  483. if(!priority && !isEarliest(false))
  484. return false;
  485. if(myAnim->framesInGroup(CCreatureAnim::TURN_L))
  486. {
  487. myAnim->setType(CCreatureAnim::TURN_L);
  488. myAnim->onAnimationReset += std::bind(&CReverseAnimation::setupSecondPart, this);
  489. }
  490. else
  491. {
  492. setupSecondPart();
  493. }
  494. return true;
  495. }
  496. void CReverseAnimation::endAnim()
  497. {
  498. CBattleAnimation::endAnim();
  499. if( stack->alive() )//don't do that if stack is dead
  500. myAnim->setType(CCreatureAnim::HOLDING);
  501. delete this;
  502. }
  503. void CReverseAnimation::rotateStack(CBattleInterface * owner, const CStack * stack, BattleHex hex)
  504. {
  505. owner->creDir[stack->ID] = !owner->creDir[stack->ID];
  506. owner->creAnims[stack->ID]->pos = CClickableHex::getXYUnitAnim(hex, stack, owner);
  507. }
  508. void CReverseAnimation::setupSecondPart()
  509. {
  510. if(!stack)
  511. {
  512. endAnim();
  513. return;
  514. }
  515. rotateStack(owner, stack, hex);
  516. if(myAnim->framesInGroup(CCreatureAnim::TURN_R))
  517. {
  518. myAnim->setType(CCreatureAnim::TURN_R);
  519. myAnim->onAnimationReset += std::bind(&CReverseAnimation::endAnim, this);
  520. }
  521. else
  522. endAnim();
  523. }
  524. CShootingAnimation::CShootingAnimation(CBattleInterface * _owner, const CStack * attacker, BattleHex _dest, const CStack * _attacked, bool _catapult, int _catapultDmg)
  525. : CAttackAnimation(_owner, attacker, _dest, _attacked), catapultDamage(_catapultDmg)
  526. {}
  527. bool CShootingAnimation::init()
  528. {
  529. if( !CAttackAnimation::checkInitialConditions() )
  530. return false;
  531. const CStack * shooter = attackingStack;
  532. if(!shooter || myAnim->isDead())
  533. {
  534. endAnim();
  535. return false;
  536. }
  537. //reverse unit if necessary
  538. if (attackingStack && attackedStack && owner->curInt->cb->isToReverse(attackingStack->position, attackedStack->position, owner->creDir[attackingStack->ID], attackingStack->doubleWide(), owner->creDir[attackedStack->ID]))
  539. {
  540. owner->addNewAnim(new CReverseAnimation(owner, attackingStack, attackingStack->position, true));
  541. return false;
  542. }
  543. // opponent must face attacker ( = different directions) before he can be attacked
  544. if (attackingStack && attackedStack &&
  545. owner->creDir[attackingStack->ID] == owner->creDir[attackedStack->ID])
  546. return false;
  547. // Create the projectile animation
  548. //maximal angle in radians between straight horizontal line and shooting line for which shot is considered to be straight (absoulte value)
  549. static const double straightAngle = 0.2;
  550. // Get further info about the shooter e.g. relative pos of projectile to unit.
  551. // If the creature id is 149 then it's a arrow tower which has no additional info so get the
  552. // actual arrow tower shooter instead.
  553. const CCreature *shooterInfo = shooter->getCreature();
  554. if (shooterInfo->idNumber == CreatureID::ARROW_TOWERS)
  555. {
  556. int creID = owner->siegeH->town->town->clientInfo.siegeShooter;
  557. shooterInfo = CGI->creh->creatures[creID];
  558. }
  559. ProjectileInfo spi;
  560. spi.shotDone = false;
  561. spi.creID = shooter->getCreature()->idNumber;
  562. spi.stackID = shooter->ID;
  563. // reverse if creature is facing right OR this is non-existing stack that is not tower (war machines)
  564. spi.reverse = attackingStack ? !owner->creDir[attackingStack->ID] : shooter->getCreature()->idNumber != CreatureID::ARROW_TOWERS ;
  565. spi.step = 0;
  566. spi.frameNum = 0;
  567. Point fromPos;
  568. Point destPos;
  569. // NOTE: two lines below return different positions (very notable with 2-hex creatures). Obtaining via creanims seems to be more precise
  570. fromPos = owner->creAnims[spi.stackID]->pos.topLeft();
  571. //xycoord = CClickableHex::getXYUnitAnim(shooter->position, true, shooter, owner);
  572. destPos = CClickableHex::getXYUnitAnim(dest, attackedStack, owner);
  573. // to properly translate coordinates when shooter is rotated
  574. int multiplier = spi.reverse ? -1 : 1;
  575. double projectileAngle = atan2(fabs((double)destPos.y - fromPos.y), fabs((double)destPos.x - fromPos.x));
  576. if(shooter->position < dest)
  577. projectileAngle = -projectileAngle;
  578. // Calculate projectile start position. Offsets are read out of the CRANIM.TXT.
  579. if (projectileAngle > straightAngle)
  580. {
  581. //upper shot
  582. spi.x = fromPos.x + 222 + ( -25 + shooterInfo->animation.upperRightMissleOffsetX ) * multiplier;
  583. spi.y = fromPos.y + 265 + shooterInfo->animation.upperRightMissleOffsetY;
  584. }
  585. else if (projectileAngle < -straightAngle)
  586. {
  587. //lower shot
  588. spi.x = fromPos.x + 222 + ( -25 + shooterInfo->animation.lowerRightMissleOffsetX ) * multiplier;
  589. spi.y = fromPos.y + 265 + shooterInfo->animation.lowerRightMissleOffsetY;
  590. }
  591. else
  592. {
  593. //straight shot
  594. spi.x = fromPos.x + 222 + ( -25 + shooterInfo->animation.rightMissleOffsetX ) * multiplier;
  595. spi.y = fromPos.y + 265 + shooterInfo->animation.rightMissleOffsetY;
  596. }
  597. destPos += Point(225, 225);
  598. // recalculate angle taking in account offsets
  599. //projectileAngle = atan2(fabs(destPos.y - spi.y), fabs(destPos.x - spi.x));
  600. //if(shooter->position < dest)
  601. // projectileAngle = -projectileAngle;
  602. if (attackedStack)
  603. {
  604. double animSpeed = AnimationControls::getProjectileSpeed(); // flight speed of projectile
  605. spi.lastStep = static_cast<int>(sqrt(static_cast<double>((destPos.x - spi.x) * (destPos.x - spi.x) + (destPos.y - spi.y) * (destPos.y - spi.y))) / animSpeed);
  606. if(spi.lastStep == 0)
  607. spi.lastStep = 1;
  608. spi.dx = (destPos.x - spi.x) / spi.lastStep;
  609. spi.dy = (destPos.y - spi.y) / spi.lastStep;
  610. }
  611. else
  612. {
  613. // Catapult attack
  614. spi.catapultInfo.reset(new CatapultProjectileInfo(Point(spi.x, spi.y), destPos));
  615. double animSpeed = AnimationControls::getProjectileSpeed() / 10;
  616. spi.lastStep = abs((destPos.x - spi.x) / animSpeed);
  617. spi.dx = animSpeed;
  618. spi.dy = 0;
  619. SDL_Surface * img = owner->idToProjectile[spi.creID]->ourImages[0].bitmap;
  620. // Add explosion anim
  621. Point animPos(destPos.x - 126 + img->w / 2,
  622. destPos.y - 105 + img->h / 2);
  623. owner->addNewAnim( new CSpellEffectAnimation(owner, catapultDamage ? "SGEXPL.DEF" : "CSGRCK.DEF", animPos.x, animPos.y));
  624. }
  625. auto & angles = shooterInfo->animation.missleFrameAngles;
  626. double pi = boost::math::constants::pi<double>();
  627. // only frames below maxFrame are usable: anything higher is either no present or we don't know when it should be used
  628. size_t maxFrame = std::min<size_t>(angles.size(), owner->idToProjectile[spi.creID]->ourImages.size());
  629. assert(maxFrame > 0);
  630. // values in angles array indicate position from which this frame was rendered, in degrees.
  631. // find frame that has closest angle to one that we need for this shot
  632. size_t bestID = 0;
  633. double bestDiff = fabs( angles[0] / 180 * pi - projectileAngle );
  634. for (size_t i=1; i<maxFrame; i++)
  635. {
  636. double currentDiff = fabs( angles[i] / 180 * pi - projectileAngle );
  637. if (currentDiff < bestDiff)
  638. {
  639. bestID = i;
  640. bestDiff = currentDiff;
  641. }
  642. }
  643. spi.frameNum = bestID;
  644. // Set projectile animation start delay which is specified in frames
  645. spi.animStartDelay = shooterInfo->animation.attackClimaxFrame;
  646. owner->projectiles.push_back(spi);
  647. //attack animation
  648. shooting = true;
  649. if(projectileAngle > straightAngle) //upper shot
  650. group = CCreatureAnim::SHOOT_UP;
  651. else if(projectileAngle < -straightAngle) //lower shot
  652. group = CCreatureAnim::SHOOT_DOWN;
  653. else //straight shot
  654. group = CCreatureAnim::SHOOT_FRONT;
  655. return true;
  656. }
  657. void CShootingAnimation::nextFrame()
  658. {
  659. for(auto & it : owner->pendingAnims)
  660. {
  661. CMovementStartAnimation * anim = dynamic_cast<CMovementStartAnimation *>(it.first);
  662. CReverseAnimation * anim2 = dynamic_cast<CReverseAnimation *>(it.first);
  663. if( (anim && anim->stack->ID == stack->ID) || (anim2 && anim2->stack->ID == stack->ID && anim2->priority ) )
  664. return;
  665. }
  666. CAttackAnimation::nextFrame();
  667. }
  668. void CShootingAnimation::endAnim()
  669. {
  670. CAttackAnimation::endAnim();
  671. delete this;
  672. }
  673. CSpellEffectAnimation::CSpellEffectAnimation(CBattleInterface * _owner, ui32 _effect, BattleHex _destTile, int _dx, int _dy, bool _Vflip, bool _areaEffect)
  674. :CBattleAnimation(_owner), effect(_effect), destTile(_destTile), customAnim(""), x(0), y(0), dx(_dx), dy(_dy), Vflip(_Vflip) , areaEffect(_areaEffect)
  675. {}
  676. CSpellEffectAnimation::CSpellEffectAnimation(CBattleInterface * _owner, std::string _customAnim, int _x, int _y, int _dx, int _dy, bool _Vflip, bool _areaEffect)
  677. :CBattleAnimation(_owner), effect(-1), destTile(0), customAnim(_customAnim), x(_x), y(_y), dx(_dx), dy(_dy), Vflip(_Vflip), areaEffect(_areaEffect)
  678. {}
  679. bool CSpellEffectAnimation::init()
  680. {
  681. if(!isEarliest(true))
  682. return false;
  683. if(effect == 12) //armageddon
  684. {
  685. if(effect == -1 || graphics->battleACToDef[effect].size() != 0)
  686. {
  687. CDefHandler * anim;
  688. if(customAnim.size())
  689. anim = CDefHandler::giveDef(customAnim);
  690. else
  691. anim = CDefHandler::giveDef(graphics->battleACToDef[effect][0]);
  692. if (Vflip)
  693. {
  694. for (auto & elem : anim->ourImages)
  695. {
  696. CSDL_Ext::VflipSurf(elem.bitmap);
  697. }
  698. }
  699. for(int i=0; i * anim->width < owner->pos.w ; ++i)
  700. {
  701. for(int j=0; j * anim->height < owner->pos.h ; ++j)
  702. {
  703. BattleEffect be;
  704. be.effectID = ID;
  705. be.anim = CDefHandler::giveDef(graphics->battleACToDef[effect][0]);
  706. if (Vflip)
  707. {
  708. for (auto & elem : be.anim->ourImages)
  709. {
  710. CSDL_Ext::VflipSurf(elem.bitmap);
  711. }
  712. }
  713. be.currentFrame = 0;
  714. be.maxFrame = be.anim->ourImages.size();
  715. be.x = i * anim->width + owner->pos.x;
  716. be.y = j * anim->height + owner->pos.y;
  717. be.position = BattleHex::INVALID;
  718. owner->battleEffects.push_back(be);
  719. }
  720. }
  721. }
  722. else //there is nothing to play
  723. {
  724. endAnim();
  725. return false;
  726. }
  727. }
  728. else // Effects targeted at a specific creature/hex.
  729. {
  730. if(effect == -1 || graphics->battleACToDef[effect].size() != 0)
  731. {
  732. const CStack* destStack = owner->curInt->cb->battleGetStackByPos(destTile, false);
  733. Rect &tilePos = owner->bfield[destTile]->pos;
  734. BattleEffect be;
  735. be.effectID = ID;
  736. if(customAnim.size())
  737. be.anim = CDefHandler::giveDef(customAnim);
  738. else
  739. be.anim = CDefHandler::giveDef(graphics->battleACToDef[effect][0]);
  740. if (Vflip)
  741. {
  742. for (auto & elem : be.anim->ourImages)
  743. {
  744. CSDL_Ext::VflipSurf(elem.bitmap);
  745. }
  746. }
  747. be.currentFrame = 0;
  748. be.maxFrame = be.anim->ourImages.size();
  749. if(effect == 1)
  750. be.maxFrame = 3;
  751. switch (effect)
  752. {
  753. case ui32(-1):
  754. be.x = x;
  755. be.y = y;
  756. break;
  757. case 0: // Prayer and Lightning Bolt.
  758. case 1:
  759. case 19: // Slow
  760. // Position effect with it's bottom center touching the bottom center of affected tile(s).
  761. be.x = tilePos.x + tilePos.w/2 - be.anim->width/2;
  762. be.y = tilePos.y + tilePos.h - be.anim->height;
  763. break;
  764. default:
  765. // Position effect with it's center touching the top center of affected tile(s).
  766. be.x = tilePos.x + tilePos.w/2 - be.anim->width/2;
  767. be.y = tilePos.y - be.anim->height/2;
  768. break;
  769. }
  770. // Correction for 2-hex creatures.
  771. if (destStack != nullptr && destStack->doubleWide())
  772. be.x += (destStack->attackerOwned ? -1 : 1)*tilePos.w/2;
  773. //Indicate if effect should be drawn on top of everything or just on top of the hex
  774. if(areaEffect)
  775. be.position = BattleHex::INVALID;
  776. else
  777. be.position = destTile;
  778. owner->battleEffects.push_back(be);
  779. }
  780. else //there is nothing to play
  781. {
  782. endAnim();
  783. return false;
  784. }
  785. }
  786. //battleEffects
  787. return true;
  788. }
  789. void CSpellEffectAnimation::nextFrame()
  790. {
  791. //notice: there may be more than one effect in owner->battleEffects correcponding to this animation (ie. armageddon)
  792. for(auto & elem : owner->battleEffects)
  793. {
  794. if(elem.effectID == ID)
  795. {
  796. elem.currentFrame += AnimationControls::getSpellEffectSpeed() * GH.mainFPSmng->getElapsedMilliseconds() / 1000;
  797. if(elem.currentFrame >= elem.maxFrame)
  798. {
  799. endAnim();
  800. break;
  801. }
  802. else
  803. {
  804. elem.x += dx;
  805. elem.y += dy;
  806. }
  807. }
  808. }
  809. }
  810. void CSpellEffectAnimation::endAnim()
  811. {
  812. CBattleAnimation::endAnim();
  813. std::vector<std::list<BattleEffect>::iterator> toDel;
  814. for(auto it = owner->battleEffects.begin(); it != owner->battleEffects.end(); ++it)
  815. {
  816. if(it->effectID == ID)
  817. {
  818. toDel.push_back(it);
  819. }
  820. }
  821. for(auto & elem : toDel)
  822. {
  823. delete elem->anim;
  824. owner->battleEffects.erase(elem);
  825. }
  826. delete this;
  827. }