Blinn-Phong 光照模型实现

一、Phong光照模型

物体表面反射光线由三部分组成:环境光+漫反射光+镜面反射光

环境光:unity_AmbientSky,Unity引擎在Window>Rendering>Lighting Setting 里面设置

漫反射光:灯光颜色 * 物体表面漫反射颜色 * 法线与光源方向的点积

DiffuseColor = _LightColor0 * tex2D(uv, _MainTex) * saturate(dot(normal, lightDir))

镜面反射:灯光颜色 * 物体表面镜面反射颜色 * 光照反射方向与视角方向点积的光泽度次方幂

SpecularColor = _LightColor0 * tex2D(uv, _SpecularTex) * pow(saturate(dot(reflect, viewDir)), _Shinness)

reflect :光照方向的反射方向 

_Shinness :光泽度

二、Blinn-Phong光照模型

Blinn-Phong光照模型算法是对Phong光照模型的改进,修改的是镜面反射光的算法。先计算入射光线l和视角方向v的角平分线h,再计算h和法线normal的点积,来替代dot(reflect, viewDir)。

SpecularColor = _LightColor0 * tex2D(uv, _SpecularTex) * pow(saturate(dot(h, normal)), _Shinness)

三、Shader代码

Shader "Unlit/Sphere"
{
    Properties
    {
        _MainTex("Texture", 2D) = "white" {}
        _SpecularTex("Specular", 2D) = "white" {}
        _Shininess("Shininess", Float) = 0
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"
            #include "Lighting.cginc"

            struct v2f
            {
                float4 pos: SV_POSITION;
                float3 normal: NORMAL;
                float4 vertex: TEXCOORD0;
                float2 uv : TEXCOORD1;
                float2 uv2 : TEXCOORD2;
            };
            
            sampler2D _MainTex;
            float4 _MainTex_ST;
            sampler2D _SpecularTex;
            float4 _SpecularTex_ST;
            float _Shininess;

            v2f vert (appdata_base v)
            {
                v2f o;
                o.pos = UnityObjectToClipPos(v.vertex);
                o.normal = v.normal;
                o.vertex = v.vertex;
                o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
                o.uv2 = TRANSFORM_TEX(v.texcoord, _SpecularTex);
                return o;
            }

            fixed4 frag(v2f i) : SV_Target
            {
                float3 normal = UnityObjectToWorldNormal(i.normal);
                normal = normalize(normal);
                float3 l = WorldSpaceLightDir(i.vertex);
                float ndotl = saturate(dot(normal, l));
                fixed4 diffuse = tex2D(_MainTex, i.uv) * _LightColor0 * ndotl;

                float3 v = normalize(WorldSpaceViewDir(i.vertex));
                float3 h = normalize(v + l);
                float ndoth = saturate(dot(normal, h));
                fixed4 specular = tex2D(_SpecularTex, i.uv2) * _LightColor0 * pow(ndoth, _Shininess);

                return diffuse + specular + unity_AmbientSky;
            }
            ENDCG
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值