AnimTimer.h 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /*
  2. * Copyright 2015 Google Inc.
  3. *
  4. * Use of this source code is governed by a BSD-style license that can be
  5. * found in the LICENSE file.
  6. */
  7. #include "include/core/SkScalar.h"
  8. #include "include/core/SkTime.h"
  9. #ifndef AnimTimer_DEFINED
  10. #define AnimTimer_DEFINED
  11. /**
  12. * Class to track a "timer". It supports 3 states: stopped, paused, and running.
  13. * Playback speed is variable.
  14. *
  15. * The caller must call updateTime() to resync with the clock (typically just before
  16. * using the timer). Forcing the caller to do this ensures that the timer's return values
  17. * are consistent if called repeatedly, as they only reflect the time since the last
  18. * calle to updateTimer().
  19. */
  20. class AnimTimer {
  21. public:
  22. /**
  23. * Class begins in the "stopped" state.
  24. */
  25. AnimTimer() {}
  26. enum State { kStopped_State, kPaused_State, kRunning_State };
  27. State state() const { return fState; }
  28. double nanos() const { return fElapsedNanos; }
  29. /**
  30. * Control the rate at which time advances.
  31. */
  32. float getSpeed() const { return fSpeed; }
  33. void setSpeed(float speed) { fSpeed = speed; }
  34. /**
  35. * If the timer is paused or stopped, it will resume (or start if it was stopped).
  36. */
  37. void run() {
  38. switch (this->state()) {
  39. case kStopped_State:
  40. fPreviousNanos = SkTime::GetNSecs();
  41. fElapsedNanos = 0;
  42. break;
  43. case kPaused_State: // they want "resume"
  44. fPreviousNanos = SkTime::GetNSecs();
  45. break;
  46. case kRunning_State: break;
  47. }
  48. fState = kRunning_State;
  49. }
  50. void pause() {
  51. if (kRunning_State == this->state()) {
  52. fState = kPaused_State;
  53. } // else stay stopped or paused
  54. }
  55. /**
  56. * If the timer is stopped, start running, else it toggles between paused and running.
  57. */
  58. void togglePauseResume() {
  59. if (kRunning_State == this->state()) {
  60. this->pause();
  61. } else {
  62. this->run();
  63. }
  64. }
  65. /**
  66. * Call this each time you want to sample the clock for the timer. This is NOT done
  67. * automatically, so that repeated calls to msec() or secs() will always return the
  68. * same value.
  69. *
  70. * This may safely be called with the timer in any state.
  71. */
  72. void updateTime() {
  73. if (kRunning_State == this->state()) {
  74. double now = SkTime::GetNSecs();
  75. fElapsedNanos += (now - fPreviousNanos) * fSpeed;
  76. fPreviousNanos = now;
  77. }
  78. }
  79. private:
  80. double fPreviousNanos = 0;
  81. double fElapsedNanos = 0;
  82. float fSpeed = 1;
  83. State fState = kStopped_State;
  84. };
  85. #endif