Raheel Khan
Raheel Khan

Reputation: 14787

Rendering a point or plane in 3D

Although my current project is XNA, this question is about the basic mathematics of 3D to 2D mapping. In fact, and for the same reason, let's assume a WinForms graphics surface to draw on.

I have the following configuration:

I want to transform these coordinates and draw them on a 2D surface. So depending on the camera, the line segment should transform from (x1, y1, z1),(x2, y2, z2) to (x1, y1),(x2, y2).

Upvotes: 2

Views: 1996

Answers (1)

John Alexiou
John Alexiou

Reputation: 29274

I think you are looking for an orthogonal or perspective projection. There is a lot of information online if you search for it but here is the gist.

A camera looking at the origin, located a distance d along the z-axis will project a point at (x,y,z) onto a plane as:

// Orthogonal
planar_x = x
planar_y = y

// Perspective
planar_x = x*d/(d-z)
planar_y = y*d/(d-z)

Example

A point at (10,10,10) with the camera located a distance of 500 along the z axis will have planar coordinates (10*500/(500-10), 10*500/(500-10)) = (10.204, 10.204)

A point at (10,10,100) with the camera located a distance of 500 along the z axis will have planar coordinates (10*500/(500-100), 10*500/(500-100)) = (12.5, 12.5)

So the closer a shape is to the camera the larger it appears.

To transform the planar model coordinates to pixel coordinates I use the following scaling

scale = max_model_size/Math.Min(Height,Width);
pixel_x = Width/2 + x/scale;
pixel_y = Height/2- y/scale;

This is how I can use GDI to draw 3D shapes on a windows form.

Form

Of course if you want to use OpenGL then look here for a similar question.

Upvotes: 3

Related Questions