HLSL Effects: Grayscale

Rendering an image in grayscale is another very simple effect that can be added with little difficulty. By applying a standard grayscale equation, you can convert the colors of every pixel to a shade of gray using the dot function. Replace your pixel shader with this code:

float4 PixelShader(VertexOut input) : COLOR0
{
    float4 color;
    color = tex2D( ColoredTextureSampler, input.textureCoordinates.xy);
    return dot(color, float3(0.3, 0.59, 0.11));
}

What's this doing? First, the shader function retrieves the color of the pixel at the coordinate of the pixel. Then the dot function retrieves a dot product using two vectors: the color of the pixel from the texture, and a vector generated using (0.3, 0.59, 0.11). Why these numbers? Well, you could just use 0.33 for each of them and get an average color, which would look pretty decent in grayscale. However, a long time ago, somebody much smarter than myself figured out that these numbers much more closely approximate grayscale as seen by the human eye. I hate to quote Wikipedia in a book like this, but it's a great resource to read about these numbers (see http://en.wikipedia.org/wiki/Grayscale).

The resulting image will be drawn in grayscale, as shown in Figure 13-9.

Scary and spooky grayscale!!!

Figure 13-9. Scary and spooky grayscale!!!

As you can see, there are endless possibilities when dealing with HLSL effects. These are only a few samples of ...

Get Learning XNA 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.