Search Unity

How to get pixel normal in surface shader

Discussion in 'Shaders' started by djweinbaum, Mar 29, 2017.

  1. djweinbaum

    djweinbaum

    Joined:
    Nov 3, 2013
    Posts:
    533
    This seems quite basic, but I'm having trouble getting the perturbed pixel normal in a surface shader. I've looked at the docs and example shaders, but my results still seem curious. Consider the following surf function. Its supposed to be a flat normal map, and then the dot product of the view dir and surface normal.

    Code (CSharp):
    1. void surf (Input IN, inout SurfaceOutputStandardSpecular o) {
    2.     o.Normal = half3(0, 0, 1);
    3.     float3 n = WorldNormalVector (IN, o.Normal);
    4.  
    5.     o.Emission = dot(IN.viewDir, n);
    6.     o.Albedo = 0;
    7.     o.Specular = 0;
    8. }
    The result of that shader is the sphere on the left, but I'd expect something like the sphere on the right. What am I doing wrong?

     

    Attached Files:

  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,352
    I believe for surface shaders IN.viewDir is in tangent space, so try dot(IN.viewDir, o.Normal)
     
    LingDar777 likes this.
  3. djweinbaum

    djweinbaum

    Joined:
    Nov 3, 2013
    Posts:
    533
    That was exactly it! Thanks so much! Would have never tried that, haha. Seems so natural to me that the view direction would be in world space.