Skip to content

Instantly share code, notes, and snippets.

@Aeldrion
Last active December 30, 2023 10:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Aeldrion/48c82912f632eec4c8b9da7394b89c5d to your computer and use it in GitHub Desktop.
Save Aeldrion/48c82912f632eec4c8b9da7394b89c5d to your computer and use it in GitHub Desktop.
GLSL functions for HSV to RGB and RGB to HSV conversion
vec3 hsv_to_rgb(vec3 color) {
// Translates HSV color to RGB color
// H: 0.0 - 360.0, S: 0.0 - 100.0, V: 0.0 - 100.0
// R, G, B: 0.0 - 1.0
float hue = color.x;
float saturation = color.y;
float value = color.z;
float c = (value/100) * (saturation/100);
float x = c * (1 - abs(mod(hue/60, 2) - 1));
float m = (value/100) - c;
float r = 0;
float g = 0;
float b = 0;
if (hue >= 0 && hue < 60) {
r = c;
g = x;
b = 0;
} else if (hue >= 60 && hue < 120) {
r = x;
g = c;
b = 0;
} else if (hue >= 120 && hue < 180) {
r = 0;
g = c;
b = x;
} else if (hue >= 180 && hue < 240) {
r = 0;
g = x;
b = c;
} else if (hue >= 240 && hue < 300) {
r = x;
g = 0;
b = c;
} else if (hue >= 300 && hue < 360) {
r = c;
g = 0;
b = x;
}
r += m;
g += m;
b += m;
return vec3(r, g, b);
}
vec3 rgb_to_hsv(vec3 color) {
// Translates RGB to HSV
// R, G, B: 0.0 - 1.0
// H: 0.0 - 360.0, S: 0.0 - 100.0, V: 0.0 - 100.0
float cmax = max(color.r, max(color.g, color.b));
float cmin = min(color.r, min(color.g, color.b));
float delta = cmax - cmin;
float hue = 0;
float saturation = 0;
float value = 0;
// Hue calculation
if (delta = 0) {
hue = 0;
} else if (cmax = color.r) {
hue = 60 * mod((color.g - color.b)/delta, 6);
} else if (cmax = color.g) {
hue = 60 * ((color.b - color.r)/delta + 2);
} else {
hue = 60 * ((color.r - color.b)/delta + 4);
}
// Saturation calculation
if (cmax = 0) {
saturation = 0;
} else {
saturation = delta/cmax;
}
// Value
value = cmax;
return vec3(hue, saturation, value);
}
vec4 rgba_to_hsva(vec4 color) {
return vec4(rgb_to_hsv(color.rgb), color.a);
}
vec4 hsva_to_rgba(vec4 color) {
return vec4(hsv_to_rgb(color.xyz), color.a);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment