esp32-sk6812/src/Animation/AnimationController.cpp

140 lines
3.5 KiB
C++

#include "Animation/AnimationController.h"
#include "Animation/AllAnimations.h"
#include "Font.h"
const constexpr
std::array<const char*, AnimationController::NUM_DEFAULT_ANIMATIONS>
AnimationController::AnimationNames;
AnimationController::AnimationController(Fader *fader)
: m_fader(fader), m_animation(nullptr), m_frame(0), m_animationInitiator(NONE), m_lastDefaultAnimation(FIRE_HOT)
{
m_updateMutex = xSemaphoreCreateMutex();
}
void AnimationController::changeAnimation(std::unique_ptr<Animation> anim, bool transition,
AnimationController::AnimationInitiator animInitiator)
{
xSemaphoreTake(m_updateMutex, portMAX_DELAY);
if(transition && m_animation) {
m_nextAnimation = std::move(anim);
m_animation->stop();
} else {
m_frame = 0;
m_animation = std::move(anim);
m_nextAnimation.reset(nullptr);
}
m_animationInitiator = animInitiator;
xSemaphoreGive(m_updateMutex);
}
void AnimationController::changeAnimation(AnimationController::DefaultAnimation animation_id, bool transition,
AnimationController::AnimationInitiator animInitiator)
{
std::unique_ptr<Animation> anim(nullptr);
switch(animation_id) {
case FIRE_HOT:
anim.reset(new FireAnimation(m_fader, false));
break;
case FIRE_COLD:
anim.reset(new FireAnimation(m_fader, true));
break;
case SNOWFALL:
anim.reset(new SnowfallAnimation(m_fader));
break;
case MATRIX_CODE:
anim.reset(new MatrixCodeAnimation(m_fader));
break;
case FIREWORK:
anim.reset(new FireworkAnimation(m_fader, 64, 1));
break;
case FONT_TEST:
{
Bitmap bmp(0, 0);
Font::textToBitmap("Hello World! ABCDEFGHIJKLMNOPQRSTUVWXYZ", &bmp, Fader::Color{0, 0, 32, 32});
changeAnimation(std::unique_ptr<Animation>(new ImageScrollerAnimation(m_fader, &bmp, 5)), transition);
}
break;
case STELLAR:
anim.reset(new StellarAnimation(m_fader));
break;
case RGBW_SINUS:
anim.reset(new RgbwSinusAnimation(m_fader));
break;
case RGBW_PSYCHEDELIC:
anim.reset(new RgbwPsychedelicAnimation(m_fader));
break;
case CHRISTMAS_GLITTER:
anim.reset(new ChristmasGlitterAnimation(m_fader));
break;
case RACERS:
anim.reset(new RacerAnimation(m_fader, m_fader->strips() * m_fader->modules_per_strip() / 8));
break;
default:
return; // unknown id, do nothing
}
m_lastDefaultAnimation = animation_id;
if(anim) {
changeAnimation(std::move(anim), transition, animInitiator);
}
}
void AnimationController::loop(void)
{
xSemaphoreTake(m_updateMutex, portMAX_DELAY);
if(m_animation && !m_animation->finished()) {
m_animation->loop(m_frame);
}
m_frame++;
if(m_nextAnimation &&
(!m_animation || m_animation->finished())) {
// old animation has finished or is unset -> start the new one
m_frame = 0;
m_animation.swap(m_nextAnimation);
m_nextAnimation.reset(nullptr);
}
xSemaphoreGive(m_updateMutex);
}
void AnimationController::stop(void)
{
if(m_animation) {
m_animation->stop();
}
}
void AnimationController::restart(void)
{
if(m_animation) {
m_animation->reset();
}
m_frame = 0;
}