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

World Space coordinates and camera view

Last chapter we drew a 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.

So we'll start with redefining our triangle coordinates in world space. Replace the code in your OnPaint method with this code:

 CustomVertex.PositionColored[] vertices = new CustomVertex.PositionColored[3];
 vertices[0].Position = new Vector3(0f, 0f, 0f);
 vertices[0].Color = Color.Red.ToArgb();
 vertices[1].Position = new Vector3(10f, 0f, 0f);
 vertices[1].Color = Color.Green.ToArgb();
 vertices[2].Position = new Vector3(5f, 10f, 0f);
 vertices[2].Color = Color.Yellow.ToArgb();

All you've done here is changed the format from pre-transformed coordinates to 'normal' coordinates. Also let the device know your format has changed :

 device.VertexFormat = CustomVertex.PositionColored.Format;

Let's run this code.

Very nice, your triangle has disappeared again. Why's that ? Easy, because you haven't told DirectX yet where to position the camera and where to look at! To position your camera, simply add the following code as the first lines in your OnPaint method :

 device.Transform.Projection = Matrix.PerspectiveFovLH((float)Math.PI/4, this.Width/this.Height, 1f, 50f);
 device.Transform.View = Matrix.LookAtLH(new Vector3(0,0,30), new Vector3(0,0,0), new Vector3(0,1,0));

The first line tells the device what and how the camera should look at the scene. The first parameter sets the view angle, 90° in our case. The we set the view aspect ratio, which is 1 in our case, but will be different if our window is a rectangle instead of a square. The last parameters define the view range. Any objects closer to the camera than 1f will not be shown. Any object farther than 50f won't be shown either. These distances are called the near and the far clipping planes, since all objects between these planes will be clipped (=not drawn).

The second line actually positions the camera. The first parameter defines the position. We position it 30 units above our (0,0,0) point, the origin. The next parameter sets the target point the camera is looking at. We will be looking at our origin. At this point, we have defined the viewing axis of our camera, but we can still rotate our camera around this axe. So we still need to define which vector will be considered as 'up'. Now run the code again.

This time, we see a triangle, but it's all black! This is because world space is a little more advanced than our previous chapter. Here we are also required to place some lights. However, these will be handled in a following chapter, thus here we will simply tell our device not to expect any lights. Add the following line underneath your camera definition and you'll see our colored triangle again:

 device.RenderState.Lighting = false;

Now everything has been set to use world space coordinates. One thing you should notice: you'll see the green corner of the triangle on the LEFT side of the window, while you defined it on the POSITIVE x-axis. This is because DirectX uses left-handed coordinates!! So, if you would position your camera on the negative z-axis:

 device.Transform.View = Matrix.LookAtLH(new Vector3(0,0,-30), new Vector3(0,0,0), new Vector3(0,1,0));

you would expect to see the green point in the right half of the window. Try to run this now.

This might again not be exactly what you expected. Something very important has happened. DirectX only draws triangles that are facing the camera. DirectX defines that triangles facing the camera should be drawn clockwise relative to the camera. If you position the camera on the negative z-axis, the triangle will be defined counter-clockwise relative to the camera, and thus will not be drawn! One way to remove this problem is simply redefining the vertices clockwise (this time clockwise relative to our camera on the negative part of the Z axis) :

 vertices[2].Position = new Vector3(0f, 0f, 0f);
 vertices[2].Color = Color.Red.ToArgb();
 vertices[0].Position = new Vector3(5f, 10f, 0f);
 vertices[0].Color = Color.Yellow.ToArgb();
 vertices[1].Position = new Vector3(10f, 0f, 0f);
 vertices[1].Color = Color.Green.ToArgb();

This will indeed draw the triangle with the green point to the right. The other way is to add the following line after you camera definition :

 device.RenderState.CullMode = Cull.None;

This will simply draw all triangles, even those not facing the camera. You should note that this should never be done in a final product, because it slows down the drawing process, as all triangles will be drawn, even those not facing the camera! However, while designing, it is wise to turn off culling, so you'll always see everything you draw. Also, I chose the background color to be non-black, again because if your triangle might be wrongly defined and drawn black, you'ld still see it. So, while designing, you should turn culling off and set a non-black background color.




DirectX Tutorial 4 - 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:
  • I have a problem(with camera i think)
          Hello, great tutorial. But i have a problem, I've...
  • Camera Movement with Mouse
          I have come up with some code to rotate the camera...
  • mistake found
           hi, first i wanna say that i like you...
  • zbuffer needed?
          I have the same problem as in the other post - the...
  • Error in lesson
          I don't know if anyone has spotted it but there i...
  • worldspace coordinates
          I'm confused about the world space coordinates. I...
  • FOV Angle
           device.Transform.Projection = Matrix.Perspe...



    You can find some more information on culling in the Culling chapter of the C++ part of this tutorial, where I have made a small animation to visualize the culling process.

    Here's the complete code again :

     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 Device device;
             private System.ComponentModel.Container components = null;
      
             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);
             }
      
             protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
             {
                 device.Transform.Projection = Matrix.PerspectiveFovLH((float)Math.PI/4, this.Width/this.Height, 1f, 50f);
                 device.Transform.View = Matrix.LookAtLH(new Vector3(0,0,-30), new Vector3(0,0,0), new Vector3(0,1,0));
                 device.RenderState.Lighting = false;
                 device.RenderState.CullMode = Cull.None;
      
                 CustomVertex.PositionColored[] vertices = new CustomVertex.PositionColored[3];
                 vertices[0].Position = new Vector3(0f, 0f, 0f);
                 vertices[0].Color = Color.Red.ToArgb();
                 vertices[1].Position = new Vector3(10f, 0f, 0f);
                 vertices[1].Color = Color.Green.ToArgb();
                 vertices[2].Position = new Vector3(5f, 10f, 0f);
                 vertices[2].Color = Color.Yellow.ToArgb();
     
      
                 device.Clear(ClearFlags.Target, Color.DarkSlateBlue , 1.0f, 0);
      
                 device.BeginScene();
                 device.VertexFormat = CustomVertex.PositionColored.Format;
                 device.DrawUserPrimitives(PrimitiveType.TriangleList, 1, vertices);
                 device.EndScene();
     
                 device.Present();
      
                 this.Invalidate();
             }
      
             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.InitializeDevice();
                     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!