物体坐标系向世界坐标系转变
前文提到过,vertex shader阶段用POSITION
语义修饰的输入参数指的是物体的坐标,而且是mesh以自身所在的坐标系统为准的坐标。因此所有的物体最终需要统一转换到一个共同的坐标系统——世界坐标
关于坐标系统转换更多知识参见Vertex Transformations
从模型空间转换到世界空间需要一个4x4的矩阵,该矩阵称之为模型矩阵
,该矩阵在Unity3D中已经定义好了
uniform float4x4 unity_ObjectToWorld;
在shader脚本中不需要重复定义,直接使用即可。
示例shader:
Shader "My/ShaderInWorldSpace"
{
SubShader
{
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
struct vertexInput{
float4 vertex:POSITION;
};
struct vertexOutput{
float4 pos:SV_POSITION;
float4 posWorldSpace:TEXCOORD0;
};
vertexOutput vert (vertexInput input)
{
vertexOutput output;
output.pos=UnityObjectToClipPos(input.vertex);
output.posWorldSpace=mul(unity_ObjectToWorld,input.vertex);
return output;
}
fixed4 frag (vertexOutput input) : COLOR
{
//computes the distance between the fragment positiion and the origin.
//note:the 4th coordinate should always be 1 for points
float dis=distance(input.posWorldSpace,float4(0.0,0.0,0.0,1.0));
if(dis<5.0)
{
return float4(0.0,1.0,0.0,1.0);//color near origin
}
else
{
return float4(0.4,0.1,0.1,1.0);//color far from origin
}
}
ENDCG
}
}
}
更多内置统一参数
unifrom float4 _Time,_SinTime,_CosTime; //时间
uniform float4 _ProjectionParams;
// x = 1 or -1 (-1 if projection is flipped)
// y = near plane;
// z = far plane;
// w = 1/far plane
uniform float4 _ScreenParams;
// x = width;
// y = height;
// z = 1 + 1/width;
// w = 1 + 1/height
uniform float3 _WorldSpaceCameraPos;
uniform float4x4 unity_ObjectToWorld; //模型矩阵
uniform float4x4 unity_WorldToObject; // 反向模型矩阵
uniform float4 _WorldSpaceLightPos0;
// position or direction of light source for forward rendering
uniform float4x4 UNITY_MATRIX_MVP;
// model view projection matrix
// in some cases, UnityObjectToClipPos() just uses this matrix
uniform float4x4 UNITY_MATRIX_MV; // model view matrix
uniform float4x4 UNITY_MATRIX_V; // view matrix
uniform float4x4 UNITY_MATRIX_P; // projection matrix
uniform float4x4 UNITY_MATRIX_VP; // view projection matrix
uniform float4x4 UNITY_MATRIX_T_MV;
// transpose of model view matrix
uniform float4x4 UNITY_MATRIX_IT_MV;
// transpose of the inverse model view matrix
uniform float4 UNITY_LIGHTMODEL_AMBIENT;
// ambient color(环境色)
更多详细的Unity3D内置的shader参数,可以参见Unity文档Built-in shader variables
大部分的参数都在UnityShaderVariables.cginc
中定义,该文件从Unity4.0之后会被自动包含。因此在shader代码中不需要再次引用。
依然会有些内置的参数没有自动定义,比如_LightColor0
,定义在Lighting.cginc
中。因此在shader中使用的时候,要么自己手动定义一下uniform float4 _LightColor0
或者在shader中引用对应的cginc文件#include "Lighting.cginc"
。
需要注意的是,诸如_WorldSpaceLightPos0
和_LightColor0
只有在Pass{...}
代码的第一行中加了Tags{"LightMode"="ForwardBase"}
后才会生效。详见Diffuse Reflection