《Unity Shader入门精要》自学笔记(一)

时间:2022-07-14 20:02:21
Shader "Custom/zhudingdian" {
Properties {
_Diffuse("Diffuse",color) = (1,1,1,1)
//用于颜色设置
}
SubShader {
pass{
tags{"LightMode" = "ForwardBase"}
CGPROGRAM

float4 _Diffuse;

//取用设置中的颜色信息

#pragma vertex vert
#pragma fragment frag
#include "Lighting.cginc"


struct a2v {
float4 vertex:POSITION;
float3 normal :NORMAL;


};


struct v2f{
float4 pos :SV_POSITION;
float3 color :color;
};


v2f vert(a2v i){
v2f o;

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

//将顶点坐标变换到世界坐标系

float3 worldNormal = normalize(mul(i.normal,(float3x3)unity_WorldToObject));

//把顶点法线变换到世界坐标系

float3 ambient = UNITY_LIGHTMODEL_AMBIENT.rgb;

//取得环境光的颜色信息

float3 worldLight = normalize(_WorldSpaceLightPos0.xyz);

//获得世界中光的入射信息

float3 diffuse = _LightColor0.rgb*_Diffuse.rgb*saturate(dot(worldNormal,worldLight));

//进行计算。公式为 :入射光信息*自身反射信息*(法线和入射光的点积)

o.color = ambient + diffuse;

//加入环境光

return o;
}


fixed4 frag(v2f i):SV_Target{
return float4(i.color,1.0);
}
ENDCG
}
}
FallBack "Diffuse"

}


以上为逐顶点计算,为非线性,过度较为不均匀


增加:逐像素计算也贴上

Shader "Custom/zhuxiangsu" {
Properties {
_Diffuse("Diffuse",color) = (1,1,1,1)
}
SubShader {
pass{
tags{"LightMode" = "ForwardBase"}
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "Lighting.cginc"
float4 _Diffuse;


struct a2v{
float4 vertex :POSITION;
float3 normal :NORMAL;
};


struct v2f{
float4 pos:SV_POSITION;
fixed3 worldNormal:TEXCOORD0;
};


v2f vert(a2v i){
v2f o;
o.pos = mul(UNITY_MATRIX_MVP,i.vertex);
o.worldNormal = mul(i.normal,(float3x3)unity_WorldToObject);
return o;
}


fixed4 frag(v2f i):SV_Target{
float3 worldNormal = normalize(i.worldNormal);
float3 ambient = UNITY_LIGHTMODEL_AMBIENT.rgb;
float3 worldLight = normalize(_WorldSpaceLightPos0.xyz);
fixed3 diffuse = _LightColor0.rgb*_Diffuse.rgb*saturate(dot(worldNormal,worldLight));
fixed3 color = diffuse + ambient;
return fixed4(color,1.0);
}
ENDCG


}
}
FallBack "Diffuse"
}


逐像素过度较为均匀,但是消耗增加