Skip to Main Content
Learning XNA 3.0
book

Learning XNA 3.0

by Aaron Reed
November 2008
Beginner content levelBeginner
510 pages
16h 24m
English
O'Reilly Media, Inc.
Content preview from Learning XNA 3.0

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 the ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning XNA 4.0

Learning XNA 4.0

Aaron Reed
Beginning C# 7 Programming with Visual Studio 2017

Beginning C# 7 Programming with Visual Studio 2017

Benjamin Perkins, Jacob Vibe Hammer, Jon D. Reid

Publisher Resources

ISBN: 9780596154905Supplemental ContentErrata Page