3D Projection (Perspective). Not what I would expect…

I have some code based on the 3d perspective projection formula I found on wiki.

http://en.wikipedia.org/wiki/3D_projection

It works great... mostly :)

I recently started making the code do z ordering/culling... but I was getting weird results. After a lot of debugging I came to realise my formula for working out the zorder value is wrong.

So... I created this in sketchup.

The params I use to do the projection are CoordinateToProject, CameraPosition, CameraRotation, ViewerPosition.

1) What exactly is the formula I need calculate the zorder value/distance, please?

2) Why does my code not support -Z? Is it a most likely a bug in my code or a limitation of the formula?

THANKS :)

Edit: I am now happy with the answer to number 2. I just need to know how to calculate the z order.... any links/help would be appreciated!!!!

-

Could you give more information on which coordinates you use(left handed, right handed)? The exact matrix will relate on the handedness.

If you are using an OpenGL style projection, you would better look at this: glFrustum

Notice that both nearZ and farZ are positive.

finally a hint: you need to do more than just projection since you may want linear z value(1/z)

EDIT: I find this may help you: projection matrix

EDIT for question #1:

this is a perspective projection matrix $$\begin{bmatrix} \frac{2n}{r-l} & 0 & -\frac{r+l}{r-l} & 0\\ 0 & \frac{2n}{t-b} & -\frac{t+b}{t-b} & 0\\ 0 & 0 & \frac{f}{f-n} & -\frac{fn}{f-n}\\ 0 & 0 & 1 & 0 \end{bmatrix}$$ ATTENTION please: this is a projection transformation for left handed coordinate system and it is a column-major matrix(every column forms a frame bases), and it maps Z to [0,1] in NDC(if you do not know what it is, search "Normalized Device Coordinates"), and notice that the Z is NOT linear(that is, a median point in Z direction will not be mapped to 0.5)

-
Thanks for the z positive bit. –  Beakie Aug 22 '12 at 2:07
I use Left handed. –  Beakie Aug 22 '12 at 2:08
I don't use OpenGL ...yet... i am coding it all to ensure i understand everything fully... will then look at hardware acceleration. –  Beakie Aug 22 '12 at 2:13
@Beakie Could you post your code relevant to your problem? –  craftsman.don Aug 22 '12 at 2:41
Not really. It's fragmented across many classes/quite unreadable. The code is simply based on wikis formula. It works fine. I am happy with the responses by craftsman.don. My question now really is only about the z order. Thanks –  Beakie Aug 22 '12 at 3:00