Modern GPUs are very good at determining whether one set of polygons is obscured by another set. We can use this to our advantage when creating lens flares within a HiDef profile.
Getting ready
This recipe assumes that you've already got a scene, rendering correctly, albeit without a lens flare.
How to do it...
To create a lens flare within the HiDef profile:
Create a new class to hold the lens flare behavior:
class HiDefLensFlare
{
Add some instance-level variables to hold the details of the occlusion test, the lighting, and the glow image:
Complete the class by adding a Draw() method to render the glow:
public void Draw()
{
if (lightBehindCamera || occlusionAlpha <= 0)
return;
Color color = Color.White * occlusionAlpha;
Vector2 origin = new Vector2(glow.Width, glow.Height) / 2;
float scale = glowScale * 2 / glow.Width;
spriteBatch.Begin();
spriteBatch.Draw(glow, lightPosition, null, color, 0,
origin, scale, SpriteEffects.None, 0);
spriteBatch.End();
}
How it works...
XNA and the underlying DirectX infrastructure contain a rather handy little diagnostic tool in the form of the occlusion test. With this test, you can count how many pixels were filled when trying to render a particular portion of a scene.
We utilize this in the lens flare example by attempting to render a small rectangle across the opposite side of the scene from the player's viewpoint, and measuring how much of it is obscured by the scene's meshes. With this number, we adjust the opacity of the lens flare's glow texture up or down to simulate the sun disappearing either partially or completely behind an object.