Shader Note(1): Diffuse shader

Posted on

This series will be my shader note of Unity 5.x Shaders and Effects Cookbook.

Diffuse shader is the simplest shader.  The object will only have one uniform color.

First, you should define the shader to let it know it is a surf shader:

#pragma  surface  surf  Standard  fullforwardshadows

It follows the grammar of:

#pragma  surface  surfaceFunction  lightModel  [optionalparams]

In this case, surfaceFunction will be surf, which is the name we will use later.

Light Model is how Unity calculate the final looking based on your inputs such as albedo and normal.

The surf function is a simple in and out function. We define the input struct we need and  then produce the output we want.

struct Input {
       float2 uv_MainTex;
};

The full list is

  • float3 viewDir – contains view direction, for computing Parallax effects, rim lighting etc.
  • float4 with COLOR semantic – contains interpolated per-vertex color.
  • float4 screenPos – contains screen space position for reflection or screenspace effects. Note that this is not suitable for GrabPass; you need to compute custom UV yourself using ComputeGrabScreenPos function.
  • float3 worldPos – contains world space position.
  • float3 worldRefl – contains world reflection vector if surface shader does not write to o.Normal. See Reflect-Diffuse shader for example.
  • float3 worldNormal – contains world normal vector if surface shader does not write to o.Normal.
  • float3 worldRefl; INTERNAL_DATA – contains world reflection vector if surface shader writes to o.Normal. To get the reflection vector based on per-pixel normal map, use WorldReflectionVector (IN, o.Normal). See Reflect-Bumped shader for example.
  • float3 worldNormal; INTERNAL_DATA – contains world normal vector if surface shader writes to o.Normal. To get the normal vector based on per-pixel normal map, use WorldNormalVector (IN, o.Normal).

 

In our surface function, we just need a base color for our model, so we just assign color to the Albedo parameter of the ouput:

void surf(Input IN, inout SurfaceOutputStandard o) {
o.Albedo = _Color.rgb;
}

The full shader will be like:


Shader "Unlit/diffuse_shader"
{
Properties
{
_Color ("Color", Color) = (1,1,1,1)
}

SubShader
{

CGPROGRAM
#pragma surface surf Standard fullforwardshadows
#pragma target 3.0
struct Input {
float2 uv_MainTex;
};

fixed4 _Color;

void surf(Input IN, inout SurfaceOutputStandard o) {
o.Albedo = _Color.rgb;
}
ENDCG
}
FallBack "Diffuse"
}

 


Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s