Code Snippet: HSV to RGB and Vice versa in Shader


This Code snipped will show two custom operation that we normally need to use in our post effect shaders. They are the conversion between the RGB space to HSV and vice versa.

The shader is pretty simple and is shown below (this code is used inside a post effect, you can grab the HSVtoRBG and the RGBtoHSV functions and use at your own):

float2 halfPixel;
float4 toAdd;
float4 toMultiply;

texture cena;
sampler cenaSampler = sampler_state
{
   Texture = ;
   MinFilter = LINEAR;
   MagFilter = LINEAR;
   MipFilter = LINEAR;
   AddressU  = Clamp;
   AddressV  = Clamp;
};

struct VertexShaderOutput
{
    float4 Position : POSITION0;
    float2 TexCoord : TEXCOORD0;
    float2 Pos : TEXCOORD1;
};
VertexShaderOutput VShader( float4 Pos: POSITION, float2 Tex : TEXCOORD)
{
	VertexShaderOutput output;
    output.Position = float4(Pos);
    output.Pos = float4(Pos);
    output.TexCoord = Tex - halfPixel;
    return output;
}

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));
}

float4 HSVtoRGB(in float3 HSV)
{
    return float4(((Hue(HSV.x) - 1) * HSV.y + 1) * HSV.z,1);
}

float4 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 float4(HSV,1);
}

float4 PShader(VertexShaderOutput input) : COLOR
{
    float4 cen = tex2D(cenaSampler ,input.TexCoord );
    return HSVtoRGB(toMultiply * RGBtoHSV(cen) + toAdd);

}

technique Normal
{
	pass P0
	{
		VertexShader = compile vs_3_0 VShader();
		PixelShader = compile ps_3_0 PShader();
	}
}

, ,

  1. #1 by auto insurance rates San Mateo CA on 21 de julho de 2017 - 3:06 pm

    I told my kids we’d play after I found what I needed. Damnit.

  2. #2 by Bangla Sahib on 21 de julho de 2017 - 3:33 pm

    I’m extremely impressed with your writing skills as well as with
    the layout on your weblog. Is this a paid theme or did you modify it yourself?
    Either way keep up the nice quality writing, it’s rare to see
    a nice blog like this one today.

  3. #3 by ostrich egg on 21 de julho de 2017 - 3:48 pm

    Hey, basically grew to become tuned in to ones weblog by means of Search engines, and located it is really helpful. I shall be watchful for the town. I’ll be pleased just in case you proceed this from now on. A lot of people might be gained from a writing. Cheers!

1 569 570 571
(não será publicado)