XNA for C#
DirectX 9 for C#
DirectX 9 for C++
DirectX 9 for VB
Forum
   
My XNA Book
      
       Go to section on this site

Additional info


Latest Forum posts

 Tutorial 3 for Windows Phone 7
  Posted by: Anonymous
  When: 20/05/2013 at 02:30:13

 No download link for 2d series: shooter
  Posted by: zaboleq
  When: 07/05/2013 at 15:46:28

 Collision Class?
  Posted by: Anonymous
  When: 05/05/2013 at 19:03:59

 stack overflow
  Posted by: cityguy
  When: 07/04/2013 at 01:58:38

 Meshes looks strange.
  Posted by: ab_saratov
  When: 01/04/2013 at 04:31:08

 Lamppost Not loaded
  Posted by: Anonymous
  When: 22/03/2013 at 06:43:52

 Collision Class?
  Posted by: Da_Boom
  When: 21/03/2013 at 01:23:09

 Math boggles me
  Posted by: cityguy
  When: 17/03/2013 at 03:44:48

 Collision Class?
  Posted by: Da_Boom
  When: 16/03/2013 at 03:44:42

 Tree update
  Posted by: Anonymous
  When: 15/03/2013 at 21:11:22


Ads

Handling Lost Devices – Solving the Resizing problem

Because this question is asked many times on the forum, I’ve decided to dedicate a small page to it. Maybe you think the contents of this page should have been included into the standard tutorials, but it handles a lot of memory management issues that you would NOT like to meet on your first DirectX day.

The DirectX resources are all connected to the device, which again is connected to its host, the form (or the screen, when talking about a fullscreen app). Whenever anything happens to this host (resizing, change of resolution), it is only logical that a lot of the DirectX resources have to be redeclared. Such resources include images linked to your device, index and vertex buffers, but also camera matrices and render states.

Whenever the user resizes the form, the device will become ‘lost’. This means that all the resources will be discarded. When the app regains focus (eg. Immediately after the resizing action) the device will be reset.

Then again, there is a big difference between resources that have been created In the Default memory, and others that reside in the Managed memory pool. Of all the resources in the Managed memory pool, DirectX keeps a copy in the main system memory (=RAM), so DirectX will be able to reallocate memory for the Managed resources. However, the contents will be LOST. So the difference between managed and default resources is that default resources have to be reallocated and filled by the user, where managed resources only have to be filled by the user.

Let’s have a look at our page on ‘Terrain Creation’, as we use both index and vertex buffers in that case. We’re simply going to hook the Reset Event to a new function. To do this, add this line immediately after your device creation:

 device.DeviceReset += new EventHandler(HandleResetEvent);

So whenever the device is reset, our HandleResetEvent method is fired. In this method, we’re simply going to make sure all our resources are refilled:

 private void HandleResetEvent(object caller, EventArgs args)
 {
  device.RenderState.FillMode = FillMode.WireFrame;
  device.RenderState.CullMode = Cull.None;
  CameraPositioning();
  VertexDeclaration();
  IndicesDeclaration();
 }

As you see, the renderstates, camera matrices and buffers are restored. This should already do the trick. The rest of this page will cover some more details.

When you have a look at the CameraPositioning method, you’ll that the resolution of the form is passed to DirectX by using this.Width and this.Height:

 device.Transform.Projection = Matrix.PerspectiveFovLH((float)Math.PI / 4, (float)(this.Width / this.Height), 1f, 50f);

So when the window is resized, our application will automatically use the correct aspect ratio!

Next I should give some more detail about the buffers. As you can see, I have created our buffers in the Default memory pool. When you have a look at the first line of the VertexDeclaration method, you’ll see I re-create the buffer each time the device is reset. This is needed, because we’re using the Default memory pool.

In the case we had created our buffer using the Managed memory pool, we would only have had to create this buffer once, because on device reset it would automatically be created by DirectX. Remember you still would have to refill it with data.



Click here to go to the forum on this chapter!

