Search code examples
javaprojectionorthographic

How to correctly calculate an orthographic projection matrix?


I've came across many different formulas how to build the projection matrix which all give different outputs, but i feel like I'm misunderstanding the concept. Currently I have this:

//x = 10 | y = 10 | width = 800 | height = 600
        float left = x;
        float top = y;
        float right = x + width;
        float bottom = y + height;

        final Matrix4f pMatrix = new Matrix4f();
        pMatrix.m[0][0] = 2f / (right - left);
        pMatrix.m[1][1] = 2f / (top - bottom);
        pMatrix.m[2][2] = -2f / (farZ - nearZ);
        pMatrix.m[3][0] = -(right + left) / (right - left);
        pMatrix.m[3][1] = -(top + bottom) / (top - bottom);
        pMatrix.m[3][2] = -(farZ + nearZ) / (farZ - nearZ);
        pMatrix.m[3][3] = 1;

With the given output:

0.0025, 0.0, 0.0, -1.025
0.0, -0.0033333334, 0.0, 1.0333333
0.0, 0.0, -0.0068965517, -2.724138
0.0, 0.0, 0.0, 1.0

However I'm not sure whether the right and bottom constant are x + width & y + height or simply width & height? In some articles on the web people use different formulas using both.


Solution

  • Right and Bottom, in this calculation, should be absolute - that is, right = x + width. Your calculation looks correct. The main hint is lines like this one:

    pMatrix.m[0][0] = 2f / (right - left);
    

    The x component is being scaled by the width of the screen. Now, with your current setup, right - left is the same as (x + width) - x. That's definitely going to give width. If instead, you used right = width, then the calculation would become width - x, which makes very little sense.