CBattleAnimations.cpp 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229
  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. CBattleAnimation::CBattleAnimation(CBattleInterface * _owner)
  29. : owner(_owner), ID(_owner->animIDhelper++)
  30. {
  31. logAnim->trace("Animation #%d created", ID);
  32. }
  33. CBattleAnimation::~CBattleAnimation()
  34. {
  35. logAnim->trace("Animation #%d deleted", ID);
  36. }
  37. void CBattleAnimation::endAnim()
  38. {
  39. logAnim->trace("Animation #%d ended, type is %s", ID, typeid(this).name());
  40. for(auto & elem : owner->pendingAnims)
  41. {
  42. if(elem.first == this)
  43. {
  44. elem.first = nullptr;
  45. }
  46. }
  47. }
  48. bool CBattleAnimation::isEarliest(bool perStackConcurrency)
  49. {
  50. int lowestMoveID = owner->animIDhelper + 5;
  51. CBattleStackAnimation * thAnim = dynamic_cast<CBattleStackAnimation *>(this);
  52. CEffectAnimation * thSen = dynamic_cast<CEffectAnimation *>(this);
  53. for(auto & elem : owner->pendingAnims)
  54. {
  55. CBattleStackAnimation * stAnim = dynamic_cast<CBattleStackAnimation *>(elem.first);
  56. CEffectAnimation * sen = dynamic_cast<CEffectAnimation *>(elem.first);
  57. if(perStackConcurrency && stAnim && thAnim && stAnim->stack->ID != thAnim->stack->ID)
  58. continue;
  59. if(perStackConcurrency && sen && thSen && sen != thSen)
  60. continue;
  61. CReverseAnimation * revAnim = dynamic_cast<CReverseAnimation *>(stAnim);
  62. if(revAnim && thAnim && stAnim && stAnim->stack->ID == thAnim->stack->ID && revAnim->priority)
  63. return false;
  64. if(elem.first)
  65. vstd::amin(lowestMoveID, elem.first->ID);
  66. }
  67. return (ID == lowestMoveID) || (lowestMoveID == (owner->animIDhelper + 5));
  68. }
  69. CBattleStackAnimation::CBattleStackAnimation(CBattleInterface * owner, const CStack * stack)
  70. : CBattleAnimation(owner),
  71. myAnim(owner->creAnims[stack->ID]),
  72. stack(stack)
  73. {
  74. assert(myAnim);
  75. }
  76. void CBattleStackAnimation::shiftColor(const ColorShifter * shifter)
  77. {
  78. assert(myAnim);
  79. myAnim->shiftColor(shifter);
  80. }
  81. void CAttackAnimation::nextFrame()
  82. {
  83. if(myAnim->getType() != group)
  84. {
  85. myAnim->setType(group);
  86. myAnim->onAnimationReset += std::bind(&CAttackAnimation::endAnim, this);
  87. }
  88. if(!soundPlayed)
  89. {
  90. if(shooting)
  91. CCS->soundh->playSound(battle_sound(attackingStack->getCreature(), shoot));
  92. else
  93. CCS->soundh->playSound(battle_sound(attackingStack->getCreature(), attack));
  94. soundPlayed = true;
  95. }
  96. CBattleAnimation::nextFrame();
  97. }
  98. void CAttackAnimation::endAnim()
  99. {
  100. myAnim->setType(CCreatureAnim::HOLDING);
  101. CBattleStackAnimation::endAnim();
  102. }
  103. bool CAttackAnimation::checkInitialConditions()
  104. {
  105. for(auto & elem : owner->pendingAnims)
  106. {
  107. CBattleStackAnimation * stAnim = dynamic_cast<CBattleStackAnimation *>(elem.first);
  108. CReverseAnimation * revAnim = dynamic_cast<CReverseAnimation *>(stAnim);
  109. if(revAnim && attackedStack) // enemy must be fully reversed
  110. {
  111. if (revAnim->stack->ID == attackedStack->ID)
  112. return false;
  113. }
  114. }
  115. return isEarliest(false);
  116. }
  117. CAttackAnimation::CAttackAnimation(CBattleInterface *_owner, const CStack *attacker, BattleHex _dest, const CStack *defender)
  118. : CBattleStackAnimation(_owner, attacker),
  119. shooting(false), group(CCreatureAnim::SHOOT_FRONT),
  120. soundPlayed(false),
  121. dest(_dest), attackedStack(defender), attackingStack(attacker)
  122. {
  123. assert(attackingStack && "attackingStack is nullptr in CBattleAttack::CBattleAttack !\n");
  124. attackingStackPosBeforeReturn = attackingStack->getPosition();
  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->getPosition(), attacker->getPosition(), owner->creDir[stack->ID], attacker->doubleWide(), owner->creDir[attacker->ID]))
  159. {
  160. owner->addNewAnim(new CReverseAnimation(owner, stack, stack->getPosition(), true));
  161. return false;
  162. }
  163. //unit reversed
  164. if(rangedAttack && attacker != nullptr) //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].get(), 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. else if(stack->defendingAnim)
  195. return battle_sound(stack->getCreature(), defend);
  196. else
  197. return battle_sound(stack->getCreature(), wince);
  198. }
  199. CCreatureAnim::EAnimType CDefenceAnimation::getMyAnimType()
  200. {
  201. if(killed)
  202. {
  203. if(rangedAttack && myAnim->framesInGroup(CCreatureAnim::DEATH_RANGED) > 0)
  204. return CCreatureAnim::DEATH_RANGED;
  205. else
  206. return CCreatureAnim::DEATH;
  207. }
  208. if(stack->defendingAnim)
  209. return CCreatureAnim::DEFENCE;
  210. else
  211. return CCreatureAnim::HITTED;
  212. }
  213. void CDefenceAnimation::startAnimation()
  214. {
  215. CCS->soundh->playSound(getMySound());
  216. myAnim->setType(getMyAnimType());
  217. myAnim->onAnimationReset += std::bind(&CDefenceAnimation::endAnim, this);
  218. }
  219. void CDefenceAnimation::nextFrame()
  220. {
  221. if (timeToWait > 0)
  222. {
  223. timeToWait -= float(GH.mainFPSmng->getElapsedMilliseconds()) / 1000;
  224. if (timeToWait <= 0)
  225. startAnimation();
  226. }
  227. CBattleAnimation::nextFrame();
  228. }
  229. void CDefenceAnimation::endAnim()
  230. {
  231. if(killed)
  232. {
  233. if(rangedAttack && myAnim->framesInGroup(CCreatureAnim::DEAD_RANGED) > 0)
  234. myAnim->setType(CCreatureAnim::DEAD_RANGED);
  235. else
  236. myAnim->setType(CCreatureAnim::DEAD);
  237. }
  238. else
  239. {
  240. myAnim->setType(CCreatureAnim::HOLDING);
  241. }
  242. CBattleAnimation::endAnim();
  243. delete this;
  244. }
  245. CDummyAnimation::CDummyAnimation(CBattleInterface * _owner, int howManyFrames)
  246. : CBattleAnimation(_owner), counter(0), howMany(howManyFrames)
  247. {
  248. logAnim->debug("Created dummy animation for %d frames", howManyFrames);
  249. }
  250. bool CDummyAnimation::init()
  251. {
  252. return true;
  253. }
  254. void CDummyAnimation::nextFrame()
  255. {
  256. counter++;
  257. if(counter > howMany)
  258. endAnim();
  259. }
  260. void CDummyAnimation::endAnim()
  261. {
  262. CBattleAnimation::endAnim();
  263. delete this;
  264. }
  265. bool CMeleeAttackAnimation::init()
  266. {
  267. if(!CAttackAnimation::checkInitialConditions())
  268. return false;
  269. if(!attackingStack || myAnim->isDead())
  270. {
  271. endAnim();
  272. return false;
  273. }
  274. bool toReverse = owner->getCurrentPlayerInterface()->cb->isToReverse(attackingStackPosBeforeReturn, attackedStack->getPosition(), owner->creDir[stack->ID], attackedStack->doubleWide(), owner->creDir[attackedStack->ID]);
  275. if(toReverse)
  276. {
  277. owner->addNewAnim(new CReverseAnimation(owner, stack, attackingStackPosBeforeReturn, true));
  278. return false;
  279. }
  280. // opponent must face attacker ( = different directions) before he can be attacked
  281. if(attackingStack && attackedStack &&
  282. owner->creDir[attackingStack->ID] == owner->creDir[attackedStack->ID])
  283. return false;
  284. //reversed
  285. shooting = false;
  286. static const CCreatureAnim::EAnimType mutPosToGroup[] =
  287. {
  288. CCreatureAnim::ATTACK_UP,
  289. CCreatureAnim::ATTACK_UP,
  290. CCreatureAnim::ATTACK_FRONT,
  291. CCreatureAnim::ATTACK_DOWN,
  292. CCreatureAnim::ATTACK_DOWN,
  293. CCreatureAnim::ATTACK_FRONT
  294. };
  295. static const CCreatureAnim::EAnimType mutPosToGroup2H[] =
  296. {
  297. CCreatureAnim::VCMI_2HEX_UP,
  298. CCreatureAnim::VCMI_2HEX_UP,
  299. CCreatureAnim::VCMI_2HEX_FRONT,
  300. CCreatureAnim::VCMI_2HEX_DOWN,
  301. CCreatureAnim::VCMI_2HEX_DOWN,
  302. CCreatureAnim::VCMI_2HEX_FRONT
  303. };
  304. int revShiftattacker = (attackingStack->side == BattleSide::ATTACKER ? -1 : 1);
  305. int mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn, dest);
  306. if(mutPos == -1 && attackingStack->doubleWide())
  307. {
  308. mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn + revShiftattacker, attackedStack->getPosition());
  309. }
  310. if (mutPos == -1 && attackedStack->doubleWide())
  311. {
  312. mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn, attackedStack->occupiedHex());
  313. }
  314. if (mutPos == -1 && attackedStack->doubleWide() && attackingStack->doubleWide())
  315. {
  316. mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn + revShiftattacker, attackedStack->occupiedHex());
  317. }
  318. switch(mutPos) //attack direction
  319. {
  320. case 0:
  321. case 1:
  322. case 2:
  323. case 3:
  324. case 4:
  325. case 5:
  326. group = mutPosToGroup[mutPos];
  327. if(attackingStack->hasBonusOfType(Bonus::TWO_HEX_ATTACK_BREATH))
  328. {
  329. CCreatureAnim::EAnimType group2H = mutPosToGroup2H[mutPos];
  330. if(myAnim->framesInGroup(group2H)>0)
  331. group = group2H;
  332. }
  333. break;
  334. default:
  335. logGlobal->error("Critical Error! Wrong dest in stackAttacking! dest: %d; attacking stack pos: %d; mutual pos: %d", dest.hex, attackingStackPosBeforeReturn, mutPos);
  336. group = CCreatureAnim::ATTACK_FRONT;
  337. break;
  338. }
  339. return true;
  340. }
  341. CMeleeAttackAnimation::CMeleeAttackAnimation(CBattleInterface * _owner, const CStack * attacker, BattleHex _dest, const CStack * _attacked)
  342. : CAttackAnimation(_owner, attacker, _dest, _attacked)
  343. {
  344. logAnim->debug("Created melee attack anim for %s", attacker->getName());
  345. }
  346. void CMeleeAttackAnimation::endAnim()
  347. {
  348. CAttackAnimation::endAnim();
  349. delete this;
  350. }
  351. bool CMovementAnimation::init()
  352. {
  353. if( !isEarliest(false) )
  354. return false;
  355. if(!stack || myAnim->isDead())
  356. {
  357. endAnim();
  358. return false;
  359. }
  360. if(owner->creAnims[stack->ID]->framesInGroup(CCreatureAnim::MOVING) == 0 ||
  361. stack->hasBonus(Selector::typeSubtype(Bonus::FLYING, 1)))
  362. {
  363. //no movement or teleport, end immediately
  364. endAnim();
  365. return false;
  366. }
  367. //reverse unit if necessary
  368. if(owner->shouldRotate(stack, oldPos, nextHex))
  369. {
  370. // it seems that H3 does NOT plays full rotation animation here in most situations
  371. // Logical since it takes quite a lot of time
  372. if (curentMoveIndex == 0) // full rotation only for moving towards first tile.
  373. {
  374. owner->addNewAnim(new CReverseAnimation(owner, stack, oldPos, true));
  375. return false;
  376. }
  377. else
  378. {
  379. CReverseAnimation::rotateStack(owner, stack, oldPos);
  380. }
  381. }
  382. if(myAnim->getType() != CCreatureAnim::MOVING)
  383. {
  384. myAnim->setType(CCreatureAnim::MOVING);
  385. }
  386. if (owner->moveSoundHander == -1)
  387. {
  388. owner->moveSoundHander = CCS->soundh->playSound(battle_sound(stack->getCreature(), move), -1);
  389. }
  390. Point begPosition = CClickableHex::getXYUnitAnim(oldPos, stack, owner);
  391. Point endPosition = CClickableHex::getXYUnitAnim(nextHex, stack, owner);
  392. timeToMove = AnimationControls::getMovementDuration(stack->getCreature());
  393. begX = begPosition.x;
  394. begY = begPosition.y;
  395. progress = 0;
  396. distanceX = endPosition.x - begPosition.x;
  397. distanceY = endPosition.y - begPosition.y;
  398. if (stack->hasBonus(Selector::type()(Bonus::FLYING)))
  399. {
  400. float distance = static_cast<float>(sqrt(distanceX * distanceX + distanceY * distanceY));
  401. timeToMove *= AnimationControls::getFlightDistance(stack->getCreature()) / distance;
  402. }
  403. return true;
  404. }
  405. void CMovementAnimation::nextFrame()
  406. {
  407. progress += float(GH.mainFPSmng->getElapsedMilliseconds()) / 1000 * timeToMove;
  408. //moving instructions
  409. myAnim->pos.x = static_cast<Sint16>(begX + distanceX * progress );
  410. myAnim->pos.y = static_cast<Sint16>(begY + distanceY * progress );
  411. CBattleAnimation::nextFrame();
  412. if(progress >= 1.0)
  413. {
  414. // Sets the position of the creature animation sprites
  415. Point coords = CClickableHex::getXYUnitAnim(nextHex, stack, owner);
  416. myAnim->pos = coords;
  417. // true if creature haven't reached the final destination hex
  418. if ((curentMoveIndex + 1) < destTiles.size())
  419. {
  420. // update the next hex field which has to be reached by the stack
  421. curentMoveIndex++;
  422. oldPos = nextHex;
  423. nextHex = destTiles[curentMoveIndex];
  424. // re-init animation
  425. for(auto & elem : owner->pendingAnims)
  426. {
  427. if (elem.first == this)
  428. {
  429. elem.second = false;
  430. break;
  431. }
  432. }
  433. }
  434. else
  435. endAnim();
  436. }
  437. }
  438. void CMovementAnimation::endAnim()
  439. {
  440. assert(stack);
  441. myAnim->pos = CClickableHex::getXYUnitAnim(nextHex, stack, owner);
  442. CBattleAnimation::endAnim();
  443. owner->addNewAnim(new CMovementEndAnimation(owner, stack, nextHex));
  444. if(owner->moveSoundHander != -1)
  445. {
  446. CCS->soundh->stopSound(owner->moveSoundHander);
  447. owner->moveSoundHander = -1;
  448. }
  449. delete this;
  450. }
  451. CMovementAnimation::CMovementAnimation(CBattleInterface *_owner, const CStack *_stack, std::vector<BattleHex> _destTiles, int _distance)
  452. : CBattleStackAnimation(_owner, _stack),
  453. destTiles(_destTiles),
  454. curentMoveIndex(0),
  455. oldPos(stack->getPosition()),
  456. begX(0), begY(0),
  457. distanceX(0), distanceY(0),
  458. timeToMove(0.0),
  459. progress(0.0),
  460. nextHex(destTiles.front())
  461. {
  462. logAnim->debug("Created movement anim for %s", stack->getName());
  463. }
  464. CMovementEndAnimation::CMovementEndAnimation(CBattleInterface * _owner, const CStack * _stack, BattleHex destTile)
  465. : CBattleStackAnimation(_owner, _stack), destinationTile(destTile)
  466. {
  467. logAnim->debug("Created movement end anim for %s", stack->getName());
  468. }
  469. bool CMovementEndAnimation::init()
  470. {
  471. if( !isEarliest(true) )
  472. return false;
  473. if(!stack || myAnim->framesInGroup(CCreatureAnim::MOVE_END) == 0 ||
  474. myAnim->isDead())
  475. {
  476. endAnim();
  477. return false;
  478. }
  479. CCS->soundh->playSound(battle_sound(stack->getCreature(), endMoving));
  480. myAnim->setType(CCreatureAnim::MOVE_END);
  481. myAnim->onAnimationReset += std::bind(&CMovementEndAnimation::endAnim, this);
  482. return true;
  483. }
  484. void CMovementEndAnimation::endAnim()
  485. {
  486. CBattleAnimation::endAnim();
  487. if(myAnim->getType() != CCreatureAnim::DEAD)
  488. myAnim->setType(CCreatureAnim::HOLDING); //resetting to default
  489. CCS->curh->show();
  490. delete this;
  491. }
  492. CMovementStartAnimation::CMovementStartAnimation(CBattleInterface * _owner, const CStack * _stack)
  493. : CBattleStackAnimation(_owner, _stack)
  494. {
  495. logAnim->debug("Created movement start anim for %s", stack->getName());
  496. }
  497. bool CMovementStartAnimation::init()
  498. {
  499. if( !isEarliest(false) )
  500. return false;
  501. if(!stack || myAnim->isDead())
  502. {
  503. CMovementStartAnimation::endAnim();
  504. return false;
  505. }
  506. CCS->soundh->playSound(battle_sound(stack->getCreature(), startMoving));
  507. myAnim->setType(CCreatureAnim::MOVE_START);
  508. myAnim->onAnimationReset += std::bind(&CMovementStartAnimation::endAnim, this);
  509. return true;
  510. }
  511. void CMovementStartAnimation::endAnim()
  512. {
  513. CBattleAnimation::endAnim();
  514. delete this;
  515. }
  516. CReverseAnimation::CReverseAnimation(CBattleInterface * _owner, const CStack * stack, BattleHex dest, bool _priority)
  517. : CBattleStackAnimation(_owner, stack), hex(dest), priority(_priority)
  518. {
  519. logAnim->debug("Created reverse anim for %s", stack->getName());
  520. }
  521. bool CReverseAnimation::init()
  522. {
  523. if(myAnim == nullptr || myAnim->isDead())
  524. {
  525. endAnim();
  526. return false; //there is no such creature
  527. }
  528. if(!priority && !isEarliest(false))
  529. return false;
  530. if(myAnim->framesInGroup(CCreatureAnim::TURN_L))
  531. {
  532. myAnim->setType(CCreatureAnim::TURN_L);
  533. myAnim->onAnimationReset += std::bind(&CReverseAnimation::setupSecondPart, this);
  534. }
  535. else
  536. {
  537. setupSecondPart();
  538. }
  539. return true;
  540. }
  541. void CReverseAnimation::endAnim()
  542. {
  543. CBattleAnimation::endAnim();
  544. if( stack->alive() )//don't do that if stack is dead
  545. myAnim->setType(CCreatureAnim::HOLDING);
  546. delete this;
  547. }
  548. void CReverseAnimation::rotateStack(CBattleInterface * owner, const CStack * stack, BattleHex hex)
  549. {
  550. owner->creDir[stack->ID] = !owner->creDir[stack->ID];
  551. owner->creAnims[stack->ID]->pos = CClickableHex::getXYUnitAnim(hex, stack, owner);
  552. }
  553. void CReverseAnimation::setupSecondPart()
  554. {
  555. if(!stack)
  556. {
  557. endAnim();
  558. return;
  559. }
  560. rotateStack(owner, stack, hex);
  561. if(myAnim->framesInGroup(CCreatureAnim::TURN_R))
  562. {
  563. myAnim->setType(CCreatureAnim::TURN_R);
  564. myAnim->onAnimationReset += std::bind(&CReverseAnimation::endAnim, this);
  565. }
  566. else
  567. endAnim();
  568. }
  569. CRangedAttackAnimation::CRangedAttackAnimation(CBattleInterface * owner_, const CStack * attacker, BattleHex dest_, const CStack * defender)
  570. : CAttackAnimation(owner_, attacker, dest_, defender)
  571. {
  572. }
  573. CShootingAnimation::CShootingAnimation(CBattleInterface * _owner, const CStack * attacker, BattleHex _dest, const CStack * _attacked, bool _catapult, int _catapultDmg)
  574. : CRangedAttackAnimation(_owner, attacker, _dest, _attacked),
  575. catapultDamage(_catapultDmg)
  576. {
  577. logAnim->debug("Created shooting anim for %s", stack->getName());
  578. }
  579. bool CShootingAnimation::init()
  580. {
  581. if( !CAttackAnimation::checkInitialConditions() )
  582. return false;
  583. const CStack * shooter = attackingStack;
  584. if(!shooter || myAnim->isDead())
  585. {
  586. endAnim();
  587. return false;
  588. }
  589. //reverse unit if necessary
  590. if (attackingStack && attackedStack && owner->getCurrentPlayerInterface()->cb->isToReverse(attackingStack->getPosition(), attackedStack->getPosition(), owner->creDir[attackingStack->ID], attackingStack->doubleWide(), owner->creDir[attackedStack->ID]))
  591. {
  592. owner->addNewAnim(new CReverseAnimation(owner, attackingStack, attackingStack->getPosition(), true));
  593. return false;
  594. }
  595. // opponent must face attacker ( = different directions) before he can be attacked
  596. //FIXME: this cause freeze
  597. // if (attackingStack && attackedStack &&
  598. // owner->creDir[attackingStack->ID] == owner->creDir[attackedStack->ID])
  599. // return false;
  600. // Create the projectile animation
  601. //maximal angle in radians between straight horizontal line and shooting line for which shot is considered to be straight (absoulte value)
  602. static const double straightAngle = 0.2;
  603. // Get further info about the shooter e.g. relative pos of projectile to unit.
  604. // If the creature id is 149 then it's a arrow tower which has no additional info so get the
  605. // actual arrow tower shooter instead.
  606. const CCreature *shooterInfo = shooter->getCreature();
  607. if(shooterInfo->idNumber == CreatureID::ARROW_TOWERS)
  608. {
  609. int creID = owner->siegeH->town->town->clientInfo.siegeShooter;
  610. shooterInfo = CGI->creh->operator[](creID);
  611. }
  612. if(!shooterInfo->animation.missleFrameAngles.size())
  613. logAnim->error("Mod error: Creature '%s' on the Archer's tower is not a shooter. Mod should be fixed. Trying to use archer's data instead..."
  614. , shooterInfo->nameSing);
  615. auto & angles = shooterInfo->animation.missleFrameAngles.size()
  616. ? shooterInfo->animation.missleFrameAngles
  617. : CGI->creh->operator[](CreatureID::ARCHER)->animation.missleFrameAngles;
  618. ProjectileInfo spi;
  619. spi.shotDone = false;
  620. spi.creID = shooter->getCreature()->idNumber;
  621. spi.stackID = shooter->ID;
  622. // reverse if creature is facing right OR this is non-existing stack that is not tower (war machines)
  623. spi.reverse = attackingStack ? !owner->creDir[attackingStack->ID] : shooter->getCreature()->idNumber != CreatureID::ARROW_TOWERS ;
  624. spi.step = 0;
  625. spi.frameNum = 0;
  626. Point fromPos;
  627. Point destPos;
  628. // NOTE: two lines below return different positions (very notable with 2-hex creatures). Obtaining via creanims seems to be more precise
  629. fromPos = owner->creAnims[spi.stackID]->pos.topLeft();
  630. //xycoord = CClickableHex::getXYUnitAnim(shooter->position, true, shooter, owner);
  631. destPos = CClickableHex::getXYUnitAnim(dest, attackedStack, owner);
  632. // to properly translate coordinates when shooter is rotated
  633. int multiplier = spi.reverse ? -1 : 1;
  634. double projectileAngle = atan2(fabs((double)destPos.y - fromPos.y), fabs((double)destPos.x - fromPos.x));
  635. if(shooter->getPosition() < dest)
  636. projectileAngle = -projectileAngle;
  637. // Calculate projectile start position. Offsets are read out of the CRANIM.TXT.
  638. if (projectileAngle > straightAngle)
  639. {
  640. //upper shot
  641. spi.x0 = fromPos.x + 222 + ( -25 + shooterInfo->animation.upperRightMissleOffsetX ) * multiplier;
  642. spi.y0 = fromPos.y + 265 + shooterInfo->animation.upperRightMissleOffsetY;
  643. }
  644. else if (projectileAngle < -straightAngle)
  645. {
  646. //lower shot
  647. spi.x0 = fromPos.x + 222 + ( -25 + shooterInfo->animation.lowerRightMissleOffsetX ) * multiplier;
  648. spi.y0 = fromPos.y + 265 + shooterInfo->animation.lowerRightMissleOffsetY;
  649. }
  650. else
  651. {
  652. //straight shot
  653. spi.x0 = fromPos.x + 222 + ( -25 + shooterInfo->animation.rightMissleOffsetX ) * multiplier;
  654. spi.y0 = fromPos.y + 265 + shooterInfo->animation.rightMissleOffsetY;
  655. }
  656. spi.x = spi.x0;
  657. spi.y = spi.y0;
  658. destPos += Point(225, 225);
  659. // recalculate angle taking in account offsets
  660. //projectileAngle = atan2(fabs(destPos.y - spi.y), fabs(destPos.x - spi.x));
  661. //if(shooter->position < dest)
  662. // projectileAngle = -projectileAngle;
  663. if (attackedStack)
  664. {
  665. double animSpeed = AnimationControls::getProjectileSpeed(); // flight speed of projectile
  666. double distanceSquared = (destPos.x - spi.x) * (destPos.x - spi.x) + (destPos.y - spi.y) * (destPos.y - spi.y);
  667. double distance = sqrt(distanceSquared);
  668. spi.lastStep = std::round(distance / animSpeed);
  669. if(spi.lastStep == 0)
  670. spi.lastStep = 1;
  671. spi.dx = (destPos.x - spi.x) / spi.lastStep;
  672. spi.dy = (destPos.y - spi.y) / spi.lastStep;
  673. }
  674. else
  675. {
  676. // Catapult attack
  677. spi.catapultInfo.reset(new CatapultProjectileInfo(Point((int)spi.x, (int)spi.y), destPos));
  678. double animSpeed = AnimationControls::getProjectileSpeed() / 10;
  679. spi.lastStep = static_cast<int>(std::abs((destPos.x - spi.x) / animSpeed));
  680. spi.dx = animSpeed;
  681. spi.dy = 0;
  682. auto img = owner->idToProjectile[spi.creID]->getImage(0);
  683. // Add explosion anim
  684. Point animPos(destPos.x - 126 + img->width() / 2,
  685. destPos.y - 105 + img->height() / 2);
  686. owner->addNewAnim( new CEffectAnimation(owner, catapultDamage ? "SGEXPL.DEF" : "CSGRCK.DEF", animPos.x, animPos.y));
  687. }
  688. double pi = boost::math::constants::pi<double>();
  689. //in some cases (known one: hero grants shooter bonus to unit) the shooter stack's projectile may not be properly initialized
  690. if (!owner->idToProjectile.count(spi.creID) && !owner->idToRay.count(spi.creID))
  691. owner->initStackProjectile(shooter);
  692. if (owner->idToProjectile.count(spi.creID))
  693. {
  694. // only frames below maxFrame are usable: anything higher is either no present or we don't know when it should be used
  695. size_t maxFrame = std::min<size_t>(angles.size(), owner->idToProjectile.at(spi.creID)->size(0));
  696. assert(maxFrame > 0);
  697. // values in angles array indicate position from which this frame was rendered, in degrees.
  698. // find frame that has closest angle to one that we need for this shot
  699. size_t bestID = 0;
  700. double bestDiff = fabs( angles[0] / 180 * pi - projectileAngle );
  701. for (size_t i=1; i<maxFrame; i++)
  702. {
  703. double currentDiff = fabs( angles[i] / 180 * pi - projectileAngle );
  704. if (currentDiff < bestDiff)
  705. {
  706. bestID = i;
  707. bestDiff = currentDiff;
  708. }
  709. }
  710. spi.frameNum = static_cast<int>(bestID);
  711. }
  712. else if (owner->idToRay.count(spi.creID))
  713. {
  714. // no-op
  715. }
  716. else
  717. {
  718. logGlobal->error("Unable to find valid projectile for shooter %d", spi.creID);
  719. }
  720. // Set projectile animation start delay which is specified in frames
  721. spi.animStartDelay = shooterInfo->animation.attackClimaxFrame;
  722. owner->projectiles.push_back(spi);
  723. //attack animation
  724. shooting = true;
  725. if(projectileAngle > straightAngle)
  726. group = CCreatureAnim::SHOOT_UP;
  727. else if(projectileAngle < -straightAngle)
  728. group = CCreatureAnim::SHOOT_DOWN;
  729. else //straight shot
  730. group = CCreatureAnim::SHOOT_FRONT;
  731. return true;
  732. }
  733. void CShootingAnimation::nextFrame()
  734. {
  735. for(auto & it : owner->pendingAnims)
  736. {
  737. CMovementStartAnimation * anim = dynamic_cast<CMovementStartAnimation *>(it.first);
  738. CReverseAnimation * anim2 = dynamic_cast<CReverseAnimation *>(it.first);
  739. if( (anim && anim->stack->ID == stack->ID) || (anim2 && anim2->stack->ID == stack->ID && anim2->priority ) )
  740. return;
  741. }
  742. CAttackAnimation::nextFrame();
  743. }
  744. void CShootingAnimation::endAnim()
  745. {
  746. // play wall hit/miss sound for catapult attack
  747. if(!attackedStack)
  748. {
  749. if(catapultDamage > 0)
  750. {
  751. CCS->soundh->playSound("WALLHIT");
  752. }
  753. else
  754. {
  755. CCS->soundh->playSound("WALLMISS");
  756. }
  757. }
  758. CAttackAnimation::endAnim();
  759. delete this;
  760. }
  761. CCastAnimation::CCastAnimation(CBattleInterface * owner_, const CStack * attacker, BattleHex dest_, const CStack * defender)
  762. : CRangedAttackAnimation(owner_, attacker, dest_, defender)
  763. {
  764. if(!dest_.isValid() && defender)
  765. dest = defender->getPosition();
  766. }
  767. bool CCastAnimation::init()
  768. {
  769. if(!CAttackAnimation::checkInitialConditions())
  770. return false;
  771. if(!attackingStack || myAnim->isDead())
  772. {
  773. endAnim();
  774. return false;
  775. }
  776. //reverse unit if necessary
  777. if(attackedStack)
  778. {
  779. if(owner->getCurrentPlayerInterface()->cb->isToReverse(attackingStack->getPosition(), attackedStack->getPosition(), owner->creDir[attackingStack->ID], attackingStack->doubleWide(), owner->creDir[attackedStack->ID]))
  780. {
  781. owner->addNewAnim(new CReverseAnimation(owner, attackingStack, attackingStack->getPosition(), true));
  782. return false;
  783. }
  784. }
  785. else
  786. {
  787. if(dest.isValid() && owner->getCurrentPlayerInterface()->cb->isToReverse(attackingStack->getPosition(), dest, owner->creDir[attackingStack->ID], false, false))
  788. {
  789. owner->addNewAnim(new CReverseAnimation(owner, attackingStack, attackingStack->getPosition(), true));
  790. return false;
  791. }
  792. }
  793. //TODO: display spell projectile here
  794. static const double straightAngle = 0.2;
  795. Point fromPos;
  796. Point destPos;
  797. // NOTE: two lines below return different positions (very notable with 2-hex creatures). Obtaining via creanims seems to be more precise
  798. fromPos = owner->creAnims[attackingStack->ID]->pos.topLeft();
  799. //xycoord = CClickableHex::getXYUnitAnim(shooter->getPosition(), true, shooter, owner);
  800. destPos = CClickableHex::getXYUnitAnim(dest, attackedStack, owner);
  801. double projectileAngle = atan2(fabs((double)destPos.y - fromPos.y), fabs((double)destPos.x - fromPos.x));
  802. if(attackingStack->getPosition() < dest)
  803. projectileAngle = -projectileAngle;
  804. if(projectileAngle > straightAngle)
  805. group = CCreatureAnim::VCMI_CAST_UP;
  806. else if(projectileAngle < -straightAngle)
  807. group = CCreatureAnim::VCMI_CAST_DOWN;
  808. else
  809. group = CCreatureAnim::VCMI_CAST_FRONT;
  810. //fall back to H3 cast/2hex
  811. //even if creature have 2hex attack instead of cast it is ok since we fall back to attack anyway
  812. if(myAnim->framesInGroup(group) == 0)
  813. {
  814. if(projectileAngle > straightAngle)
  815. group = CCreatureAnim::CAST_UP;
  816. else if(projectileAngle < -straightAngle)
  817. group = CCreatureAnim::CAST_DOWN;
  818. else
  819. group = CCreatureAnim::CAST_FRONT;
  820. }
  821. //fall back to ranged attack
  822. if(myAnim->framesInGroup(group) == 0)
  823. {
  824. if(projectileAngle > straightAngle)
  825. group = CCreatureAnim::SHOOT_UP;
  826. else if(projectileAngle < -straightAngle)
  827. group = CCreatureAnim::SHOOT_DOWN;
  828. else
  829. group = CCreatureAnim::SHOOT_FRONT;
  830. }
  831. //fall back to normal attack
  832. if(myAnim->framesInGroup(group) == 0)
  833. {
  834. if(projectileAngle > straightAngle)
  835. group = CCreatureAnim::ATTACK_UP;
  836. else if(projectileAngle < -straightAngle)
  837. group = CCreatureAnim::ATTACK_DOWN;
  838. else
  839. group = CCreatureAnim::ATTACK_FRONT;
  840. }
  841. return true;
  842. }
  843. void CCastAnimation::nextFrame()
  844. {
  845. for(auto & it : owner->pendingAnims)
  846. {
  847. CReverseAnimation * anim = dynamic_cast<CReverseAnimation *>(it.first);
  848. if(anim && anim->stack->ID == stack->ID && anim->priority)
  849. return;
  850. }
  851. if(myAnim->getType() != group)
  852. {
  853. myAnim->setType(group);
  854. myAnim->onAnimationReset += std::bind(&CAttackAnimation::endAnim, this);
  855. }
  856. CBattleAnimation::nextFrame();
  857. }
  858. void CCastAnimation::endAnim()
  859. {
  860. CAttackAnimation::endAnim();
  861. delete this;
  862. }
  863. CEffectAnimation::CEffectAnimation(CBattleInterface * _owner, std::string _customAnim, int _x, int _y, int _dx, int _dy, bool _Vflip, bool _alignToBottom)
  864. : CBattleAnimation(_owner),
  865. destTile(BattleHex::INVALID),
  866. x(_x),
  867. y(_y),
  868. dx(_dx),
  869. dy(_dy),
  870. Vflip(_Vflip),
  871. alignToBottom(_alignToBottom)
  872. {
  873. logAnim->debug("Created effect animation %s", _customAnim);
  874. customAnim = std::make_shared<CAnimation>(_customAnim);
  875. }
  876. CEffectAnimation::CEffectAnimation(CBattleInterface * _owner, std::shared_ptr<CAnimation> _customAnim, int _x, int _y, int _dx, int _dy)
  877. : CBattleAnimation(_owner),
  878. destTile(BattleHex::INVALID),
  879. customAnim(_customAnim),
  880. x(_x),
  881. y(_y),
  882. dx(_dx),
  883. dy(_dy),
  884. Vflip(false),
  885. alignToBottom(false)
  886. {
  887. logAnim->debug("Created custom effect animation");
  888. }
  889. CEffectAnimation::CEffectAnimation(CBattleInterface * _owner, std::string _customAnim, BattleHex _destTile, bool _Vflip, bool _alignToBottom)
  890. : CBattleAnimation(_owner),
  891. destTile(_destTile),
  892. x(-1),
  893. y(-1),
  894. dx(0),
  895. dy(0),
  896. Vflip(_Vflip),
  897. alignToBottom(_alignToBottom)
  898. {
  899. logAnim->debug("Created effect animation %s", _customAnim);
  900. customAnim = std::make_shared<CAnimation>(_customAnim);
  901. }
  902. bool CEffectAnimation::init()
  903. {
  904. if(!isEarliest(true))
  905. return false;
  906. const bool areaEffect = (!destTile.isValid() && x == -1 && y == -1);
  907. std::shared_ptr<CAnimation> animation = customAnim;
  908. animation->preload();
  909. if(Vflip)
  910. animation->verticalFlip();
  911. auto first = animation->getImage(0, 0, true);
  912. if(!first)
  913. {
  914. endAnim();
  915. return false;
  916. }
  917. if(areaEffect) //f.e. armageddon
  918. {
  919. for(int i=0; i * first->width() < owner->pos.w ; ++i)
  920. {
  921. for(int j=0; j * first->height() < owner->pos.h ; ++j)
  922. {
  923. BattleEffect be;
  924. be.effectID = ID;
  925. be.animation = animation;
  926. be.currentFrame = 0;
  927. be.x = i * first->width() + owner->pos.x;
  928. be.y = j * first->height() + owner->pos.y;
  929. be.position = BattleHex::INVALID;
  930. owner->battleEffects.push_back(be);
  931. }
  932. }
  933. }
  934. else // Effects targeted at a specific creature/hex.
  935. {
  936. const CStack * destStack = owner->getCurrentPlayerInterface()->cb->battleGetStackByPos(destTile, false);
  937. BattleEffect be;
  938. be.effectID = ID;
  939. be.animation = animation;
  940. be.currentFrame = 0;
  941. //todo: lightning anim frame count override
  942. // if(effect == 1)
  943. // be.maxFrame = 3;
  944. be.x = x;
  945. be.y = y;
  946. if(destTile.isValid())
  947. {
  948. Rect & tilePos = owner->bfield[destTile]->pos;
  949. if(x == -1)
  950. be.x = tilePos.x + tilePos.w/2 - first->width()/2;
  951. if(y == -1)
  952. {
  953. if(alignToBottom)
  954. be.y = tilePos.y + tilePos.h - first->height();
  955. else
  956. be.y = tilePos.y - first->height()/2;
  957. }
  958. // Correction for 2-hex creatures.
  959. if(destStack != nullptr && destStack->doubleWide())
  960. be.x += (destStack->side == BattleSide::ATTACKER ? -1 : 1)*tilePos.w/2;
  961. }
  962. assert(be.x != -1 && be.y != -1);
  963. //Indicate if effect should be drawn on top of everything or just on top of the hex
  964. be.position = destTile;
  965. owner->battleEffects.push_back(be);
  966. }
  967. //battleEffects
  968. return true;
  969. }
  970. void CEffectAnimation::nextFrame()
  971. {
  972. //notice: there may be more than one effect in owner->battleEffects correcponding to this animation (ie. armageddon)
  973. for(auto & elem : owner->battleEffects)
  974. {
  975. if(elem.effectID == ID)
  976. {
  977. elem.currentFrame += AnimationControls::getSpellEffectSpeed() * GH.mainFPSmng->getElapsedMilliseconds() / 1000;
  978. if(elem.currentFrame >= elem.animation->size())
  979. {
  980. endAnim();
  981. break;
  982. }
  983. else
  984. {
  985. elem.x += dx;
  986. elem.y += dy;
  987. }
  988. }
  989. }
  990. }
  991. void CEffectAnimation::endAnim()
  992. {
  993. CBattleAnimation::endAnim();
  994. std::vector<std::list<BattleEffect>::iterator> toDel;
  995. for(auto it = owner->battleEffects.begin(); it != owner->battleEffects.end(); ++it)
  996. {
  997. if(it->effectID == ID)
  998. {
  999. toDel.push_back(it);
  1000. }
  1001. }
  1002. for(auto & elem : toDel)
  1003. {
  1004. owner->battleEffects.erase(elem);
  1005. }
  1006. delete this;
  1007. }