Skip to content

Instantly share code, notes, and snippets.

@v21
Created June 3, 2014 13:31
Show Gist options
  • Save v21/5f3ea035cc0c349f8d1a to your computer and use it in GitHub Desktop.
Save v21/5f3ea035cc0c349f8d1a to your computer and use it in GitHub Desktop.
RGB to HSV and vice versa (in shaders)
float3 Hue(float H)
{
float R = abs(H * 6 - 3) - 1;
float G = 2 - abs(H * 6 - 2);
float B = 2 - abs(H * 6 - 4);
return saturate(float3(R,G,B));
}
float3 HSVtoRGB(in float3 HSV)
{
return ((Hue(HSV.x) - 1) * HSV.y + 1) * HSV.z;
}
float3 RGBtoHSV(in float3 RGB)
{
float3 HSV = 0;
HSV.z = max(RGB.r, max(RGB.g, RGB.b));
float M = min(RGB.r, min(RGB.g, RGB.b));
float C = HSV.z - M;
if (C != 0)
{
HSV.y = C / HSV.z;
float3 Delta = (HSV.z - RGB) / C;
Delta.rgb -= Delta.brg;
Delta.rg += float2(2,4);
if (RGB.r >= HSV.z)
HSV.x = Delta.b;
else if (RGB.g >= HSV.z)
HSV.x = Delta.r;
else
HSV.x = Delta.g;
HSV.x = frac(HSV.x / 6);
}
return HSV;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment