I’m having some difficulties calculating a projection matrix in C for use with OpenGL.
The task is to write a function that takes the vertical fov, the aspect ratio and the distance from the camera to the near- and far-view-plane.
So far I’ve tried different input parameters but every time I’m adding it to the chain of transformation in the shader everything disappears and nothing is visible anymore.
So far my function looks like this:
The result is being saved in a 4×4 matrix (here called “out”) in column-major order.
The calculations inside the matrix where given.
//Creates a projection matrix based on the given parameters and puts it into out
void perspective(GLfloat* out, GLfloat fovy, GLfloat aspect, GLfloat near, GLfloat far) {
GLfloat top = near * tan(fovy / 2);
GLfloat right = top / aspect;
GLfloat left = -1 * right;
GLfloat bottom = -1 * top;
out[0] = 2.0f / (right - left);
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = 2 / (top - bottom);
out[6] = 0;
out[7] = 0;
out[8] = ((right + left) / (right - left)) / near;
out[9] = ((top + bottom) / (top - bottom)) / near;
out[10] = ((far + near) / (far - near)) * -1 / near;
out[11] = -1.0f / near;
out[12] = 0;
out[13] = 0;
out[14] = (-2.0f * far) / (far - near);
out[15] = 0;
}
In case more code is needed i could provide more but it would already be nice to know whether the calculations itself are right or not.
Maximilian Becker is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.