《unity shader入门精要》自学笔记(二)

时间:2022-06-18 10:21:16

逐顶点高光反射的shader:

Shader "Custom/zhudingdiangaoguang" {

Properties {
_Diffuse("Diffuse",color) = (1,1,1,1)
_Specular("Specular",color) = (1,1,1,1)
_Gloss("Gloss",range(8,256)) = 20
}


SubShader {
pass{
tags{"LightMode" = "ForwardBase"}
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "Lighting.cginc"
fixed4 _Diffuse;
fixed4 _Specular;
float _Gloss;
struct a2v{
float4 vertex:POSITION;
fixed3 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);
fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz;
fixed3 worldNormal = normalize(mul(i.normal,(float3x3)unity_WorldToObject));
fixed3 worldLightDir = normalize(_WorldSpaceLightPos0.xyz);
fixed3 diffuse = _LightColor0.rgb * _Diffuse.rgb * saturate(dot(worldNormal,worldLightDir));
fixed3 reflectDir = normalize(reflect(-worldLightDir,worldNormal));
计算反射
fixed3 viewDir = normalize(_WorldSpaceCameraPos.xyz - mul(unity_ObjectToWorld,i.vertex).xyz);
计算空间视角方向
fixed3 specular = _LightColor0.rgb * _Specular.rgb * pow(saturate(dot(reflectDir,viewDir)),_Gloss);
高光反射公式:光照信息 * 反射信息 * (视角方向点积反射方向)的_Gloss方
o.color = ambient + diffuse + specular;
return o;
}
fixed4 frag(v2f i):SV_Target{
return fixed4(i.color,1.0);

}



ENDCG
}
}

}


逐像素高光如下:

Shader "Custom/zhuxiangsugaoguang" {
Properties {
_Diffuse("Diffuse",color) = (1,1,1,1)
_Specular("Specular",color) = (1,1,1,1)
_Gloss("Gloss",range(8,256)) = 16
}
SubShader {
pass{
tags{"RanderMode" = "ForwardBase"}
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "Lighting.cginc"
fixed4 _Diffuse;
fixed4 _Specular;
float _Gloss;


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


struct v2f{
float4 position:SV_POSITION;
float3 worldNormal:TEXCOORD0;
float3 worldPos:TEXCOORD1;
};


v2f vert(a2v i){
v2f o;
o.position = mul(UNITY_MATRIX_MVP,i.vertex);
//float3 ambient = UNITY_LIGHTMODEL_AMBIENT.rgb;
o.worldNormal = normalize(mul(i.normal,(float3x3)unity_WorldToObject));
o.worldPos = mul(unity_ObjectToWorld,i.vertex).xyz;


return o;


}


float4 frag(v2f i):SV_Target{
float3 ambient = UNITY_LIGHTMODEL_AMBIENT.rgb;
float3 worldLightDir = normalize(_WorldSpaceLightPos0.xyz);
float3 diffuse = _LightColor0.rgb * _Diffuse.rgb * saturate(dot(i.worldNormal,worldLightDir));


float3 reflectDir = normalize(reflect(-worldLightDir,i.worldNormal));


float3 viewDir = normalize(_WorldSpaceCameraPos.xyz - i.worldPos.xyz);
float3 specular = _LightColor0.rgb * _Specular.rgb * pow(saturate(dot(reflectDir,viewDir)),_Gloss);
float3 color = diffuse + ambient + specular;
return float4(color,1.0);
}


ENDCG
}
}
FallBack "Diffuse"
}