File indexing completed on 2024-02-18 04:04:51

0001 /*
0002     SPDX-FileCopyrightText: 2007 Paolo Capriotti <p.capriotti@gmail.com>
0003 
0004     SPDX-License-Identifier: GPL-2.0-or-later
0005 */
0006 #include "animation.h"
0007 #include "knavalbattle_debug.h"
0008 
0009 Animation::~Animation()
0010 {
0011     Q_EMIT done();
0012 }
0013 
0014 AnimationGroup::AnimationGroup()
0015 : m_running(-1)
0016 {
0017 }
0018 
0019 AnimationGroup::~AnimationGroup()
0020 {
0021     stop();
0022 }
0023 
0024 void AnimationGroup::start(int t)
0025 {
0026     m_running = t;
0027     for (Animation* a : std::as_const(m_animations)) {
0028         a->start(t);
0029     }
0030 }
0031 
0032 void AnimationGroup::stop()
0033 {
0034     m_running = -1;
0035     qDeleteAll(m_animations);
0036     m_animations.clear();
0037 }
0038 
0039 bool AnimationGroup::step(int t)
0040 {
0041     m_running = t;
0042     for (Animations::iterator i = m_animations.begin();
0043             i != m_animations.end(); ) {
0044         if ((*i)->step(t)) {
0045             delete *i;
0046             i = m_animations.erase(i);
0047         }
0048         else {
0049             ++i;
0050         }
0051     }
0052     return m_animations.empty();
0053 }
0054 
0055 void AnimationGroup::add(Animation* a)
0056 {
0057     m_animations.append(a);
0058     if (m_running != -1) {
0059         a->start(m_running);
0060     }
0061 }
0062 
0063 FadeAnimation::FadeAnimation(QGraphicsItem* sprite, int from, qreal to, int time)
0064 : m_sprite(sprite)
0065 , m_from(from)
0066 , m_to(to)
0067 , m_time(time)
0068 , m_start(0)
0069 {
0070 }
0071 
0072 void FadeAnimation::start(int t)
0073 {
0074     m_start = t;
0075     m_sprite->setOpacity(m_from);
0076 }
0077 
0078 bool FadeAnimation::step(int t)
0079 {
0080     if (t >= m_time + m_start) {
0081         m_sprite->setOpacity(m_to);
0082         return true;
0083     }
0084     else {
0085         if (m_to > m_from) {
0086             m_sprite->setOpacity(m_from + t * (m_to / m_time));
0087         }
0088         else {
0089             m_sprite->setOpacity(m_from - t * (m_to / m_time));
0090         }
0091         return false;
0092     }
0093 }
0094 
0095 
0096 MovementAnimation::MovementAnimation(QGraphicsItem* sprite, const QPointF& from, 
0097                                      const QPointF& to, int time)
0098 : m_sprite(sprite)
0099 , m_from(from)
0100 , m_to(to)
0101 , m_time(time)
0102 , m_start(0)
0103 {
0104 }
0105 
0106 void MovementAnimation::start(int t)
0107 {
0108     m_start = t;
0109     m_sprite->setPos(m_from);
0110 }
0111 
0112 bool MovementAnimation::step(int t)
0113 {
0114     if (t >= m_start + m_time) {
0115         m_sprite->setPos(m_to);
0116         return true;
0117     }
0118     else {
0119         QPointF pos = m_from + (m_to - m_from) * (t - m_start) / m_time;
0120         m_sprite->setPos(pos);
0121         return false;
0122     }
0123 }
0124 
0125 #include "moc_animation.cpp"