esp32-sk6812/src/Fader.cpp

120 lines
2.9 KiB
C++
Raw Normal View History

#include "Fader.h"
Fader::Fader(std::size_t nstrips, std::size_t nmodules_per_strip, uint8_t fadestep, uint32_t flip_strips_mask)
: m_strips(nstrips),
m_modulesPerStrip(nmodules_per_strip),
m_fadestep(fadestep),
m_flipStripsMask(flip_strips_mask),
m_curColor(nstrips * nmodules_per_strip),
m_targetColor(nstrips * nmodules_per_strip)
{}
void Fader::set_color(uint32_t strip, uint32_t module, const Fader::Color &color)
{
uint32_t idx = make_module_idx(strip, module);
m_targetColor[idx] = m_curColor[idx] = color;
m_somethingChanged = true;
}
void Fader::add_color(uint32_t strip, uint32_t module, const Fader::Color &color)
{
uint32_t idx = make_module_idx(strip, module);
m_curColor[idx] += color;
m_curColor[idx].normalize();
m_targetColor[idx] += color;
m_targetColor[idx].normalize();
m_somethingChanged = true;
}
void Fader::fade_color(uint32_t strip, uint32_t module, const Fader::Color &color)
{
uint32_t idx = make_module_idx(strip, module);
m_targetColor[idx] = color;
m_somethingChanged = true;
}
void Fader::set_color(const Fader::Color &color)
{
for(std::size_t module = 0; module < m_curColor.size(); module++) {
m_targetColor[module] = m_curColor[module] = color;
}
m_somethingChanged = true;
}
void Fader::add_color(const Fader::Color &color)
{
for (std::size_t module = 0; module < m_curColor.size(); module++) {
m_curColor[module] += color;
m_curColor[module].normalize();
m_targetColor[module] += color;
m_targetColor[module].normalize();
}
m_somethingChanged = true;
}
void Fader::fade_color(const Fader::Color &color)
{
for (std::size_t module = 0; module < m_curColor.size(); module++) {
m_targetColor[module] = color;
}
}
void Fader::set_fadestep(uint8_t newFadestep)
{
m_fadestep = newFadestep;
}
/* internal function */
bool Fader::update_fade(int16_t *cur, const int16_t *target)
{
int16_t diff;
if(*cur > *target) {
diff = *cur - *target;
if(diff < m_fadestep) {
*cur = *target;
} else {
*cur -= m_fadestep;
}
return true;
} else if(*cur < *target) {
diff = *target - *cur;
if(diff < m_fadestep) {
*cur = *target;
} else {
*cur += m_fadestep;
}
return true;
}
return false;
}
void Fader::update(void)
{
for(std::size_t i = 0; i < m_curColor.size(); i++) {
m_somethingChanged = update_fade(&(m_curColor[i].r), &(m_targetColor[i].r)) || m_somethingChanged;
m_somethingChanged = update_fade(&(m_curColor[i].g), &(m_targetColor[i].g)) || m_somethingChanged;
m_somethingChanged = update_fade(&(m_curColor[i].b), &(m_targetColor[i].b)) || m_somethingChanged;
m_somethingChanged = update_fade(&(m_curColor[i].w), &(m_targetColor[i].w)) || m_somethingChanged;
}
}
uint32_t Fader::make_module_idx(uint32_t strip, uint32_t module)
{
bool flip = m_flipStripsMask & (1 << strip);
if(flip) {
module = m_modulesPerStrip - module - 1;
}
return strip * m_modulesPerStrip + module;
}