1. 程式人生 > >UnityShader 學習筆記 11 高階紋理之反射

UnityShader 學習筆記 11 高階紋理之反射



Shader "_MyShader/7_Advanced/0_Reflection"

{

    Properties

    {

        _Color("Color",COLOR) = (1,1,1,1)

            _ReflectColor("ReflectColor",COLOR) = (1,1,1,1)

            _ReflectAmount("ReflectAmount",Range(0,1.5)) = 1

            _CubeMap("CubeMap",Cube) = "_Skybox"{}

    }

    SubShader

    {

        Tags { "RenderType"="ForwardBase" }



        Pass

        {

            CGPROGRAM

            #pragma vertex vert

            #pragma fragment frag



            #include "UnityCG.cginc"

            #include "Lighting.cginc"

            #include "AutoLight.cginc"



            fixed4 _Color;

            fixed4 _ReflectColor;

            float _ReflectAmount;

            samplerCUBE _CubeMap;



            struct a2v{

                float4 vertex:POSITION;

                float3 normal:NORMAL;

            };



            struct v2f{

                float4 pos:SV_POSITION;

                float4 worldPos:TEXCOORD1;

                float3 worldNormal:TEXCOORD2;

                float3 worldLight:TEXCOORD3;

                float3 worldView:TEXCOORD4;

                float3 worldReflect:TEXCOORD6;

                SHADOW_COORDS(5)

            };



            v2f vert(a2v v){

                v2f o;

                o.pos = mul(UNITY_MATRIX_MVP, v.vertex);

                o.worldPos = mul(_Object2World, v.vertex);

                o.worldNormal = UnityObjectToWorldNormal(v.normal);

                o.worldLight = UnityWorldSpaceLightDir(o.worldPos);

                o.worldView = UnityWorldSpaceViewDir(o.worldPos);

                o.worldReflect = reflect(-o.worldView, o.worldNormal);



                TRANSFER_SHADOW(o);



                return o;

            }



            fixed4 frag(v2f i) : SV_Target{

                fixed3 worldNormalDir = normalize(i.worldNormal);

                fixed3 worldLightDir = normalize(i.worldLight);

                fixed3 worldViewDir = normalize(i.worldView);

                fixed3 worldReflectDir = normalize(i.worldReflect);



                fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz;



                fixed3 diffuseColor = _LightColor0.rgb * _Color.rgb * saturate(dot(worldNormalDir, worldLightDir));



                fixed3 reflection = texCUBE(_CubeMap, worldReflectDir).rgb * _ReflectColor.rgb;



                UNITY_LIGHT_ATTENUATION(atten, i, i.worldPos);



                fixed3 color = ambient + lerp(diffuseColor, reflection, _ReflectAmount) * atten;



                return fixed4(color, 1);

            }





            ENDCG

        }

    }

}