I'm trying to render a simple triangle with OpenGL in Java using LWJGL3.
Everything is working great, but the projection matrix (perspective) is not working. In C++ I just used to apply the glm::perspective()
method which works just great. But in Java, I implemented it myself since there are no libraries like GLM handling it.
So here the code for the perspective in Java :
public mat4 perspective(float fov, float aspectRatio, float zNear, float zFar){
mat4 perspective = new mat4();
float halfTanFov = (float) Math.tan(Math.toRadians(fov/2));
float range = zNear - zFar;
perspective.m00 = 1f / halfTanFov * aspectRatio;
perspective.m11 = 1f / halfTanFov ;
perspective.m22 = - (zFar - zNear) / range;
perspective.m23 = -1;
perspective.m32 = (2f * zFar * zNear) / range;
return perspective;
}
Of course I tested this multiplication and a compared a result with my TI output, and it worked great.
Other information, the default constructor
for the mat4
class is putting all the values to 0.
here is the code :
public void setZero(){
m00 = 0; m01 = 0; m02 = 0; m03 = 0;
m10 = 0; m11 = 0; m12 = 0; m13 = 0;
m20 = 0; m21 = 0; m22 = 0; m23 = 0;
m30 = 0; m31 = 0; m32 = 0; m33 = 0;
}
the viewMatrix()
in the other hand is working great. It's a simple implementation of the lookAt()
method.
So when it's lookAtMatrix * modelMatrix * position
where the position
is a vec4
the result is good.
But when I try to add the projection matrix for the MVP : perspective * lookatMatrix * model * position
the result is nothing.
Here where I do it in the code :
public mat4 getViewProjection() {
mViewProjection = MatrixTransform.getInstance().lookAt(mPosition, mPosition.add(mDirection), mUp);
return mViewProjection;
}
public mat4 getMVP(mat4 model){
return mPerspective.mult(getViewProjection()).mult(model);
}
And here is my simple GLSL shader (for the vertex shader ) :
#version 430
layout(location=0) in vec3 position;
uniform mat4 MVP;
void main(void){
gl_Position = MVP * vec4(position, 1);
}
I tried other implementation of the perspective without success, so I guess my mistake is somewhere else, but sadly enough, I can't figure out where. If someone could help, it'd be great ! thank you. If you other informations, please ask me and I'll post it.
EDIT : Here is how I put a mat4 into a uniform :
public void uniform(String variableName, mat4 matrix){
int loc = glGetUniformLocation(mId, variableName);
FloatBuffer buffer = BufferUtils.createFloatBuffer(16);
matrix.putIntoBuffer(buffer);
buffer.flip();
glUniformMatrix4(loc, false, buffer);
}
and the method putIntoBuffer()
:
public void putIntoBuffer(FloatBuffer buffer){
buffer.put(m00);
buffer.put(m01);
buffer.put(m02);
buffer.put(m03);
buffer.put(m10);
buffer.put(m11);
buffer.put(m12);
buffer.put(m13);
buffer.put(m20);
buffer.put(m21);
buffer.put(m22);
buffer.put(m23);
buffer.put(m30);
buffer.put(m31);
buffer.put(m32);
buffer.put(m33);
}