BattleAnimationClasses.cpp 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226
  1. /*
  2. * BattleAnimationClasses.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 "BattleAnimationClasses.h"
  12. #include <boost/math/constants/constants.hpp>
  13. #include "BattleInterfaceClasses.h"
  14. #include "BattleInterface.h"
  15. #include "BattleProjectileController.h"
  16. #include "BattleSiegeController.h"
  17. #include "BattleFieldController.h"
  18. #include "BattleEffectsController.h"
  19. #include "BattleStacksController.h"
  20. #include "CreatureAnimation.h"
  21. #include "../CGameInfo.h"
  22. #include "../CMusicHandler.h"
  23. #include "../CPlayerInterface.h"
  24. #include "../Graphics.h"
  25. #include "../gui/CAnimation.h"
  26. #include "../gui/CCursorHandler.h"
  27. #include "../gui/CGuiHandler.h"
  28. #include "../../CCallback.h"
  29. #include "../../lib/CStack.h"
  30. #include "../../lib/CTownHandler.h"
  31. #include "../../lib/mapObjects/CGTownInstance.h"
  32. CBattleAnimation::CBattleAnimation(BattleInterface & owner)
  33. : owner(owner),
  34. ID(owner.stacksController->animIDhelper++),
  35. initialized(false)
  36. {
  37. logAnim->trace("Animation #%d created", ID);
  38. }
  39. bool CBattleAnimation::tryInitialize()
  40. {
  41. assert(!initialized);
  42. if ( init() )
  43. {
  44. initialized = true;
  45. return true;
  46. }
  47. return false;
  48. }
  49. bool CBattleAnimation::isInitialized()
  50. {
  51. return initialized;
  52. }
  53. CBattleAnimation::~CBattleAnimation()
  54. {
  55. logAnim->trace("Animation #%d ended, type is %s", ID, typeid(this).name());
  56. for(auto & elem : pendingAnimations())
  57. {
  58. if(elem == this)
  59. elem = nullptr;
  60. }
  61. logAnim->trace("Animation #%d deleted", ID);
  62. }
  63. std::vector<CBattleAnimation *> & CBattleAnimation::pendingAnimations()
  64. {
  65. return owner.stacksController->currentAnimations;
  66. }
  67. std::shared_ptr<CreatureAnimation> CBattleAnimation::stackAnimation(const CStack * stack) const
  68. {
  69. return owner.stacksController->stackAnimation[stack->ID];
  70. }
  71. bool CBattleAnimation::stackFacingRight(const CStack * stack)
  72. {
  73. return owner.stacksController->stackFacingRight[stack->ID];
  74. }
  75. void CBattleAnimation::setStackFacingRight(const CStack * stack, bool facingRight)
  76. {
  77. owner.stacksController->stackFacingRight[stack->ID] = facingRight;
  78. }
  79. bool CBattleAnimation::checkInitialConditions()
  80. {
  81. int lowestMoveID = ID;
  82. auto * thAnim = dynamic_cast<CBattleStackAnimation *>(this);
  83. auto * thSen = dynamic_cast<CPointEffectAnimation *>(this);
  84. for(auto & elem : pendingAnimations())
  85. {
  86. auto * sen = dynamic_cast<CPointEffectAnimation *>(elem);
  87. // all effect animations can play concurrently with each other
  88. if(sen && thSen && sen != thSen)
  89. continue;
  90. auto * revAnim = dynamic_cast<CReverseAnimation *>(elem);
  91. // if there is high-priority reverse animation affecting our stack then this animation will wait
  92. if(revAnim && thAnim && revAnim && revAnim->stack->ID == thAnim->stack->ID && revAnim->priority)
  93. return false;
  94. if(elem)
  95. vstd::amin(lowestMoveID, elem->ID);
  96. }
  97. return ID == lowestMoveID;
  98. }
  99. CBattleStackAnimation::CBattleStackAnimation(BattleInterface & owner, const CStack * stack)
  100. : CBattleAnimation(owner),
  101. myAnim(stackAnimation(stack)),
  102. stack(stack)
  103. {
  104. assert(myAnim);
  105. }
  106. void CBattleStackAnimation::shiftColor(const ColorShifter * shifter)
  107. {
  108. assert(myAnim);
  109. myAnim->shiftColor(shifter);
  110. }
  111. void CAttackAnimation::nextFrame()
  112. {
  113. if(myAnim->getType() != group)
  114. {
  115. myAnim->setType(group);
  116. myAnim->onAnimationReset += [&](){ delete this; };
  117. }
  118. if(!soundPlayed)
  119. {
  120. if(shooting)
  121. CCS->soundh->playSound(battle_sound(getCreature(), shoot));
  122. else
  123. CCS->soundh->playSound(battle_sound(getCreature(), attack));
  124. soundPlayed = true;
  125. }
  126. }
  127. CAttackAnimation::~CAttackAnimation()
  128. {
  129. myAnim->setType(CCreatureAnim::HOLDING);
  130. }
  131. bool CAttackAnimation::checkInitialConditions()
  132. {
  133. for(auto & elem : pendingAnimations())
  134. {
  135. CBattleStackAnimation * stAnim = dynamic_cast<CBattleStackAnimation *>(elem);
  136. CReverseAnimation * revAnim = dynamic_cast<CReverseAnimation *>(stAnim);
  137. if(revAnim && attackedStack) // enemy must be fully reversed
  138. {
  139. if (revAnim->stack->ID == attackedStack->ID)
  140. return false;
  141. }
  142. }
  143. return CBattleAnimation::checkInitialConditions();
  144. }
  145. const CCreature * CAttackAnimation::getCreature() const
  146. {
  147. if (attackingStack->getCreature()->idNumber == CreatureID::ARROW_TOWERS)
  148. return owner.siegeController->getTurretCreature();
  149. else
  150. return attackingStack->getCreature();
  151. }
  152. CAttackAnimation::CAttackAnimation(BattleInterface & owner, const CStack *attacker, BattleHex _dest, const CStack *defender)
  153. : CBattleStackAnimation(owner, attacker),
  154. shooting(false),
  155. group(CCreatureAnim::SHOOT_FRONT),
  156. soundPlayed(false),
  157. dest(_dest),
  158. attackedStack(defender),
  159. attackingStack(attacker)
  160. {
  161. assert(attackingStack && "attackingStack is nullptr in CBattleAttack::CBattleAttack !\n");
  162. attackingStackPosBeforeReturn = attackingStack->getPosition();
  163. }
  164. CDefenceAnimation::CDefenceAnimation(StackAttackedInfo _attackedInfo, BattleInterface & owner)
  165. : CBattleStackAnimation(owner, _attackedInfo.defender),
  166. attacker(_attackedInfo.attacker),
  167. rangedAttack(_attackedInfo.indirectAttack),
  168. killed(_attackedInfo.killed),
  169. timeToWait(0)
  170. {
  171. logAnim->debug("Created defence anim for %s", _attackedInfo.defender->getName());
  172. }
  173. bool CDefenceAnimation::init()
  174. {
  175. ui32 lowestMoveID = ID;
  176. for(auto & elem : pendingAnimations())
  177. {
  178. auto * defAnim = dynamic_cast<CDefenceAnimation *>(elem);
  179. if(defAnim && defAnim->stack->ID != stack->ID)
  180. continue;
  181. auto * attAnim = dynamic_cast<CAttackAnimation *>(elem);
  182. if(attAnim && attAnim->stack->ID != stack->ID)
  183. continue;
  184. auto * sen = dynamic_cast<CPointEffectAnimation *>(elem);
  185. if (sen && attacker == nullptr)
  186. return false;
  187. if (sen)
  188. continue;
  189. CReverseAnimation * animAsRev = dynamic_cast<CReverseAnimation *>(elem);
  190. if(animAsRev)
  191. return false;
  192. if(elem)
  193. vstd::amin(lowestMoveID, elem->ID);
  194. }
  195. if(ID > lowestMoveID)
  196. return false;
  197. //reverse unit if necessary
  198. if(attacker && owner.getCurrentPlayerInterface()->cb->isToReverse(stack->getPosition(), attacker->getPosition(), stackFacingRight(stack), attacker->doubleWide(), stackFacingRight(attacker)))
  199. {
  200. owner.stacksController->addNewAnim(new CReverseAnimation(owner, stack, stack->getPosition(), true));
  201. return false;
  202. }
  203. //unit reversed
  204. if(rangedAttack && attacker != nullptr && owner.projectilesController->hasActiveProjectile(attacker)) //delay hit animation
  205. {
  206. return false;
  207. }
  208. // synchronize animation with attacker, unless defending or attacked by shooter:
  209. // wait for 1/2 of attack animation
  210. if (!rangedAttack && getMyAnimType() != CCreatureAnim::DEFENCE)
  211. {
  212. float frameLength = AnimationControls::getCreatureAnimationSpeed(
  213. stack->getCreature(), stackAnimation(stack).get(), getMyAnimType());
  214. timeToWait = myAnim->framesInGroup(getMyAnimType()) * frameLength / 2;
  215. myAnim->setType(CCreatureAnim::HOLDING);
  216. }
  217. else
  218. {
  219. timeToWait = 0;
  220. startAnimation();
  221. }
  222. return true; //initialized successfuly
  223. }
  224. std::string CDefenceAnimation::getMySound()
  225. {
  226. if(killed)
  227. return battle_sound(stack->getCreature(), killed);
  228. else if(stack->defendingAnim)
  229. return battle_sound(stack->getCreature(), defend);
  230. else
  231. return battle_sound(stack->getCreature(), wince);
  232. }
  233. CCreatureAnim::EAnimType CDefenceAnimation::getMyAnimType()
  234. {
  235. if(killed)
  236. {
  237. if(rangedAttack && myAnim->framesInGroup(CCreatureAnim::DEATH_RANGED) > 0)
  238. return CCreatureAnim::DEATH_RANGED;
  239. else
  240. return CCreatureAnim::DEATH;
  241. }
  242. if(stack->defendingAnim)
  243. return CCreatureAnim::DEFENCE;
  244. else
  245. return CCreatureAnim::HITTED;
  246. }
  247. void CDefenceAnimation::startAnimation()
  248. {
  249. CCS->soundh->playSound(getMySound());
  250. myAnim->setType(getMyAnimType());
  251. myAnim->onAnimationReset += [&](){ delete this; };
  252. }
  253. void CDefenceAnimation::nextFrame()
  254. {
  255. if (timeToWait > 0)
  256. {
  257. timeToWait -= float(GH.mainFPSmng->getElapsedMilliseconds()) / 1000;
  258. if (timeToWait <= 0)
  259. startAnimation();
  260. }
  261. CBattleAnimation::nextFrame();
  262. }
  263. CDefenceAnimation::~CDefenceAnimation()
  264. {
  265. if(killed)
  266. {
  267. if(rangedAttack && myAnim->framesInGroup(CCreatureAnim::DEAD_RANGED) > 0)
  268. myAnim->setType(CCreatureAnim::DEAD_RANGED);
  269. else
  270. myAnim->setType(CCreatureAnim::DEAD);
  271. }
  272. else
  273. {
  274. myAnim->setType(CCreatureAnim::HOLDING);
  275. }
  276. }
  277. CDummyAnimation::CDummyAnimation(BattleInterface & owner, int howManyFrames)
  278. : CBattleAnimation(owner),
  279. counter(0),
  280. howMany(howManyFrames)
  281. {
  282. logAnim->debug("Created dummy animation for %d frames", howManyFrames);
  283. }
  284. bool CDummyAnimation::init()
  285. {
  286. return true;
  287. }
  288. void CDummyAnimation::nextFrame()
  289. {
  290. counter++;
  291. if(counter > howMany)
  292. delete this;
  293. }
  294. bool CMeleeAttackAnimation::init()
  295. {
  296. if(!CAttackAnimation::checkInitialConditions())
  297. return false;
  298. if(!attackingStack || myAnim->isDeadOrDying())
  299. {
  300. delete this;
  301. return false;
  302. }
  303. bool toReverse = owner.getCurrentPlayerInterface()->cb->isToReverse(attackingStackPosBeforeReturn, attackedStack->getPosition(), stackFacingRight(stack), attackedStack->doubleWide(), stackFacingRight(attackedStack));
  304. if(toReverse)
  305. {
  306. owner.stacksController->addNewAnim(new CReverseAnimation(owner, stack, attackingStackPosBeforeReturn, true));
  307. return false;
  308. }
  309. // opponent must face attacker ( = different directions) before he can be attacked
  310. if(attackingStack && attackedStack &&
  311. stackFacingRight(attackingStack) == stackFacingRight(attackedStack))
  312. return false;
  313. //reversed
  314. shooting = false;
  315. static const CCreatureAnim::EAnimType mutPosToGroup[] =
  316. {
  317. CCreatureAnim::ATTACK_UP,
  318. CCreatureAnim::ATTACK_UP,
  319. CCreatureAnim::ATTACK_FRONT,
  320. CCreatureAnim::ATTACK_DOWN,
  321. CCreatureAnim::ATTACK_DOWN,
  322. CCreatureAnim::ATTACK_FRONT
  323. };
  324. static const CCreatureAnim::EAnimType mutPosToGroup2H[] =
  325. {
  326. CCreatureAnim::VCMI_2HEX_UP,
  327. CCreatureAnim::VCMI_2HEX_UP,
  328. CCreatureAnim::VCMI_2HEX_FRONT,
  329. CCreatureAnim::VCMI_2HEX_DOWN,
  330. CCreatureAnim::VCMI_2HEX_DOWN,
  331. CCreatureAnim::VCMI_2HEX_FRONT
  332. };
  333. int revShiftattacker = (attackingStack->side == BattleSide::ATTACKER ? -1 : 1);
  334. int mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn, dest);
  335. if(mutPos == -1 && attackingStack->doubleWide())
  336. {
  337. mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn + revShiftattacker, attackedStack->getPosition());
  338. }
  339. if (mutPos == -1 && attackedStack->doubleWide())
  340. {
  341. mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn, attackedStack->occupiedHex());
  342. }
  343. if (mutPos == -1 && attackedStack->doubleWide() && attackingStack->doubleWide())
  344. {
  345. mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn + revShiftattacker, attackedStack->occupiedHex());
  346. }
  347. switch(mutPos) //attack direction
  348. {
  349. case 0:
  350. case 1:
  351. case 2:
  352. case 3:
  353. case 4:
  354. case 5:
  355. group = mutPosToGroup[mutPos];
  356. if(attackingStack->hasBonusOfType(Bonus::TWO_HEX_ATTACK_BREATH))
  357. {
  358. CCreatureAnim::EAnimType group2H = mutPosToGroup2H[mutPos];
  359. if(myAnim->framesInGroup(group2H)>0)
  360. group = group2H;
  361. }
  362. break;
  363. default:
  364. logGlobal->error("Critical Error! Wrong dest in stackAttacking! dest: %d; attacking stack pos: %d; mutual pos: %d", dest.hex, attackingStackPosBeforeReturn, mutPos);
  365. group = CCreatureAnim::ATTACK_FRONT;
  366. break;
  367. }
  368. return true;
  369. }
  370. CMeleeAttackAnimation::CMeleeAttackAnimation(BattleInterface & owner, const CStack * attacker, BattleHex _dest, const CStack * _attacked)
  371. : CAttackAnimation(owner, attacker, _dest, _attacked)
  372. {
  373. logAnim->debug("Created melee attack anim for %s", attacker->getName());
  374. }
  375. CStackMoveAnimation::CStackMoveAnimation(BattleInterface & owner, const CStack * _stack, BattleHex _currentHex):
  376. CBattleStackAnimation(owner, _stack),
  377. currentHex(_currentHex)
  378. {
  379. }
  380. bool CMovementAnimation::init()
  381. {
  382. if( !CBattleAnimation::checkInitialConditions() )
  383. return false;
  384. if(!stack || myAnim->isDeadOrDying())
  385. {
  386. delete this;
  387. return false;
  388. }
  389. if(stackAnimation(stack)->framesInGroup(CCreatureAnim::MOVING) == 0 ||
  390. stack->hasBonus(Selector::typeSubtype(Bonus::FLYING, 1)))
  391. {
  392. //no movement or teleport, end immediately
  393. delete this;
  394. return false;
  395. }
  396. //reverse unit if necessary
  397. if(owner.stacksController->shouldRotate(stack, oldPos, currentHex))
  398. {
  399. // it seems that H3 does NOT plays full rotation animation here in most situations
  400. // Logical since it takes quite a lot of time
  401. if (curentMoveIndex == 0) // full rotation only for moving towards first tile.
  402. {
  403. owner.stacksController->addNewAnim(new CReverseAnimation(owner, stack, oldPos, true));
  404. return false;
  405. }
  406. else
  407. {
  408. rotateStack(oldPos);
  409. }
  410. }
  411. if(myAnim->getType() != CCreatureAnim::MOVING)
  412. {
  413. myAnim->setType(CCreatureAnim::MOVING);
  414. }
  415. if (owner.moveSoundHander == -1)
  416. {
  417. owner.moveSoundHander = CCS->soundh->playSound(battle_sound(stack->getCreature(), move), -1);
  418. }
  419. Point begPosition = owner.stacksController->getStackPositionAtHex(oldPos, stack);
  420. Point endPosition = owner.stacksController->getStackPositionAtHex(currentHex, stack);
  421. timeToMove = AnimationControls::getMovementDuration(stack->getCreature());
  422. begX = begPosition.x;
  423. begY = begPosition.y;
  424. progress = 0;
  425. distanceX = endPosition.x - begPosition.x;
  426. distanceY = endPosition.y - begPosition.y;
  427. if (stack->hasBonus(Selector::type()(Bonus::FLYING)))
  428. {
  429. float distance = static_cast<float>(sqrt(distanceX * distanceX + distanceY * distanceY));
  430. timeToMove *= AnimationControls::getFlightDistance(stack->getCreature()) / distance;
  431. }
  432. return true;
  433. }
  434. void CMovementAnimation::nextFrame()
  435. {
  436. progress += float(GH.mainFPSmng->getElapsedMilliseconds()) / 1000 * timeToMove;
  437. //moving instructions
  438. myAnim->pos.x = static_cast<Sint16>(begX + distanceX * progress );
  439. myAnim->pos.y = static_cast<Sint16>(begY + distanceY * progress );
  440. CBattleAnimation::nextFrame();
  441. if(progress >= 1.0)
  442. {
  443. // Sets the position of the creature animation sprites
  444. Point coords = owner.stacksController->getStackPositionAtHex(currentHex, stack);
  445. myAnim->pos = coords;
  446. // true if creature haven't reached the final destination hex
  447. if ((curentMoveIndex + 1) < destTiles.size())
  448. {
  449. // update the next hex field which has to be reached by the stack
  450. curentMoveIndex++;
  451. oldPos = currentHex;
  452. currentHex = destTiles[curentMoveIndex];
  453. // request re-initialization
  454. initialized = false;
  455. }
  456. else
  457. delete this;
  458. }
  459. }
  460. CMovementAnimation::~CMovementAnimation()
  461. {
  462. assert(stack);
  463. myAnim->pos = owner.stacksController->getStackPositionAtHex(currentHex, stack);
  464. owner.stacksController->addNewAnim(new CMovementEndAnimation(owner, stack, currentHex));
  465. if(owner.moveSoundHander != -1)
  466. {
  467. CCS->soundh->stopSound(owner.moveSoundHander);
  468. owner.moveSoundHander = -1;
  469. }
  470. }
  471. CMovementAnimation::CMovementAnimation(BattleInterface & owner, const CStack *_stack, std::vector<BattleHex> _destTiles, int _distance)
  472. : CStackMoveAnimation(owner, _stack, _destTiles.front()),
  473. destTiles(_destTiles),
  474. curentMoveIndex(0),
  475. oldPos(stack->getPosition()),
  476. begX(0), begY(0),
  477. distanceX(0), distanceY(0),
  478. timeToMove(0.0),
  479. progress(0.0)
  480. {
  481. logAnim->debug("Created movement anim for %s", stack->getName());
  482. }
  483. CMovementEndAnimation::CMovementEndAnimation(BattleInterface & owner, const CStack * _stack, BattleHex destTile)
  484. : CStackMoveAnimation(owner, _stack, destTile)
  485. {
  486. logAnim->debug("Created movement end anim for %s", stack->getName());
  487. }
  488. bool CMovementEndAnimation::init()
  489. {
  490. //if( !isEarliest(true) )
  491. // return false;
  492. if(!stack || myAnim->framesInGroup(CCreatureAnim::MOVE_END) == 0 ||
  493. myAnim->isDeadOrDying())
  494. {
  495. delete this;
  496. return false;
  497. }
  498. CCS->soundh->playSound(battle_sound(stack->getCreature(), endMoving));
  499. myAnim->setType(CCreatureAnim::MOVE_END);
  500. myAnim->onAnimationReset += [&](){ delete this; };
  501. return true;
  502. }
  503. CMovementEndAnimation::~CMovementEndAnimation()
  504. {
  505. if(myAnim->getType() != CCreatureAnim::DEAD)
  506. myAnim->setType(CCreatureAnim::HOLDING); //resetting to default
  507. CCS->curh->show();
  508. }
  509. CMovementStartAnimation::CMovementStartAnimation(BattleInterface & owner, const CStack * _stack)
  510. : CStackMoveAnimation(owner, _stack, _stack->getPosition())
  511. {
  512. logAnim->debug("Created movement start anim for %s", stack->getName());
  513. }
  514. bool CMovementStartAnimation::init()
  515. {
  516. if( !CBattleAnimation::checkInitialConditions() )
  517. return false;
  518. if(!stack || myAnim->isDeadOrDying())
  519. {
  520. delete this;
  521. return false;
  522. }
  523. CCS->soundh->playSound(battle_sound(stack->getCreature(), startMoving));
  524. myAnim->setType(CCreatureAnim::MOVE_START);
  525. myAnim->onAnimationReset += [&](){ delete this; };
  526. return true;
  527. }
  528. CReverseAnimation::CReverseAnimation(BattleInterface & owner, const CStack * stack, BattleHex dest, bool _priority)
  529. : CStackMoveAnimation(owner, stack, dest),
  530. priority(_priority)
  531. {
  532. logAnim->debug("Created reverse anim for %s", stack->getName());
  533. }
  534. bool CReverseAnimation::init()
  535. {
  536. if(myAnim == nullptr || myAnim->isDeadOrDying())
  537. {
  538. delete this;
  539. return false; //there is no such creature
  540. }
  541. if(!priority && !CBattleAnimation::checkInitialConditions())
  542. return false;
  543. if(myAnim->framesInGroup(CCreatureAnim::TURN_L))
  544. {
  545. myAnim->setType(CCreatureAnim::TURN_L);
  546. myAnim->onAnimationReset += std::bind(&CReverseAnimation::setupSecondPart, this);
  547. }
  548. else
  549. {
  550. setupSecondPart();
  551. }
  552. return true;
  553. }
  554. CReverseAnimation::~CReverseAnimation()
  555. {
  556. if( stack && stack->alive() )//don't do that if stack is dead
  557. myAnim->setType(CCreatureAnim::HOLDING);
  558. }
  559. void CBattleStackAnimation::rotateStack(BattleHex hex)
  560. {
  561. setStackFacingRight(stack, !stackFacingRight(stack));
  562. stackAnimation(stack)->pos = owner.stacksController->getStackPositionAtHex(hex, stack);
  563. }
  564. void CReverseAnimation::setupSecondPart()
  565. {
  566. if(!stack)
  567. {
  568. delete this;
  569. return;
  570. }
  571. rotateStack(currentHex);
  572. if(myAnim->framesInGroup(CCreatureAnim::TURN_R))
  573. {
  574. myAnim->setType(CCreatureAnim::TURN_R);
  575. myAnim->onAnimationReset += [&](){ delete this; };
  576. }
  577. else
  578. delete this;
  579. }
  580. CRangedAttackAnimation::CRangedAttackAnimation(BattleInterface & owner, const CStack * attacker, BattleHex dest_, const CStack * defender)
  581. : CAttackAnimation(owner, attacker, dest_, defender),
  582. projectileEmitted(false)
  583. {
  584. logAnim->info("Ranged attack animation created");
  585. }
  586. bool CRangedAttackAnimation::init()
  587. {
  588. if( !CAttackAnimation::checkInitialConditions() )
  589. return false;
  590. assert(attackingStack);
  591. assert(!myAnim->isDeadOrDying());
  592. if(!attackingStack || myAnim->isDeadOrDying())
  593. {
  594. //FIXME: how is this possible?
  595. logAnim->warn("Shooting animation has not started yet but attacker is dead! Aborting...");
  596. delete this;
  597. return false;
  598. }
  599. //reverse unit if necessary
  600. if (attackingStack && attackedStack && owner.getCurrentPlayerInterface()->cb->isToReverse(attackingStack->getPosition(), attackedStack->getPosition(), stackFacingRight(attackingStack), attackingStack->doubleWide(), stackFacingRight(attackedStack)))
  601. {
  602. owner.stacksController->addNewAnim(new CReverseAnimation(owner, attackingStack, attackingStack->getPosition(), true));
  603. return false;
  604. }
  605. logAnim->info("Ranged attack animation initialized");
  606. setAnimationGroup();
  607. initializeProjectile();
  608. shooting = true;
  609. return true;
  610. }
  611. void CRangedAttackAnimation::setAnimationGroup()
  612. {
  613. Point shooterPos = stackAnimation(attackingStack)->pos.topLeft();
  614. Point shotTarget = owner.stacksController->getStackPositionAtHex(dest, attackedStack);
  615. //maximal angle in radians between straight horizontal line and shooting line for which shot is considered to be straight (absoulte value)
  616. static const double straightAngle = 0.2;
  617. double projectileAngle = -atan2(shotTarget.y - shooterPos.y, std::abs(shotTarget.x - shooterPos.x));
  618. // Calculate projectile start position. Offsets are read out of the CRANIM.TXT.
  619. if (projectileAngle > straightAngle)
  620. group = getUpwardsGroup();
  621. else if (projectileAngle < -straightAngle)
  622. group = getDownwardsGroup();
  623. else
  624. group = getForwardGroup();
  625. }
  626. void CRangedAttackAnimation::initializeProjectile()
  627. {
  628. const CCreature *shooterInfo = getCreature();
  629. Point shotTarget = owner.stacksController->getStackPositionAtHex(dest, attackedStack) + Point(225, 225);
  630. Point shotOrigin = stackAnimation(attackingStack)->pos.topLeft() + Point(222, 265);
  631. int multiplier = stackFacingRight(attackingStack) ? 1 : -1;
  632. if (group == getUpwardsGroup())
  633. {
  634. shotOrigin.x += ( -25 + shooterInfo->animation.upperRightMissleOffsetX ) * multiplier;
  635. shotOrigin.y += shooterInfo->animation.upperRightMissleOffsetY;
  636. }
  637. else if (group == getDownwardsGroup())
  638. {
  639. shotOrigin.x += ( -25 + shooterInfo->animation.lowerRightMissleOffsetX ) * multiplier;
  640. shotOrigin.y += shooterInfo->animation.lowerRightMissleOffsetY;
  641. }
  642. else if (group == getForwardGroup())
  643. {
  644. shotOrigin.x += ( -25 + shooterInfo->animation.rightMissleOffsetX ) * multiplier;
  645. shotOrigin.y += shooterInfo->animation.rightMissleOffsetY;
  646. }
  647. else
  648. {
  649. assert(0);
  650. }
  651. createProjectile(shotOrigin, shotTarget);
  652. }
  653. void CRangedAttackAnimation::emitProjectile()
  654. {
  655. logAnim->info("Ranged attack projectile emitted");
  656. owner.projectilesController->emitStackProjectile(attackingStack);
  657. projectileEmitted = true;
  658. }
  659. void CRangedAttackAnimation::nextFrame()
  660. {
  661. for(auto & it : pendingAnimations())
  662. {
  663. CMovementStartAnimation * anim = dynamic_cast<CMovementStartAnimation *>(it);
  664. CReverseAnimation * anim2 = dynamic_cast<CReverseAnimation *>(it);
  665. if( (anim && anim->stack->ID == stack->ID) || (anim2 && anim2->stack->ID == stack->ID && anim2->priority ) )
  666. {
  667. assert(0); // FIXME: our stack started to move even though we are playing shooting animation? How?
  668. return;
  669. }
  670. }
  671. // animation should be paused if there is an active projectile
  672. if (projectileEmitted)
  673. {
  674. if (owner.projectilesController->hasActiveProjectile(attackingStack))
  675. stackAnimation(attackingStack)->pause();
  676. else
  677. stackAnimation(attackingStack)->play();
  678. }
  679. CAttackAnimation::nextFrame();
  680. if (!projectileEmitted)
  681. {
  682. logAnim->info("Ranged attack executing, %d / %d / %d",
  683. stackAnimation(attackingStack)->getCurrentFrame(),
  684. getAttackClimaxFrame(),
  685. stackAnimation(attackingStack)->framesInGroup(group));
  686. // emit projectile once animation playback reached "climax" frame
  687. if ( stackAnimation(attackingStack)->getCurrentFrame() >= getAttackClimaxFrame() )
  688. {
  689. emitProjectile();
  690. stackAnimation(attackingStack)->pause();
  691. return;
  692. }
  693. }
  694. }
  695. CRangedAttackAnimation::~CRangedAttackAnimation()
  696. {
  697. logAnim->info("Ranged attack animation is over");
  698. //FIXME: this assert triggers under some unclear, rare conditions. Possibly - if game window is inactive and/or in foreground/minimized?
  699. assert(!owner.projectilesController->hasActiveProjectile(attackingStack));
  700. assert(projectileEmitted);
  701. // FIXME: is this possible? Animation is over but we're yet to fire projectile?
  702. if (!projectileEmitted)
  703. {
  704. logAnim->warn("Shooting animation has finished but projectile was not emitted! Emitting it now...");
  705. emitProjectile();
  706. }
  707. }
  708. CShootingAnimation::CShootingAnimation(BattleInterface & owner, const CStack * attacker, BattleHex _dest, const CStack * _attacked)
  709. : CRangedAttackAnimation(owner, attacker, _dest, _attacked)
  710. {
  711. logAnim->debug("Created shooting anim for %s", stack->getName());
  712. }
  713. void CShootingAnimation::createProjectile(const Point & from, const Point & dest) const
  714. {
  715. owner.projectilesController->createProjectile(attackingStack, from, dest);
  716. }
  717. uint32_t CShootingAnimation::getAttackClimaxFrame() const
  718. {
  719. const CCreature *shooterInfo = getCreature();
  720. return shooterInfo->animation.attackClimaxFrame;
  721. }
  722. CCreatureAnim::EAnimType CShootingAnimation::getUpwardsGroup() const
  723. {
  724. return CCreatureAnim::SHOOT_UP;
  725. }
  726. CCreatureAnim::EAnimType CShootingAnimation::getForwardGroup() const
  727. {
  728. return CCreatureAnim::SHOOT_FRONT;
  729. }
  730. CCreatureAnim::EAnimType CShootingAnimation::getDownwardsGroup() const
  731. {
  732. return CCreatureAnim::SHOOT_DOWN;
  733. }
  734. CCatapultAnimation::CCatapultAnimation(BattleInterface & owner, const CStack * attacker, BattleHex _dest, const CStack * _attacked, int _catapultDmg)
  735. : CShootingAnimation(owner, attacker, _dest, _attacked),
  736. catapultDamage(_catapultDmg),
  737. explosionEmitted(false)
  738. {
  739. logAnim->debug("Created shooting anim for %s", stack->getName());
  740. }
  741. void CCatapultAnimation::nextFrame()
  742. {
  743. CShootingAnimation::nextFrame();
  744. if ( explosionEmitted)
  745. return;
  746. if ( !projectileEmitted)
  747. return;
  748. if (owner.projectilesController->hasActiveProjectile(attackingStack))
  749. return;
  750. explosionEmitted = true;
  751. Point shotTarget = owner.stacksController->getStackPositionAtHex(dest, attackedStack) + Point(225, 225) - Point(126, 105);
  752. if(catapultDamage > 0)
  753. owner.stacksController->addNewAnim( new CPointEffectAnimation(owner, soundBase::WALLHIT, "SGEXPL.DEF", shotTarget));
  754. else
  755. owner.stacksController->addNewAnim( new CPointEffectAnimation(owner, soundBase::WALLMISS, "CSGRCK.DEF", shotTarget));
  756. }
  757. void CCatapultAnimation::createProjectile(const Point & from, const Point & dest) const
  758. {
  759. owner.projectilesController->createCatapultProjectile(attackingStack, from, dest);
  760. }
  761. CCastAnimation::CCastAnimation(BattleInterface & owner, const CStack * attacker, BattleHex dest_, const CStack * defender, const CSpell * spell)
  762. : CRangedAttackAnimation(owner, attacker, dest_, defender),
  763. spell(spell)
  764. {
  765. assert(dest.isValid());// FIXME: when?
  766. if(!dest_.isValid() && defender)
  767. dest = defender->getPosition();
  768. }
  769. CCreatureAnim::EAnimType CCastAnimation::findValidGroup( const std::vector<CCreatureAnim::EAnimType> candidates ) const
  770. {
  771. for ( auto group : candidates)
  772. {
  773. if(myAnim->framesInGroup(group) > 0)
  774. return group;
  775. }
  776. assert(0);
  777. return CCreatureAnim::HOLDING;
  778. }
  779. CCreatureAnim::EAnimType CCastAnimation::getUpwardsGroup() const
  780. {
  781. return findValidGroup({
  782. CCreatureAnim::VCMI_CAST_UP,
  783. CCreatureAnim::CAST_UP,
  784. CCreatureAnim::SHOOT_UP,
  785. CCreatureAnim::ATTACK_UP
  786. });
  787. }
  788. CCreatureAnim::EAnimType CCastAnimation::getForwardGroup() const
  789. {
  790. return findValidGroup({
  791. CCreatureAnim::VCMI_CAST_FRONT,
  792. CCreatureAnim::CAST_FRONT,
  793. CCreatureAnim::SHOOT_FRONT,
  794. CCreatureAnim::ATTACK_FRONT
  795. });
  796. }
  797. CCreatureAnim::EAnimType CCastAnimation::getDownwardsGroup() const
  798. {
  799. return findValidGroup({
  800. CCreatureAnim::VCMI_CAST_DOWN,
  801. CCreatureAnim::CAST_DOWN,
  802. CCreatureAnim::SHOOT_DOWN,
  803. CCreatureAnim::ATTACK_DOWN
  804. });
  805. }
  806. void CCastAnimation::createProjectile(const Point & from, const Point & dest) const
  807. {
  808. if (!spell->animationInfo.projectile.empty())
  809. owner.projectilesController->createSpellProjectile(attackingStack, from, dest, spell);
  810. }
  811. uint32_t CCastAnimation::getAttackClimaxFrame() const
  812. {
  813. //FIXME: allow defining this parameter in config file, separately from attackClimaxFrame of missile attacks
  814. uint32_t maxFrames = stackAnimation(attackingStack)->framesInGroup(group);
  815. if (maxFrames > 2)
  816. return maxFrames - 2;
  817. return 0;
  818. }
  819. CPointEffectAnimation::CPointEffectAnimation(BattleInterface & owner, soundBase::soundID sound, std::string animationName, int effects):
  820. CBattleAnimation(owner),
  821. animation(std::make_shared<CAnimation>(animationName)),
  822. sound(sound),
  823. effectFlags(effects),
  824. soundPlayed(false),
  825. soundFinished(false),
  826. effectFinished(false)
  827. {
  828. }
  829. CPointEffectAnimation::CPointEffectAnimation(BattleInterface & owner, soundBase::soundID sound, std::string animationName, std::vector<BattleHex> hex, int effects):
  830. CPointEffectAnimation(owner, sound, animationName, effects)
  831. {
  832. battlehexes = hex;
  833. }
  834. CPointEffectAnimation::CPointEffectAnimation(BattleInterface & owner, soundBase::soundID sound, std::string animationName, BattleHex hex, int effects):
  835. CPointEffectAnimation(owner, sound, animationName, effects)
  836. {
  837. assert(hex.isValid());
  838. battlehexes.push_back(hex);
  839. }
  840. CPointEffectAnimation::CPointEffectAnimation(BattleInterface & owner, soundBase::soundID sound, std::string animationName, std::vector<Point> pos, int effects):
  841. CPointEffectAnimation(owner, sound, animationName, effects)
  842. {
  843. positions = pos;
  844. }
  845. CPointEffectAnimation::CPointEffectAnimation(BattleInterface & owner, soundBase::soundID sound, std::string animationName, Point pos, int effects):
  846. CPointEffectAnimation(owner, sound, animationName, effects)
  847. {
  848. positions.push_back(pos);
  849. }
  850. CPointEffectAnimation::CPointEffectAnimation(BattleInterface & owner, soundBase::soundID sound, std::string animationName, Point pos, BattleHex hex, int effects):
  851. CPointEffectAnimation(owner, sound, animationName, effects)
  852. {
  853. assert(hex.isValid());
  854. battlehexes.push_back(hex);
  855. positions.push_back(pos);
  856. }
  857. bool CPointEffectAnimation::init()
  858. {
  859. if(!CBattleAnimation::checkInitialConditions())
  860. return false;
  861. animation->preload();
  862. auto first = animation->getImage(0, 0, true);
  863. if(!first)
  864. {
  865. delete this;
  866. return false;
  867. }
  868. if (screenFill())
  869. {
  870. for(int i=0; i * first->width() < owner.pos.w ; ++i)
  871. for(int j=0; j * first->height() < owner.pos.h ; ++j)
  872. positions.push_back(Point( owner.pos.x + i * first->width(), owner.pos.y + j * first->height()));
  873. }
  874. BattleEffect be;
  875. be.effectID = ID;
  876. be.animation = animation;
  877. be.currentFrame = 0;
  878. for (size_t i = 0; i < std::max(battlehexes.size(), positions.size()); ++i)
  879. {
  880. bool hasTile = i < battlehexes.size();
  881. bool hasPosition = i < positions.size();
  882. if (hasTile && !forceOnTop())
  883. be.position = battlehexes[i];
  884. else
  885. be.position = BattleHex::INVALID;
  886. if (hasPosition)
  887. {
  888. be.x = positions[i].x;
  889. be.y = positions[i].y;
  890. }
  891. else
  892. {
  893. const CStack * destStack = owner.getCurrentPlayerInterface()->cb->battleGetStackByPos(battlehexes[i], false);
  894. Rect tilePos = owner.fieldController->hexPositionAbsolute(battlehexes[i]);
  895. be.x = tilePos.x + tilePos.w/2 - first->width()/2;
  896. if(destStack && destStack->doubleWide()) // Correction for 2-hex creatures.
  897. be.x += (destStack->side == BattleSide::ATTACKER ? -1 : 1)*tilePos.w/2;
  898. if (alignToBottom())
  899. be.y = tilePos.y + tilePos.h - first->height();
  900. else
  901. be.y = tilePos.y - first->height()/2;
  902. }
  903. owner.effectsController->battleEffects.push_back(be);
  904. }
  905. return true;
  906. }
  907. void CPointEffectAnimation::nextFrame()
  908. {
  909. playSound();
  910. playEffect();
  911. if (soundFinished && effectFinished)
  912. {
  913. //remove visual effect itself only if sound has finished as well - necessary for obstacles like force field
  914. clearEffect();
  915. delete this;
  916. }
  917. }
  918. bool CPointEffectAnimation::alignToBottom() const
  919. {
  920. return effectFlags & ALIGN_TO_BOTTOM;
  921. }
  922. bool CPointEffectAnimation::waitForSound() const
  923. {
  924. return effectFlags & WAIT_FOR_SOUND;
  925. }
  926. bool CPointEffectAnimation::forceOnTop() const
  927. {
  928. return effectFlags & FORCE_ON_TOP;
  929. }
  930. bool CPointEffectAnimation::screenFill() const
  931. {
  932. return effectFlags & SCREEN_FILL;
  933. }
  934. void CPointEffectAnimation::onEffectFinished()
  935. {
  936. effectFinished = true;
  937. }
  938. void CPointEffectAnimation::onSoundFinished()
  939. {
  940. soundFinished = true;
  941. }
  942. void CPointEffectAnimation::playSound()
  943. {
  944. if (soundPlayed)
  945. return;
  946. soundPlayed = true;
  947. if (sound == soundBase::invalid)
  948. {
  949. onSoundFinished();
  950. return;
  951. }
  952. int channel = CCS->soundh->playSound(sound);
  953. if (!waitForSound() || channel == -1)
  954. onSoundFinished();
  955. else
  956. CCS->soundh->setCallback(channel, [&](){ onSoundFinished(); });
  957. }
  958. void CPointEffectAnimation::playEffect()
  959. {
  960. if ( effectFinished )
  961. return;
  962. for(auto & elem : owner.effectsController->battleEffects)
  963. {
  964. if(elem.effectID == ID)
  965. {
  966. elem.currentFrame += AnimationControls::getSpellEffectSpeed() * GH.mainFPSmng->getElapsedMilliseconds() / 1000;
  967. if(elem.currentFrame >= elem.animation->size())
  968. {
  969. elem.currentFrame = elem.animation->size() - 1;
  970. onEffectFinished();
  971. break;
  972. }
  973. }
  974. }
  975. }
  976. void CPointEffectAnimation::clearEffect()
  977. {
  978. auto & effects = owner.effectsController->battleEffects;
  979. for ( auto it = effects.begin(); it != effects.end(); )
  980. {
  981. if (it->effectID == ID)
  982. it = effects.erase(it);
  983. else
  984. it++;
  985. }
  986. }
  987. CPointEffectAnimation::~CPointEffectAnimation()
  988. {
  989. assert(effectFinished);
  990. assert(soundFinished);
  991. }
  992. CWaitingAnimation::CWaitingAnimation(BattleInterface & owner):
  993. CBattleAnimation(owner)
  994. {}
  995. void CWaitingAnimation::nextFrame()
  996. {
  997. // initialization conditions fulfilled, delay is over
  998. delete this;
  999. }
  1000. CWaitingProjectileAnimation::CWaitingProjectileAnimation(BattleInterface & owner, const CStack * shooter):
  1001. CWaitingAnimation(owner),
  1002. shooter(shooter)
  1003. {}
  1004. bool CWaitingProjectileAnimation::init()
  1005. {
  1006. for(auto & elem : pendingAnimations())
  1007. {
  1008. auto * attackAnim = dynamic_cast<CRangedAttackAnimation *>(elem);
  1009. if( attackAnim && shooter && attackAnim->stack->ID == shooter->ID && !attackAnim->isInitialized() )
  1010. {
  1011. // there is ongoing ranged attack that involves our stack, but projectile was not created yet
  1012. return false;
  1013. }
  1014. }
  1015. if(owner.projectilesController->hasActiveProjectile(shooter))
  1016. return false;
  1017. return true;
  1018. }