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

 Account settings
  Posted by: igthorn
  When: 21/04/2014 at 10:20:00

 Pavtube 2014 Easter Deals with 20% off
  Posted by: igthorn
  When: 21/04/2014 at 10:16:23

 20% off on iMedia Converter for Mac
  Posted by: VIKIVannessa
  When: 20/04/2014 at 01:35:54

 Pavtube Video Converter Ultimate Deal
  Posted by: VIKIVannessa
  When: 20/04/2014 at 01:35:50

 Easter Day Deals
  Posted by: Applefly
  When: 19/04/2014 at 22:18:14

 40% OFF Pavtube DVD Ripper for Mac
  Posted by: VIKIVannessa
  When: 19/04/2014 at 02:02:54

 DVD Ripper with 40% off
  Posted by: VIKIVannessa
  When: 19/04/2014 at 02:02:22

 Get DVD Ripper Wind/Mac + $14 Coupon
  Posted by: VIKIVannessa
  When: 19/04/2014 at 02:02:03

 Backup DVD Escape Plan
  Posted by: Applefly
  When: 17/04/2014 at 06:00:12

 Disney DVDs to MP4
  Posted by: Applefly
  When: 17/04/2014 at 05:56:07


Ads

World Space coordinates and camera view

Last chapter we drew our first triangle, using 'transformed' coordinates. These coordinates are already 'transformed' so you can directly specify their position on the screen. However, you will usually use the untransformed coordinates, the so called World space coordinates. These allow you to create a whole scene using simple 3D coordinates, and, most important, to position a camera and set its viewing point.

We start from the code from chapter 5, but from last chapter we keep the line that turns culling off, because we’re in designing mode. The previous chapters used transformed coordinates, and for this reason we needed the additional ‘weight’ component. Now we’ll be using the World coordinates, and thus we must no longer use this additional component, so redefine the OURCUSTOMVERTEX struct:

 struct OURCUSTOMVERTEX
 {
     float x,y,z;
     DWORD color;
 };

Which pretty much explains itself. Also, make sure you delete the lines where you set the weights in the FillVertices method, and let’s update the coordinates of our triangle:

 cv_Vertices[0].x = 5.0f;
 cv_Vertices[0].y = 10.0f;
 cv_Vertices[0].z = 0.0f;
 cv_Vertices[0].color = 0xffff0000;
 
 cv_Vertices[1].x = 10.0f;
 cv_Vertices[1].y = 0.0f;
 cv_Vertices[1].z = 0.0f;
 cv_Vertices[1].color = 0xff00ff00;
 
 cv_Vertices[2].x = 0.0f;
 cv_Vertices[2].y = 0.0f;
 cv_Vertices[2].z = 0.0f;
 cv_Vertices[2].color = 0xff00ffff;

Also remember you told DirectX twice which kind of vertex information it should expect. Change this to D3DFVF_XYZ|D3DFVF_DIFFUSE, which indicates that you are defining triangles in world coordinates and with a color. This code will already compile, and if you’re lucky you might see a black triangle. But this isn’t what we want. We still need to define where and how we want to position our camera, through which we look at the scene. To this end, we are going to write a new method called SetUpCamera, that does exactly what the name implies. It will need a pointer to the device:

 void SetUpCamera(LPDIRECT3DDEVICE9 p_dx_Device)
 {
 }

First we start intuitively by defining the position of our camera, also in 3D coordinates. Then we need to define which point the camera has to look at, which is our targeting point. If you think of it, with these two positions defined, there are still multiple ways how you can position your camera, because you can still rotate around your viewing axe. So to uniquely define a camera, we need to define an ‘Up’ vector of the camera:

 D3DXVECTOR3 m_EyePos(0, 0, -30);
 D3DXVECTOR3 m_TargetPos(0, 0, 0);
 D3DXVECTOR3 m_UpVector(0, 1, 0);
 D3DXMATRIXA16 m_View;
 D3DXMatrixLookAtLH(&m_View, &m_EyePos, &m_TargetPos, &m_UpVector);
 p_dx_Device->SetTransform(D3DTS_VIEW, &m_View);

The first three lines do exactly what is described above. Then you define a matrix and transform this matrix so it represents the position and rotation of your camera. So what exactly is a matrix? Put simply, a matrix is an array of numbers, a 2D collection of numbers. A D3DXMATRIXA16 struct contains 4 rows of 4 numbers. With this kind of array, you can mathematically describe any position of an object, together with its rotation. Only the last sentence is of importance when working with matrices in DirectX, DirectX does all the maths for you. Such as the D3DXMatrixLookAtLH method, which creates a such a 4x4 matrix corresponding to the position and rotation of your camera. It is this matrix m_View that you can pass to your device to define your camera.

