CBattleAnimations.cpp 29 KB

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