views:

203

answers:

2

Hi there, I'm using a 3d engine and need to translate between 3d world space and 2d screen space using perspective projection, so I can place 2d text labels on items in 3d space. I've seen a few posts of various answers to this problem but they seem to use components I don't have.

I have a Camera object, and can only set it's current position and lookat position, it cannot roll. The camera is moving along a path and certain target object may appear in it's view then disappear. I have only the following values

  • lookat position
  • position
  • vertical FOV
  • Z far
  • Z near
  • and obviously the position of the target object.

Can anyone please give me an algorithm that will do this using just these components?

Many thanks.

+3  A: 

all graphics engines use matrices to transform between different coordinats systems. Indeed OpenGL and DirectX uses them, because they are the standard way.

Cameras usually construct the matrices using the parameters you have:

  • view matrix (transform the world to position in a way you look at it from the camera position), it uses lookat position and camera position (also the up vector which usually is 0,1,0)

  • projection matrix (transforms from 3D coordinates to 2D Coordinates), it uses the fov, near, far and aspect.

You could find information of how to construct the matrices in internet searching for the opengl functions that create them:

  • gluLookat creates a viewmatrix

  • gluPerspective: creates the projection matrix

But I cant imagine an engine that doesnt allow you to get these matrices, because I can ensure you they are somewhere, the engine is using it.

Once you have those matrices, you multiply them, to get the viewprojeciton matrix. This matrix transform from World coordinates to Screen Coordinates. So just multiply the matrix with the position you want to know (in vector 4 format, being the 4º component 1.0).

But wait, the result will be in homogeneous coordinates, you need to divide X,Y,Z of the resulting vector by W, and then you have the position in Normalized screen coordinates (0 means the center, 0.5 means right, etc).

From here it is easy to transform multiplying by width and height.

Good luck :)

P.S: when you work with 3D it is really important to understand the three matrices (model, view and projection), otherwise you will stumble every time.

tamat
A: 

so I can place 2d text labels on items in 3d space

Have you looked up "billboard" techniques? Sometimes just knowing the right term to search under is all you need. This refers to polygons (typically rectangles) that always face the camera, regardless of camera position or orientation.

LarsH