One last thing we have to do is to define the lens of the camera, if you will. T
his info will also be stored in a matrix, which is passed later to the device. You will define the viewing angle of your camera, which usually is 45° or PI/4. Then we need to give the relation of the width of our window to the height of our window, which is 500/500=1 in our case. As a last thing, we need to define the near and far clipping plane. All objects in the scene closer to the camera than the near clipping plane will not be displayed, the same for all objects further away from the camera than the far clipping plane. This way DirectX does not have to draw every object you define in the scene. All objects far away from the camera will be very small anyway, but otherwise DirectX would have to draw them all. And drawing a small triangle takes the same amount of time as drawing a large one.

 D3DXMATRIX m_Projection;
 D3DXMatrixPerspectiveFovLH(&m_Projection, D3DX_PI/4, 500/500, 1, 50);
 p_dx_Device->SetTransform(D3DTS_PROJECTION, &m_Projection);

The last line actually passes the matrix to the device. Don’t forget to call the SetUpCamera method from within the WinMain method. When you compile and run this code, you should see a triangle, but it’s all black. This is because in World coordinates, DirectX expects some lights. Because lights will be covered in a future chapter, let’s simply tell DirectX that we won’t be using any lights:

 p_dx_Device->SetRenderState(D3DRS_LIGHTING,false);

Put this code immediately after you create your device.




DirectX Tutorial 7 - Camera

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



Click here to go to the forum on this chapter!

