Im struggling with the following problem. Im working with bone animation and I want (ie) the head of the player to follow an another object in space. My up axis is +Z my forward axis is +Y, and the magnitude of the quaternion is in W. I tried to use the mesa code for gluLookAt and use the 3x3 matrix to transform to a quaternion but it doesn't work as expected so I go in another direction...
So far I got the following code that is "almost" working at least the head of the player is rotating (however the X angle seems to affect the Y rotation axis) in the good direction but its looking straight up instead on following an object on the floor at about 65 degree:
qt LookRotation( v3 lookAt, v3 upDirection )
{
qt t;
v3 forward = lookAt;
v3 up = upDirection;
OrthoNormalize( &forward, &up );
v3 right = v3_cross( up, forward );
mat3 m = mat3_make( right.x, up.x, forward.x,
right.y, up.y, forward.y,
right.z, up.z, forward.z );
t.w = sqrtf( 1.0f +
m.r[ 0 ].x +
m.r[ 1 ].y +
m.r[ 2 ].z ) * 0.5f;
float w4_recip = 1.0f / ( 4.0f * t.w );
t.x = ( m.r[ 2 ].y - m.r[ 1 ].z ) * w4_recip;
t.y = ( m.r[ 0 ].z - m.r[ 2 ].x ) * w4_recip;
t.z = ( m.r[ 1 ].x - m.r[ 0 ].y ) * w4_recip;
t = qt_normalize( t );
return t;
}
...
...
...
v3 v = v3_sub( vec4_to_v3( transform.world.r[ 3 ] /* The object XYZ location in the world */),
skeleton->final_pose.location[ i ] /* i = The head joint location */ );
v = v3_normalize( v );
qt q = LookRotation( v,
v3_make( 0.0f, 0.0f, 1.0f ) );
Can someone help me figuring out this problem... Im kinda new with quaternions and don't really know where I could have messed up. After quite some research basically what I want to do is something like the Unity API: http://docs.unity3d.com/Documentation/ScriptReference/Quaternion.LookRotation.html
I think this function will do what you need:
/// <summary>
/// Evaluates a rotation needed to be applied to an object positioned at sourcePoint to face destPoint
/// </summary>
/// <param name="sourcePoint">Coordinates of source point</param>
/// <param name="destPoint">Coordinates of destionation point</param>
/// <returns></returns>
public static Quaternion LookAt(Vector3 sourcePoint, Vector3 destPoint)
{
Vector3 forwardVector = Vector3.Normalize(destPoint - sourcePoint);
float dot = Vector3.Dot(Vector3.forward, forwardVector);
if (Math.Abs(dot - (-1.0f)) < 0.000001f)
{
return new Quaternion(Vector3.up.x, Vector3.up.y, Vector3.up.z, 3.1415926535897932f);
}
if (Math.Abs(dot - (1.0f)) < 0.000001f)
{
return Quaternion.identity;
}
float rotAngle = (float)Math.Acos(dot);
Vector3 rotAxis = Vector3.Cross(Vector3.forward, forwardVector);
rotAxis = Vector3.Normalize(rotAxis);
return CreateFromAxisAngle(rotAxis, rotAngle);
}
// just in case you need that function also
public static Quaternion CreateFromAxisAngle(Vector3 axis, float angle)
{
float halfAngle = angle * .5f;
float s = (float)System.Math.Sin(halfAngle);
Quaternion q;
q.x = axis.x * s;
q.y = axis.y * s;
q.z = axis.z * s;
q.w = (float)System.Math.Cos(halfAngle);
return q;
}
This code comes from here:
https://gamedev.stackexchange.com/questions/15070/orienting-a-model-to-face-a-target
I just slightly modified it to fit my case, which was implementation of the transform.LookAt without using Unity3D.
Both of current answers have various problems for edge cases. The accepted answer is not correct for other reasons as well including the fact that it sets w=pi for one of the cases and also it doesn't do proper norms. After looking around quite a bit and testing several cases, I also found out that you need front and up vector to do this computation. So without further ado below is the code I'm using:
Quaternion lookAt(const Vector3f& sourcePoint, const Vector3f& destPoint, const Vector3f& front, const Vector3f& up)
{
Vector3f toVector = (destPoint - sourcePoint).normalized();
//compute rotation axis
Vector3f rotAxis = front.cross(toVector).normalized();
if (rotAxis.squaredNorm() == 0)
rotAxis = up;
//find the angle around rotation axis
float dot = VectorMath::front().dot(toVector);
float ang = std::acosf(dot);
//convert axis angle to quaternion
return Eigen::AngleAxisf(rotAxis, ang);
}
Bove uses popular Eigen library. If you don't want to use that then you might need following replacement for Eigen::AngleAxisf:
//Angle-Axis to Quaternion
Quaternionr angleAxisf(const Vector3r& axis, float angle) {
auto s = std::sinf(angle / 2);
auto u = axis.normalized();
return Quaternionr(std::cosf(angle / 2), u.x() * s, u.y() * s, u.z() * s);
}
Note that special cases for dot product 0 or 1 or -1 gets automatically handled because normalized() returns 0 for the zero vector in Eigen library.
On the side note, for all your conversions worries, this is a great document to go to.
You don't need to use acos and axis angle (which will in turn do 2 more trig functions) to get the quaternion from 2 vectors:
public static Quaternion LookAt(Vector3 sourcePoint, Vector3 destPoint)
{
Vector3 forwardVector = Vector3.Normalize(destPoint - sourcePoint);
Vector3 rotAxis = Vector3.Cross(Vector3.forward, forwardVector);
float dot = Vector3.Dot(Vector3.forward, forwardVector);
Quaternion q;
q.x = rotAxis.x;
q.y = rotAxis.y;
q.z = rotAxis.z;
q.w = dot+1;
return q.normalize();
}
The reason for the dot+1 and subsequent normalize is because if you don't, you'll get the quaternion for the double rotation. Those 2 steps will effectively do slerp(identity, q, 0.5) which will be the proper quaternion.
Related
i'm making a car race for the first time using opengl,the first problem i face is how to make the camera follow the car with constant distance..here is the code for keyboard function.V is the velocity of the car.
void OnSpecial(int key, int x, int y)
{
float step = 5;
switch(key) {
case GLUT_KEY_LEFTa:
carAngle = step;
V.z = carAngle ;
camera.Strafe(-step/2);
break;
case GLUT_KEY_RIGHT:
carAngle = -step;
V.z = carAngle ;
camera.Strafe(step/2);
break;
case GLUT_KEY_UP:
V.x += (-step);
camera.Walk(step/2);
break;
case GLUT_KEY_DOWN:
if(V.x<0)
{
V.x += step;
camera.Walk(-step/2);
}
break;
}
}
Something like that maybe ?
vec3 cameraPosition = carPosition + vec3(20*cos(carAngle), 10,20*sin(carAngle));
vec3 cameraTarget = carPosition;
vec3 cameraUp = vec3(0,1,0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity()
gluLookAt(cameraPosition, cameraTarget, cameraUp);
glTranslate(carPosition);
drawCar();
It you're not using the old and deprecated openGL API (glBegin & stuff) you'll have to do something like
mat4 ViewMatrix = LookAt(cameraPosition, cameraTarget, cameraUp); // adapt depending on what math library you use
The answer to that is simple. You have player controlled object (car) so you have its position and orientation via ModelViewMatrix in world space (usually pointed to the center of 3D model)
To transform it to the correct follow ModelViewMatrix you must:
obtain or construct car ModelMatrix as double M[16]
translate/rotate it to the new position (inside cockpit or behind car)
so the Z axis is pointing the way you want to see. Its usual to have the follow distance as a function of speed
Invert M so M=Inverse(M)
use M as ModelViewMatrix
render
so in an nutshell:
ModelViewMatrix = rendered_object_matrix * Inverse(following_object_matrix * local_view_offset)
for additional stuff you need for this look at my answer here:
https://stackoverflow.com/a/18041433/2521214
I'm writing a C program to render a Mandelbrot set and currently, I'm stuck with trying out to figure out how to zoom in properly.
I want for the zoom to be able to follow the mouse pointer on the screen - so that the fractal zooms in into the cursor position.
I have a window defined by:
# define WIDTH 800
# define HEIGHT 600
My Re_max, Re_min, Im_Max, Im_Min are defined and initialized as follows:
man->re_max = 2.0;
man->re_min = -2.0;
man->im_max = 2.0;
man->im_min = -2.0;
The interpolation value (more on in later) is defined and initialized as follows:
pos->interp = 1.0;
To map the pixel coordinates to the center of the screen, I'm using the position function:
void position(int x, int y, t_mandel *man)
{
double *s_x;
double *s_y;
s_x = &man->pos->shift_x;
s_y = &man->pos->shift_y;
man->c_re = (x / (WIDTH / (man->re_max - man->re_min)) + man->re_min) + *s_x;
man->c_im =(y / (HEIGHT / (man->im_max - man->re_min)) + man->im_min) + *s_y;
man->c_im *= 0.8;
}
To zoom in, I first get the coordinates of the mouse pointer and map them to the visible area given by the rectangle defined by the (Re_Max, Re_Min, Im_Max, Im_Min) using this function, where x and y are coordinates of the pointer on a screen:
int mouse_move(int x, int y, void *p)
{
t_fract *fract;
t_mandel *man;
fract = (t_fract *)p;
man = fract->mandel;
fract->mouse->Re = x / (WIDTH / (man->re_max - man->re_min)) + man->re_min;
fract->mouse->Im = y / (HEIGHT / (man->im_max - man->re_min)) + man->im_min;
return (0);
}
This function is called when a mouse wheel scroll is registered. The actual zooming is achieved by this function:
void zoom_control(int key, t_fract *fract)
{
double *interp;
interp = &fract->mandel->pos->interp;
if (key == 5) // zoom in
{
*interp = 1.0 / 1.03;
apply_zoom(fract->mandel, fract->mouse->Re, fract->mouse->Im, *interp);
}
else if (key == 4) // zoom out
{
*interp = 1.0 * 1.03;
apply_zoom(fract->mandel, fract->mouse->Re, fract->mouse->Im, *interp);
}
}
Which calls this:
void apply_zoom(t_mandel *man, double m_re, double m_im, double interp)
{
man->re_min = interpolate(m_re, man->re_min, interp);
man->im_min = interpolate(m_im, man->im_min, interp);
man->re_max = interpolate(m_re, man->re_max, interp);
man->im_max = interpolate(m_im, man->im_max, interp);
}
I have a simple interpolate function to redefine the area bounding rectangle:
double interpolate(double start, double end, double interp)
{
return (start + ((end - start) * interp));
}
So the problem is:
My code renders the fractal like this -
Mandelbrot set
But when I try to zoom in as described with the mouse, instead of going nicely "in", it just distorts like this, the image just sort of collapses onto itself instead of actually diving into the fractal.
I would really appreciate help with this one as I've been stuck on it for a while now.
If you please could also explain the actual math behind your solutions, I would be overjoyed!
Thank you!
After quite a bit of headache and a lot of paper wasted on recalculation interpolation methods, I've realized that the way I've mapped my complex numbers on-screen was incorrect, to begin with. Reworking my mapping method solved my problem, so I'll share what have I done.
-------------------------------OLD WAY--------------------------------------
I've initialized my Re_max, Re_min, Im_Max, Im_Min values, which define the visible area in the following way:
re_max = 2.0;
re_min = -2.0;
im_max = 2.0;
im_min = -2.0;
Then, I used this method to convert my on-screen coordinates to the complex numbers used to calculate the fractal (note that the coordinates used for mapping the mouse position for zoom interpolation and coordinates used to calculate the fractal itself use the same method):
Re = x / (WIDTH / (re_max - re_min)) + re_min;
Im = y / (HEIGHT / (im_max - re_min)) + im_min;
However, this way I didn't take the screen ratio into account and I've neglected the fact (due to a lack of knowledge) that the y coordinate on-screen is inverse (at least in my program) - negative direction is up, positive is down.
This way, when I tried to zoom in with my interpolation, naturally, the image distorted.
------------------------------CORRECT WAY-----------------------------------
When defining the bounding rectangle of the set, maximum imaginary im_max) part should be calculated, based on the screen ratio, to avoid image distortion when the display window isn't a square:
re_max = 2.0;
re_min = -2.0;
im_min = -2.0;
im_max = im_min + (re_max - re_min) * HEIGHT / WIDTH;
To map the on-screen coordinates to the complex numbers, I first found the "coordinate-to-number* ratio, which is equal to *rectangle length / screen width*:
re_factor = (re_max - re_min) / (WIDTH - 1);
im_factor = (im_max - im_min) / (HEIGHT - 1);
Then, I've mapped my pixel coordinates to the real and imaginary part of a complex number used in calculations like so:
c_re = re_min + x * re_factor;
c_im = im_max - y * im_factor;
After implementing those changes, I was finally able to smoothly zoom into the mouse position without any distortion or image "jumps".
If I understand you correctly, you want to make the point where the mouse is located a new center of the image, and change the scale of the image by a factor of 1.03. I would try something like that:
Your position() and mouse_move() functions remain the same.
in zoom_control() just change the way how you set the new value of interpolation, it should not be a fixed constant, but should be based on its current value. Also, pass the new scaling factor to the apply_zoom():
void zoom_control(int key, t_fract *fract)
{
double *interp;
interp = &fract->mandel->pos->interp;
double zoom_factor = 1.03;
if (key == 5) // zoom in
{
*interp /= zoom_factor;
apply_zoom(fract->mandel, fract->mouse->Re, fract->mouse->Im, 1.0 / zoom_factor);
}
else if (key == 4) // zoom out
{
*interp *= zoom_factor;
apply_zoom(fract->mandel, fract->mouse->Re, fract->mouse->Im, zoom_factor);
}
}
modify the apply zoom function:
void apply_zoom(t_mandel *man, double m_re, double m_im, double zoom_factor)
{
// Calculate the new ranges along the real and imaginary axes.
// They are equal to the current ranges multiplied by the zoom_factor.
double re_range = (man->re_max - man->re_min) * zoom_factor;
double im_range = (man->im_max - man->im_min) * zoom_factor;
// Set the new min/max values for real and imaginary axes with the center at
// mouse coordinates m_re and m_im.
man->re_min = m_re - re_range / 2;
man->re_max = m_re + re_range / 2;
man->im_min = m_im - im_range / 2;
man->im_max = m_im + im_range / 2;
}
I have checked out several solutions in here and other pages for calculating vertex normals. The common solution which seems to work best for my own implementation which renders a 3D terrain is to calculate the face normals, which isn't a problem. And then go over each face and add it's normal to the vertices which make it up and then normalize those when done. It seems to work for the most part, but I have some strange graphical problems, mainly where the light transitions from light to dark, you can tell where the faces are. In the following image you can see this near the lower right side, at the top of this hill.
So I am wondering what is causing this strange pattern. It has something to do with how I am calculating the normals, but I am just not seeing where the issue is. Any help would be appreciated.
The code to calculate the normals is...
// Calclulate surface normals
vec3 v1, v2, v3, vec1, vec2;
for(GLuint i = 0; i < terrain->NumFaces; i++) {
v1 = terrain->Vertices[terrain->Faces[i].vert_indices[0]];
v2 = terrain->Vertices[terrain->Faces[i].vert_indices[1]];
vec1 = vector(&v2, &v1);
v3 = terrain->Vertices[terrain->Faces[i].vert_indices[2]];
vec2 = vector(&v3, &v1);
terrain->Faces[i].surface_normal = crossProduct(&vec1, &vec2);
normalize(&terrain->Faces[i].surface_normal);
}
// Calculate vertex normals...
// Add all the surface normals to their attached vertex normals
for(GLuint currentFace = 0; currentFace < terrain->NumFaces; currentFace++) {
vec3 *f = &terrain->Faces[currentFace].surface_normal;
for(GLuint faceVertex = 0; faceVertex < 3; faceVertex++) {
vec3 *n = &terrain->Normals[terrain->Faces[currentFace].vert_indices[faceVertex]];
*n = vec3Add(n, f); // adds vector f to n
}
}
// Go over all vertices and normalize them
for(GLuint currentVertice = 0; currentVertice < terrain->NumVertices; currentVertice++)
normalize(&terrain->Normals[currentVertice]);
Other utility functions I use in the above code are...
// Returns the vector between two vertices
vec3 vector(const vec3 *vp1, const vec3 *vp2)
{
vec3 ret;
ret.x = vp1->x - vp2->x;
ret.y = vp1->y - vp2->y;
ret.z = vp1->z - vp2->z;
return ret;
}
// Returns the normal of two vectors
vec3 crossProduct(const vec3 *v1, const vec3 *v2)
{
vec3 normal;
normal.x = v1->y * v2->z - v1->z * v2->y;
normal.y = v1->z * v2->x - v1->x * v2->z;
normal.z = v1->x * v2->y - v1->y * v2->x;
return normal;
}
// Returns the length of a vector
float vec3Length(vec3 *v1) {
return sqrt(v1->x * v1->x + v1->y * v1->y + v1->z * v1->z);
}
// Normalizes a vector
void normalize(vec3 *v1)
{
float len = vec3Length(v1);
if(len < EPSILON) return;
float inv = 1.0f / len;
v1->x *= inv;
v1->y *= inv;
v1->z *= inv;
}
// Adds vector v2 to v1
vec3 vec3Add(vec3 *v1, vec3 *v2)
{
vec3 v;
v.x = v1->x + v2->x;
v.y = v1->y + v2->y;
v.z = v1->z + v2->z;
return v;
}
One problem with using the average of the face normals to compute the vertex normals is that the computed normals can be biased. For example, imagine that there is a ridge that runs north/south. One vertex on the peak of the ridge has three polygons on the east side, and two on the west. The vertex normal will be angled to the east. This can cause darker lighting at that point when the illumination is coming from the west.
A possible improvement would be to apply a weight to each face's normal, proportional to the angle that corner of the face has at that vertex, but this will not get rid of all of the bias.
After experimenting with different solutions, I discovered that my own normal generation in this post actually works extremely well, it's virtually instant and wasn't the problem. The problem seemed to be in using a large texture for the terrain. I changed the texture I used for the terrain to use a tiled texture which wouldn't get stretched so much and the graphic issue seems to have went away. It was a relief that the normal generation I posted works well as other solutions were horribly slow. This is what I ended up with and as you can see, there are no graphical problems. Plus it looks better with more detail. I wanted to post what I found out in case anyone else sees the same problem.
I'm drawing some Bezier curves in WPF and for the most part it's working but I'm getting some faint separations between each segment. As you can see they even appear in straight sections so I don't believe the issue is due to an insufficient number of segments. (This image is at 4x magnification.)
I'm using a collection of System.Windows.Shapes.Line objects to paint them. They are instantiated in code like so:
Shapes.Line Line = new Shapes.Line();
Line.Stroke = Brush;
Line.HorizontalAlignment = Windows.HorizontalAlignment.Left;
Line.VerticalAlignment = Windows.VerticalAlignment.Center;
Line.StrokeThickness = 10;
My theory is that this separation is due to the fact that the point where one line ends is the same point where the next begins but I unsure what's the best way to fix this. I'm fairly new at this so I don't want to go hacking away before I ask if anyone has any tried and true solutions to make these faint separations disappear.
EDIT:
Here is the code I'm using to generate the segments. The ILine interface is something I created but it's point values are simply translated to the System.Windows.Shapes.Line respective values later on in the program.
public static void FormBezier(List<ILine> Lines, Point[] pt)
{
if (Lines.Count == 0) return;
double t, dt, x0, y0, x1, y1;
t = 0.0;
dt = 1.0 / Lines.Count;
x1 = X(t, new double[] { pt[0].X, pt[1].X, pt[2].X, pt[3].X });
y1 = X(t, new double[] { pt[0].Y, pt[1].Y, pt[2].Y, pt[3].Y });
t += dt;
for(int index = 1; index < Lines.Count - 1; index++)
{
x0 = x1;
y0 = y1;
x1 = X(t, new double[] { pt[0].X, pt[1].X, pt[2].X, pt[3].X });
y1 = X(t, new double[] { pt[0].Y, pt[1].Y, pt[2].Y, pt[3].Y });
Lines[index].Start.X = x0;
Lines[index].End.X = x1;
Lines[index].Start.Y = y0;
Lines[index].End.Y = y1;
t += dt;
}
t = 1.0;
x0 = x1;
y0 = y1;
x1 = X(t, new double[] { pt[0].X, pt[1].X, pt[2].X, pt[3].X });
y1 = X(t, new double[] { pt[0].Y, pt[1].Y, pt[2].Y, pt[3].Y });
Lines[Lines.Count - 1].Start.X = x0;
Lines[Lines.Count - 1].End.X = x1;
Lines[Lines.Count - 1].Start.Y = y0;
Lines[Lines.Count - 1].End.Y = y1;
}
public static double X(double t, double[] x)
{
return
x[0] * Math.Pow((1 - t), 3) +
x[1] * 3 * t * Math.Pow((1 - t), 2) +
x[2] * 3 * Math.Pow(t, 2) * (1 - t) +
x[3] * Math.Pow(t, 3);
}
At a wild guess, it's probably a rounding error. The units used in WPF aren't pixels, they are resolution independent units. When WPF actually draws something it has to convert those units to real pixels on whatever screen it's drawing to. If the conversion ends up being half way between real pixels, it'll shade those pixels to try and approximate half a pixel in each real pixel. Hence you sometimes get gray pixels around a supposedly black line (anti-aliasing).
The property SnapsToDevicePixels might help you.
Clearly a fault in drawing algorithm. I am not best at WPF but you may want to have a look at this blog post.
I've searched SO but I just can't figure this out. The other questions didn't help or I didn't understand them.
The problem is, I have a bunch of points in a 3D image. The points are for a rectangle, which doesn't look like a rectangle from the 3d camera's view because of perspective. The task is to map the points from that rectangle to the screen. I've seen some ways which some call "quad to quad transformations" but most of them are for mapping a 2d quadrilateral to another one. But I've got the X, Y and Z coordinates of the rectangle in the real world so I'm looking for some easier ways. Does anyone know any practical algorithm or method of doing this?
If it helps, my 3d camera is actually a Kinect device with OpenNI and NITE middlewares, and I'm using WPF.
Thanks in advance.
edit:
I also found the 3d-projection page on Wikipedia that used angles and cosines but that seems to be a difficult way (finding angles in the 3d image) and I'm not sure if it's the real solution or not.
You might want to check out projection matrices
That's how any 3D rasterizer "flattens" 3D volumes on a 2D screen.
See this code to get the projection matrix for a given WPF camera:
private static Matrix3D GetProjectionMatrix(OrthographicCamera camera, double aspectRatio)
{
// This math is identical to what you find documented for
// D3DXMatrixOrthoRH with the exception that in WPF only
// the camera's width is specified. Height is calculated
// from width and the aspect ratio.
double w = camera.Width;
double h = w / aspectRatio;
double zn = camera.NearPlaneDistance;
double zf = camera.FarPlaneDistance;
double m33 = 1 / (zn - zf);
double m43 = zn * m33;
return new Matrix3D(
2 / w, 0, 0, 0,
0, 2 / h, 0, 0,
0, 0, m33, 0,
0, 0, m43, 1);
}
private static Matrix3D GetProjectionMatrix(PerspectiveCamera camera, double aspectRatio)
{
// This math is identical to what you find documented for
// D3DXMatrixPerspectiveFovRH with the exception that in
// WPF the camera's horizontal rather the vertical
// field-of-view is specified.
double hFoV = MathUtils.DegreesToRadians(camera.FieldOfView);
double zn = camera.NearPlaneDistance;
double zf = camera.FarPlaneDistance;
double xScale = 1 / Math.Tan(hFoV / 2);
double yScale = aspectRatio * xScale;
double m33 = (zf == double.PositiveInfinity) ? -1 : (zf / (zn - zf));
double m43 = zn * m33;
return new Matrix3D(
xScale, 0, 0, 0,
0, yScale, 0, 0,
0, 0, m33, -1,
0, 0, m43, 0);
}
/// <summary>
/// Computes the effective projection matrix for the given
/// camera.
/// </summary>
public static Matrix3D GetProjectionMatrix(Camera camera, double aspectRatio)
{
if (camera == null)
{
throw new ArgumentNullException("camera");
}
PerspectiveCamera perspectiveCamera = camera as PerspectiveCamera;
if (perspectiveCamera != null)
{
return GetProjectionMatrix(perspectiveCamera, aspectRatio);
}
OrthographicCamera orthographicCamera = camera as OrthographicCamera;
if (orthographicCamera != null)
{
return GetProjectionMatrix(orthographicCamera, aspectRatio);
}
MatrixCamera matrixCamera = camera as MatrixCamera;
if (matrixCamera != null)
{
return matrixCamera.ProjectionMatrix;
}
throw new ArgumentException(String.Format("Unsupported camera type '{0}'.", camera.GetType().FullName), "camera");
}
You could do a basic orthographic projection (I'm thinking in terms of raytracing, so this might not apply to what you're doing):
The code is quite intuitive:
for y in image.height:
for x in image.width:
ray = new Ray(x, 0, z, Vector(0, 1, 0)) # Pointing forward
intersection = prism.intersection(ray) # Since you aren't shading, you can check only for intersections.
image.setPixel(x, y, intersection) # Returns black and white image of prism mapped to plane
You just shoot vectors with a direction of (0, 1, 0) directly out into space and record which ones hit.
I found this. Uses straight forward mathematics instead of matricies.
This is called perspective projection to convert from a 3D vertex to a 2D screen vertex. I used this to help me with my 3D program I have made.
HorizontalFactor = ScreenWidth / Tan(PI / 4)
VerticalFactor = ScreenHeight / Tan(PI / 4)
ScreenX = ((X * HorizontalFactor) / Y) + HalfWidth
ScreenY = ((Z * VerticalFactor) / Y) + HalfHeight
Hope this could help. I think its what you where looking for. Sorry about the formatting (new here)
Mapping points in a 3d world to a 2d screen is part of the job of frameworks like OpenGL and Direct3d. It's called Rasterisation like Heandel said. Perhaps you could use Direct3d?