[每日Shader]ShaderX.2.Introductions and Tutorials with DirectX 9 (3)A simple sample-Pixel Shader
Posted on 2008-11-01 18:53 活着就是幸福 阅读(338) 评论(0) 收藏 举报Below, we see a simple HLSL procedural wood pixel shader. This pixel shader, which is written to work with the vertex shader we just described, will be compiled for the ps_2_0 target.
下面,我们看看一个简单的用程序产生木头的像素着色器。这个像素着色器用来和前面描述的顶点着色器协同工作,会被编译成ps_2_0对象。
float4 lightWood; // xyz == Light Wood Color
float4 darkWood; // xyz == Dark Wood Color
float ringFreq; // ring frequency
sampler PulseTrainSampler;
float4 hlsl_rings (float4 Pshade : TEXCOORD0) : COLOR
{
float scaledDistFromZAxis = sqrt(dot(Pshade.xy, Pshade.xy)) * ringFreq;
float blendFactor = tex1D (PulseTrainSampler, scaledDistFromZAxis);
return lerp (darkWood, lightWood, blendFactor);
}
The first few lines of this shader are the declaration of a pair of floating-point 4tuples and one scalar float at global scope. Following these variables, a sampler called PulseTrainSampler is declared. Samplers will be discussed in more detail later in the chapter but for now you can just think of a sampler as a window into video memory with associated state defining things like filtering, and texture coordinate addressing modes. With variable and sampler declarations out of the way, we move on to the body of the shader code. You can see that there is one input parameter called Pshade, which is interpolated across the polygon. This is the value that was computed at each vertex by the vertex shader above. In the pixel shader, the Cartesian distance from the shader-space z axis is computed, scaled and used as a 1D texture coordinate to access the texture bound to the PulseTrainSampler. The scalar color that is returned from the tex1D() sampling function is used as a blend factor to blend between the two constant colors (lightWoodand darkWood) declared at global scope of the shader. The 4D vector result of this blend is the final output of the pixel shader. All pixel shaders must return a 4D RGBA color at a minimum. We will discuss additional optional pixel shader outputs later in the chapter.
这个着色器的开始几行是2个4元浮点数组变量和一个浮点标量在全局域中的声明。而后声明了一个叫做PulseTrainSampler的采样器。采样器的细节会在本章的晚些时候被讨论。迄今为止,你可以认为采样器就是显示内存里的一个关联了某些状态的窗口,这些状态包括过滤(filtering)、纹理坐标寻址模式(texture coordinate addressing mode)等等。跳过变量和采样器,我们继续关注着色器代码的函数体。您可以看到有一个叫做Pshade的输入参数被通过多边形进行了内插值。这就是上面的顶点着色器对每个顶点进行计算后的值。在像素着色器内,来自着色器空间的Z轴上的笛卡尔距离被计算、缩放后用作1维纹理坐标来存取绑定到采样器纹理PulseTrainSampler上的纹理。tex1D()采样函数返回的标量颜色被用来作为一个混合因子在两个在全局域里声明的常量颜色lightWoodand和darkWood之间进行混合。混合的结果是一个4维向量,作为像素着色器的最终输出。所有的像素着色器都至少输出一个4维的RGBA颜色。我们会在本章的晚些时候讨论可选的额外像素着色器输出。
-----------------------------------------------------------
每天进步一点
浙公网安备 33010602011771号