Dot Product

I've typed this example straight into blogspot so who knows what will happen if you paste it straight into your IDE?
Here we're using the dot product to create a basic fresnel rim shader. We allow the user to specify the colour of the rim and also the falloff. Things of note - in the Input struct we have a vector viewDir, which is the normal that the user- or camera -has of the object. We want to calculate the DOT product of  this vector with the surface normal.

Without going into the actual maths - the dot prodcut will return a value of 1 if the 2 vectors are aligned in the same direction. They return a value of 0 if the vectors are at 90degrees/Perpendicular. They return a value of -1 if they are in opposite directions.

In the surface function we take the 1- dotproduct, so that we get a 0 value on the polygons that face us and a 1 value on the polygons that are towards the edges. We then raise this value to the power of _rimPower, to make the falloff sharper or smoother, then multiply this by the color.rgb.

 It's important not to label your dotproduct variable as "dot", as this seems to get the compiler confused - it is a function after all.

 

 Shader "Dave/dotProd"

{

    CGPROGRAM

    Properties

    {

        _rimColor("rim",color)=(1,1,1,1)

        _rimPower("rimPower",Range(0.5,3)=1

    }

    SubShader

    {

        #pragma surface surf Lambert

        struct Input

        {

            float3 viewDir;

        };

 

        fixed4 _rimColor;

        float _rimPower;

    void surf(Input IN, inout SurfaceOutput o)
    {

      half dotproduct=1-dot(IN.viewDir,o.normal);

    o.Albedo= _rimColor.rgb*pow(dotproduct,_rimPower);

      }

    ENDCG

}

Fallback "Diffuse"

}

Comments

Popular posts from this blog

Unity's "new" input system and Keijiro's Minis midi stuff

setting VFX graph properties using C#