CBattleAnimations.cpp 28 KB

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