[Shader]最简单的Unity投射和接收阴影代码

2020/08 21 23:08
Shader "Custom/FullShadowShader"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {
            Tags 
            {
                "LightMode"="ForwardBase"
            }

            Cull Off

            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma multi_compile_fwdbase_fullshadows 
            #include "UnityCG.cginc"
            #include "AutoLight.cginc"
            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };
            struct v2f
            {
                float4 vertex : SV_POSITION;
                float2 uv : TEXCOORD0;
                float3 wpos: TEXCOORD1;
                SHADOW_COORDS(2)
            };

            sampler2D _MainTex;
            
            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.wpos = mul(unity_ObjectToWorld, v.vertex);
                o.uv = v.uv;
                TRANSFER_SHADOW(o);
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                UNITY_LIGHT_ATTENUATION(atten, i, i.wpos);
                atten = saturate( atten* 2 );
                fixed4 col = tex2D(_MainTex, i.uv);
                return fixed4( col.rgb * atten, col.a);
            }
            ENDCG
        }

        Pass 
        {
            Tags 
            {
                "LightMode"="ShadowCaster"
            }
            Offset 1, 1
            Cull Off
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"
            struct app_data 
            {
                float4 vertex : POSITION;
            };
            struct v2f 
            {
                V2F_SHADOW_CASTER;
            };
            v2f vert (app_data v) 
            {
                v2f o;
                TRANSFER_SHADOW_CASTER(o)
                return o;
            }
            float4 frag(v2f i) : COLOR 
            {
                SHADOW_CASTER_FRAGMENT(i)
            }
            ENDCG
        }
    }
}