git.haldean.org plotter / master lib / hsvrgb.cpp
master

Tree @master (Download .tar.gz)

hsvrgb.cpp @masterraw · history · blame

#include <cmath>

void
hsv2rgb(double h, double s, double v, double &r, double &g, double &b)
{
    double      hh, p, q, t, ff;
    long        i;

    if(s <= 0.0) {       // < is bogus, just shuts up warnings
        r = v;
        g = v;
        b = v;
        return;
    }
    hh = h;
    if(hh >= 360.0) hh = 0.0;
    hh /= 60.0;
    i = (long)hh;
    ff = hh - i;
    p = v * (1.0 - s);
    q = v * (1.0 - (s * ff));
    t = v * (1.0 - (s * (1.0 - ff)));

    switch(i) {
    case 0:
        r = v;
        g = t;
        b = p;
        break;
    case 1:
        r = q;
        g = v;
        b = p;
        break;
    case 2:
        r = p;
        g = v;
        b = t;
        break;

    case 3:
        r = p;
        g = q;
        b = v;
        break;
    case 4:
        r = t;
        g = p;
        b = v;
        break;
    case 5:
    default:
        r = v;
        g = p;
        b = q;
        break;
    }
}

void rainbow(double t, uint8_t &r, uint8_t &g, uint8_t &b) {
  double rd, gd, bd;
  hsv2rgb(360.0 * t, 1, 1, rd, gd, bd);
  r = floor(255 * rd);
  g = floor(255 * gd);
  b = floor(255 * bd);
}