CFadeAnimation.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /*
  2. * CFadeAnimation.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 "CFadeAnimation.h"
  12. #include "../renderSDL/SDL_Extensions.h"
  13. #include <SDL_surface.h>
  14. float CFadeAnimation::initialCounter() const
  15. {
  16. if (fadingMode == EMode::OUT)
  17. return 1.0f;
  18. return 0.0f;
  19. }
  20. void CFadeAnimation::update()
  21. {
  22. if (!fading)
  23. return;
  24. if (fadingMode == EMode::OUT)
  25. fadingCounter -= delta;
  26. else
  27. fadingCounter += delta;
  28. if (isFinished())
  29. {
  30. fading = false;
  31. if (shouldFreeSurface)
  32. {
  33. SDL_FreeSurface(fadingSurface);
  34. fadingSurface = nullptr;
  35. }
  36. }
  37. }
  38. bool CFadeAnimation::isFinished() const
  39. {
  40. if (fadingMode == EMode::OUT)
  41. return fadingCounter <= 0.0f;
  42. return fadingCounter >= 1.0f;
  43. }
  44. CFadeAnimation::CFadeAnimation()
  45. : delta(0), fadingSurface(nullptr), fading(false), fadingCounter(0), shouldFreeSurface(false),
  46. fadingMode(EMode::NONE)
  47. {
  48. }
  49. CFadeAnimation::~CFadeAnimation()
  50. {
  51. if (fadingSurface && shouldFreeSurface)
  52. SDL_FreeSurface(fadingSurface);
  53. }
  54. void CFadeAnimation::init(EMode mode, SDL_Surface * sourceSurface, bool freeSurfaceAtEnd, float animDelta)
  55. {
  56. if (fading)
  57. {
  58. // in that case, immediately finish the previous fade
  59. // (alternatively, we could just return here to ignore the new fade request until this one finished (but we'd need to free the passed bitmap to avoid leaks))
  60. logGlobal->warn("Tried to init fading animation that is already running.");
  61. if (fadingSurface && shouldFreeSurface)
  62. SDL_FreeSurface(fadingSurface);
  63. }
  64. if (animDelta <= 0.0f)
  65. {
  66. logGlobal->warn("Fade anim: delta should be positive; %f given.", animDelta);
  67. animDelta = DEFAULT_DELTA;
  68. }
  69. if (sourceSurface)
  70. fadingSurface = sourceSurface;
  71. delta = animDelta;
  72. fadingMode = mode;
  73. fadingCounter = initialCounter();
  74. fading = true;
  75. shouldFreeSurface = freeSurfaceAtEnd;
  76. }
  77. void CFadeAnimation::draw(SDL_Surface * targetSurface, const Point &targetPoint)
  78. {
  79. if (!fading || !fadingSurface || fadingMode == EMode::NONE)
  80. {
  81. fading = false;
  82. return;
  83. }
  84. CSDL_Ext::setAlpha(fadingSurface, (int)(fadingCounter * 255));
  85. CSDL_Ext::blitSurface(fadingSurface, targetSurface, targetPoint); //FIXME
  86. CSDL_Ext::setAlpha(fadingSurface, 255);
  87. }