Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenGL projection matrix for perspective with fovy and aspect

I'm making my custom frustum and perspective implementations, part of the reasons are that I might need to do it myself, without library, in the future, and I want to polish up computer graphics skills before the exam.

I'm following a book and I am converting their examples in C++ to my ones in Java/LWJGL, however one example strikes me, it is the projection of a cube.
My cube is projected much further away (about double?) as theirs, which is odd.

This are my implemenations in column-major order:

public static Matrix4f frustum(final float left, final float right, final float bottom, final float top, final float near, final float far) {
    return new Matrix4f(new float[] {
        2 * near / (right - left),          0.0f,                               0.0f,                           0.0f,   //X column
        0.0f,                               2 * near / (top - bottom),          0.0f,                           0.0f,   //Y column
        (right + left) / (right - left),    (top + bottom) / (top - bottom),    (near + far) / (near - far),    -1.0f,  //Z column
        0.0f,                               0.0f,                               2 * near * far / (near - far),  0.0f    //Z column
    });
}

public static Matrix4f perspective(final float fovy, final float aspect, final float near, final float far) {
    float y2 = near * (float)Math.tan(Math.toRadians(fovy));
    float y1 = -y2;
    float x1 = y1 * aspect;
    float x2 = y2 * aspect;
    return frustum(x1, x2, y1, y2, near, far);
}

I've seen somewhere where they use a similar y2 as I have but divide it by 2, however I do not want to make a dirty fix without exactly understanding why it is going wrong.

Could someone verify whether the perspective matrix I am using, and point me out what the other reasons could be that my object looks to be further away?

I have got my other matrix math right and I am only translating the cube by (0f, 0f, -4f) and verified that that was also correct.

Would a wrongly implemented perspective matrix cause my object to be further away?

like image 769
skiwi Avatar asked Nov 27 '25 14:11

skiwi


1 Answers

Your implementation of frustum seems correct.

In your implementation of perspective, fovy should be fovy / 2 instead.

See this answer: https://stackoverflow.com/a/21064935/3146587

like image 139
user3146587 Avatar answered Nov 30 '25 02:11

user3146587



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!