Or click on one of the topics on this chapter to go there:
  • External symbols error
          When using this chapter, I get the following error...
  • Camera placement
          Is there a rule of thumb for setting up the best c...
  • Heelllp!!
          Hello all, Pls I've compiled this tutorial and...
  • Transforms in my own code
          In another futile attempt to use my own D3D code, ...
  • can't find d3dx9d.dll?
          I compiled with the new code for setting up the ca...



    The code for this chapter:


    #include<windows.h>
    #include<d3d9.h>
    #include<d3dx9.h>

     struct OURCUSTOMVERTEX
     {
         float x,y,z;
         DWORD color;
     };
     
     int int_AppRunning = 1;
     
     LRESULT CALLBACK OurWindowProcedure(HWND han_Wind,UINT uint_Message,WPARAM parameter1,LPARAM parameter2)
     {
         switch(uint_Message)
         {
             case WM_KEYDOWN:
             {
                 int_AppRunning = 0;
                 break;
             }
             break;
         }
     
         return DefWindowProc(han_Wind,uint_Message,parameter1,parameter2);
     }
     
     HWND NewWindow(LPCTSTR str_Title,int int_XPos, int int_YPos, int int_Width, int int_Height)
     {
         WNDCLASSEX wnd_Structure;
     
         wnd_Structure.cbSize = sizeof(WNDCLASSEX);
         wnd_Structure.style = CS_HREDRAW | CS_VREDRAW;
         wnd_Structure.lpfnWndProc = OurWindowProcedure;
         wnd_Structure.cbClsExtra = 0;
         wnd_Structure.cbWndExtra = 0;
         wnd_Structure.hInstance = GetModuleHandle(NULL);
         wnd_Structure.hIcon = NULL;
         wnd_Structure.hCursor = NULL;
         wnd_Structure.hbrBackground = GetSysColorBrush(COLOR_BTNFACE);
         wnd_Structure.lpszMenuName = NULL;
         wnd_Structure.lpszClassName = "WindowClassName";
         wnd_Structure.hIconSm = LoadIcon(NULL,IDI_APPLICATION);
     
         RegisterClassEx(&wnd_Structure);
     
         return CreateWindowEx(WS_EX_CONTROLPARENT, "WindowClassName", str_Title, WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_VISIBLE, int_XPos, int_YPos, int_Width, int_Height, NULL, NULL, GetModuleHandle(NULL), NULL);
     }
     
     LPDIRECT3DDEVICE9 InitializeDevice(HWND han_WindowToBindTo)
     {
         LPDIRECT3D9 p_dx_Object;
         LPDIRECT3DDEVICE9 p_dx_Device;
     
         p_dx_Object = Direct3DCreate9(D3D_SDK_VERSION);
         if (p_dx_Object == NULL)
         {
             MessageBox(han_WindowToBindTo,"DirectX Runtime library not installed!","InitializeDevice()",MB_OK);
         }
     
         D3DPRESENT_PARAMETERS dx_PresParams;
         ZeroMemory( &dx_PresParams, sizeof(dx_PresParams) );
         dx_PresParams.Windowed = TRUE;
         dx_PresParams.SwapEffect = D3DSWAPEFFECT_DISCARD;
         dx_PresParams.BackBufferFormat = D3DFMT_UNKNOWN;
     
         if (FAILED(p_dx_Object->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, han_WindowToBindTo, D3DCREATE_HARDWARE_VERTEXPROCESSING, &dx_PresParams, &p_dx_Device)))
         {
             if (FAILED(p_dx_Object->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_REF, han_WindowToBindTo, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &dx_PresParams, &p_dx_Device)))
             {
                 MessageBox(han_WindowToBindTo,"Failed to create even the reference device!","InitializeDevice()",MB_OK);
             }
      }
     
         p_dx_Device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
         p_dx_Device->SetRenderState(D3DRS_LIGHTING,false);
     
         return p_dx_Device;
     }
     
     void DrawScene(LPDIRECT3DDEVICE9 p_dx_Device, LPDIRECT3DVERTEXBUFFER9 p_dx_VertexBuffer)
     {
         p_dx_Device->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(72,61,139), 1.0f, 0);
         p_dx_Device->BeginScene();
     
         p_dx_Device->SetStreamSource(0, p_dx_VertexBuffer, 0, sizeof(OURCUSTOMVERTEX));
         p_dx_Device->SetFVF(D3DFVF_XYZ|D3DFVF_DIFFUSE);
         p_dx_Device->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 1);
     
         p_dx_Device->EndScene();
         p_dx_Device->Present(NULL, NULL, NULL, NULL);
     }
     
     LPDIRECT3DVERTEXBUFFER9 FillVertices(HWND han_Window, LPDIRECT3DDEVICE9 p_dx_Device)
     {
         OURCUSTOMVERTEX cv_Vertices[3];
         LPDIRECT3DVERTEXBUFFER9 p_dx_VertexBuffer;
     
         cv_Vertices[0].x = 5.0f;
         cv_Vertices[0].y = 10.0f;
         cv_Vertices[0].z = 0.0f;
         cv_Vertices[0].color = 0xffff0000;
     
         cv_Vertices[1].x = 10.0f;
         cv_Vertices[1].y = 0.0f;
         cv_Vertices[1].z = 0.0f;
         cv_Vertices[1].color = 0xff00ff00;
     
         cv_Vertices[2].x = 0.0f;
         cv_Vertices[2].y = 0.0f;
         cv_Vertices[2].z = 0.0f;
         cv_Vertices[2].color = 0xff00ffff;
     
         if (FAILED(p_dx_Device->CreateVertexBuffer(3*sizeof(OURCUSTOMVERTEX), 0, D3DFVF_XYZ|D3DFVF_DIFFUSE, D3DPOOL_DEFAULT, &p_dx_VertexBuffer, NULL)))
         {
             MessageBox(han_Window,"Error while creating VertexBuffer","FillVertices()",MB_OK);
         }
     
         VOID* p_Vertices;
         if (FAILED(p_dx_VertexBuffer->Lock(0, 3*sizeof(OURCUSTOMVERTEX), (void**)&p_Vertices, 0)))
         {
             MessageBox(han_Window,"Error trying to lock","FillVertices()",MB_OK);
         }else{
             memcpy(p_Vertices, cv_Vertices, 3*sizeof(OURCUSTOMVERTEX));
             p_dx_VertexBuffer->Unlock();
         }
     
         return p_dx_VertexBuffer;
     }
     
     void SetUpCamera(LPDIRECT3DDEVICE9 p_dx_Device)
     {
         D3DXVECTOR3 m_EyePos(0, 0, -30);
         D3DXVECTOR3 m_TargetPos(0, 0, 0);
         D3DXVECTOR3 m_UpVector(0, 1, 0);
         D3DXMATRIXA16 m_View;
         D3DXMatrixLookAtLH(&m_View, &m_EyePos, &m_TargetPos, &m_UpVector);
         p_dx_Device->SetTransform(D3DTS_VIEW, &m_View);
     
         D3DXMATRIX m_Projection;
         D3DXMatrixPerspectiveFovLH(&m_Projection, D3DX_PI/4, 500/500, 1, 50);
         p_dx_Device->SetTransform(D3DTS_PROJECTION, &m_Projection);
     }
     
     int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPreviousInstance,LPSTR lpcmdline,int nCmdShow)
     {
         MSG msg_Message;
     
         HWND han_Window = NewWindow("DirectX C++ Tutorial",100,100,500,500);
         LPDIRECT3DDEVICE9 p_Device = InitializeDevice(han_Window);
         LPDIRECT3DVERTEXBUFFER9 p_dx_VB = FillVertices(han_Window, p_Device);
         SetUpCamera(p_Device);
     
         while(int_AppRunning)
         {
             if(PeekMessage(&msg_Message,han_Window,0,0,PM_REMOVE))
             {
                 DispatchMessage(&msg_Message);
             }
             DrawScene(p_Device, p_dx_VB);
         }
     
         p_Device->Release();
         DestroyWindow(han_Window);
     
         return 0;
     }


    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)
    XNA 3.0 Recipes Book (8)
    Downloads
    Extra Reading (3)
    Matrices: geometrical
    Matrix Mathematics
    Homogenous matrices
    Community Projects (1)
    Tutorials (160)
    XNA 4.0 using C# (89)
    DirectX using C# (54)
    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)
    -- Expand all --


    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!