Thursday, April 26, 2007

XNA: GraphicsDevice.DeviceLost Doesn't Fire

What is device loss?
Device loss occurs when Windows takes the graphics device from an application, preventing the application from rendering. The easiest way to trigger device loss is to lock your work station. To render the locked workstation screen, Windows will steal the graphics device. When the application gets the device back it must recreate the graphics content that is no longer valid.

GraphicsDevice.DeviceLost Event
This event fires when GraphicsDevice.Present() is called on a lost device. In most cases, including the "Game" class in XNA, this event will never fire because the render loop simply won't call Present()if the device is lost. The render loop might look something like this:

if (device.GraphicsDeviceStatus == GraphicDeviceStatus.Lost)
{
device.Reset();
}
if (device.GraphicsDeviceStatus == GraphicDeviceStatus.Normal)
{

device.Present();
}

I suppose the device could be lost between checking the GraphicsDeviceStatus and calling Present() then DeviceLost would fire, but that is generally unlikely.

Labels:

Wednesday, January 24, 2007

Tip: Vector2.Normalize()

Vector2.Normalize() will fail silently if both members X and Y are zero. When it fails, the method will set X and Y to NaN (which stands for Not a Number.) Most operations using NaN will yield NaN so pretty soon all of your floating point values will become NaN!

When using Normalize() use the following pattern:

Vector2 delta = new
Vector();
if (delta
!=
Vector2.Zero)
{
delta.Normalize();
}


Or:


Vector2 delta = new
Vector();
if
(delta.LengthSquared > 0)

{

delta.Normalize();

}

You may be tempted to use the following because it is most "mathematically" correct:

Vector2 delta = new Vector();
if (delta.Length > 0)
{
delta.Normalize();
}

But don't do it! The Length property causes a square root operation which is really expensive.

Labels:

New Goal: XNA Hints and Tips

From now on I'm going to post XNA hints and tips as I come across them. The XNA platform enables garage developers to create games for Windows and Xbox360 for free. You can find more information here: http://msdn.microsoft.com/directx/XNA/default.aspx

Labels: