CBattleAnimations.cpp 29 KB

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