Skip to content

Instantly share code, notes, and snippets.

@matteocaberlotto
Created June 19, 2024 07:31
Show Gist options
  • Save matteocaberlotto/0eb56d0c3e918de451670a003d0831bc to your computer and use it in GitHub Desktop.
Save matteocaberlotto/0eb56d0c3e918de451670a003d0831bc to your computer and use it in GitHub Desktop.
An helper to cycle RGB colors in cpp
/**
* Example usage:
Color *colors[100] = {
new Color(255,0,0),
new Color(0,255,0),
new Color(0,0,255)
};
ColorLoop *loop = new ColorLoop(colors, 3, 50);
while (true) {
loop->nextStep();
// do your stuff with updated color
// loop will continuously cycle through colors
}
*
*/
/**
* Color representation
*/
class Color
{
int m_red;
int m_green;
int m_blue;
public:
Color(int r, int g, int b)
{
m_red = r;
m_green = g;
m_blue = b;
}
int red()
{
return m_red;
}
int green()
{
return m_green;
}
int blue()
{
return m_blue;
}
void update(int r, int g, int b)
{
m_red = r;
m_green = g;
m_blue = b;
}
};
/**
* Represent transition between two colors.
*/
class ColorTransition
{
Color *m_source;
Color *m_destination;
Color *m_current;
int m_steps;
int m_progress;
public:
ColorTransition(Color *source, Color *destination, int steps = 100)
{
m_source = source;
m_current = new Color(
source->red(),
source->green(),
source->blue()
);
m_destination = destination;
m_steps = steps;
m_progress = 0;
}
bool complete()
{
return m_progress == m_steps;
}
void nextStep()
{
int r = (int) (m_source->red() + m_progress * (m_destination->red() - m_source->red()) / (m_steps - 1));
int g = (int) (m_source->green() + m_progress * (m_destination->green() - m_source->green()) / (m_steps - 1));
int b = (int) (m_source->blue() + m_progress * (m_destination->blue() - m_source->blue()) / (m_steps - 1));
m_current->update(r, g, b);
m_progress++;
}
Color* current()
{
return m_current;
}
};
/**
* Handles transition between colors from an array.
*/
class ColorLoop
{
int m_size = 0;
int m_steps = 0;
int m_index = 0;
ColorTransition *m_ct = NULL;
Color **m_colors;
public:
ColorLoop(Color **colors, int size, int steps)
{
m_colors = colors;
m_size = size;
m_steps = steps;
}
void nextStep()
{
if (!m_ct || m_ct->complete()) {
this->nextTransition();
}
m_ct->nextStep();
}
Color* current()
{
return m_ct->current();
}
void nextTransition()
{
if (m_index > m_size - 1) {
m_index = 0;
}
int next = m_index + 1;
if (next > m_size - 1) {
next = 0;
}
m_ct = new ColorTransition(
m_colors[m_index],
m_colors[next],
m_steps
);
m_index++;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment