I'm currently trying to program with openGL using java and the LWJGL 3 library. I tried to implement the perspective projection matrix, but with the current state, the models won't show up.
public static Matrix4f pespectiveProjectionMatrix(float screenWidth, float screenHeight, float FOV, float near, float far) {
Matrix4f result = identity();
float aspectRatio = screenWidth / screenHeight;
result.elements[0 + 0 * 4] = (float) ((1 / tan(toRadians(FOV / 2))) / aspectRatio);
result.elements[1 + 1 * 4] = (float) (1 / tan(FOV / 2));
result.elements[2 + 2 * 4] = -(far + near) / (far - near);
result.elements[2 + 3 * 4] = -1;
result.elements[3 + 2 * 4] = -(2 * far * near) / (far - near);
result.elements[3 + 3 * 4] = 0;
return result;
}
The Matrix4f class provides an "elements" array, that contains a 4 * 4 matrix.The identity() method returns a simple identity matrix.
This is what the current matrix looks like:
0.75 |0.0 |0.0 |0.0 |
0.0 |0.6173696|0.0 |0.0 |
0.0 |0.0 |-1.0001999|-1.0 |
0.0 |0.0 |-0.20002 |0.0 |
vertex shader:
#version 400 core
in vec3 position;
in vec2 textureCoords;
out vec2 pass_textureCoords;
uniform mat4 transformationMatrix;
uniform mat4 projectionMatrix;
void main(void) {
gl_Position = projectionMatrix * transformationMatrix * vec4(position, 1.0);
pass_textureCoords = textureCoords;
}
rendering:
Matrix4f projectionMatrix = Matrix4f.pespectiveProjectionMatrix(800.0f, 600.0f, 90.0f, 0.1f, 1000.0f); //Creates the projection matrix (screenWidth, screenHeight, FOV, near cutting plane, far cutting plane)
shader.loadTransformationMatrix(transformationMatrix); //loads the transformationMatrix
shader.loadProjectionMatrix(projectionMatrix); //Load the projection matrix in a uniform variable
My problem was, that I forgot to convert FOV to radians on the second line:
result.elements[1 + 1 * 4] = (float) (1 / tan(FOV / 2));
Should be
result.elements[1 + 1 * 4] = (float) (1 / tan(toRadians(FOV / 2)));