用Unity Shader实现漫反射
Untiy原来的效果
image.png
逐顶点
Shader "Unlit/Chapter6DiffuseVertextLevel"
{
Properties
{
_Diffuse("Diffuse", Color) = (1, 1, 1, 1)
}
SubShader
{
Pass
{
Tags { "LightMode" = "ForwardBase" }
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "Lighting.cginc"
fixed4 _Diffuse;
struct a2v {
float4 vertex : POSITION;
float3 normal : NORMAL;
};
struct v2f {
float4 pos : SV_POSITION;
fixed3 color : COLOR;
};
v2f vert(a2v v) {
v2f obj;
// Transform
obj.pos = UnityObjectToClipPos(v.vertex);
// Get ambient term
fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz;
// Transform the normal fram obj space to world space
fixed3 worldNormal = normalize(mul(v.normal, (float3x3)unity_WorldToObject));
// Get the light diraction in world space
fixed3 worldLight = normalize(_WorldSpaceLightPos0.xyz);
// Compute diffuse term
fixed3 diffuse = _LightColor0.rgb * _Diffuse.rgb * saturate(dot(worldNormal, worldLight));
obj.color = ambient + diffuse;
return obj;
}
fixed4 frag(v2f i) : SV_Target{
return fixed4(i.color, 1.0);
}
ENDCG
}
}
Fallback "Diffuse"
}
最终效果
image.png
image.png
可以看到逐顶点着色在边缘有锯齿感,逐像素着色可以解决这个问题
逐像素着色
Shader "Unlit/Chapter6DiffusePixelLevel"
{
Properties
{
_Diffuse("Diffuse", Color) = (1, 1, 1, 1)
}
SubShader
{
Pass
{
Tags { "LightMode" = "ForwardBase" }
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "Lighting.cginc"
fixed4 _Diffuse;
struct a2v {
float4 vertex : POSITION;
float3 normal : NORMAL;
};
struct v2f {
float4 pos : SV_POSITION;
float3 worldNormal: TEXCOORD0;
};
v2f vert(a2v v) {
v2f obj;
// Transform
obj.pos = UnityObjectToClipPos(v.vertex);
obj.worldNormal = mul(v.normal, (float3x3)unity_WorldToObject);
return obj;
}
fixed4 frag(v2f i) : SV_Target{
// Get ambient term
fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz;
// Transform the normal fram obj space to world space
fixed3 worldNormal = normalize(i.worldNormal);
// Get the light diraction in world space
fixed3 worldLight = normalize(_WorldSpaceLightPos0.xyz);
// Compute diffuse term
fixed3 diffuse = _LightColor0.rgb * _Diffuse.rgb * saturate(dot(worldNormal, worldLight));
fixed3 color = ambient + diffuse;
return fixed4(color, 1.0);
}
ENDCG
}
}
Fallback "Diffuse"
}
image.png
可以看到边缘锯齿感好很多了,但是阴影是全黑的,不太行
半兰伯特模型
经验公式
fixed4 frag(v2f i): SV_Target{
...
fixed halfLamber = dot(worldNormal, worldLight) * 0.5 + 0.5;
fixed3 diffuse = _LightColor0.rgb * _Diffuse.rgb * halfLamber;
fixed3 color = ambient + diffuse;
}
image.png