sftools  2.0 dev
Bunch of tools for SFML application development
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Pages
Animation/Animation.hpp
Go to the documentation of this file.
1 /*
2 
3  sftools - Copyright (c) 2012-2013 Marco Antognini <antognini.marco@gmail.com>
4 
5  This software is provided 'as-is', without any express or implied warranty. In
6  no event will the authors be held liable for any damages arising from the use
7  of this software.
8 
9  Permission is granted to anyone to use this software for any purpose, including
10  commercial applications, and to alter it and redistribute it freely, subject to
11  the following restrictions:
12 
13  1. The origin of this software must not be misrepresented; you must not claim
14  that you wrote the original software. If you use this software in a product,
15  an acknowledgment in the product documentation would be appreciated but is
16  not required.
17 
18  2. Altered source versions must be plainly marked as such, and must not be
19  misrepresented as being the original software.
20 
21  3. This notice may not be removed or altered from any source distribution.
22 
23  */
24 
30 #ifndef __SFTOOLS_ANIMATION_HPP__
31 #define __SFTOOLS_ANIMATION_HPP__
32 
33 #include <SFML/Graphics/Drawable.hpp>
34 #include <SFML/Graphics/Transformable.hpp>
35 
37 
42 namespace sftools
43 {
44 
54  class Animation : public sf::Drawable, public sf::Transformable
55  {
56  public:
64  Animation(FrameStream const& stream, sf::Time initialTime = sf::Time::Zero)
65  : m_stream(0)
66  {
67  setFrameStream(stream);
68  restart(initialTime);
69  }
70 
76  void setFrameStream(FrameStream const& stream)
77  {
78  m_stream = &stream;
79 
80  updateRender();
81  }
82 
88  void restart(sf::Time initialTime = sf::Time::Zero)
89  {
90  m_timeElapsed = initialTime;
91 
92  updateRender();
93  }
94 
104  void update(sf::Time dt)
105  {
106  m_timeElapsed += dt;
107 
108  updateRender();
109  }
110 
116  virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const
117  {
118  // Note : if the stream was not set it will simply draw nothing, like a sprite without any texture
119 
120  states.transform *= getTransform();
121  target.draw(m_sprite, states);
122  }
123 
124  private:
130  void updateRender()
131  {
132  if (m_stream)
133  {
134  Frame frame = m_stream->getFrameAt(m_timeElapsed);
135 
136  if (frame.texture) m_sprite.setTexture(*frame.texture);
137  m_sprite.setTextureRect(frame.area);
138  m_sprite.setColor(frame.color);
139  }
140  }
141 
142  private:
143  FrameStream const* m_stream;
144  sf::Time m_timeElapsed;
145  sf::Sprite m_sprite;
146  };
147 
148 }
149 
150 #endif // __SFTOOLS_ANIMATION_HPP__