Sharing Code: HSV to RGB & Line Drawing Functions

Hey Everyone,

New LittleFoot/Blocks developer here. After noodling a bit with LittleFoot, I ported a few functions for drawing that are pretty common, but missing from the core LightFoot’s API. I figured I would share them here in case anyone else found them useful.

First one up is a line drawing function based on Bresenham’s Line Drawing Algorithm:

int c : the colour of the line to draw
int x0 : the line’s beginning x position
int y0 : the line’s beginning y position
int x1 : the line’s ending x position
int y1 : the line’s ending y position

The range for the values: 0,0 = left/top, 15/15 = right/bottom

void line(int c, int x0, int y0, int x1, int y1) {
 
  int dx = abs(x1-x0), sx = x0<x1 ? 1 : -1;
  int dy = abs(y1-y0), sy = y0<y1 ? 1 : -1; 
  int err = (dx>dy ? dx : -dy)/2, e2;
 
  while(true){
    fillPixel(c, x0, y0);
    if (x0==x1 && y0==y1) break;
    e2 = err;
    if (e2 >-dx) { err -= dy; x0 += sx; }
    if (e2 < dy) { err += dx; y0 += sy; }
  }
}

Next is a Hue/Saturation/Value to Red/Green/Blue colour conversion function that supports alpha as well. Since the fmod function is also missing from LittleFoot but required by the algorithm I added a really crap (but sufficient for this use) version; you will need to add both functions for this to work.

The function returns a LittleFoot ARGB colour as an integer.

float h : hue (range 0.0 to 1.0)
float s : saturation (range 0.0 to 1.0)
float v : value (range 0.0 to 1.0)
float a : alpha (range 0.0 to 1.0)

int hsv2rgb(float h, float s, float v, float a)
{   
    float H = h * 360.0;
    float C = s*v;
    float X = C*(1-abs(fmod(H/60.0, 2.0)-1));
    float m = v-C;
    float r,g,b;
    
    if(H >= 0 && H < 60){
        r = C; g = X; b = 0;
    }
    else if(H >= 60 && H < 120){
        r = X;g = C;b = 0;
    }
    else if(H >= 120 && H < 180){
        r = 0;g = C;b = X;
    }
    else if(H >= 180 && H < 240){
        r = 0;g = X;b = C;
    }
    else if(H >= 240 && H < 300){
        r = X;g = 0;b = C;
    }
    else{
        r = C;g = 0;b = X;
    }
    
    int R = int((r + m) * 255);
    int G = int((g + m) * 255);
    int B = int((b + m) * 255);
    int A = int(a * 255);
    return (A << 24) | (R << 16) | (G << 8) | B;    
}

float fmod(float a, float b)
{
    int adb = int(a / b);
    return ((a - adb * b));
}

Cheers!

3 Likes