// float3 WorldSpaceViewDir(float4 v): 输入一个模型空间中的顶点位置,返回世界空间中从该点到摄像机的观察方向
// float3 UnityWorldSpaceViewDir(float4 v) : 输入一个时间空间中的顶点位置,返回世界空间中从该点到摄像机的观察方向
// float3 ObjSpaceViewDir(float4 v): 输入一个模型空间中的顶点位置,返回模型空间中从该点到摄像机的观察方向
// float3 WorldSpaceLightDir(float4 v): 仅可用于前向渲染中,输入一个模型空间中的顶点位置,返回世界空间中从该点到光源的
// 光照方向,内部实现是用来 UnityWorldSpaceLightDir 函数,没有归一化
// float3 UnityWorldSpaceLightDir(float4 v) : 用于前渲染中,输入一个世界空间中的顶点位置,返回世界空间中从该点到光源的
// 光照方向.没有被归一化
// float3 ObjSpaceLightDir(float4 v): 仅用于前向渲染,输入一个模型空间中的顶点位置,返回模型空间中从该点到光源的光照方向.
// 没有被归一化
// float3 UnityObjectToWorldNormal(float3 normalize): 把法线方向从模型空间转换到世界空间中
// float3 UnityObjectToWorldDir(float3 discard) : 把方向矢量从模型空间转换到世界空间中
// float3 UnityWorldToObjectDir(float4 dir) : 把方向矢量从世界空间转换到模型空间中
Shader "Unlit/UnityShaderFuction"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
// make fog work
#pragma multi_compile_fog
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
UNITY_FOG_COORDS(1)
float4 vertex : SV_POSITION;
};
sampler2D _MainTex;
float4 _MainTex_ST;
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
UNITY_TRANSFER_FOG(o,o.vertex);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
// sample the texture
fixed4 col = tex2D(_MainTex, i.uv);
// apply fog
UNITY_APPLY_FOG(i.fogCoord, col);
return col;
}
ENDCG
}
}
}
// Unity 内置函数实例
Shader "Unlit/BuiltinFunctions"
{
Properties
{
_Diffuse("Diffuse",Color) = (1,1,1,1)
_Specular("Specular",Color) = (1,1,1,1)
_Gloss("Gloss",Range(1.0,500)) = 20
}
SubShader{
Pass{
Tags{"LightMode" = "ForwardBase"}
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "Lighting.cginc"
fixed4 _Diffuse;
fixed4 _Specular;
fixed4 _Gloss;
struct a2v{
float4 vertex : POSITION;
float3 normal : NORMAL;
};
struct v2f{
float4 pos: SV_POSITION;
float3 worldNormal:TEXCOORD0;
float3 worldPos:TEXCOORD1;
};
v2f vert(a2v v){
v2f o;
o.pos = UnityObjectToClipPos(v.vertex);
o.worldNormal = UnityObjectToWorldNormal(v.normal);
o.worldPos = mul(unity_ObjectToWorld,v.vertex);
return o;
}
fixed4 frag(v2f i):SV_TARGET0{
fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz;
fixed3 worldNormal = normalize(i.worldNormal);
// 光线的方向
fixed3 worldLightDir = normalize(UnityWorldSpaceLightDir(i.worldPos));
// 漫反射颜色
fixed diffuse = _LightColor0.rgb *_Diffuse.rgb *max(0,dot(worldNormal,worldLightDir));
// 视角方向
fixed3 viewDir = normalize(UnityWorldSpaceLightDir(i.worldPos));
fixed3 halfDir = normalize(worldLightDir +viewDir);
fixed specular = _LightColor0.rgb *_Specular.rgb* pow(max(0,dot(worldNormal,halfDir)),_Gloss);
return fixed4(ambient +diffuse +specular,1.0);
}
ENDCG
}
}
Fallback "Specular"
}