Graphics Reference
In-Depth Information
Listing 33.4: The fragment shader for the Gouraud shading program.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/ ** Diffuse/ambient surface color * /
uniform vec3 diffuseColor;
/ ** Intensity of the diffuse term. * /
uniform float diffuse;
/ ** Color of the light source * /
uniform vec3 lightColor;
/ ** dot product of surf normal with light * /
varying float gouraudFactor;
void main() {
gl_FragColor.rgb = diffuse * diffuseColor *
(max(gouraudFactor, 0.0) * lightColor);
}
Once again, three uniform variables, whose values were established in the host
program, get used in the fragment shader: the diffuse reflectivity, the color of the
surface, and the color of the light.
We also, in the fragment shader, have access to the gouraudFactor that was
computed in the vertex shader. At any fragment, the value for this variable is the
result of interpolating the values at the three vertices of the triangle. In the shader,
we do a very simple operation: We multiply the diffuse reflectivity by the diffuse
color to get a vec3 , and multiply the gouraudFactor (if it's positive) by the light
color, giving another vec3 . We then take the term-by-term product of these two
(using the * operator) and assign it to the gl_FragColor.rgb . If the light is pure
red and the surface is pure blue, then the product will be all zeroes. But in general,
we are taking the product of the amount of red light and how well the surface
reflects red light (and how well it reflects in this direction at all), and similarly for
green and blue, to get a color for the fragment.
Every fragment shader is responsible for setting the value of gl_FragColor ,
which is used by the remainder of the graphics pipeline.
That's it! This simple host program and two simple shaders implement
Gouraud shading. The results are shown in Figure 33.3. In the version of the pro-
gram available on the topic's website, we've added one GUI that allows you to
pick a diffuse color and set the reflectivity interactively, and another that allows
you to rotate the icosahedron to any position you like, but the essential ideas are
unchanged.
Figure 33.3: An icosahedron ren-
dered by our first shader.
33.5 A Phong Shader
In generalizing this to implement the Phong model, there are no real surprises.
We have to declare a few more variables in the host program, such as the specu-
lar exponent shine , the specular reflection coefficient specular , and the specular
color specularColor , and we also include ambient light as ambientLightColor ,
but we're confident that you can do this without seeing the code.
Recall that the basic Phong model of Chapter 6 tells us to compute the pixel
color using
n ) n s I d ,
color = k d O d I a + k d O d I d ( n
·
)+ k s O s ( r
·
(33.2)
 
 
 
Search WWH ::




Custom Search