CBattleAnimations.cpp 29 KB

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