So, I feel like an idiot and I'm losing faith in my ability to understand 3-D maths.
I want to project a triangle from 3-D space into 2-D space. Sounds simple enough, just use a model-view-projection matrix. Got it, easy. However, I just don't seem to get a grasp on how to implement near clip plane intersection.
See, transforming the triangle into 2-D is easy enough as long as all of the vertices are in front of the viewer. As soon as one, or worse two vertices lie behind the viewer, I can't calculate the screen coordinates of these vertices.
Of course, asking here was the last straw, and I've read a lot of articles and discussions and poured many hours into trying to solve this problem, to no avail.
The solution I've read sounds simple enough: find the intersection point between the vertex in front of and the one behind the viewer with the near clip plane (so that W=1
). I understand the reasoning and the necessity, however there is one case that just breaks my brain:
In this video, when one vertex lies behind the viewer, I switch which vertex in front of the viewer to use to compute the intersection with the near clip plane each frame, resulting in the correct screen coordinates in one frame, and the wrong coordinates in the other.
-- EDIT -- I just realized that I may not be allowed to upload videos to YouTube with necessary frame rate, so the video I uploaded doesn't quite show what I'm referring to.
As you can see, intersecting the near clip plane with two different vertices in front the viewer gives different results.
I just don't get how to determine which one of those vertices in front the viewer to use to calculate the correct screen-space coordinates for vertices behind the viewer.
This code intersects with the near clip plane (at 1.0
):
float s = (1.0 - bw) / (fw - bw);
// fx, fy, fw is the vertex in front of the viewer
// bx, by, bw is the vertex behind the viewer
float screen_x = bx + (fx - bx) * s;
float screen_y = by + (fy - by) * s;
Thanks in advance for any kind of help!
-- EDIT --
Turns out, I am an idiot. Of course intersecting the near clip plane with two different lines (sharing the vertex behind the viewer) would result in different intersection points, because clipping the triangle with the near clip plane turns the triangle into a quad (formed by the two vertices in front of the viewer and two vertices from the intersection with the near clip plane.)
The forest was hidden behind all those trees.