CBattleAnimations.cpp 28 KB

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