CBattleAnimations.cpp 28 KB

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