Or click on one of the topics on this chapter to go there:
  • Black geometry after resize
          I used the DeviceLost event in my project exactly ...
  • Not 100% reliable when shrinking window
          The code presented in this section works fine when...


    If you have any questions on this text, feel free to post them in the forum. Here you can find the code integrated into our tutorial:

     using System;
     using System.Drawing;
     using System.Collections;
     using System.ComponentModel;
     using System.Windows.Forms;
     using System.Data;
     using Microsoft.DirectX;
     using Microsoft.DirectX.Direct3D;
     
     namespace DirectX_Tutorial
     {
     
         public class WinForm : System.Windows.Forms.Form
         {
             private int WIDTH = 4;
             private int HEIGHT = 3;
             private Device device;
             private System.ComponentModel.Container components = null;
             private float angle = 0f;
             private CustomVertex.PositionColored[] vertices;
             private int[,] heightData;
             private int[] indices;
             private IndexBuffer ib;
             private VertexBuffer vb;
     
     
             public WinForm()
             {
                 InitializeComponent();
                 this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.Opaque, true);
             }
     
             public void InitializeDevice()
             {
                 PresentParameters presentParams = new PresentParameters();
                 presentParams.Windowed = true;
                 presentParams.SwapEffect = SwapEffect.Discard;
                 device = new Device(0, DeviceType.Hardware, this, CreateFlags.SoftwareVertexProcessing, presentParams);
                 device.RenderState.FillMode = FillMode.WireFrame;
                 device.RenderState.CullMode = Cull.None;
     
                 device.DeviceReset += new EventHandler(HandleResetEvent);
             }
     
             private void HandleResetEvent(object caller, EventArgs args)
             {
                 device.RenderState.FillMode = FillMode.WireFrame;
                 device.RenderState.CullMode = Cull.None;
                 CameraPositioning();
                 VertexDeclaration();
                 IndicesDeclaration();
             }
     
             private void CameraPositioning()
             {
                 device.Transform.Projection = Matrix.PerspectiveFovLH((float)Math.PI / 4, (float)(this.Width / this.Height), 1f, 50f);
                 device.Transform.View = Matrix.LookAtLH(new Vector3(0, 0, 15), new Vector3(0, 0, 0), new Vector3(0, 1, 0));
                 device.RenderState.Lighting = false;
                 device.RenderState.CullMode = Cull.None;
             }
     
             private void VertexDeclaration()
             {
                 vb = new VertexBuffer(typeof(CustomVertex.PositionColored), WIDTH * HEIGHT, device, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionColored.Format, Pool.Default);
                 vertices = new CustomVertex.PositionColored[WIDTH * HEIGHT];
                 for (int x = 0; x < WIDTH; x++)
                 {
                     for (int y = 0; y < HEIGHT; y++)
                     {
                         vertices[x + y * WIDTH].Position = new Vector3(x, y, heightData[x, y]);
                         vertices[x + y * WIDTH].Color = Color.White.ToArgb();
                     }
                 }
     
                 vb.SetData(vertices, 0, LockFlags.None);
             }
     
             private void IndicesDeclaration()
             {
                 ib = new IndexBuffer(typeof(int), (WIDTH - 1) * (HEIGHT - 1) * 6, device, Usage.WriteOnly, Pool.Default);
                 indices = new int[(WIDTH - 1) * (HEIGHT - 1) * 6];
                 for (int x = 0; x < WIDTH - 1; x++)
                 {
                     for (int y = 0; y < HEIGHT - 1; y++)
                     {
                         indices[(x + y * (WIDTH - 1)) * 6] = (x + 1) + (y + 1) * WIDTH;
                         indices[(x + y * (WIDTH - 1)) * 6 + 1] = (x + 1) + y * WIDTH;
                         indices[(x + y * (WIDTH - 1)) * 6 + 2] = x + y * WIDTH;
     
                         indices[(x + y * (WIDTH - 1)) * 6 + 3] = (x + 1) + (y + 1) * WIDTH;
                         indices[(x + y * (WIDTH - 1)) * 6 + 4] = x + y * WIDTH;
                         indices[(x + y * (WIDTH - 1)) * 6 + 5] = x + (y + 1) * WIDTH;
                     }
                 }
                 ib.SetData(indices, 0, LockFlags.None);
             }
     
     
             protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
             {
                 device.Clear(ClearFlags.Target, Color.DarkSlateBlue, 1.0f, 0);
     
                 device.BeginScene();
                 device.VertexFormat = CustomVertex.PositionColored.Format;
                 device.SetStreamSource(0, vb, 0);
                 device.Indices = ib;
     
                 device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, WIDTH * HEIGHT, 0, indices.Length / 3);
                 device.EndScene();
     
                 device.Present();
     
                 this.Invalidate();
                 angle += 0.05f;
             }
     
             private void LoadHeightData()
             {
                 heightData = new int[4, 3];
     
                 heightData[0, 0] = 0;
                 heightData[1, 0] = 0;
                 heightData[2, 0] = 0;
                 heightData[3, 0] = 0;
     
                 heightData[0, 1] = 1;
                 heightData[1, 1] = 0;
                 heightData[2, 1] = 2;
                 heightData[3, 1] = 2;
     
                 heightData[0, 2] = 2;
                 heightData[1, 2] = 2;
                 heightData[2, 2] = 4;
                 heightData[3, 2] = 2;
             }
     
             protected override void Dispose(bool disposing)
             {
                 if (disposing)
                 {
                     if (components != null)
                     {
                         components.Dispose();
                     }
                 }
                 base.Dispose(disposing);
             }
     
             private void InitializeComponent()
             {
                 this.components = new System.ComponentModel.Container();
                 this.Size = new System.Drawing.Size(500, 500);
                 this.Text = "DirectX Tutorial";
             }
     
             static void Main()
             {
                 using (WinForm our_directx_form = new WinForm())
                 {
                     our_directx_form.LoadHeightData();
                     our_directx_form.InitializeDevice();
                     our_directx_form.CameraPositioning();
                     our_directx_form.VertexDeclaration();
                     our_directx_form.IndicesDeclaration();
                     Application.Run(our_directx_form);
                 }
             }
         }
     }
     


    Google
     
    Webwww.riemers.net


    If you appreciate the amount of time I spend creating and updating
    these pages, feel free to donate -- any amount is welcome !



    - Website design & XNA + DirectX code : Riemer Grootjans -
    ©2003 - 2011 Riemer Grootjans
  • Translations

    This site in English
    This site in Korean
    This site in Czech

    Microsoft MVP Award



    2007 - 2011 MVP Award
    DirectX - XNA

    Contents

    News
    Home
    Forum
    XNA 2.0 Recipes Book (8)
    Chapter 1
    Chapter 2
    Chapter 3
    Chapter 4
    Chapter 5
    Chapter 6
    Chapter 7
    Chapter 8
    XNA 3.0 Recipes Book (8)
    Chapter 1
    Chapter 2
    Chapter 3
    Chapter 4
    Chapter 5
    Chapter 6
    Chapter 7
    Chapter 8
    Downloads
    Extra Reading (3)
    Matrices: geometrical
    Matrix Mathematics
    Homogenous matrices
    Community Projects (1)
    Team Project (1)
    News
    Tutorials (160)
    XNA 4.0 using C# (89)
    2D Series: Shooters (22)
    Starting a project
    Drawing fullscreen images
    Positioning images
    SpriteBatch.Draw()
    Rotation
    Keyboard input
    Writing text
    Angle to Direction
    Direction to Angle
    Smoke trail
    Manual texture creation
    Random terrain
    Texture to Colors
    Coll Detection Overview
    Coll Detection Matrices
    Putting CD into practice
    Particles
    Additive alpha blending
    Particle engine
    Adding craters
    Sound in XNA
    Resolution independency
    3D Series 1: Terrain (13)
    Starting a project
    The effect file
    The first triangle
    World space
    Rotation - translation
    Indices
    Terrain basics
    Terrain from file
    Keyboard
    Adding colors
    Lighting basics
    Terrain lighting
    VertexBuffer & IndexBuffer
    3D Series 2: Flightsim (14)
    Starting point
    Textures
    Loading the floorplan
    Creating the 3D city
    Loading a Model
    Ambient and diffuse
    Quaternion camera
    Flight kinematics
    Collision detection
    Adding targets
    Point sprites
    Alpha blending
    Skybox
    Camera delay
    3D Series 3: HLSL (18)
    Starting point
    HLSL introduction
    Vertex format
    Vertex shader
    Pixel shader
    Per-pixel colors
    Textured triangle
    Triangle strip
    World transform
    World normals
    Per-pixel lighting
    Shadow map
    Render to texture
    Projective texturing
    Real shadow
    Shaping the light
    Preshaders
    3D Series 4: Adv. terrain (19)
    Starting code
    Mouse camera
    Textured terrain
    Multitexturing
    Adding detail
    Skydome
    The water technique
    Refraction map
    Reflection map
    Perfect mirror
    Ripples
    The Fresnel term
    Moving water
    Specular highlights
    Billboarding
    Region growing
    Billboarding renderstates
    Perlin noise
    Gradient skybox
    Short Tuts (3)
    Run XNA on older pcs
    MessageBox in XNA
    Normal generation
    DirectX using C# (54)
    Series 1:Terrain (14)
    Opening a window
    Linking to the Device
    Drawing a triangle
    Camera
    Rotation - Translation
    Indices
    Terrain creation
    Terrain from file
    DirectInput
    Importing bmp files
    Colored vertices
    DirectX Light basics
    Mesh creation
    Mesh lighting
    Series 2: Flightsim (19)
    Starting code
    Textures
    The floorplan
    Creating the 3D City
    Meshloading from file
    Ambient light
    Action
    Flight kinematics
    Collision detection
    Skybox
    Texture filtering
    Adding targets
    Point sprites
    Alpha blending
    DirectSound
    Sounds in 3D
    Playing MP3 files
    Displaying text
    Going fullscreen
    Series 3: HLSL (19)
    Starting point
    HLSL Introduction
    Vertex Shader
    Shaded triangle
    Pixel Shader
    Textured Triangle
    Triangle Strip
    World transform
    Adding normals
    The first light
    Shadow mapping
    Render To Texture
    Projective texturing
    The first shadow
    Shaping the light
    Preshaders
    Multiple lights
    Adjusting Z values
    Finishing touch
    Short Tuts (2)
    Resizing problem
    Checking Device caps
    DirectX using C++ (15)
    Series 1: Terrain (15)
    Opening a window
    Ending the game loop
    Linking to the Device
    Clearing your window
    Drawing a triangle
    Culling
    Camera
    Rotation - Translation
    Indices
    Terrain creation
    Terrain from file
    DirectInput
    Importing .bmp files
    Adding colors
    DirectX Light basics
    DirectX using VB (2)
    Series 1: Intro (2)
    The first triangle
    Rotation - translation
    -- Tree view --


    Thank you!

    Support this site --
    any amount is welcome !

    Stay up-to-date

    I don't have the time to keep a News section, so stay informed about the updates by clicking on this RSS file!